Journey through software development

Pattern

This week I had the chance to attend the second edition of the NCrafts conference. This conference takes place in Paris and had a lot of awesome speakers from all over Europe.

If you don’t how what this conference is about, have a look at the manifesto below, it will give you an idea.

It’s about programming but also about experience and feedback

It’s not only about technologies but also about practices

It’s not only about software craftsmanship but also about learning and exchanges for everyone

It’s not only about business and applications but mainly about people

In other words, it’s a software conference for developers by developers. We love crafting software with art, passion and technology and share it with everyone.

This manifesto reflects my philosophy and what I try to show in my blog posts. And this exactly what happened during the conference, the speakers and the attendees where very open-minded and we were able to discover new practices.

The Workshops

The day before the conference some workshops were organized by several speakers and I chose to go to the “Event Storming” workshop hosted by Alberto Brandolini and Mathias Verraes.

I will not get into the details of this workshop since I intend to write a full blog post about this experience.

To summarize, the “Event Storming” is an interactive practice that aims to bring the domain experts and the developers closer to each others. You need space on a wall, a lot of space, sticky notes and markers to use this practice.

The goal of this workout is to model the process based on domain events. At the end the developers should have a good idea of how the system should behave and what are the business rules to implement.

DDD, TDD & Functional programming

The conference lasted two days with two talks tracks for each day, there was a lot of awesome content in each talks, a lot of food for thoughts.

Domain Driven Design (DDD) was part of this conference and it makes sense since I believe that, as professional developers, we cannot produce valuable software for our clients without knowing their domain.

