Monday, March 6, 2017

Deep Dive into Java 9’s Stack-Walking API

The stack-walking API, released as part of Java 9, offers an efficient way to access the execution stack. (The execution stack represents the chain of method calls - it starts with the public static void main(String[]) method or the run method of a thread, contains a frame for each method that was called but did not yet return, and ends at the execution point of the StackWalker call.) In this article we will explore the different functionalities of the stack-walking API, followed by a look at its performance characteristics.

This article requires working knowledge of Java, particularly lambda expressions and streams.

Who Called Me?

There are situations when you need to know who called your method. For example, to do security checks or to identify the source of a resource leak. Every method call creates a frame on the stack and Java allows code to access the stack, so it can analyze it.

Before Java 9, the way most people would access the stack information was via instantiating a Throwable and use it to get the stack trace.

StackTraceElement[] stackTrace = new Throwable().getStackTrace();

This works but it is quite costly and hacky. It captures all the frames - except the hidden ones - even if you need only the first 2 and does not give you access to the actual Class instance in which the method is declared. To get the class you need to extend SecurityManager that has a protected method getClassContext that will return an array of Class.

To address those drawbacks Java 9 introduces the new stack-walking API (with JEP 259). We will now explore the different functionalities of the API followed by a look at its performance characteristics.

StackWalker Basics

Java 9 ships with a new type, the StackWalker, which gives access to the stack. We will now see how to get an instance and how to use it to execute a simple stack walk.

Getting a StackWalker

A StackWalker is easily accessible with the static getInstance methods:

StackWalker stackWalker1 =
        StackWalker.getInstance();
StackWalker stackWalker2 =
        StackWalker.getInstance(RETAIN_CLASS_REFERENCE);
StackWalker stackWalker3 =
        StackWalker.getInstance(
               Set.of(RETAIN_CLASS_REFERENCE, SHOW_HIDDEN_FRAMES));
StackWalker stackWalker4 =
        StackWalker.getInstance(Set.of(RETAIN_CLASS_REFERENCE), 32);

The different calls allow you to specify one option or a set of them as well as the estimated size of the number of frames to capture - I will discuss both further below.

Once you have your StackWalker you can access the stack information using the following methods.

The forEach Method

The forEach method will forward all the unfiltered frames to the specified Consumer<StackFrame> callback. So, for example, to just print the frames you do:

stackWalker.forEach(System.out::println);

Walk the walk

The walk method takes a function that gets a stream of stack frames and returns the desired result. It has the following signature (plus some wildcards that I removed to make it more readable):

<T> T walk(Function<Stream<StackWalker.StackFrame>, T> function)

You might ask why does it not just return the Stream? Let's come back to that later. First, we'll see how we can use it. For example, to collect the frames in a List you would write:

// collect the frames
List<StackWalker.StackFrame> frames = stackWalker.walk(
        frames -> frames.collect(Collectors.toList()));

To count them:

// count the number of frames
long nbFrames = stackWalker.walk(
        // the lambda returns a long
        frames -> frames.count());

One of the big advantages of using the walk method is that because the stack-walking API lazily evaluates frames, the use of the limit operator actually reduces the number of frames that are recovered. The following code will retrieve the first two frames, which, as we will see later, is much cheaper than capturing the full stack.

List<StackWalker.StackFrame> caller = stackWalker.walk(
        frames -> frames
                .limit(2)
                .collect(Collectors.toList()));

[caption id="attachment_149082" align="aligncenter" width="1024"]Concrete Stack Walker Published by Rory Hyde under CC-BY-SA 2.0 / SitePoint changed colorization and field of view and shares under the same license[/caption]

Advanced StackWalker

Continue reading %Deep Dive into Java 9’s Stack-Walking API%


by Arnaud Roger via SitePoint

pull-to-reload – Pull to Refresh Implementation for Web

pull-to-reload is a pull to refresh implementation for the web. Designed to work with both mobile and desktop devices. Fits nicely with web-apps or single-page applications (SPA)


by via jQuery-Plugins.net RSS Feed

Web Design Weekly #270

Headlines

Container Queries

Ethan Marcotte puts forward some really good points on why container queries really have a place as our designs become more modular and pattern-driven. (ethanmarcotte.com)

