Tuesday, 25 February 2014

paranoia testing

Somebody told me once a funny story about a woman who day after day kept arriving late to work, because once on her way to the office, she kept having the need to go back home again and again just to check that she unplugged the iron from the wall socket. Her unfounded fear was such that one day she finally decided to take the iron with her to the office in her handbag.

A common unfounded fear that some developers sometimes have when working with the database, is that they will fail to query it for whatever reason and they feel the need of testing that the database is returning them the expected values. It is common to see horrible tests like this one:

   @Test  
   public void whenAddingANewUserTheUserIsSavedToTheDatabase() {  
     //Tell hibernate to add this user to the database   
     ormAdapter.add(userFactory("djordje", "123"));  
     //Find the user and check its values  
     User savedValueInDatabase = adapter.find("djordje");  
     assertThat(savedValueInDatabase.getName(),is("djordje"));  
     assertThat(savedValueInDatabase.getPassword(),is("123"));  
     //Delete the test data  
     ormAdapter.delete(savedValueInDatabase.getName());  
   }   

The above test has many problems, not just it is slow, also it is wrongly aimed because is not testing the functionality of the application, it just testing that some third party framework(hibernate in this case) is working properly.

Developers who do this, don't understand that the database is just a detail/add-on of the application.
It is fine to perform a smoke test to ping the database if they want(just to verify that the configuration of the ORM framework was correctly done), but testing that the HQL or the hibernate criteria are returning some values is wrong.
"Hibernate, MySQL, Oracle... all are just vendors, their solutions will work, you don't need to test them again!"

Focus on testing the functionality by mocking the dependencies you have with the database.
The only thing that counts at the end of the day is that the inputs and outputs to the service layer are processed correctly. If the data comes from a database, a file, a socket... doesn't matter at all.
Here an alternative test that will mock a dependency to the database and will check that the data is processed correctly:

   @Test  
   public void loginTest() {   
     PersonManagementAdapterORM adapterORM = mock(PersonManagementAdapterORM.class);  
     when(adapterORM.find("djordje","123")).thenReturn(new Person("djordje","123"));  
     LoginService service = new LoginServiceImpl(adapterORM);  
     boolean authorized = service.login("djordje","123");  
     verify(adapterORM).find("djordje","123");  
     assertThat(authorized,is(true));  
   }  

Now tests main concern is the functionality and not how the data is added to, or retrieved from the database.
I trained the mock to behave as expected and I verified that its behavoir was executed as expected.
The database was not at all a concern.

Friday, 24 January 2014

Contextual Vs Composable design

Today at work, a colleague told me about a very interesting topic I never before thought about; Composable Vs Contextual software. I decided to read a bit more on the topic and just post some brief conclusions.

When designing new software, probably one of the most important questions we want to ask ourselves are:
-Who is going to use it?
-How is going to use it?

By talking to the future users of the solution, we can gather relevant information that will help us give answers to the above questions and therefore, determine if what we have to build has to be composable or contextual.

So what is composable and what is contextual then?
If you type in google "define:composable design" or "define:contextual design" you will get really good definitions(Just in case is not clear what I am about to say next). But I will also try to give a more reductionist definition with my own words:

-Composable: For me a composable system, is boundaryless in what regards the interactions the user can have with its components.

-Contextual: For me a contextual system is a system that defines constraints, flows, etc... to guide the user in a predefined way, when it comes to the interactions with its components.

Pros and Cons
So as I said before the important thing is, to understand who the user is and how is going to use the system, but is also good to be aware of some advantages and disadvantages of both designs:

Composable
Pro: Big flexibility.
Con: With great power comes great responsibility(It can be dangerous if in wrong hands).

Pro: Less maintainability
Con: May require training/mentorship for less experienced users

Pro: Generic/Multipurpose
Con: Non-Specific, could be used for the wrong purpose.

Pro: Fast for experienced users
Con: Slow for less experienced users

Contextual
Pro: Solves a problem
Con: Is limited to just that problem/Not reusable in other problems

Pro: Its easy to use
Con: Needs maintenance

Pro: Fast for less experienced users
Con: A constraint for experienced users

Pro: Does most of what you want fast and easy.
Con: Dietzler’s Law for Access(Does 80% of what the user wants easily, but does another 10% with difficulties and finally is unable to do the other 10%)

