Monday, December 5, 2016

Reflection vs Encapsulation – Stand Off in the Java Module System

Historically reflection could be used to break into any code that ran in the same JVM. With Java 9 this is going to change. One of the two main goals of the new module system is strong encapsulation; giving modules a safe space into which no code can intrude. These two techniques are clearly at odds so how can this stand off be resolved? After considerable discussions it looks like the recent proposal of open modules would show a way out.

If you're all down with the module system and what reflection does, you can skip the following back story and jump right into the stand off.

Setting the Scene

Let me set the scene of how the module system implements strong encapsulation and how that clashes with reflection.

Module Crash Course

The Java Platform Module Saloon (JPMS) is introducing the concept of modules, which in the end are just regular JARs with a module descriptor. The descriptor is compiled from a module-info.java file that defines a module's name, its dependencies on other modules, and the packages it makes available:

module some.module {

    requires some.other.module;
    requires yet.another.module;

    exports some.module.package;
    exports some.module.other.package;

}

In the context of encapsulation there are two points to take note of:

  • Only public types, methods, and fields in exported packages are accessible.
  • They are only accessible to modules that require the exporting module.

Here, "being accessible" means that code can be compiled against such elements and that the JVM will allow accessing them at run time. So if code in module a user depends on code in a module owner, all we need to do to make that work is have user require owner and have owner export the packages containing the required types:

module user {
    requires owner;
}

module owner {
    exports owner.api.package;
}

This is the common case and apart from making the dependencies and API explicit and known to the module system all works as we're used to.

So far everybody's having fun! Then, in comes Reflection... conversations halt mid-sentence, the piano player stops his tune.

Reflection

Before Java 9, reflection was allowed to break into any code. Aside from some pesky calls to setAccessible every type, method, or field in any class could be made available, could be called, could be changed - hell, even final fields were not safe!

Integer two = 2;

Field value = Integer.class.getDeclaredField("value");
value.setAccessible(true);
value.set(two, 3);

if (1 + 1 != two)
    System.out.println("Math died!");

This power drives all kinds of frameworks - starting with JPA providers like Hibernate, coming by testing libraries like JUnit and TestNG, to dependency injectors like Guice, and ending with obsessed class path scanners like Spring - which reflect over our application or test code to work their magic. On the other side we have libraries that need something from the JDK that it would rather not expose (did anybody say sun.misc.Unsafe?). Here as well, reflection was the answer.

So this guy, being used to getting what he wants, now walks into the Module Saloon and the bartender has to tell him no, not this time.

The Stand Off

