Java vs. JavaScript Build Tools

When you come from a Java background like I do and you take a look at JavaScript build tools, the sheer mass of tools is overwhelming.The eco system is evolving very fast with new tools coming up every couple of months. Below, I tried to give a comparison between Java build tools and their equivalent in the JavaScript world.

Preface

The list below aims to show similarities – not differences. Of course, every tool has its own set of features and individual strengths. The tools on the left are not the very as the tools on right, just for another software stack. However, to see some similarities might help to better understand how the JavaScript world works.

Runtime

java nodejs
  • Platform where all tools will run on
  • Executes scripts, tests, etc.

Taks Runner

gradleant gruntgulp
  • Executes scripts and orchestrates tasks
  • Copy files, uglify, minify, package…

Package Manager

maven bower300
  • Dependency Management
  • Versioning

Test Runner

junit karma
  • Tests
  • Test Suits

Mocking/Assertion Library

bildschirmfoto-2016-11-14-um-09-17-07 Jasmine
  • Assertions and expectations (assertThat(1 + 1, is(2)))
  • Mocks and stups

Best regards,
Thomas

Don’t use transitive dependencies in AngularJS modules

Whenever you write an AngularJS application, you will use modules. Modules divide you application into small logical pieces. Some pieces might depended on other, some might be totally independent.

In the example above, you see three modules. A module called MainModule depending on two other modules, called UserModule and UtilModule. Note that this is just a very simple example. In the real world, things become much more complicated.

Let’s assume the following dependency: UserModule depends on some service from UtilModule. However, we forgot to add this dependency to the modul declaration. But because we always run our MainModule for our application, everything will work perfectly fine, because MainModule will load the dependency which the other module will need. So we won’t see this hidden transitive dependency easily.

However, we have problem now: we don’t know anymore which dependencies our module has. Even worse, our module depends on another module, because it provides its dependencies. We end up with a cyclic dependency as MainModule depends on UserModule and vice versa. One cannot run without the other.

But why is that a practical, not just a theoretical problem?

It becomes a practical problem when it comes down to testing. Whenever you do unit testing, you want to test things isolated:

You want to test a small piece with as less dependencies as possible. But what happens if you did’t specify your dependencies right?

Well, you also need to load modules which you don’t actually need. This could easily break your test if something in the other module changes.

Keep your modules clean!

Best regards,
Thomas

AngularJS provider and app configuration

AngularJS provides 3 different ways to create a service:

Factory

A factory is a well known pattern in software development. It aims to create a certain object, in this case a service. In AngularJS this is simply a function which returns an object with methods. In my opinion, this is the cleanest way to create a service in AngularJS.

Service

Another way to create a service is a mechanism called “service”. In this case, your service is a function which has other functions attached to this. It is the shortest way to create a service in AngularJS. However, it sometimes becomes confusing when you need to refer to your own functions using this.

Provider

The last way to create a service, is a provider. A provider fulfils a certain interface and implements a method called $get. This method returns a function which in turn returns the service object. So by calling $get on a provider, you will receive a service factory. This is obviously the most verbose way to create a service.

So why should I use a provider?

So if a provider is the most verbose method you have to create a service, why should you use it at all? To answer this question, it’s important to know that no matter which way you use – factory, service or provider – AngularJS will always create a provider for you internally. That’s why you will sometimes see an error message like this:

When an AngularJS app is started, it has a certain “boot-order”. From the perspective of a developer, it looks like this:

After you defined your application/module, you have a configuration phase and a run phase. The difference between both phases is the service instantiation. During the config phase, the providers have been registered, but they have not been called yet! During the run phase all providers have been called and their services have been registered. This means that you cannot inject any service during the config phase and that you cannot inject any provider during the run phase. Though you can use the config phase to configure your providers and it’s service.

Let’s take a look at the AngularJS UI-Router for an example. If you don’t know it, you can find the documentation at https://github.com/angular-ui/ui-router/wiki/quick-reference.