Powerful Web Design Software. CMS & Hosting Included.

Design, launch and manage pixel-perfect websites faster with Webydo’s all-in-one web design software. Perfect for web designers and digital agencies, Webydo has all the tools you need to run and grow a web design business from client billing to white label branding and more. (webydo.com)

Articles

Moving Airbnb Search to React

Horace Ko from Airbnb explains how the dev team were able to use experiments to confidently launch a refactored search page. (medium.com)

Getting started with Angular’s Router

A great guide put together by Todd Motto that covers and explores the ins and outs of the Angular router. (toddmotto.com)

The Unexpected Power of Viewport Units in CSS

If you want great flexibility in tailoring a site’s elements to a wide array of devices, viewport units are the perfect fit. (lullabot.com)

The Case Of The Forgotten Typeface (fastcodesign.com)

Tools / Resources

Implementing Critical CSS on your website

Andrew Welch shares some great advice on why you should take the time to implement Critical CSS for your projects. (nystudio107.com)

15 reasons why Affinity Designer is the best choice for UX designers

A new version of Affinity Designer is out and with an impressive feature set. They took the best of Sketch, Photoshop and Illustrator and mashed it into one app. (affinity.serif.com)

Shape Shifter

A web-app that simplifies the process of creating SVG-based path morphing animations. (alexjlockwood.github.io)

MaintainableCSS

Write CSS without worrying that overzealous, pre-existing styles will cause problems. MaintainableCSS is an approach to writing modular, scalable and of course, maintainable CSS. (maintainablecss.com)

SparkPost

Email delivery services built for developers, by developers. (sparkpost.com)

Powerful new features for businesses on GitHub.com (github.com)

CSS Tip: Use :not to Save Time and Lines of Code (theboldreport.net)

React FAQ (reactfaq.site)

Inspiration

Hoefler&Co. Typeface Review (twitter.com)

Interview with Harry Roberts (ignaciodenuevo.com)

The CodePen Spark (codepen.io)

Jobs

Product Designer at Scribd

Scribd is seeking a Product Designer who will drive the vision and direction of our design efforts across mobile and web platforms. (scribd.com)

Front-End Engineering Manager at MailChimp

MailChimp is seeking a Front-end Manager to help us build the MailChimp application. You’ll manage our front-end product development team and work with our customer–service team to resolve issues as they arise and to build new functionality into our product. (mailchimp.com)

Need to find passionate developers or designers? Why not advertise in the next newsletter

Last but not least…

Image CDNs to the Rescue

This week Glen Maddern released another Front End Center episode for all of you to enjoy. Glen offers a pro subscription and this weeks was next level awesomeness. He even created a nifty little resource to help learn more about Z-Index which goes hand in hand with that episode. (youtube.com)

The post Web Design Weekly #270 appeared first on Web Design Weekly.


by Jake Bresnehan via Web Design Weekly

What Is the Best Book for Learning JavaScript?

This is the editorial from our latest JavaScript newsletter, you can subscribe here.

"What's the best book to learn JavaScript?" is a question that I've heard asked a lot lately. There are certainly a lot of to choose from. A quick search of Amazon reveals that (at the time of writing) 34 new JavaScript books have appeared in the last 30 days. And another 40 are marked as coming soon. Madness!

So how should you go about choosing the right book for you? Obviously there is no one-size-fits-all approach, but today I'd like to present three of my favorites. I hope they will provide some inspiration and offer additional pathways to explore on your learning journey.

Note: We all have preferences about how we learn, as well as what we expect from learning material. This is not a definitive list, rather a selection of books that I enjoyed and which have helped me further my JavaScript knowledge.

Eloquent JavaScript, 2nd Edition

1. Best Book for Learning JavaScript - Eloquent JavaScript, 2nd Edition

Eloquent JavaScript by Marijn Haverbeke is a book is aimed at ambitious beginners. The author assumes no prior JavaScript knowledge on the part of the reader and does a great job of introducing them to the language in an informative, yet entertaining way. One of my favorite things about this book is that it doesn't just focus on the mechanics of the language, rather it teaches the fundamental concepts of programming and computer science to boot.