Inside the module system (let's drop the saloon, I think you got the joke) reflection could only ever access code in exported packages. Packages internal to a module were off limits and this already caused quite a ruckus. But it still allowed to use reflection to access everything else in an exported package, like package-visible classes or private fields and methods - this was called deep reflection. In September rules got even stricter! Now deep reflection was forbidden as well and reflection was no more powerful than the statically typed code we would write otherwise: Only public types, methods, and fields in exported packages were accessible.

All if this caused a lot of discussions of course - some heated, some amicable but all with the sense of utter importance.

Some (myself included) favor strong encapsulation, arguing that modules need a safe space in which they can organize their internals without the risk of other code easily depending on it. Examples I like to give are JUnit 4, where one big reason for the rewrite was that tools depended on implementation details, reflecting down to the level of private fields; and Unsafe, whose pending removal put a lot of pressure on a lot of libraries.

Others argue that the flexibility provided by reflection not only enables great usability for the many frameworks relying on it, where annotating some entities and dropping hibernate.jar onto the class path suffices to make things work. It also gives freedom to library users, who can use their dependencies the way they want, which might not always be the way the maintainers intended to. Here, Unsafe comes in as an example for the other side: Many libraries and frameworks that are now critical to the Java ecosystem were only feasible exactly because some hacks were possible without the JDK team's approval.

Even though I tend towards encapsulation, I see the other arguments' validity as well. So what to do? What choices to developers have besides encapsulating their internals and giving up on reflection?

reflection-vs-encapsulation-module-system

Choice of Weapons

So let's say we are in a position where we need to make a module's internals available via reflection. Maybe to expose it to a library or framework module or maybe because we are that other module and want to break into the first one. In the rest of the article we'll explore all available choices, looking for answers to these questions:

  • What privileges do we need to employ that approach?
  • Who can access the internals?
  • Can they be accessed at compile time as well?

For this exploration we will create two modules. One is called owner and contains a single class Owner (in the package owner) with one method per visibility that does nothing. The other, intruder, contains a class Intruder that has no compile time dependency on Owner but tries to call its methods via reflection. Its code comes down to this:

Class<?> owner = Class.forName("owner.Owner");
Method owned = owner.getDeclaredMethod(methodName);
owned.setAccessible(true);
owned.invoke(null);

The call to setAccessible is the critical part here, it succeeds or fails depending on how we decide to create and execute our modules. In the end we get output as follows:

public: ✓   protected: ✗   default: ✗   private: ✗   

(Here only the public method could be accessed.)

All the code I'm using here can be found in a GitHub repository, including Linux scripts that run it for you.

Continue reading %Reflection vs Encapsulation – Stand Off in the Java Module System%


by Nicolai Parlog via SitePoint

Web Design Weekly #261

Headlines

Why I’m Thankful for JS Fatigue

Eric Elliott has been involved in the JavaScript community since the early days and shares some words of wisdom for those that are finding the current pace hard to deal with. (medium.com)

CSS Inheritance, The Cascade And Global Scope (smashingmagazine.com)

Sponsor Web Design Weekly and reach over 22,000 passionate designers and developers

Articles

How to perform a good code review

There are several approaches you can take to review code and this article shares a few guidelines that could potentially be worth applying to your day-to-day review process. (alphasmanifesto.com)

Inside a Design Critique with Facebook

Tanner Christensen shares an insight into how the Facebook design team generally conduct critiques. She highlights what makes critiques work well and what often causes issues. (medium.com)

CSS Selectors Explained By Going Car Shopping

A quirky way to explain CSS selectors but it works. (medium.freecodecamp.com)

for..in versus for..of Loops

Ire Aderinokun’s blog posts during the last year have been exceptional and this one is just another reminder that you should subscribe to her blog. She dives into the in’s and out’s of the ‘for’ loop. (bitsofco.de)

The magic behind Styled Components (mxstbr.blog)

Tools / Resources

CSS Reference – A visual guide to CSS

This handy resource features the most popular properties and explains them with illustrated and animated examples. (cssreference.io)

Font style matcher

A neat tool that helps you match the x-height and width of a websafe font and a webfont that you’ve chosen to minimise the flash of unstyled text experience. (meowni.ca)

Practical Redux

Keen to get a good overview of Redux? Well Mark Erikson has your back. He has put together 5 great articles that look at various aspects that will give you a deep understanding and turn you into a pro in no time. (blog.isquaredsoftware.com)

Research Resources

A handy list of books and articles put together by Gregg Bernstein that are suitable for researchers, designers or product managers of any level of expertise. (gregg.io)

Text-decoration-skip: ink, color, style and line position now in Canary (twitter.com)

Svelte – The magical disappearing UI framework (svelte.technology)

Style List Markers in CSS (css-tricks.com)

Welcome.js (booktwo.org)

Inspiration

I Wanted To Make Outer Space Prettier And Now People Are Hiring Me (cosmaschema.com)

5 Things I Learnt as a Designer at LEGO (5thingsilearned.com)

Between the Wires – Chris Coyier (betweenthewires.org)

Jobs

JavaScript Developers wanted at Headforwards, Cornwall, UK

Headforwards have some exciting roles available for experienced JavaScript developers working on a web application for one of the largest telecoms companies in the world. (headforwards.com)

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

Last but not least…

15kb of CSS is all you’ll ever need (medium.com)

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


by Jake Bresnehan via Web Design Weekly

Building a Cross-platform Desktop App with NW.js

NW.js is a framework for creating native applications using web technologies like HTML, JavaScript and CSS. In the simplest case, you're developing a web application using your normal workflow. At the end of the process, you run a generator that compiles everything to a native application that then just displays your web application like a browser does. These applications are called "hybrid apps".

Hybrid apps aren't just great because they're written in languages you're already familiar with (HTML, JavaScript and CSS), but also because they offer essential advantages over normal web apps:

  • Control over browser and browser version (you know which browser your application is called by). NW.js hybrid apps are displayed using Chromium --- an open-source browser running behind Google Chrome. Therefore, apps that are working in Chrome should also work with NW.js.
  • Control over viewports. You could, for example, define a fixed or minimum/maximum viewport.
  • No same-origin policy restrictions due to local files. If you open a local file from the file system, the browser blocks XMLHttpRequest requests of files that aren't located within the same directory. This behavior can be disabled in NW.js apps.

They also offer custom APIs that bring the following advantages:

  • Node.js integration
  • clipboard access
  • access to the file system
  • hardware access (e.g. to get a list of printers)
  • tray icons
  • custom file chooser dialogs
  • shell integration (open files or URLs in default file explorer or browser)
  • the option to customize the entire window (close buttons, menu bar) and context menus
  • the ability set and get zoom level.

Sounds great? Then let's get started. In this article, we'll become familiar with NW.js in practice and learn how to create a hybrid application. An example application that was built using the instructions from this article can be found on GitHub.

Advantages of NW.js in Comparison to Electron

First, there's one thing to mention: NW.js isn't the only framework for hybrid apps. There's another competitor called Electron. It started in 2013, two years after NW.js, but because it's from GitHub it quickly became well known. Now you might be interested in the differences between them. Here are the advantages of NW.js compared to Electron:

  • Supports chrome.* APIs. These APIs can be used to interact with the browser. (You can find more information about this in the NW.js docs.)
  • Has Chrome apps support. Chrome apps are packaged applications that are written with web languages. (More info in the Chrome developer docs.) These applications are different from NW.js, because they have no Node.js integration and are published using the Chrome Web Store. (Chromium will remove its support until August, 2018 (see their blog post). But according to this post NW.js will still support Chrome apps.)
  • Supports NaCl (Native Client) and PNaCl (Portable Native Client) applications. They focus on performance and are therefore primarily written in C and C++. (See this tutorial about how to use them in NW.js.)
  • Has a V8 snapshot source code protection, used to secure your application's source code. Using the nwjc tool, your code will be compiled to native code. (See this article for more information.)
  • Has a built-in PDF viewer.
  • Allows print previews.
  • Supports Node.js integration in Web Workers. They are used to write multi-threaded applications.

However, Electron also has some advantages worth mentioning:

  • Built-in auto-updater (you can follow this issue about an auto-updater for NW.js).
  • Automatic crash reporting to a remote server. NW.js only writes a local file that can then be submitted manually.

There's also a fundamental difference. NW.js applications specify their entry point in the form of an HTML file. This HTML file will be opened in the GUI directly.

Electron applications, on the other hand, specify a JavaScript file as their entry point. This JavaScript file is opened in a separate main process, and can then open an HTML file in the GUI. This means that you could theoretically run Electron apps without a GUI. Also, closing the GUI won't close the main process; you'll need to terminate it manually by calling an API method.

While Electron opens the door for desktop applications written with JavaScript and without a GUI, NW.js applications are probably easier to set up, in case you just want to display an HTML-based application.

Note: If you really prefer the advantages of Electron, check out SitePoint's recent article on creating desktop apps with Electron.

Continue reading %Building a Cross-platform Desktop App with NW.js%


by Julian Motz via SitePoint

New Coffee Break Course: JavaScript Without jQuery

KUTE.js – Javascript Animation Engine

KUTE.js is a minimal native Javascript animation engine with jQuery plugin and with most essential features for web developers, designers and animators, delivering easy to use methods to set up high performance, cross-browser animations. The focus is flexibility, performance and size.


by via jQuery-Plugins.net RSS Feed

Sati

Sati

'Sati' is a free* under construction WordPress theme that offers a dark or light color scheme, both pictured here. Other than the common newsletter sign up box, there are bonus (overlay) sections for About, Portfolio Gallery, Skills and Contact.

*Please note you have to sign up to the DryThemes newsletter to download this WordPress theme.

by Rob Hope via One Page Love

The Delicious Evils of PHP

I want to look at two PHP functions: eval and exec. They're so often thrown under the sensible-developers-never-use-these bus that I sometimes wonder how many awesome applications we miss out on.

Like every other function in the standard library, these have their uses. They can be abused. Their danger lies in the amount of flexibility and power they offer even the most novice of developers.

Let me show you some of the ways I've seen these used, and then we can talk about safety precautions and moderation.

Evil elephpant

Dynamic Class Creation

The first time I ever saw dynamic class creation was in the bowels of CodeIgniter. At the time, CodeIgniter was using it to create ORM classes. eval is still used to rewrite short open tags for systems that don't have the feature enabled...

More recently, though, my friend Adam Wathan tweeted about using it to dynamically create Laravel facades. Take a look at what the classes usually look like:

namespace Illuminate\Support\Facades;

class Artisan extends Facade
{
    protected static function getFacadeAccessor()
    {
        return "Illuminate\Contracts\Console\Kernel";
    }
}

This is from http://ift.tt/2guo630

These facade classes aren't facades in the traditional sense, but they do act as static references to objects stored in Laravel's service locator class. They project an easy way to refer to objects defined and configured elsewhere, and have benefits over traditional static (or singleton) classes. One of these benefits is in testing:

public function testNotificationWasQueued()
{
    Artisan::shouldReceive("queue")
        ->once()
        ->with(
            "user:notify",
            Mockery::subset(["user" => 1])
        );

    $service = new App\Service\UserService();
    $service->notifyUser(1);
}

...and though these facades are simple to create, there are a lot of them. That's not the kind of code I find interesting to write. It seems Adam felt the same what when we wrote the tweet.

So, how could we create these facade classes dynamically? I haven't seen Adam's implementation code, but I'm guessing it looks something like:

function facade($name, $className) {
    if (class_exists($name)) {
        return;
    }

    eval("
        class $name extends Facade
        {
            protected static function getFacadeAccessor()
            {
                return $className::class;
            }
        }
    ");
}

That's a neat trick. Whether of not you use (or even like) Laravel facades, I'm guessing you can see the benefits of writing less code. Sure, this probably adds to the execution time of each request, but we'd have to profile performance to decide if it even matters much.

Continue reading %The Delicious Evils of PHP%


by Christopher Pitt via SitePoint