Pages

Showing posts with label patterns. Show all posts
Showing posts with label patterns. Show all posts

Friday, September 18, 2015

Don't be afraid of chinese restaurants ;)

How many times in your life have you shout to a non english speaking Chinese waitress at a restaurant in Soho, something like: "HEY!!! Why are you swapping the card 4 times?!?!?!!"
In this post I will prove that Chinese waitress are honest and often people panic, because they don't understand what Idempotency is.

The debit cards payment gateways are the classic example of idempotency.

In distributed systems terminology, we say that a service is Idempotent, when its clients can repeatedly send the same requests while the service produces the same result.
In other words, multiple identical requests are treaded by the service as a single request.

Important to note that this doesn't mean that the response is identical, it is just the service result that will be identical.
While the state of the response may change between requests, the result will always be the same, for identical requests.
In other words, it is save to call the service multiple times.

Let's have a look at a simple example of an idempotent function in java:

Receipt process(DebitCard debitCard, Amount amount) { throws NoPatienceException 
      if(not(transactionSentFor(debitCard,amount))) {  
           return cardProcessor.process(debitCard, amount);  
      }  
      else {           
           return blankReceiptFor(debitCard, amount);  
      }  
 }  

In the example above, we can clearly see that the conditional statement is safeguarding us from starting probably a distributed transaction across multiple parts of a distributed system. Instead of that, if we try to process again,  a blank/identical receipt with the returned



Come on, stop being affraid of chinese restaurants. 


Wednesday, September 4, 2013

In London you will never be hungry.

I recently arrived to London, I have to say that I am very impressed.
Everything is really beatiful and the weather is great. One of the things that kept my attention is the huge amount of places you can pick for eating. I love food, and while eating at an Indian place at whitechappel yesterday, I've got inspired for my next blog post.

Did your programming teacher ever gave you that exercise, where you had to create a program to pick some food from a restaurant menu and try to apply some design pattern to it?
While looking through the menu at that Indian place I was remembering that homework, and I think it was some kind of factory pattern what we were expected to use back then to solve it.

This article is about the "abstract factory" pattern. Because of its purpose, some people may also refer to it as the "Toolkit pattern".
Let's have a look at it...

The "abstract factory" pattern is an enhancement of the "factory method" pattern(maybe better to say-It uses it...). Let's just refresh quickly our minds about the "factory method" pattern.

The "factory method" pattern is a creational pattern that intents to release the client from the task of creating objects.
The main reasons are:
 -objects may have a complex/dependant initialization mechanism which does not interest the client.
 -the client doesn't know which is the object type that he needs until runtime.

To implement a factory method what we need is create a method that will take an argument(passed at runtime) and add to it conditional logic that will create one object type or other based on the passed parameter.

The only way in which abstract factory differs from factory method is that with abstract factory we just create factories and let the client use the factories for create objects.

Both "abstract factory" and "factory method" are widely used in software engineering. Now let's have look a simple example where an "abstract factory".

In this UML diagram, we see how the client interacts only with the abstract factory and even the objects that creates using those factories are abstract(Food). The client does not know or care at all how those objects are created. As a result, the client call is simplier and does not have complex conditional logic to decide the object that is required.


 public class Customer {  
   public void orderFood() {  
     System.out.println("Which type of food would you like?");  
     Scanner scanner = new Scanner(System.in);  
     System.out.println("1- Mexican");  
     System.out.println("2- Chinese");  
     System.out.println("3- Indian");  
     int option = scanner.nextInt();  
     FoodFactory factory = FactoryMaker.getFactory(option);  
     Food food = factory.prepareFood();  
     System.out.print("Here are your " + food.getClass().getName());  
   }  
 }  
In the above code we see what we just mentioned above. The client using the abstract factory only interacts with abstractions, so there is not much client code.
 public interface FoodFactory {  
   public Food prepareFood();  
 }  
If we want to extend our software and have some other types of factories, we need to implement the comon interface that the client uses to access the factories.
 public class MexicanFoodFactory implements FoodFactory {  
   @Override  
   public MexicanFood prepareFood() {  
     Scanner scanner = new Scanner(System.in);  
     System.out.println("Mexican food menu:");  
     System.out.println("1- Fajitas");  
     System.out.println("2- Tacos");  
     return getFood(scanner.nextInt());  
   }  
   private MexicanFood getFood(int choice) {  
     switch (choice) {  
       case 1:  
         return new Fajitas();  
       case 2:  
         return new Tacos();  
     }  
     return null;  
   }  
 }  
