Monday, June 30, 2014

Command pattern

Command pattern: Encapsulates a request as an object, thereby letting you parametrize
other objects with different requests, queue or log requests, and support
undoable operations.
.
The command pattern allows you to decouple the requester of an action from the object actually performing the action. By introducing 'command objects' into the application design, we can encapsulate a request to do something.
command pattern uml
(command pattern)
A nice example would be programming a software for a remote. This remote should work with various devices and therefore does not know what it should do for each device. For each button we will assign a command object that knows how to communicate with the right object (receiver) that gets the work done. Using an API (application programming interface) command objects can be loaded into button slots, allowing the remote code to stay very simple.
// every class you want to use as a command object will have
// to implement this interface
public interface Command {
  public void execute();
}
Each 'command object' is bound to a specific object before it is assigned to the remote (e.g., create one LightOnCommand object for the kitchen light and one for the living room light). 
public class LightOnCommand implements Command() {
  Light light; // receiver

  public LightOnCommand(Light light) {
    this.light = light;
  }

  public void execute() {
    light.on(); // here we execute everything we want to do with the receiver object
  }
}
public class SimpleRemoteControl() { // in the UML: invoker
  Command[] commands;

  public SimpleRemoteControl() {
    commands = new Command[5];
    // it might be a good idea to initialize all commands with a NullObject
    // (an object implementing the Command interface, which does nothing -
    // this way you wont have to check if an element of commands is null)
  }

  // the command object may be changed at runtime
  public void setCommand(int slot, Command command) {
    commands[slot] = command;
  }

  // if the remote button is pressed we call the execute method of
  // our Command object
  public void buttonWasPressed(int slot) {
    commands[slot].execute();
  }
} 
The remote object does not care what command object is in its slot, as long as it implements the Command interface. The command pattern is extremely useful as the following sections will show (besides what you have already read):

Undo
With the command pattern it is very easy to implement undo actions. Simply add another method to the Command interface. When implementing this method, perform the exact opposite action/s you implemented in execute. You will also have to add a reference to the last Command that was performed (set whenever method buttonWasPressed() is called), as well as a new method undoButtonWasPushed() to our SimpleRemoteControl class.
public interface Command {
  public void execute();
  public void undo();
}
public class LightOnCommand implements Command() {
  Light light; // receiver

  public LightOnCommand(Light light) {
    this.light = light;
  }

  public void execute() {
    light.on();
  }

  public void undo() {
    light.off(); // oposite action of turning a light on
  }
}
This is easy for objects, which have only two states. If there are more states you will have to maintain a variable storing the previous state every time a new state is set. In case of an undo action you will just have to set the current state equal to the previous state.
Sometimes you want to be able to press an undo button multiple times. To implement such an undo history, instead of keeping track of just the last Command executed, you keep a stack of previous commands. Every time the undo button is pressed, you can pop a command object off the stack and execute its undo method.

Macro command
If you have a situation where several commands should be executed at once you can still use our usual command interface, but use an Array of commands for the constructor. Neat isn't it?:
public class MacroCommand implements Command() {
  Command[] commands; // command array

  public MacroCommand(Command[] commands) {
    this.commands = command;
  }

  public void execute() {
    for(int i=0; i<commands.length; ++i) {
      commands[i].execute();
    }
  }

  public void undo() {
    for(int i=0; i<commands.length; ++i) {
      commands[i].undo();
    }
  }
}

Queuing requests
The command pattern offers the possibility to package a piece of computation and pass it around as first class object. The actual computation may be invoked long after some client application creates the command object. This is very nice if you are working with multiple threads. You can use this for schedulers, thread pools, job queues, ...
Furthermore threads don't even have to be assigned for specific tasks. One time a thread may be computing a math problem, and the next time it may be sending something over the network. Using the command pattern, the job queue classes are totally decoupled form the objects that are doing the computation.