Just to complete this post, lets write some examples of Contextual vs Composable:

-GUI Vs Terminal
-Framework Vs Programmatical approach
-Wizard Vs copy&paste files into directories








As a conclusion, all I can say is that the decision on which design to go for, will depends on the type of user you are dealing with.

Resources:
-http://gigaom.com/2013/02/16/devops-complexity-and-anti-fragility-in-it-context-and-composition/
-http://nealford.com/memeagora/2013/01/22/why_everyone_eventually_hates_maven.html
-www.google/com

Monday, 20 January 2014

It's been a while. Glad to see you are back.

When doing certain tasks that are tedious, difficult or just we are to exausted to do them; we often whish there was an altruistic someone to give as a hand and make them easier. Sometimes in this situations we would be ready to accept help from anybody, even from an strange visitor...


Visitor is a behavioral design pattern that intends to add or remove functionality from a class without changing its original implementation. It can help leverage complexity and also allows to keep concerns separated. Also is non intrusive, since will be only the clients choice to either allow the visitor to come by and provide support or not, by just calling a method.

Let's have a look at a bit of UML:

 
The only modification needed in the original class it to add a method that accepts a visitor.
That method will be called only by the client and the visitor to visit that class will also be provided by the client. The visitor just have a visit method that takes a concrete implementation of the class that has to visit. If you used the Visitable interface as parameter in visit method is not wrong but you will restrict the visitor to just what sees in the interface(In occasions can be desirable).

Now lets have a look at an example.
Here the Visitable interface and a couple of implementations:

 public interface FormulaOnePitOperation {  
   public void perform();  
   public void accept(Mechanic visitor);  
   public int dangerLevel();  
 } 
 public class PetrolFilling implements FormulaOnePitOperation{  
   private int petrolLevels;  
   public void perform() {  
     System.out.print("Filling the tank as we always do...");  
   }  
   public void accept(Mechanic visitor) {  
     visitor.visit(this);  
   }  
   public int dangerLevel() {  
     return petrolLevels;  
   }  
 } 
 public class WheelsReplacement implements FormulaOnePitOperation{  
   private int presureIndicator;  
   public void perform() {  
     System.out.print("Changing the wheels as we always do...");  
   }  
   public void accept(Mechanic visitor) {  
     visitor.visit(this);  
   }  
   public int dangerLevel() {  
     return presureIndicator;  
   }  
 }  

As we see in the above code, the visitor is passed in the parameter of the accept method that is used to trigger the visit.

Lets now have a look at the visitor's side

 public interface Mechanic {  
   public void visit(FormulaOnePitOperation formulaOnePitOperation);  
 } 
 public class PetrolPumpMechanic implements Mechanic {  
  public void visit(FormulaOnePitOperation formulaOnePitOperation) {  
     System.out.print("You are doing well guys keep going, I am just keeping an eye on the pump here. I won't disturb you");  
     if(formulaOnePitOperation.dangerLevel() > 100)  
       System.err.print("STOP!!! CLOSE THE PUMP NOW!!!!");  
   }  
 } 
 public class WheelsMechanic implements Mechanic{  
   public void visit(FormulaOnePitOperation formulaOnePitOperation) {  
     System.out.print("Just supervising the wheels replacement operation! Not disturbing");  
     if(formulaOnePitOperation.dangerLevel()>45)  
       System.out.print("Be careful you are pumping them too much");  
   }  
 }  

In the visitor side, the functionality of the FormulaOnePitOperation can be modified without changing any of the original code. Also another thing to notice in the above example is that since we are using the interface as parameter, we may be limmited to only use what is defined on it. In occasions is just enough and there is no need to access the concrete classes, but note that the UML diagram encorages to use the concrete implementations(In my personal opinion, I think there is not a big difference since the methods on the concrete classes could not be exposed publicly)

Now finally just the client class:

 public class Pit {  
   public static void main(String[] args) {  
     FormulaOnePitOperation petrolFilling = new PetrolFilling();  
     FormulaOnePitOperation wheelsReplacement = new WheelsReplacement();  
     petrolFilling.perform();  
     petrolFilling.accept(new PetrolPumpMechanic());  
     wheelsReplacement.perform();  
     wheelsReplacement.accept(new WheelsMechanic());  
   }  
 }  