The AngularJS UI-Router provides both, a provider called $stateProvider as well as a service called $state. The usage would look like this:

By using a provider we have the possibility to configure a service before the AngularJS application runs. We can setup things in advance which can be constant during our application lifecycle. If you need something like this, go with a provider. Other wise use a factory or service.

More

Best regards,
Thomas

Programming to an interface

Interface Message Processor Front Panel

There are many types of interfaces

Program to an interface, not an implementation.

This short sentence, introduced in 1994 by the GoF, is one of the most important design principles in software development. However, I have seen several projects where this principle has gone wrong. Here’s why:

Interface vs. Interface

If you come from a Java background like myself and you hear the word interface you will typically think of something like that:

Yes, that’s an interface. No doubt. However, it’s not the same interface as in “program to an interface“! Sounds strange? Not at all.

Many modern programming languages doesn’t have a keyword called “interface”. JavaScript has no interface keyword; Ruby has no interface keyword; Scala has not interface keyword; and so on… But it’s still possible to program to an interface in all of those languages.

An interface might be a language keyword and an interface might be a design principle. Don’t confuse both!

The language keyword

The language keyword interface can be found in typed languages like Java or C#. It enables the programmer to create an abstract type with multiple concrete implementations.

A consumer can use the interface without even knowing about the concrete implementations.

You should use an interface whenever you have multiple implementations. For example if you use a different persistence in production as in development or if you have an algorithm which is interchangeable.

The design principle

The design principle interface refers to lose coupling between modules or systems.

Whenever you build a larger piece of software, you will have dependencies to other systems. For example to a relational database or to a REST service. All of those dependencies represent tools for your software to fulfil its goals. Such a goal might be to manage contacts in an address bock app or to process orders in an online shop. But whatever the goal of your software is, your goal as a software developer should be to model your problem domain nice and clean.

To achieve such a clean domain layer in your application, you need to create a separation between your domain and external systems. So instead of programming to a relational database, you program to a “data store interface”. Instead of programming to a REST service, you program to a “client interface”. This will make your application independent of all dependencies and focused on its own domain. If you use MongoDB instead of a relational database tomorrow, it’s no problem. All you code is developed to an interface and doesn’t even know that there is any database behind it.

untitled-drawing

Pitfalls

So working with interfaces isn’t as easy as it sounds like. Here are some typical pitfalls in my opinion.

#1: Using an interface, but don’t program to an interface

If you want to achieve the design principle of programming to an interface, it’s very likely that you will use a language construct called interface if your programming language has such (e.g. Java). However, just using an interface keyword, doesn’t mean that you are also programming to an interface. Let’s make an example:

In the example above, your dependency (obviously a relational database) defines your interface. Because the database requires a technical ID for each entity, your interface just reflects this. It doesn’t hide the fact that you use a database, it even has the word “Database” in its name and returns database entities instead of domain objects.

By using such an interface, you don’t decouple your software from the other system. Wherever you use the interface, you will know that you work with a database and you will need to deal with the entity classes from the database layer.

#2: An interface for everything

Of course, we want to do things right. But sometimes, too much is wrong. I have seen some projects where there was an interface for (nearly) everything:

Whenever you have an interface which is a one-to-one copy of a class called ...Impl, something is wrong and you should consider if you really need this interface. There are two rules to think of:

  • Use interfaces (the language keyword) if you have multiple concrete implementations.
  • Use interfaces (the design principle) to decouple your own system from external system.

So if you have a domain service (e.g. AccountingService) there is no need to have an interface (the language keyword) for this service if you don’t have multiple types of it (e.g. CreditCardAccountingService and PayPalAccountingService). Such a service is also part of your own application, so there is no need to decouple yourself from it. There will always be just one single implementation! Our own!

Best regards,
Thomas

Reusable AngularJS form components

Whenever you build software, you want to create reusable and independent components. In the world of user interfaces, those components are often called widgets. Here’s an example how we can achieve this with AngularJS.

An example