The book is split into three parts — the first concentrates on the language itself, the second concerns using JavaScript in the browser and the third (and smallest) part is devoted to Node.js. It also contains exercises and project chapters (in my opinion a great way of reinforcing the concepts learned). These see readers build such things as an artificial life simulation and their own programming language (I did say ambitious).

Although Eloquent JavaScript starts of slow (looking at variables, functions, basic control flow etc) it soon picks up the pace with topics as recursion, polymorphism and higher-order functions being covered in the first part of the book. This might mean that the absolute beginner has to take multiple passes at the reading, but it also means that there plenty of good stuff for the intermediate level programmer to get their teeth into.

My only gripe with Eloquent JavaScript is that it focuses on ECMAScript 5 with ES6 hardly getting a look in. This is a shame (and I hope it is addressed in the next edition), but overall I don't think that it detracts from the value of the book as a great learning resource.

Eloquent JavaScript is available as a paperback, as well a being free to read online.

You Don't Know JS

2. Best Book for Learning JavaScript - You Don't Know JS

You Don't Know JS by Kyle Simpson is a series of books that examine the inner workings of the JavaScript language. Book one of this series assumes little or no prior JavaScript knowledge and introduces various programming building blocks which are explored in more depth in subsequent books. Saying that, I would hesitate to recommend this series to a beginner, as by the end of book two (Scope and Closures) the author is already tackling some pretty advanced stuff. For example exploring closures through implementing his own module loader.

Continue reading %What Is the Best Book for Learning JavaScript?%


by James Hibbard via SitePoint

How to Design and Sell Themes (with Success)

Theme Marketplaces

“Designing themes, can you even make money doing that anymore?”

Of course, when themes are designed well, touted to a demanding customer-base, and the customer is treated well even after the sale, they can certainly spawn revenue. But you need a plan; you need to understand your customers’ needs and where they shop to fulfill those needs. Let's talk about the three stages of theme creating: selling, designing and maintaining.

Where to Sell Themes

Most theme creators fail to earn enough revenue because they seek a customer-base that doesn’t exist; they let their eagerness to try out fancy new trends dictate the outcome of their theme. If you’re wondering why “selling” comes before “designing”, it’s because you need to discover where the demand is, and then supply what those customers are looking for.

Avoid trying to design “the most beautiful theme ever” and uploading it to the biggest marketplaces on the web by default. The big theme marketplaces focus on spotlighting their top 5% of sellers. If you're not currently that, getting your theme spotted in amongst the other 95% of sellers is hard work. You're a needle in a theme haystack.

Finding Demand

While it doesn’t hurt to spread your wings far and wide, marketing takes time, and many theme creators waste a lot of it by choosing “everybody” as their target demographic (i.e. uploading to the biggest and most oversaturated marketplaces).

Start by looking at CMS marketplaces like WordPress. Plain HTML/CSS themes are fine, but they don’t play nice with CMS’s — a lot of work (customers don’t like extra work!) is required to turn HTML into usable CMS themes, so don’t make vanilla HTML versions the focus of your theme.

WordPress actually powers about 25% of the internet, so the customer-base is definitely there, but is the demand there? There’s an endless amount of WordPress themes to choose from, a lot of competition, so why not tune your focus a little more?

If you’re creating an e-commerce theme, you could sell it on the Shopify marketplace, or you could sell blog themes directly on the Ghost marketplace. Do they have more customers? No, but there is less competition — the bigger the marketplace, the harder it is to outshine the competition.

Most customers looking for a theme will turn to their CMS’s own marketplace first because all of the themes listed are built specifically for that CMS; that’s where the demand is.

Most marketplaces have search filters — WordPress does — see which categories are lacking quality themes or use established communities to find out what types of themes are in high-demand.

WordPress Theme Directory

Designing and Coding Themes

We’ll skip the obvious advice where I tell you that clean layouts with documented code (for code-based themes) and appropriately named layers (for UI kits) are a must-have; let's focus on your overall approach to designing usable themes.

Flexibility

Flexibility is key to building exceptional themes. Customers understand that themes are sold to other customers, and they also understand that your theme might not be 100% suited to their needs — they’re going to want to tweak it a little at least. If your theme can’t be modified with ease, it stands very little chance at succeeding. Customers need to know this before buying, so it’s vital that you craft a description that inspires confidence in the theme, along with some kind of theme documentation that the customer can refer to when they’re stuck.