Not much to say about the client, it just uses the classes as usual with the only difference that as per need now can pass a visitor to help add certain tasks. I mentioned at the beggining that Visitor is a non intrusive pattern, by this what I want to say is that nothing mandates the client to call a visitor if he doesn't want to.


A little dissadvantage that this patter has, both methods accept() and visit() have hardwired dependencies in their parameters that can make them hard to unit test.


          It's been a while. Glad to see you are back.
Pair programmers in action

Tuesday, 31 December 2013

In matters of style, swim with the current; in matters of principle, stand like a rock.

I like very much that quote in the title(by Thomas Jefferson).
I found it in the programming book "The pragmatic programmer" some months ago.

Inspired by that quote, for the end of 2013 I want to briefly write a little post about an interesting and distinctive object oriented principle: "Tell don't ask"

It encourages "NOT TO" retrieve the state from an object, "IF" it is going to be used by the client code to make a decission on what to do next.

In my opinion, the reason why this is important is because we want to avoid client's decision becoming dependant on some state that is not under their control. Also exposing unnecesarily the state of the object(unless immutable) to the client code may not always be desirable.
We should try as much as possible, to avoid giving to the client code clues about the state of the object they are calling.

Let's have a look at an example that does not worry much about this principle(The Ask don't tell way - The opposite of Tell don't ask):

 public class Bouncer {  
    //...  
    public Person letIntoParty(Person person) {  
     if(person.getAge() >= 18)  
       return person  
     throw new UnderAgeException(person);  
    }  
   //..  
 }  

At first glance, this code doesn't really look wrong, but the thing is, that the logic of the bouncers object, is dependant on the age of the person. This kind of invisible logical dependency that the bouncer has with the persons age, makes the software less object oriented(Is not capable of making decissions by its own).

It may sound funny but in a Tell don't ask scenario, the person should be aware that cannot get into the party if is under 18.

Now an example of how we could do the same via Tell don't ask:

 public interface BouncerFriendly {  
   //...  
   public Person goParty();  
 }   
 public class Person implements BouncerFriendly {  
   private int age;  
   //...  
   public Person goParty() {  
     if(age >= 18)   
      return this;  
     throw new UnderAgeException(this);  
   }  
   //...  
 }  

There can be different ways of implementing it, but I like to "program to an interface not an implementation". As you can see the decision is made by the person and we avoid giving to the client code clues about the state. Therefore dangerous client decisions based on the state of the object that they are calling are no longer possible.

best wishes for the year 2014!

Sunday, 3 November 2013

If you could pick a superpower what would it be?


The other day at lunch time I had a very interesting conversation with my fellow colleagues.
We were talking about which superpower would be the most awesome to have.
There are so many superpowers to pick its difficult to decide which one is the best and most awesome.
I think that pretty much we all agreed that it would depend on which situation you are in.
That evening going back home by London's tube via central line, the huge crowd made me wish I coulda teleport.
I was meditating about this and I came to the conclusion that teleportation could probably be a bit risky(I yet don't know london very well and I didn't want to land in the wrong place so I gave up that idea). I changed my mind and a wished I could travel time, to go back have a little walk and take a tube latter when less people at the station.
Do you think is there one that can allow you to travel time?
The answer is Yes! there is one.
In this screencast I will show you the advantages time traveling can have for your software and your company and also I will show you how to prepare your software for time traveling when things get ugly. 

Note: Don't forget to set the quality to HD in the video player



Sunday, 6 October 2013

Can you please wrap the gift? It is for my grandma.

Have you ever been in the situation where you have to buy a gift for someone's birthday but you completely forgot until the very last moment?


What if that someone was somebody who you loved so much, let's say your grandma?

Thats not a good feeling uh?

Don't worry this things happen...

Mmmm... yeah... but what to do?
Maybe you have just some time to quickly go to the mall and get something simple and small...

Unfortunately, you know that It won't work, everyone will notice that you forgot to buy a gift and you just bought the first thing you found on your way to the birthday party.

Well... unless you are a gift wrapping expert ;)...


Yeah... I bet you guys know what this blog post is about.