This code above is just one sample implementation of one of those factories. As you can see, it has a "factory method" pattern in itself that will help return the appropiate food object(Just notice that the return type is an abstract class)
 public class FactoryMaker {  
   public static FoodFactory getFactory(int choice) {  
     switch (choice) {  
       case 1:  
         return new MexicanFoodFactory();  
       case 2:  
         return new ChineseFoodFactory();  
       case 3:  
         return new IndianFoodFactory();  
     }  
     return null;  
   }  
 }  
But to allow the client create the factories we will need some kind of gadget that will allow the client create one factory or other at runtime. That is why we need this class called FactoryMaker(This is again another sample of "factory method" but it will return an abstract/interface type)
 public abstract class Food {  
 }  
 public abstract class MexicanFood extends Food {  
 }  
 public class Fajitas extends MexicanFood {  
 }  
This 3 classes above are just part of the domain model.If you want you can make abstract those that you don't need to instantiate using the "new" keyword. The factories task is to create each of the concrete objects but use abstract return types so the client does not know about the type of the object being returned.

 Even if this pattern looks really interesting there are 2 important disadvantages of using it:
 - the bigger the model gets(more products), the more difficult is to maintain.
 - it violates the open-closed principle


Bon Appetit!

Friday, March 22, 2013

How do private methods affect our software testability?

 How many times did we hear the question:
“Should we test private methods?”
In this post I want to share with you my thoughts about this question and how I think we should proceed when having this doubt.
Methods with the access modifier private are code as the rest of the application, so this mean that they can potentially hide bugs.  So after a first impression my answer to that question is: “Yes, we should!”.  
Wait, a second… before you get mad at me. I want to rephrase my statement.
I think that question is completely not in place.  Instead of asking “Should we test private methods?”, we should ask: “How do private methods affect our software testability?”
Let’s consider different approaches to deal with private methods and see their pros and cons from the testability point of view:

Scenario 1 – Ok,ok you leave me no choice but reflection
This is what the official Java tutorials say about reflection: 
“Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.”
Ok, let’s  give it a try, imagine we have some private method, such as this one:



Hhmmm… So how to do this? Oh my god, do I really have to use reflection? Are you sure?
Let’s investigate a bit before making any decision.
Weeks ago I spent one full afternoon searching the internet looking for testability assurance pattern to test this in java. The only interesting discovery I did was that C# developers have a pattern for this called  “Internals Visible To Attribute”.  Unfortunately (Or maybe fortunately hehe…) that technique is not compatible with java.
There has to be an alternative, why can’t we just change the access modifier and test it normally?...
The common answer you get, when you ask that is:  You will compromise security, you will break encapsulation, you are lazy…
Ok,ok,you leave me no choice but reflection:

 Please don’t do this at your workplace J
Let’s see the Pros and Cons now.

Pros:
- The test is green and I tested the piece of code that I wanted to test
- I did not compromise the security of my software(:P Whatever….)
- I am an expert because the official java tutorials say that only cool dudes like me can use reflection.
Cons:
- A simple rename done by anybody to the method, return type or parameter will break the test and I will have to come back to rewrite the test. This type of test is very difficult to maintain.
- I broke the Security of my software. What am I talking about??? How is that possible if the method still private in the production code?? Hacking the internals of a class is a security.
- See how long that test is. Imagine you have to do this for a longer and more complex method.
More drawbacks(Taken from Java official tutorials website):



Scenario 2 – There is always a way out.
As mentioned in the previous scenario a design pattern that can help us testing private fields does not exist. But there are always ways out. Here I am going to suggest 2 and explain them:

- Protect your method: Just change the access modifier to protected. This will allow you to stub the method call and test using a pattern called Subclass & Override. Basically on your test package, you will be creating a fake that extends the class under test and then override using your expectations. You will then use that fake on your test.
This is a very common breaking dependency technique, since that private method will for sure be called somewhere else within the class and present a dependency inside other method/s(Must be broken in order to increase testability).
I don’t agree with this being a security risk because various reasons, one of them is that probably that method should not be private or, is too long to be tested indirectly, or probably that method should not even be there.
The only disadvantage I see is a decrease in the quality of the design, but I will justify that as the price we need to pay when we build software without using TDD or having testability in mind.