Mockups vs. UI Kits

Although mostly applicable to design resources, these terms can be applied to coded themes too, and they correspond to how far you should go to demonstrate the usage of your theme. In short, a UI kit consists of the individual elements that make up your design (checkboxes, dropdowns, etc), whereas a mockup is a complete example (and sometimes extra variations) of the layout.

How many variations should you sample? Or should you simply create a UI kit and let the customer add their own uniqueness to it? Well, since proficiency will differ from customer to customer, it’s best to offer a little of both: a segmented UI kit where customers can build their own layouts, or complete examples where customers can tweak maybe one or two things.

Tip: if you code your themes vs. only providing a design file, try something like Bootstrap where the documentation and class styles are already defined, you only need to create visual style on top of the Bootstrap base theme.

Maintaining Documentation and Offering Customer Support

You’ve created a theme, you’ve uploaded it to a marketplace (or several), and you’ve even made some sales. Your work is done — or is it? Maintaining a theme and offering ongoing customer support is actually as important as designing the theme itself.

When deciding on a theme, customers will almost certainly read the reviews to see what previous buyers have said about it.

Documentation and FAQ

From the very beginning, and as your theme expands over time, create and maintain a documentation (or at least a concise FAQ) so that the majority of customers can refer to it without having to wait for your responses when they need help.

Continue reading %How to Design and Sell Themes (with Success)%


by Daniel Schwarz via SitePoint

CSS Architecture Block-Element-Modifier (BEM)

The following is an extract from our book, CSS Master, written by Tiffany Brown. Copies are sold in stores worldwide, or you can buy it in ebook form here.

BEM, or Block-Element-Modifier, is a methodology, a naming system, and a suite of related tools. Created at Yandex, BEM was designed for rapid development by sizable development teams. In this section, we’ll focus on the concept and the naming system.

BEM methodology encourages designers and developers to think of a website as a collection of reusable component blocks that can be mixed and matched to create interfaces. A block is simply a section of a document, such as a header, footer, or sidebar, illustrated in Figure 2.3. Perhaps confusingly, “block” here refers to the segments of HTML that make up a page or application.

Continue reading %CSS Architecture Block-Element-Modifier (BEM)%


by Tiffany Brown via SitePoint

Decoding the Proxy Class in OpenCart

More often than not, we take things for granted. If something is working as expected, we don't bother about the inner workings of it to understand the underlying mechanism. Or to put it another way, we don't dig into something until we're in some sort of trouble!

Similarly, I was always wondering about a couple of concepts in OpenCart that were used in the underlying framework, and one of them was the Proxy class. It took me a while to understand it, and I thought it's great stuff to share with you as it's always to fun to know something new.

What Is a Proxy Class?

Although you'll find various materials online that define the term proxy, the definition from Wikipedia is striking and easy to understand.

A proxy, in its most general form, is a class functioning as an interface to something else.

So the proxy delegates the control to the object it intends to use, and thus acts on behalf of the actual class that's instantiated. In fact, the proxy design pattern is a very popular pattern that's used by popular frameworks as needed. Considering the fact that a discussion of the proxy method in itself is such a wide topic and out of the scope of this article, I'll quickly summarize what it's used for most of the time:

  • Act as a wrapper to provide additional functionality.
  • Delay the instantiation of expensive objects, also referred as lazy loading.

In the context of OpenCart, we could say that the proxy pattern is used to add functionality to the base proxy class. Having said that, the base proxy class itself doesn't provide anything except a couple of magic methods! As we'll see in the next section, the proxy class is enriched at run-time by attaching properties to it.

Before we move into the next section, let's have a quick look at the proxy class. It resides in system/engine/proxy.php.

As you can see, it implements three magic methods: __get(), __set(), and __call(). Among them, the __call() method implementation is an important one, and we'll get back to it pretty soon.

How the Proxy Class Works With the Model

In this section, I'll explain how exactly a call like $this->model_catalog_category->getCategory($category_id) works out of the box.

In fact, the story begins with the following statement.

During bootstrapping, the OpenCart framework stores all generic objects to the Registry object so that they can be fetched at will. As a result of that, the $this->load call returns the Loader object from the Registry.