Let’s say we have an online shop where a customer can make an order. To do so, the customer must provide some data, in particular an invoice address and a delivery address:

Both, invoice address and delivery address, look exactly the same. They are an example for UI elements which can be bundled in an reusable component.

An AngularJS UI component

With version 1.5 AngularJS introduced the concept of a component. AngularJS’ components are a syntactic short-cut for common directives. So if you use an AngularJS version prior to 1.5, you can achieve the very same behaviour with directives – just with a little bit more code.

An AngularJS component for our address example could look like this:

The my.address.html template would look like this:

If we got this two pieces of code, we can use our brand new component:

Pitfalls

Although our example is still very simple, there are already some pitfalls you need to be aware off.

  • While we have named our component myAddress (camelCase) in our JavaScript code, we need to name it my-address in our HTML code. Otherwise the component will not be recognized.
  • We used the controller-as syntax to name our OrderController just controller. However, inside the template of our component, we must refer to the controller as $ctrl by default.
  • We bind our data to a property which we called address. We can name this property totally as we like, but we need to make sure that we refer to this property from inside of our template: ng-model="$ctrl.address.city"
  • We have used a bi-directional binding using the = operator. So if the model changes inside our component (because the user has entered some text in one of the input fields) it will affect the same object inside our parent controller. Otherwise we wouldn’t be able to access the data.

Accessing the data

Now that we have successfully added our component to our page, we also want to use the data of the delivery and invoice address. Doing this in our parent controller (OrderController) is quite easy:

The result would look like this:

Note that invoiceAddress and deliveryAddress is nested in an object called data because we set-up the component like that:

Form validation

Another pitfall which might be a little bit tricky is form validation. Let’s start with an example again. First, we add form validation to our initial example where we don’t use any components:

This is an example of a very simple form validation build with AngularJS build-in functionality. If the one of the input fields (firstName or lastName) is invalid, a certain CSS class will be applied to mark the field as visually for the user. If we do the very same for our component, we will come to a problem: In order to apply the CSS class with ng-class we need a reference to the form:

Since we want to make an independent component, we don’t want the component to know something about the form in which it is included. This would break encapsulation and we couldn’t reuse the component wherever we want. But we cannot put the component in its own form, because HTML doesn’t allow to nest form. So if we would package our component into its own little form, the browser would ignore and remove it:

bildschirmfoto-2016-10-31-um-09-15-07

The solution is to use ng-form instead of HTML’s form. It will enable AngularJS’ form validation, but will not be touched by the browser. Our component will look like this:

Plunker

You can see the complete working example here:

https://plnkr.co/6UyqVn

More

Best regards,
Thomas

Booting an AngularJS application

Every back-end application has a boot process. Services must be instantiated, connections must be established and configurations must be loaded before the application is ready. How can we do something similar for an AngularJS application?

ng-app

The typical way to start an AngularJS application is to use the ng-app directive on an HTML element (mostly body). Using ng-app Angular will do the bootstrapping of your application automatically. This is perfectly fine for most cases. But if we need more controller of the bootstrap process of Angular, we can do thins manually.

Manual start-up

Instead of using ng-app we can write a piece of JavaScript code to start our application:

Now we are able to start our application manually and to do initialization tasks!

Task 1: Loading data from the backend

A typical start-up task would be to load some initial data (for example a configuration) from the back-end. The code below will make a GET-call to the back-end in order to retrieve some configuration. After the GET-call has finished the application will be started. This makes sure that we have all data up-front.

Task 2: Going to an initial state

Most AngularJS applications have different states. E.g. a view of the user profile (/app/user), a view of the private messages (/app/messages) or simply a home screen (/app/home). Before we start our application, we want to navigate to the correct state. While there are many ways to achieve this, here is an approach how to do it by using an bootstrap script:

The method angular.bootstrap() will return the injector of our application. We can use this injector to access all services of our application (including the routing). In the example below, we assume that we save every state in the session storage of the browser. So we can always look in the session storage to finde the last state where the user has been. If the user now reloads the page in his browser, the AngularJS application will start again. The application will look in the session storage, find the LAST_SAVED_STATE and go to it. Note that we could also use another type of storage (maybe cookies) to persist the state.

Where to put the start-up script to

We usually create one start-script per application, e.g. my.app.bootstrap.js. We code shown above is wrapped into an IIFE and included as the last dependency into our HTML code:

Best regards,
Thomas

More

AngularJS Intensive Workshop by Robin Böhm/Symetics GmbH

Last week I attended an AngularJS Intensive Workshop by Robin Böhm/Symetics GmbH. Symetics is the company behind www.angularjs.de and provides consulting and training all around JavaScript, AngularJS (1/2) and TypeScript.

original-93d514756bd905adaf57c9033f69be39

The location

The 3-days workshop was located in the UNPERFEKT Haus in Essen. The UNPERFEKT Haus is an open space for artists, students and musicians and provides rooms, WLAN and a lot of creative environment. It was a really great location for the seminar and we all felt comfortable.

The trainer

Our trainer was Robin Böhm who is the CEO/founder of Symetics GmbH. He works as a freelancer and does consulting, in-house training and workshops all around web technologies like AngularJS. During the 3-days he provided a lot of information and made a really intense workshop. However, the atmosphere was always relaxed and Robin was open for discussions and questions – even during the lunch break.

The workshop

The workshop was divided into two parts: (1) a round trip about JavaScript and (2) a dive-deep on AngularJS. It was a good mix of presentations and hands-on sessions on a prepared sample project. Robin managed to cover an huge amount of topics:

  • components vs. directives
  • routing (with the new router from AngularJS 1.5)
  • testing (with Jasmine)
  • the promise API
  • build tools
  • books to continue

Robin also tried to give us an outlook on AngularJS 2 and how we can prepare our current projects for it.

My opinion

Actually, there wasn’t much I didn’t like. The workshop covered all relevant topics and gave us a lot of useful insights into AngularJS and related stuff.

I can really recommend it!

It was fast, well prepared and very practical (we wrote code for about 1/3 of the time). The group was medium-sized, maybe 14 people (mostly Java developers). The only downside was that Robin sometimes provided to much detail on a particular topic. I’m more comfortable with staying by the underlying concepts of a technology and dive into the nitty gritty details when I’m working on it.

I’m looking forward to the next workshop! Thanks!

Thomas.

More

Using the console on Windows

I tell you a secret: I’m a Windows user. I don’t use OSX, I don’t use Linux, I use Windows. And I tell you something more: I like it 😉

Usually I develop Java or JavaScript applications which perfectly run under Windows, Linux, OSX or what so ever. So developing under Windows is no problem at all. Runtime environments, IDEs, editors – Windows has it all. However, people keep wondering how I can do the most simple task:

How do you connect to another server? Do you use Putty? – Argh, no, I just type ssh some.server.com and I’m done.

Or:

Do you use your IDE to work with GIT? Or do you have Source Tree? – Argh, no, I just type git add . and git commit -m "..." and I’m done.

But I also know, that not everybody is doing it like this. People use the weirdest tools and techniques when working under Windows. A lot of people use that f***ing small Windows CMD, Putty with its broken key-format or CygWin to be a little bit more Linux-like. But I don’t like all of these. The Windows CMD is unusable, Putty is unnecessary and CygWin is a monster you don’t need. Here is what I do.

Don’t use the Windows default CMD

The first thing I do, is to don’t use Windows’ default CMD. Why? It can’t even mark and copy things! However, there’s an easy and open-source alternative: ConEmu. ConEmu has all the simple things you expect: colors, tabs, resizable, copy-and-paste and much more. You can get it from GitHub and it even works without installation.

2016-05-21 21_51_21-Settings

Use GIT as a toolbox for Windows