- Extract until you drop: Robert C. Martin in his book “Clean Code”, describes a refactoring methodology called “Extract until you drop”, the idea is refactor the code as much as possible until the point there the methods have not more than 4 lines of code. He says that a line with just a curly braces also count as a line.  If you think about it, your methods would be able to use an “if else” statement of just one line in each of the clauses.
If we want to unit test, we need to have units.  After doing this exhaustively on the method or class under test, we will probably see how that method was probably refactored into a new class, or maybe became so small that it can be tested indirectly via another method with no risk at all, since there are no longer inflection points(Places where logic of the software can potentially take a different path).
The main disadvantages of this approach will probably be that doing it probably would take too long, also on our way and specially if we are dealing with legacy code, we will need to use a lot of breaking dependency techniques and this will present a learning curve that will push us to break some of the design rules we were highly tight too in the past when the system was initially built.  But the benefit will be visible at short, mid and long term.

If you are concern about testability and you believe that testability is the path to quality in modern software, then the right question is How do private methods affect our software testability?

Sunday, November 18, 2012

Fancy a cup of tea?

In most parts of Eastern Europe, they often drink it with lemon and honey,
in India with milk and cardamom,
in Spain they drink it just with sugar,
in Ireland they drink it with milk and some people with a fascinating new taste called brown sauce (If you dont belive me see this movie: Intermission).

But in all cases the recipe has 2 mandatory components:
  1. Boiling water
  2. Tea

In this video I am going to talk about a new design pattern that was created by Marco Castigliego, called
"The Step Builder".

"The Step Builder" is a variant of the creational pattern "Builder".
The advantages of using Castigliego's pattern are:

  • The user will see only one or few selected methods per time during the Object creation.
  • Based on the user choice different paths can be taken during the Object creation.
  • The final build step will be available only at the end, after all mandatory steps are completed returning an Object in a consistent state.
  • The user experience will be greatly improved by the fact that he will only see the next step

 methods available.

More information about this pattern and also a wiki definition of it can be found at Marco Castigliego's blog: Remove duplications and fix bad names

 Note: Don't forget to select the maximum quality in the video player




Saturday, October 20, 2012

static factory methods, an alternative to public constructors

The most widely used technique to allow other parts of our programs, to get objects of a certain type, is to create public constructors.

1:  public class Product {  
2:        //..  
3:        public Product() {  
4:        }  
5:       //..  
6:  }  

There is also another technique that provides various advantages and it would be highly recommendable for every programmer to know.
Classes can provide static factory methods. This methods are another way of returning instances.

1:  public class Product {  
2:      //..  
3:        private int price;  
4:        private String description;  
5:          
6:          
7:        private Product(int price,String description) {  
8:              this.price = price;  
9:              this.description = description;  
10:        }  
11:        public static Product getNewProduct(int price,String description) {  
12:              return new Product(price,description);  
13:        }  
14:      //..  
15:  }  

This are some of the advantages of using this technique:

Methods have names, so we can be more descriptive when constructing our objects.
Constructors cannot have names, but methods can, so by having this types of methods we can express more fluently how the object is constructed.
So instead of this:

1:  new Product("ProductA",12);   

We can create our objects like this:
1:  Product.getNewProductWithValues("ProductA",12);  

We don't have to create new objects if we don't want to. 
Every time the keyword new is called, a new instance is created. In many occasions, specially in large systems, programmers need to be careful with resources. Some techniques to do that are:
-having cached objects and manage that they are cleaned properly.(Google for Singleton pattern).
-work with immutable objects which provide predefined state.(Google for Builder Pattern)
In the following piece of code you will see a very trivial implementation of a cached object:

1:  public class Product {  
2:        private static Product product = new Product();  
3:        private Product() {  
4:        }  
5:        public static Product getDefaultProduct() {              
6:              return product;  
7:        }  
8:  }  

This type of methods can have a subclass as a return type.
By using this type of methods, we can have big flexibility because we can use sub-classes as return types.
This is a very interesting feature which can allow us to create very powerful factories:

In the following example you can see how the static factory method can be used to create instances of subtypes or implementing types.
:
1:  public final class ProductFactory {  
2:        public static Product getProduct(boolean condition) {  
3:              if(condition) {  
4:                    return new HomeMadeProduct();  
5:              }  
6:              else {  
7:                    return new FactoryMadeProduct();  
8:              }  
9:        }  
10:  }  



  

Share with your friends