Functional programming had also an important place in the conference, it was almost possible to attend only functional programming talks. Most of these talks were made using the FSharp (F#) language.

I made a small introduction to this language a few months ago and being able to see F# developers from the community sharing their tips, tricks and technic was really enjoyable.

I think that functional programming will help us solve some problems we encounter in our everyday job faster than object-oriented programming. It is not better or worse, yet some paradigms of the functional approach are really attractive.

Testing had also a place in the conference for both functional programming and object-oriented programming. If you read my blog you should now know that I write quite a lot about tests, it is a topic I really care about.

During the conference I discovered new approaches for Test Driven Development (TDD) and explanation on the difficulty to practice it. The Type Driven Development (TDD again) practice for F# was really interesting in order to design software.

Waiting for NCrafts 2016

I did not attend last year edition of NCrafts but I will definitely try to go again next year. It was 3 amazing days with a lot of great and open-minded speakers. The NCrafts team did a really great job to make the experience as smooth as possible and as enjoyable as possible.

It gave me a lot of ideas to share with my team in order to improve our technical skills, practices and processes. I can only highly recommend you to watch the talks online when they will be available.

In a lot of object-oriented programming languages there is a moment where we have to deal with null pointers/references/objects. These references must be checked to avoid any exception that might end the program in an unexpected way or moment. I think that most of us have encountered this type of error at least once in our lives. Tony Hoare said that the introduction of the null reference is its “billion-dollar mistake”. Yet sometimes it is possible to avoid the use of null pointer in our application by using the Null Object Pattern.

The intent of this pattern is to provide a specific implementation of an abstraction by doing nothing, it is used to replace manipulation of undefined references (null) when it can be and is therefore predictable (again, it does nothing).

I have created the following piece of code, in C#, to show how it can be done.

In this example, a message is sent to several users using the notification system they prefer. And they can turn off the notification system by choosing the “None” option and in this case the Notifier instance returned by the factory is null and force us to put a check in the calling code to avoid any NullReferenceException. As you can see, if the Notifier is null there is no particular behavior, this is a sign that the Null Object Pattern might be used. To use this pattern, the first thing to do is to add a new implementation of INotifier:

Since the Null Object Pattern is stateless, it is common to use it as a Singleton, this is why I used a static field to hold the reference to the pattern. I can now clean the caller code by removing the null check:

Now my application has the same behavior as before and is cleaner. With the Null Object Pattern I have been able to remove a check for a null reference in my code without losing any functionality. This pattern may look like a test double but its purpose is not for testing, it’s for production code and match a case of the domain model: in my example the absence of notification is a deliberated choice.

The Null Object Pattern is often used with the Factory pattern (like in my example). You should consider this pattern if you have null check over an abstraction that does not trigger any behavior.

I hope you like this presentation of the Null Object Pattern, and as always do not hesitate to comment.

I worked for several years as an ASP .NET MVC developer and I still do even if I do less front-end development at the moment. During my professional life I came across a few tips for this technology that helped me making my code cleaner and less coupled.

Before creating this blog I owned another one in french where I posted a few articles related to Model validation for a form. I will expose the concept of these articles in this new blog post, in english this time. Maybe it will look obvious for you but I wish I knew these tips when I started working with ASP .NET MVC and this is why I’m creating this blog entry, it might help some of you.

The problem

I created the following form for example, which ask for a name and an IP address:

I created this form using a new empty MVC application in Visual Studio and here is the Index.cshtml view:

As you can see I already put some validation logic that will only verify that the fields are not left empty. If the user fill the two text boxes he will be redirected to a page containing only a confirmation message, this is the final result.

But, as you probably guessed it, there are issues with this validation code, the IP address field can be filled with any string value and the Model will be valid. This is not what we desire, we want a more accurate validation for this field and this is what I will show in this article.

When I began working with ASP .NET MVC my first thought, when I encountered an issue like this one, was to add all the validation logic inside the POST action of the Controller. Well, it can work but this is not the place to do so, this option increase the code coupling especially when the Model to validate is huge. In my opinion the Controller should only take care of the “flow” logic of the application and the validation should be placed somewhere else.

The good news is that ASP .NET MVC has been designed to be extensible for Model validation in an easy way. Let’s see how this can be done.

IValidatableObject

It is possible to add validation at the class-level, directly on the Model itself by implementing a specific interface: IValidatableObject. There is only one method available in this interface, the Validate() method. It will be automatically called by the MVC framework when the ModelState.IsValid code is executed, which is already present in our Controller. Let’s see the new version of the Model:

In this first implementation of the Validate() method I simply check that the given address match an IP V4 format (xxx.xxx.xxx.xxx). I have nothing else to do before being able to test this new behavior in my form.

It works as expected. Yet, the validation is not over since I can put the value 800.800.800.800 (which is not valid for an IP address) without having any error, there is more validation to do:

I extended the Validate() method in order to add more logic and to check that each element of the IP address has a correct value. I did this by checking that each of them can be transformed into a byte (value from 0 to 255).

By using the IValidatableObject interface I was able to add validation logic to my Model without modifying my Controller. Doing so can be helpful when you have validation logic that depends on several properties of the Model.

In our example I used this interface only to check a single property and therefore it can look a bit “overpowered”. And if I have another form with a IP address field I will need to extract this part of the logic into a specific method to avoid code duplication. This point leads me to my next tip.

Custom attribute

To add validation to a specific field, the IP address one in our case, my advice will be to create a custom validation attribute. This will allow me to put the validation logic in one place only. Here’s the attribute implementation:

The logic is exactly the same as the one present in the IValidatableObject chapter. First checking the overall format with a regular expression and this is why I created a RegularExpressionAttribute subtype. Then the value of each byte is checked. Now I can use this attribute on my Model:

The Controller is unchanged, the Model is much cleaner and I can easily reuse my attribute for each IP address property in my application models without duplicating the logic.

My Model is now fully checked but only on the server-side, and this validation can clearly be done on the client-side as well with some JavaScript. This will avoid unnecessary HTTP requests between the browser and the server.

jQuery validation

ASP .NET now integrates a lot of third-party JavaScript libraries and among them there is jQuery which we will use to achieve client-side validation. I updated the _Layout.cshtml view to add the following lines:

The data-val-* attributes (HTML5) are used by the jquery.validate plugin to perform the client-side validation. But as you can see, there is nothing related to our regular expression pattern we defined for the IPAddressAttribute. And if you try to validate the form with an invalid IP address the form will still be posted to the server. At the moment the client-site validation is not complete.

IClientValidatable

ASP .NET MVC allow us to extend the generated HTML in order to add more control over the fields in the form. For that I will make the IpAddressAttribute implementing the IClientValidatable interface.

This method adds two new validation rule for the client-side code. The first one is for the regular expression and I use the existing ModelClientValidationRegexRule class to do so. The second one is a custom ModelClientValidationRule for which I defined the type as “ipformat”. This means that the input in the form will have a data-val-ipformat attribute.

This attribute is not recognized by the jQuery validation plugin, so I created a IPFormat.js file to extend it:

I now have my attributes for the regular expression validation and for the ipformat validation. Let’s try the form once again.

Here we are, the IP address is fully checked without being sent to the server. To achieve this I only used functionalities present in the framework, such as the IValidatableObject interface, the custom validation attributes, the IClientValidatable interface and a bit of jQuery.

This is the end of this blog post about Model validation in ASP .NET MVC on both server-side and client-side. I hope this will help you and as usual do not hesitate to comment and share this.

I am a developer, I believe in unit testing and I write a lot of them. But it was not always the case, mostly because I was working on a highly coupled code base. Whenever I wanted to test a single functionality I had to set up a lot of things (database, configuration files, …) to do so even if this functionality was not linked to these dependencies. It was spaghetti code into a big ball of mud.

Then I discovered the Dependency Injection (DI) pattern and it changed the way I designed my code and it made testing much easier. The DI purpose is to reduce coupling between software components in order to improve maintainability and testability. I created the following piece of code to demonstrate the principle :

The NotificationService sends an email to a given user if he has activated the notifications. Now if I want to test this logic I will have to set up a datasource for my repository and a mail inbox for the notifier. This is a lot of configuration for a simple piece of logic. This code is highly coupled because the NotifyUser method of my service instantiates its dependencies (the repository and the notifier), this means that the Single Responsibility Principle (SRP) is not respected. I will use the Constructor Injection technique to change the code :

The UserRepository and the EmailNotifier are unchanged, they just implement interfaces. Now the NotificationService uses these interfaces as fields that are injected through the constructor. The NotifyUser method can now use these dependencies without having to create them, the code is “cleaner”.

I added interfaces for the repository and the notifier for testing purpose, I can test my service with a fake repository and a fake notifier that do not require heavy configuration :

These two implementations are mocks, it means that they mimic the behavior of concrete classes and are used only for testing purpose. In my MockNotifier I just set a flag to true when the Notify method is called, and the GetById method of the MockRepository returns a User instance with the wanted value for HasActivatedNotification. I created a test class with NFluent to show how it is used :

I can test the logic of my service without having to configure a datasource with pre-configured users and without checking in a inbox if there is an email or not. Dependency Injection reduces code coupling and makes testing easier even if you have to create dedicated classes for them. You can find more information about DI here and here.

Constructor Injection is a pattern I use because with it I improved the maintainability of my code base with less coupling and more testing, you should try it as well if it’s not the case.