The Loader class provides various methods to load different components, but what we're interested in here is the model method. Let's quickly pull the snippet of the model method from system/engine/loader.php.

Considering the aforementioned example, the value of the $route argument is catalog/category. First, the value of the $route variable is sanitized, and following that it triggers the before event to allow other module listeners to change the value of the $route variable.

Next, it checks the existence of the requested model object in the Registry. If the Registry holds the requested object, no further processing is needed.

If the object is not found, it follows an interesting procedure to load it, and it's the snippet that we're looking for in the context of this article.

To start with, it prepares the file path of the requested model and loads it if it exists.

Following that, it instantiates the Proxy object.

Now, pay attention to the next for loop—it does a lot more than it seems.

In our case, the value of $class should be ModelCatalogCategory. The get_class_methods($class) snippet loads all methods of the ModelCatalogCategory class and loops through it. What does it do in the loop? Let's look closely.

In the loop, it calls the callback method of same class. It's interesting to note that the callback method returns the function callable that's assigned to the $proxy object with the key as the method name. Of course, the proxy object doesn't have any such properties; it'll be created on the fly using the __set() magic method!

Next, the $proxy object is added to the Registry so that it can be fetched later when needed. Have a close look at the key component of the set method. In our case, it should be model_catalog_category.

At the end, it'll call the after event to allow other module listeners to change the value of the $route variable.

That's one part of the story.

Let's go through what happens exactly when you use the following in your controller.

The $this->model_catalog_category snippet tries to find a match for the model_catalog_category key in the Registry. If you're wondering how, just look into the Controller class definition in the system/engine/controller.php file—it provides the __get() magic method that does it.

As we've just discussed, that should return the $proxy object that's assigned to that particular key. Next, it tries to call the getCategory method on that object. But the Proxy class doesn't implement such a method, so how is that going to work?

The __call() magic method comes to the rescue! Whenever you call a method that doesn't exist in the class, the control is transferred to the __call() magic method.

Let's explore it in detail to understand what's going on. Open the Proxy class file and pay attention to that method.

The $key contains the name of the function that's being called—getCategory. On the other hand, $args contains arguments passed to the method, and it should be an array of one element holding the category id that's being passed.

Next, there's an array $arg_data that stores references of arguments. Frankly, I'm not sure if the code $arg instanceof Ref makes any sense or not there. If anyone knows why it's there, I would be happy to learn.

Further, it tries to check the existence of the $key property in the $proxy object, and it results in something like this.

Recall that earlier we assigned all the methods of ModelCatalogCategory class as properties of the $proxy object using a for loop. For your convenience, I'll paste that code again.

So it should be there, and it should also return us the function callable! And finally, it calls that function callable using the call_user_func_array function by passing the function callable itself and the method arguments.

Now, let's divert our attention to the function callable definition itself. I'll grab the snippet from the callback method defined in system/engine/loader.php.

As it's an anonymous function, it has preserved the values in the form of $registry and $route variables that were passed earlier to the callback method. In this case, the value of the $route variable should be catalog/category/getCategory.

Apart from that, if we look at the important snippet in that function, it instantiates the ModelCatalogCategory object and stores it in a static $model array.

And here's a snippet that grabs the method name that needs to be called using the $route variable.

So we have an object reference and a method name that allows us to call it using the call_user_func_array function. The following snippet does just that!

At the end of the method, the resulting outcome is returned via the $output variable. And yes, that's another part of the story!

I've intentionally ignored the pre and post events code that allows you to override methods of the core OpenCart classes. Using that, you could override any core class method and tweak it according to your need. But let's keep that for some other day, as it'll be too much to fit into a single article!

So that's how it works altogether. I hope that you should be more confident about those shorthand OpenCart calls and about their inner workings.

Conclusion

What we've just discussed today is one of the interesting and ambiguous concepts in OpenCart: the use of the Proxy method in a framework to support shorthand conventions to call model methods. I hope the article was interesting enough and enriched your OpenCart framework knowledge.

I would love to know your feedback on this, and if you feel I should cover such topics in my upcoming articles, don't hesitate to drop a line about it!


by Sajal Soni via Envato Tuts+ Code