The other thing I do, is to use GIT as a toolbox for Windows. When people are talking about using the console, they are actually talking about using tools. They talks about SCP, SSH or CURL like they come with their console – but they don’t! All of those things are just individual programs installed on their machine. They are not related to the command line! So why don’t install them on Windows?

If you use GIT, you already have everything you need in the bin folder (e.g. on C:\Program Files (x86)\Git\bin\):

ssh, scp, curl, cat, grep, less, sh, bash, ls, mv, cp, diff, gzip, and much more…

2016-05-21 22_09_29-Using the console on Windows – Thomas Uhrig

The only thing you need to do is to put GIT’s bin folder to your Windows variable path. You will have everything at a fingertip in your console.

2016-05-21 22_26_43-Environment Variables

Put my SSH-certificates to my user-folder

The last thing I usually do is to put my SSH-certificates to my user folder at C:\Users\tug\.ssh, so that SSH can find them.

Best regards,
Thomas

More

Expression based security with Spring Security

Many web apps have a very simple security concept based on user roles. You might have some admin, some common users and maybe some more roles like a moderator or a super-user. Such a role concept can be easily implemented with Spring Security. For example, you could secure your app based on routes which are available for certain roles:

If you want to be more flexible, you could also annotate your controllers instead of making a central configuration. While a central security configuration can become quite complex if you have a lot of routes with different security rules, using the @PreAuthorize annotation is very simple. All security constraints are right at the method where they apply.

But what if your security model has more constraints than roles?

Spring Security makes it easy to handle roles. But there are a lot of situations where roles are not enough. Imagine an order system (something like Amazon) where an user can cancel an order. To do this, you would introduce an user role which will have the permission to cancel an order. So anonymous users will not be allowed to cancel an order. That’s good, but only half of the story! There is one more (maybe the most important) security constraint: An user can only cancel those orders which belongs to him! And not orders of somebody else!

Such a rule is a typical business rule which can be handled by a service. The service might load all orders which belongs to a customer from the database, iterate over them and check if the given order ID is contained in the list. This could look like this:

If we have such a service which simply returns true or false we can easily use it together with Spring Security:

By using the @PreAuthorize annotation, you can use any Spring Bean. In the example above, we use the OrderService: @orderService.ownsOrder(#orderId). We pass the input parameter directly from the request mapping. The service simply returns true or false and Spring will either allow or forbid the access to the controller method.

It’s also possible to combine those rules:

This makes it possible to build complex security expressions which can use roles as well as Spring beans. By using Spring beans you can implement all types of security checks.

Best regards,
Thomas

More

Inject mocks with Spring’s @ContextConfiguration

One of the biggest strengths of Spring is its ability to make your code testable. By using dependency injection and inversion of control, the Spring context defines which objects will be wired into your beans. This makes it easy to wire services, repositories or what ever you like. But how to wire mocks in your tests?

Example

Let’s create a simple test setup: we have a service called OrderService which handles orders from customers. To do this, the OrderService needs a BillingService.

A typical test setup would run the Spring context, auto-wire the OrderService and test it. But if we would do so, we would also need to include the BillingService into the Spring context. And if the BillingService would need some other service, we would need to include this too and each and every transitiv dependency. Maybe we would end up by loading your whole app just to test one simple service.

A test setup with mocks

Whenever you want Spring to inject our beans, you must create a Spring context. Every bean you want to use must be part of this context as well as every transitiv bean. In this case we need two bean: (1) the OrderService which we want to test and the (2) BillingService which is a transitiv dependency. Both beans must be part of the Spring context!

However, we don’t want to use the real BillingService but a mock. To do this, we provide a dedicated @Configuration for our test which returns such a mock (with Mockito). If we would have other dependencies, we would do this for every bean used by the OrderService.

This makes it possible to load a very small Spring context: We only need our class to test and a mock very each of its dependencies. This is more like an unit test but an integration test and will run very fast. But the nice thing is, that you can decide which dependencies you want to mock and which not. If you would like to mock the BillingService but not the CustomerService it fine. You can control the amount of mocks very easily.

Best regards,
Thomas