The "Decorator" design pattern.
Imagine, you want to include some additional functionality to a method but you don't want to have impact in what it is already doing.
What you can do, is create a decorator class, that will wrap the original call to that method, and make all the clients call the decorator instead.



Step 1 - Extract an interface that exposes the function you want to decorate.

 public interface Task {  
  public void doSomething();  
 }  
 public class TaskImpl implements Task {  
  public void doSomething() {  
    System.out.println("doing something!");  
  }  
 }  

Step 2 - Create the decorator

 //Make it implement the interface  
 public class Decorator implements Task {  
   //Use composition to make sure you are decorating the right thing  
   private Task taskToDecorate;  
   public Decorator(Task task) {  
      this.taskToDecorate = task;  
   }  
   //implement the interface, but don't forget the original call  
   public void doSomething() {  
     taskToDecorate.doSomething();  
     System.out.println("www.javing.blogspot.com");  
   }  
 }  

Step 3 - Make the client use the decorator



 public class Client {  
   public static void main(String [] args) {  
           Task taskToDecorate = new TaskImpl();  
           Decorator decorator = new Decorator(taskToDecorate);  
           decorator.doSomething();  
   }  
 }  


I want to mention that on the internet I see that the decorator is almost in every post implemented using inheritance(e.g http://java.dzone.com/articles/design-patterns-decorator).
It also looks interesting and I will not critic it but I will just paste here a link to an interesting debate on stackoverflow: http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance





Wednesday, 25 September 2013

Keep calm and S.O.L.I.D

Last winter I had the chance to attend a talk by Robert.C.Martin(aka Uncle Bob) in Dublin. I think it was awesome. Uncle Bob is the author of Clean Code(I've got it signed by him in person :p) and also is a very influential person in the software industry.

I've been thinking to write something about some of the contributions he did to the industry and post it here on my blog since that talk.

One of the last things he said to us, was to read as much as we could...
Before starting to write this post I thought about those words for a while...
I think that it was a great advice.
Nobody negates that real experience is probably best, but reading books is also very important.
They carry the experiences of persons who were there before and also the rules and the principles those persons discovered and documented on their way.
Don't get me wrong, following rules and principles strictly does not always guarantee success("the world keeps changing") but understanding them can be of great help when facing great challenges.


So finally I decided to write this post about one of the biggest contributions of Uncle Bob to the world of object oriented programming, and that is the S.O.L.I.D principles.

Principle #1 
Single Responsibility Principle
If we have a class that has multiple responsibilities/features/reasons to change; Modifications done to it carry the risk of affecting other parts of the class(other responsibilities/features/reasons to change). 
In other words: Classes that do more than one thing are difficult to maintain. 


SRP says: "A class should have only one reason to change".
Lets have a look at an example:
 public class BMI {  
     //Stuff...  
      public void calculate(int heightInCm,int weightInGrms) {  
      //Implementation...  
     }  
     public void saveResults() {  
      //Implementation...  
     }   
     public TrainingPlan getTrainingPlan() {  
      //Implementation...  
     }  
 }  
As you can see, it is a clear example of a class with multiple reasons to change:

  •  Future business requirements might involve us changing the calculate method(e.g different metrics)
  •        Future business requirements might involve us changing the way the results are saved.
  •        Future business requirements might involve us changing the way the training plan is created based in the BMI.

We don't want all the above mentioned requirement changes to affect the class. If we don't seek for modularity at an early stage of development, we will very easily end up with difficult to maintain software.

What we need to do is think just on the one unique goal that the class will have.
Also we can think in what the class definitely will not do, so we can distiguish the other reasons to change that should not be there. Follow this way of thinking when fixing a violation of the SRP and it will help you detect the classes that you need to extract:

 public class BMICalculator {  
     //Stuff...  
         public void calculate(int heightInCm,int weightInGrms) {  
      //Implementation...  
     }  
     //Other methods that support the main goal of the class...  
 }  
 public class BMIToStorage {  
     //Stuff...  
         public void save(BMIResults results) {  
      //Implementation...  
     }  
     //Other methods that support the main goal of the class...  
 }  
 public class TrainingPlanCreator {  
     //Stuff...  
         public TrainingPlan getTrainingPlan(BMIResults results) {  
      //Implementation...  
     }  
     //Other methods that support the main goal of the class...  
 }  



Principle #2 
Open Close Principle

The motivation behind the Open Close principle is to extend/change behaviour without modifying the existing code. This principle says:
"modules should be open for extension but close for modification".
You probably think, that this sounds very contradictory, but in many OO programming languages like Java, there are mechanisms that will allow you to do this. 

One of those mechanisms is polymorphism. By defining abstract functions/methods

Let's have a look first at a violation of the open closed principle:

 public class Chef {  
      public void prepareMeal(Meal meal) {  
           if(meal.type.equals("veg")) {  
                prepareVeg();  
           }  
           else if(meal.type.equals("nonVeg")){  
                prepareNonVeg();  
           }  
      }  
      private void prepareVeg() {  
           //Implementation...  
      }  
      private void prepareNonVeg() {  
           //Implementation...  
      }  
 }  
 public class Meal {  
      String type;  
 }  
 public class NonVeg extends Meal {  
      public NonVeg() {  
           type = "nonVeg";  
      }  
 }  
 public class Veg extends Meal {  
      public Veg() {  
           type = "veg";  
      }  
 }  

In the above code, if a new requirement arrives saying to make some other type of meal different than veg and non veg, the class will need to be modified. The given above example is not maintainability friendly.

Let's see how to use polymorphism to remove that conditional logic and improve the solution:
 public class Chef {  
      public void prepareMeal(Meal meal) {  
           meal.cook();  
      }  
 }  
 public abstract class Meal {  
      public abstract void cook();  
 }  
 public class NonVeg extends Meal {  
      public void cook() {  
           //...  
      }  
 }  
 public class Veg extends Meal {  
      public void cook() {  
           //...  
      }  
 }  
As you can see the solution is more flexible, now it is easier to maintain and also we got rid of an evil flag that at long term will cause only problems when manipulating it. The class Meal that contains sensitive methods is open for extension but closed for modification.

The OCP principle is very powerful but we also must have in mind that by adding levels of abstraction(as alternative you can also think about Composition versus inheritance), we also increase the complexity and it is very important to understand that this principle should be applied only in those places where there is more likely to be often requirement changes. 

Principle #3 
Liskov substitution principle
This principle is concern about sub-classes classes replacing the behavior of their base class. 
If this occurs, the new classes can produce undesired effects when they are used/called in other parts of the program.

Liskov's Substitution Principle states that if a client is calling a base class, then the reference to the base class should be able to be replaced with a derived class without affecting the functionality of base class.

Lets have a look at an example of violation of this principle:

 public class Duck {  
      public void quack(){  
           //..            
      };  
      public void swim(){  
           //..  
    };  
 }  

Also a wild duck can quack and swim.
But what about Duck toys?

 public class DuckToy extends Duck {  
     private boolean batteriesIncluded;       
      public DuckToy(boolean batteriesIncluded) {  
           //...  
      }  
      public void swim() {  
           //...(This logic depends on the batteries)  
      }  
      public void playSound() {  
           //...  
      }  
 }  

As you see, some duck toys require batteries and also they don't really quack, they just play a sound. Even if there are no compilation errors and it looks tempting to include duck toy in this inheritance chain, this is clear violation of Liskov's substitution principle.
The reason is that if a client instantiates the base class, the derived class DuckToy, is not capable of replace it because the functionality is being affected.

 public class Pond {  
      public static void main(String[] args) {  
           Duck wildDuck = new WildDuck();  
           Duck duckToy = new DuckToy(true);  
           wildDuck.quack();  
           //This should not quack  
           duckToy.quack();  
           //Compilation error, real ducks don't play sounds or use batteries  
           //duckToy.playSound();  
      }  
 }  

One solution in this case could be to have a separate class by its own, to represent the duck toy.

 public class DuckToy {  
     private boolean batteriesIncluded;       
      public DuckToy(boolean batteriesIncluded) {  
           //...  
      }  
      public void swim() {  
           //...(This logic depends on the batteries)  
      }  
     public void quack() {  
           //Duck Toys don't quack  
      }  
      public void playSound() {  
           //...  
      }  
 }  

Principle #4 
Interface segregation principle

This is a very simple to understand principle, it says that clients should not be forced to implement interfaces they don't use Just that simple. Have a look at a violation of this principle:


 public interface Animal() {  
    public void fly();  
    public void run();  
    public void swim();  
 }  
 public class Dog implements Animal {  
    public void fly() {  
    //This is empty because dogs can't fly  
    }  
    public void run() {  
     //Implementation for running  
    }  
    public void swim() {  
     //Implementation for swimming  
    }  
 }  

That was horrible uh? So there are many ways you can avoid this.
One example could be to combine specific interfaces as per needed:

 public interface Runner() {  
    public void run();  
 }  
 public interface Swimmer() {  
    public void swim();  
 }  
 public interface Flyer() {  
    public void fly();  
 }  
 public class Dog implements Swimmer,Runner{  
    public void swim(){}  
    public void run(){}  
 }  
 public class Seagull implements Swimmer,Flyer{  
     public void swim(){}    
      public void fly(){}  
 }  

Degresion: While writing this example I just remembered a post that I wrote time ago about the use of Marker interfaces, that is also another interesting way of getting flexibility using interfaces. 

Principle #5 
Dependency inversion principle



This principle says "Don't depend on anything concrete, depend only on things that are abstract." So make sure that all of your dependencies point at things that are abstract.
This will bring safety to your code and also make it flexible.
Probably you are thinking that this principle, can be a bit radical; but obiously, in real following it always strictly is just very difficult(maybe even impossible).
A tip that you can use to verify that you are following this principle when you call a function, is to program to the interface and not the realization.

One great example of this principle in practice is the Template design pattern. Lets have a look first at a common violation of the principle:

 public class PizzaMaker {  
   public Pizza makeMeatPizza() {  
      Pizza pizza = new Pizza();  
     pizza.setBase(true);  
     pizza.setCheese(true);  
     pizza.setOregano(true);  
     pizza.setTomato(true);  
     pizza.setMeat(true);  
     cook(pizza);  
   }  
   public Pizza makeVeggiePizza() {  
      Pizza pizza = new Pizza();  
     pizza.setBase(true);  
     pizza.setCheese(true);  
     pizza.setOregano(true);  
     pizza.setTomato(true);  
     pizza.setMeat(false);  
     pizza.setVegetables(true);  
     cook(pizza);  
   }  
   private Pizza cook(Pizza pizza) {  
   //...  
   }  
 }  

The above example is a badly coded class that makes 2 types of pizzas... There are many bad things in this piece of code, but I will just focus on the violation of the principle we are discussing.
Since every call done to the pizza object is to a concrete method, what we get is something very rigid and inflexible.
Every pizza has some ingredients that are mandatory, such as the base, tomato, cheese and oregano,but the rest are optional, so: why do we care about making calls to concrete methods, to set those extra ingredients, if is not even our concern?

In the following snippet of code, a template method is introduced to abstract the optional part and let sub-classes implement them.

 public abstract class PizzaMaker {  
  //A method that has a call to an unimplemented abstract function,   
  //is known as a template method  
   public Pizza make() {  
     Pizza pizza = addBasicIngredients();  
     addSpecificIngredients(pizza);  
     cook(pizza);  
     return pizza;  
   }  
   public abstract void addSpecificIngredients(Pizza pizza);  
   private Pizza addBasicIngredients() {  
     Pizza pizza = new Pizza();  
     pizza.setBase(true);  
     pizza.setCheese(true);  
     pizza.setOregano(true);  
     pizza.setTomato(true);  
     return pizza;  
   }  
   private void cook(Pizza pizza) {  
     //...  
   }  
 }  
 public class MeatPizzaMaker extends PizzaMaker {  
   @Override  
   public void addSpecificIngredients(Pizza pizza) {  
     pizza.setMeat(true);  
     pizza.setVegetables(false);  
   }  
 }    
 public class VegetablesPizzaMaker extends PizzaMaker {  
   @Override  
   public void addSpecificIngredients(Pizza pizza) {  
     pizza.setMeat(false);  
     pizza.setVegetables(true);  
   }  
 }  

The S.O.L.I.D principles, were identified by Robert C.Martin, but the Acronym was created by Michael Feathers in the year 2000, today they are well known in the world of object oriented sofwtare and many there is plenty literature on books and internet about them.

Just for the end of this post I would like to share with you a great podcast interview that I found on the web, were Uncle Bob, explains S.O.L.I.D in detail.