Logging requests
You may store and load command objects on disk, using java object serialization. Take a spreadsheet application for example: You might want to implement a failure recovery by logging the actions on a spreadsheet rather than writing a copy of the spreadsheet to disk every time a change occurs.

I hope this post gives you an idea of the usefulness of the command pattern. See you next time.

Tuesday, June 24, 2014

StreamSources

If you happen to use StreamSource for whatever reason, you might have encountered FileSystemExceptions if you used it like that:
  File xmlFile = new File("asdf.txt");
  final StreamSource source = new StreamSource(xmlFile.toFile());
  // other operations
If you try to move or delete this file later on you will get: java.nio.file.FileSystemException the process cannot access the file because it is being used by another process. The reason for this is simple. By passing File directly into StreamSource you lose control of how/when to close the file handle. Using a FileInputStream will solve this problem:
  final FileInputStream inputStream = new FileInputStream(xmlFile.toFile());
  final StreamSource source = new StreamSource(inputStream);
  // do anything you want
  inputStream.close();
We should never forget to close a stream after using it. To be certain that a stream is closed, even if something goes wrong, we have to do proper exeption handling:
   FileInputStream inputStream = null;
   try {
      inputStream = new FileInputStream(xmlFile.toFile());
      final StreamSource source = new StreamSource(inputStream);
      // other code here
   } catch (final Exception e) {
     // handle your exceptions
   } finally {
      if(inputStream!=null){
        try {
          inputStream.close();
        } catch (final IOException e) {
          // report      
        }
   }
This way the sream gets closed, even if an exception was thrown by another part of the code inside the try block.

Singleton pattern

Singleton pattern: Ensures a class has only one instance, and provides
a global point of access to it.
.
There are often situations where you want an object to exist once and only once during run time of an application (e.g., for preferences, logging, thread pools, caches ...). Instantiating more than one of these objects often causes incorrect program behavior, overuse of resources or inconsistent results (due to multiple copies of objects).

The classic implementation of a singleton uses a private constructor, which is called by a static method - acting as the global point of access, preventing other classes to create new instances on their own:

public class SingletonClass{
  private static SingletonClass instance;

  private SingletonClass(){
  }

  // the static instance variable will only get instantiated once
  // after that it wont be null and therefore the private constructor
  // wont be called again
  public static SingletonClass getInstance(){
    if(instance==null){
      instance = new SingletonClass();
    }
    return instance;
  }
}

Another effect of the singleton is that the instance variable is instantiated in a lazy fashion. The object will only be created when really needed (the moment getInstance() is first called). A global variable might be created when you application begins. If an object is resource intensive and an application does not always ends up using it, using a singleton might be the better choice.

Multithreading

You have to be careful though when using multiple threads. If two threads call the getInstance() method at the same time, it may result in creating two instances of the SingletonClass. To prevent this from happening you can add synchronized to the getInstance() method:

public static syncronized SingletonClass getInstance(){
  if(instance == null){
    instance = new SingletonClass(); 
  }
  return instance;
}


Synchronized forces every thread to wait its turn before it can enter the method. No two threads may enter the method at the same time. This is expensive, particularly because the only time synchronized is relevant/needed is the first time through this method (after that instance is not null anymore).

You have three options:
  1. Use syncronized if the performance of getInstance() is not critical to your application.
  2. Use an eagerly created instance rather than an lazily created one. The JVM guarantees that the instance will be created before any thread accesses the static instance variable.
    public class SingletonClass{
      private static SingletonClass instance = new SingletonClass();
    
      private SingletonClass(){
      }
    
      public static SingletonClass getInstance(){
        return instance;
      }
    }
  3. Use double-checked locking to reduce the use of syncronization in getInstance(). We first check to see if instance is created, and if not, we syncronize. This way we only synchronize the first time, when instance is still null.
    public static SingletonClass getInstance(){    
        if(instance==null){
          synchronized (Singleton.class){ 
            if(instance==null){
              instance = new SingletonClass();
            } 
          }
        }
        return instance;
    }
You have to be careful though if you use multiple classloaders. Each classloader defines its own namespace and therefore more than one version of a class can exist, resulting in more than one instance of the singleton. By specifying the classloader yourself you can solve this issue.

Monday, June 23, 2014

Abstract Factory Pattern

Abstract Factory Pattern: Provides an interface for creating families of
related or dependent objects without specifying their concrete
classes.
.
Often the abstract factory is mistaken for a factory method. While they are both good at decoupling applications form specific implementations, it is done in different ways. Both patterns create objects, but the factory method (factory method pattern) does it through inheritance, while the abstract factory uses object composition.

To create an object using the factory method pattern, you need to extend a class and override a factory method - which will create a concrete object. The abstract factory pattern provides an abstract type for creating a family of products (groups together a set of related products). Subclasses of this type define how those products are produced. Often you can use the factory method pattern to program an abstract factory: concrete factories implement a factory method to create their products (purely to create products).


abstract factory pattern uml
(abstract factory uml)
Using our pizza store from my previous post as an example (factory method pattern), this is how it could be implemented using the abstract factory pattern:

public class AustrianPizzaStore extends PizzaStore{
  protected Pizza createPizza(String type){
    Pizza pizza = null;
    // this is our abstract factory
    PizzaIngredientFactory ingredientFactory = new AustrianPizzaIngredientFactory();
    if(type.equals("cheese")){
      // the concrete factory is passed as argument when creating a new pizza
      pizza = new CheesePizza(ingredientFactory); 
      pizza.setName("Austrian Style Cheese Pizza");
    }else if(type.equals("veggie"){
      pizza = new VeggiePizza(ingredientFactory);
      pizza.setName("Austrian Style Veggie Pizza");
    }
    return pizza;
  }
} 

public class CheesePizza extends Pizza{
  PizzaIngredientFactory ingredientFactory;

  public CheesePizza(PizzaIngredientFactory ingredientFactory){
    this.ingredientFactory = ingredientFactory;
  }

  // the abstract pizza classhas membervariables for all
  // ingredients (e.g., Cheese, Sauce, ...)
  void prepare(){
    dough = ingredientFactory.createDough();
    sauce = ingredientFactory.createSauce();
    cheese = ingredientFactory.createCheese();
  }
}

public class AustrianPizzaIngredientFactory implements PizzaIngredientFactory {
  public Dough createDough(){
    return new ThinCrustDough();
  }
  public Sauce createSauce(){
    return new TomatoSauce();
  }
  public Cheese createCheese(){
    return new GudaCheese();
  }
  // this class has to implement every method defined in the 
  // PizzaIngredientFactory interface (Veggies, Pepperoni, Clams ...)
}
As you can see, to use the factory, one subclass is instantiated and passed into some code (AustrianPizzaFactory, CheesePizza) that is written against the abstract type. A disadvantage is that if a set of related products is extended (e.g., adding another ingredient) the whole interface has to change, which means that you have to change the interface of every subclass ... lots of work.

But the PizzaIngredientFactory allows us to handle groups of different ingredient objects. As you can imagine Austria will use different ingredients than lets say Russia or America for their cheese pizzas due to different local availability of those ingredients, or regional preferences of the population. Even though our pizza stores are using the same brand name, Austrian stores might have to use thin crust dough, gouda cheese and frozen fish, while American stores can use thick crust dough, mozzarella cheese and fresh fish.

So keep in mind to use the abstract factory whenever you have families of products that you need to create and you want to make sure that your clients create products that belong together. Use factory methods to decouple client code form concrete classes you need to instantiate, or if you don't know ahead of time which concrete classes you are going to need.

Friday, June 20, 2014

Factory Pattern


Factory Pattern: Attaches additional responsibilities to an object dynamically and 
provide a flexible alternative to subclassing for extending
functionality.
.
Often when you have a set of related classes you are forced to write code like this:
Animal animal;
if(wood){
  animal = new Bear();
}else if(sea){
  animal = new Fish();
}else if(home){
  animal = new Dog();
}
With code like this, you know that later on, when things have to be changed or extended you will have to reopen this code and check what has to be added or deleted. If this code ends up in several parts of your application maintenance and updates become cumbersome and error-prone. This can be solved using Factories - handling the details of object creation. Any time another class needs e.g. an animal, it asks the animal factory to create one.

Simple Factory & Static Factory
Encapsulating this object creation process in its own class we get a simple factory. We now have only one place to where we can implement changes. If you define this simple factory as static you get a static factory - advantage: no need to instantiate an object - disadvantage: can't subclass and change behavior.
public class SimpleAnimalFactory{
   public Animal createAnimal(String type){
    Animal animal;
    if(type.equals("wood")){
      animal = new Bear();
    }else if(type.equals("sea")){
      animal = new Fish();
    }else if(type.equals("home")){
      animal = new Dog();
    }
    return animal;
  }
}
This simple factory isn't an actual design pattern (more like an idiom) - still it is commonly used. Simple factories do not give you control over what should happen after an object was instantiated. The next two real factory patterns give you a little bit more 'quality control'.


Factory Method Pattern: A factory mehtod handles object creation and encapsulates it in 
a subclass. This decouples the client code in the superclass 
from the object creation code in the subclass.

The factory method pattern lets subclasses decide which objects should be created, but specyfies other processes which should stay the same among all subclasses. Imagine a pizza franchise where each pizza shop can decide for a regional pizza style. Still the order system should stay the same for each shop.
public abstract class PizzaStore{
  public Pizza orderPizza(String type){
    Pizza pizza = createPizza(type);
    pizza.prepare();
    pizza.bake();
    pizza.cut();
    pizza.box();
    return pizza;
  }

  abstract Pizza createPizza(String type);
}
Now each pizza shop may implement its own createPizza method, e.g., the Austrian pizza shop creates AustrianStyleCheesePizza, while the American pizza shop creates AmericanSyleCheesePizza.
if(type.equals("cheese")){
  animal = new AustrianStyleCheesePizza();
}
if(type.equals("cheese")){
  animal = new AmericanStyleCheesePizza();
}
The abstract class PizzaStore does a lot of things with a Pizza object, but because Pizza is abstract it has no idea what real concrete classes are involved - it is decoupled. With this simple transformations we have gone from having an object handling the instantiation of concrete classes (simple factory) to a set of subclasses that take on that responsibility.

The factory method pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.

factory method pattern uml
(factory method uml)
Advantages:
  • By placing all creation code in one object or method, code duplication is avoided and you provide one place to perform maintenance. 
  • Clients depend only upon interfaces rather than concrete classes required to instantiate objects (programming to an interface - more flexible, extensible).
The factory method pattern makes use of the dependency inversion principle (Check out all other design principles in this post OO principles):

Design Principle 6: Depend upon abstractions. Do not depend upon concrete classes. It suggests that our high-level components (PizzaStore) should not dpend on our low-level components (ConcretePizza).

In our factory method pattern example both the high-level component PizzaStore and the low-level components concrete pizzas depend on Pizza, the abstraction.


Next post: Abstract Factory Pattern


Tuesday, June 17, 2014

Decorator Pattern

Decorator Pattern: Attaches additional responsibilities to an object dynamically and 
provide a flexible alternative to subclassing for extending
functionality.

Since programming schemes using inheritance often result in class explosion, rigid design or adding functionality to the base class that is not appropriate for other subclasses, another design pattern may be used - the decorator pattern. This pattern follows the open-closed principle (Check out all other design principles in this post: OO principles):

Design Principle 5: Classes should be closed to change, but open to extensions. This allows to incorporate new behavior without changing existing code. This principles seems like a contradiction, but there are techniques for allowing code to be extended without direct modification.
Still be careful when choosing the areas of code that need to be extended. Applying the open-closed principle everywhere is wasteful, unnecessary, and can lead to complex, hard to understand code.

Example: Imagine a pizza shop having different types of dough and various toppings (cheese, salami, ham, ...). The pizza shop wants to be able to combine its different types of dough with all their toppings (dynamically).
The decorator pattern uses 'decorator' objects to decorate/wrap another object. This is possible since these 'decorator' objects have the same supertype as the objects they decorate. The decorator adds its own behavior either before and/or after delegating to the object it decorates to do the rest of the job.  
To implement the decorator pattern for our pizza shop, the different types of dough serve as our concrete components, while available toppings serve as our decorators. Each decorator holds (wraps/has-a) component, an instance variable that holds a reference to a component.
Decorator uml (wikipedia)
We are therefore able to decorate our doughs dynamically at run time with as many toppings as we like. By using a combination of inheritance (subclassing) and composition this pattern gains a lot more flexibility at run time. Decorators are meant to add behavior to an object they wrap.

The decorator pattern is often used in combination with other patterns, like Factory and Builder. This way the creation of concrete components with its decorators is 'well encapsulated' and does not lead to problems like increased chance of coding errors due to adding a lot of small classes, occasionally resulting in a less straightforward design (for other developers to understand)


Thursday, June 5, 2014

Observer Pattern

Observer Pattern: Defines a one to many relationship between a set of objects. When the state of one object (subject) changes, all others (Observers) are notified.

Use this pattern, if you have objects that have to be updated if data in another object changes. For the observer pattern you will have to use at least two interface classes. One for the subject and one for the observer classes.
 interface Observer{
     update();  // called by a subject
 }.
 interface Subject{
     registerObserver(Observer observer);
     deregisterObserver(Observer observer);
     notifyAll();  // iterates over a list of registered observers calling their 
                   // update method
 }
A class which implements the Subject interface has to maintain a list of observers (e.g., List<Observer>). The methods registerObserver and deregisterObserver are used to to add/remove objects implementing the observer interface. Like the Strategy Pattern from my last post, the observer pattern also uses following design principles:
  1. Identify aspects of an application that vary and separate them form what stays the same.
  2. Program to an interface, not an implementation. Exploit polymorphism by programming to a supertype.
  3. Favor composition (has-a relationships) over inheritance. 
Check out OO principles for detailed explanations of each design principle. In addition the following new one is utilized:

Design Principle 4: Strive for loosely coupled designs between objects that interact. Such objects can interact, but have very little knowledge of each other. This allows for flexible OO systems that can handle change because they minimize the interdependency between objects.

Observer uml (wikipedia)

Results:
  • The only thing that is known to the subject is that the observer implements the observer interface. (Does not need to know the actual class of the observer object)
  • The subject can add new observers at any time.
  • You will never need to modify the subject to add new types of observers.
  • You can reuse subjects or observers independently of each other.
  • Changes to either the subject or an observer will not affect the other.
Observers can work either by pushing or pulling data. void update(Subject sub, Object arg)    Never depend on order of evaluation of the Observer notifications.

Wednesday, June 4, 2014

OO Principles

These are all principles for object oriented programming in one post (will be regularly updated along with the design patterns that use them):

  1. Identify aspects of an application that vary and separate them form what stays the same. Later you will be able to alter or extend the parts that vary without affecting other parts, resulting in fewer unintended consequences from code changes and more flexibility in a system - Encapsulate. E.g.: use separate classes to delegate behavior - instanced by the class using those behaviors. This way it is also easy to change behavior on run time (getter, setter).

     class Dog(){  
         // (FightBehavior is an interface - multiple Behavior  
         // patterns may be implemented) same goes for PlayBehavior  
         FightBehavior fBehavior;  
         PlayBehavior pBehavior;  
         void fight();  
         void play();  
     }  
    

  2. Program to an interface, not an implementation. Exploit polymorphism by programming to a supertype. e.g.: do not use:
    Dog d = new Dog();
    d.bark();
    instead use:
    interface Animal();   // having a method makeNoise 
    Dog d = new Animal(); // Dog implements Animal
    d.makeNoise();

  3. Favor composition (has-a relationships) over inheritance.
  4. Strive for loosely coupled designs between objects that interact. Such objects can interact, but have very little knowledge of each other. This allows for flexible OO systems that can handle change because they minimize the interdependency between objects.
  5. Classes should be closed to change, yet open to extensions. Thereby it is easy to incorporate new behavior without modifying existing code (correct, tested, bug free code should stay unaltered - lowering chances of introducing new bugs or unintended side effects) - Open-Closed principle
  6. Depend upon abstractions. Do not depend upon concrete classes. It suggests that high-level components (like an abstract class PizzaStore) should not dpend on low-level components (ConcretePizza) - Dependency Inversion Principle

Strategy Pattern

Strategy Pattern: Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Allows for reuse of code through inheritance and composition
 
Use this pattern if you have to develop an application, that may change over time (it will change) or when features that are not known yet, should be added. The strategy pattern uses a number of design principles. I will try to explain each principle with an example.

Design Principle 1: Identify aspects of an application that vary and separate them form what stays the same. Encapsulate: Later you will be able to alter or extend the parts that vary without affecting other parts. Result: Fewer unintended consequences from code changes and more flexibility in a system. E.g.: use separate classes to delegate behavior - instanced by the class using those behaviors. This way it is also easy to change behavior on run time (getter, setter).

 class Dog(){  
     // (FightBehavior is an interface - multiple Behavior  
     // patterns may be implemented) same goes for PlayBehavior  
     FightBehavior fBehavior;  
     PlayBehavior pBehavior;  
     void fight();  
     void play();  
 }  

Design Principle 2: Program to an interface, not an implementation. Exploit polymorphism by programming to a supertype.
e.g.: not Dog d = new Dog();
      d.bark();
      use Dog d = new Animal();
      d.makeNoise();

Design Principle 3: Favor composition (has-a relationships) over inheritance.
  • has-a:  each dog has a fight behavior to which it delegates fighting (behavior is being composed with the right behavior object
  • is-a: inheriting behavior from other classes
Strategy uml
 Remember: More time is spent on code after development is complete (maintaining and changing software).

Tuesday, June 3, 2014

Design Patterns in Programming


In software development there is one constant:
CHANGE

All applications will grow and change over time, or die. As a developer it is therefore desirable for an application to be easy to understand, maintainable and flexible. You may think that knowing the object oriented basics will automatically result in such applications, but:
  • Knowing OO basics does not make you a good OO designer.
  • Good OO designs are reusable, extensible and maintainable.
  • Patterns show you how to build systems with good OO design qualities.
  • Patterns are proven OO experience.
  • Patterns don't give you code, they give you general solutions to design problems. You apply them to your secific application.
  • Patterns are not invented but discovered.
  • Most patterns and principles adress issues of change in software
  • Most patterns allow some part of a system to vary independently of all other parts.
Design patterns are not just good object-oriented design. Knowing OO basics does not mean you will automatically be good at building flexible, reusable, and maintainable systems. They are a collection of, sometimes non-obvious, ways of constructing OO systems (let you skip the hard work of finding those ways yourself). If you can not find a pattern that matches your problem, think about the Design principles that design patterns use.

Advantage of design patterns:
  1. shared vocabulary with other developers (less time explaining).
  2. do not just communicate a pattern name, but also a whole set of qualities, characteristics and constraints that the pattern represents. e.g.: Strategy Pattern encapsulated behavior into its own set of classes that can be easily expanded and changed at run time
  3. Allows to keep discussions at the design level (not too much details of implementation) better structure of applications (easy to understand, maintainable, flexible)
In the next few posts I want to cover the following topics:

OO Basics:
    Abstraction
    Encapsulation
    Polymorphism
    Inheritance
OO Principles
OO Patterns
    Strategy
    Observer
    Decorator
    Factory Method
    Abstract Factory
    Singleton
    Command 

(I will be editing this page, adding other patterns)