Showing posts with label OO design. Show all posts
Showing posts with label OO design. Show all posts

Wednesday, December 26, 2012

Iterator Pattern and Java

Hello all, in this post we'll be checking on the Iterator Pattern. A design pattern that I know many of you have already used, but maybe you didn't realize it was pattern or didn't know its great value. According to the book Head First Design

The Iterator  Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlaying representation.

Whaaaaat? Well, it says that no matter what data structure (arrays, lists, hashtables,etc.) you are using, you can always traverse it in the same way if you implement this pattern. It gives you a uniform way of accessing the elements of your data structures (aggregates), but you don't have to know what kind of data structure you are traversing... nice!
Also, it sets the responsibility of iteration on the Iterator object not on your data structure, which simplifies the coding in your data structure.

Let's check the classic class diagram for the Iterator pattern:


The actual class diagram for the Iterator Pattern has a few changes, specially in the Iterator class (interface), where we now have different methods as we'll see in a minute, but first, lets review each of the previous classes (or interfaces):

  • Aggregate: This is the base class (or interface) of our data structures, you can think of it as the java.util.Collection interface, which defines a lot of methods for the collection classes.
  • ConcreteAggregate: This is the concrete data structure that we'll be iterating, for example, java.util.ArrayList, java.util.Vector, etc.
  • Iterator: Base class (or interface) for iterators. You can find one in Java at java.util.Iterator. You can notice that the Java version has different methods that we'll be discussing later in this post. Here you define de methods you need in order to traverse the data structures.
  • ConcreteIterator: As you want to traverse different data structures you need different iterators. So a concreteIterator is an Iterator for the data structure you want to traverse.  

Now, let's take a look at the Java implementation of the Iterator Pattern. The following diagram was generated using Architexa's Free Tool for Understanding Code and it shows the relations between some classes of the Java Collections Framework where we can see a structure similar to the classic class diagram:


The above diagram shows only one implementation of the pattern in Java, there are a lot more, but they always use the java.util.Iterator interface; this is the interface you should use in your implementations of the Iterator Pattern when coding in Java. Let's compare both diagrams:


Classic Diagram
ConcreteIterator

Notice that the methods of the Iterator object in the Java example are different from the methods in the classic class diagram:
  • There is no +First() method. If you need to go to the first element, you have to instance a new iterator.
  • The +IsDone() method has been renamed to +hasNext().
  • The +Next() and +CurrentItem() has been merged into +next().
  • The +remove() method has been added.

So, if you ever have to work with different data structures and need a uniform way to traverse them and/or access their items, think about the Iterator Pattern:

//... in a class
  /**
   * Traverse a list, hashtable, vector, etc. what ever that implements
   * the Iterator Pattern
   */
  public void traverse(Iterator iter)
  {
     while(iter.hasNext())
     {
 System.out.println(iter.next());
     }
  }

Of course, you will always have to create the ConcreteIterator class for your data structure, but if you are using classes from the Java Collections Framework, it's already done.

One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.


See ya!


References:

Freeman Eric and Freeman Elisabeth and Sierra Kathy and Bates Bert (2004). Head First Design Patterns. United States of America: O'Reilly Media, Inc.

Friday, September 28, 2012

Decorator Pattern and Java

So, you want to extend behavior but want to avoid subclassing? Then the Decorator Pattern is for you. Decorators change behavior by adding new functionality to the components they decorate without modifying those components. This pattern is based on the Open-Closed OO principle:
Classes should be open for extension but closed for modification.
Designs must be flexible and opened for behavior extension but without modifications to existing code. That way, you avoid introducing new bugs to previous tested and reliable code. Let's check the definition of the Decorator pattern, according to the Head First Design Patterns book:
Attach additional responsabilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
And the basic class diagram for this pattern is as follows:


Let's review each class from the above diagram:
  • Component: Most of the time it's an abstract class with abstract methods. Represents the base class of the hierarchy.
  • ConcreteComponent: Concrete class that implements the methods from the abstract Component class, during the implementation of the methods you should define default behavior.  It's the real class you want to decorate. You may have as many ConcreteComponent classes as you need.
  • Decorator: Base class for decorators, it's abstract so decorators are required to implement the abstract methods. It's composed with a reference to the Component class, so decorators may access the object they are decorating. Notice that both ConcreteComponent and Decorator subclass the Component class, that way decorators may be transparent to you, I mean, you are going to have a reference to a Component object and it may or may not be decorated, you just don't know (or care).
  • ConcreteDecorator: A concrete decorator that implements the methods from the abstract Decorator class. It's the class that executes the real job of decorating. It can access the object it is decorating.  You can have as many ConcreteDecorator classes as you need.

OK, that's kind of confusing, I know. Let's see a real example of the Decorator pattern in action so you can understand the concept. If you have used the java.io API you have already used this pattern, just think about opening streams from a file:

//in a class...
public void printLines(String file) throws Exception
{
  DataInputStream rin = null;
  rin = new DataInputStream(new FileInputStream(file));

  //more code...
}

The last piece of code is making use of the Decorator Pattern, it is decorating a java.io.FileInputStream so we can read primitive Java data types instead of bytes. Let's review the most important points:

As you can see, every decorator adds behavior to a component (in this case to a FileInputStream so it can read primitive Java data types). The following diagram was generated using Architexa's Free Tool for Understanding Code and it shows the relations between the input-stream classes we were talking about (and some others) and we can see the exact same structure of the Decorator Pattern:


Something to be aware of is that every decorator is another class in your design, so if you have a lot of decorators, your design will have a lot of small classes and it may become complex.

One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.


See ya!

References:

Freeman Eric and Freeman Elisabeth and Sierra Kathy and Bates Bert (2004). Head First Design Patterns. United States of America: O'Reilly Media, Inc.

Wednesday, September 26, 2012

Observer Pattern and Java

"Don't call us, we'll call you"... that's the Hollywood OO (Object Oriented) Principle and it's exactly what the Observer pattern is about. In this post we'll review this pattern and how it is used in Java, you may already have used it without knowing...

According to Head First Design Patterns book, this is the definition of the Observer pattern:
Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Sounds familiar? Have you ever worked with Swing? Looks like the event handling mechanism is using the Observer Pattern. Let's think about it, suppose you have a JButton and you want other objects to be notified when the button is pressed... have you done that? sure! The other objects are not asking all the time to the button whether it is pressed or not, they only wait for a notification from the button. Swing does it using the java.awt.event.ActionListener, but in essence it is using the Observer Pattern, even if we are not using  interfaces like java.util.Observer or classes like java.util.Observable...

Now, talking about observers and observables, this two exist since JDK 1.0 and you can use them to implement the Observer Pattern in your applications. Let's see the how to do it:

The objects you want to be waiting for notifications are called Observers, they implement the interface java.util.Observer. This interface defines only one method: +update(Observable,Object):void which is called whenever the observed object is changed. The first parameter, an Observable, is the object that changed. The second parameter may be used as follows:

  • If using PUSH notifications, the Object parameter contains the information needed by the observers about the change. 
  • If using PULL notifications,  the Object parameter  is null and you should use the Observable parameter in order to extract the information needed.

When to PUSH or PULL? It's up to your implementation. The Object you want to be observed is called the Observable and it has to subclass the java.util.Observable class. Yes, subclass. That's the dark side of the built-in implementation of the Observer Pattern in Java, sometimes you simply can't subclass, we'll talk about this in a minute... Once subclassed, you will inherit the following methods, among others:

  • +addObserver(Observer):void which adds the Observer passed in as parameter to the set of observers.
  • +deleteObserver(Observer):void which deletes the Observer passed in as parameter from the set of observers.
  • setChanged():void which marks the Observable as having been changed. This method is protected, so  you can only call it if you subclass the  java.util.Observable class. Call it before notifying your observers.
  • +notifyObservers():void which notifies the registered observers using PULL. It means that when the +update(Observable,Object):void is invoked on the Observer, the Object parameter will be null.
  • +notifyObservers(Object):void  which notifies the registered observers using PUSH. It means that when the +update(Observable,Object):void is invoked on the Observer, the Object parameter will be the same parameter passed in the +notifyObservers(Object):void .

So, what happens if the class you want to be the Observable is already subclassing another class? Well, then you have to write your own Observer Pattern implementation because you can't use the one built-in Java. The following diagram shows you the basic concepts of the Observer Pattern, so you can built your own implementation:


One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.


See ya!

References:

Freeman Eric and Freeman Elisabeth and Sierra Kathy and Bates Bert (2004). Head First Design Patterns. United States of America: O'Reilly Media, Inc.

Sunday, August 26, 2012

Architexa's Free Tool for Understanding Code

Hello everyone, in this post I'm going to present you a new awesome tool for understanding code through the use of Layered Diagrams, Class Diagrams and Sequence Diagrams generated right from your eclipse IDE! No need of extra software, just an eclipse plug-in. Generate your diagram as general or specific as you want, collaborate and share them through e-mail or through architexa's collaboration server and it's free for individual use!

You: Why do I need a tool to understand my own code? Why this tool if there is project/code documentation? Why do I need this tool if I have the source code and I can read it?
Me: Very often the code you work with wasn't written by you and don't tell me you remember everything  you coded 6+ months ago... Nowadays productivity is key to any company, to any developer so you can't afford spending most of your time reading and trying to understand code and because real world isn't perfect, documentation may not be synced...
You may, also, find this tool useful for rearchitecting your applications as it lets you see the big picture, collaborate and share project documentation.


Layered Diagram
Taken from
http://www.architexa.com/
See relationships between packages in a project using the Layered Diagram. This is actually a nice feature as it lets you check the relantionships not only at package level, but also at class level. You may find this useful when trying to reduce dependency between layers...low coupling? You got it!  You can then share the diagram or upload it to architexa's collaboration server.
You just need eclipse IDE and the architexa's plug-in in order to generate this diagram, right from your IDE and in a matter of seconds.





Class Diagram
Taken from
http://www.architexa.com/
Easily visualize relationships between classes and their methods using the Class Diagram. Great feature when you want to see if that pattern you want to implement fits your design or when you need to present part or the entire application to your co-workers or when you need to check on the coupling between your classes. You may generate the diagram to contain a part or the entire set of classes.  You can then share the diagram or upload it to architexa's collaboration server.
Again, you just need eclipse IDE and the architexa's plug-in in order to generate this diagram, right from your IDE and in a matter of seconds.




Sequence Diagram
Taken from
http://www.architexa.com/
Gain an understanding of code behavior and logic through the intuitive use of the Sequence Diagram. So you need to explain to your team what a method is doing? This feature got your back! Right click on a method to generate its sequence diagram. You can generate a general diagram or a fine-grained one, as you wish, include as many other classes and methods as you want. You can then share the diagram or upload it to architexa's collaboration server.
Again, you just need eclipse IDE and the architexa's plug-in in order to generate this diagram, right from your IDE and in a matter of seconds.




In order to start using Architexa's Free Tool for Understaing Code you should follow three simple steps:
  1. Register: Really easy, just your name, password, email and one or two more questions. Your username and password will be requested to activate the eclipse plug-in.
  2. Download: Start your eclipse IDE, review the instructions to download depending on your eclipse version and let the IDE install the plug-in for you.
  3. Take a Tour: Videos and documentation to get you an idea of which features will benifit you the most.
Get your plug-in from architexa's web site: http://www.architexa.com/

I already installed the plug-in on my Eclipse Helios IDE and I can tell it was a smooth process, just followed the documentation online and installed in less than 10 minutes. I then created a "Hello Architexa" application and tried some of the diagrams they offer. What I liked:
  • Easy right click on package, class or method  to access menu in order to generate diagrams.
  • General to fine-grained diagrams as you wish. Also, you can reorganize the components of the diagram.
  • Ctrl+Z behavior on diagrams.
  • Share diagrams through e-mail (as attached images) in simple steps. And the email was not detected as SPAM by gmail.
  • New menu on the Eclipse menu bar for diagrams and collaboration options and to access online documentation about the tool directly from the IDE, no need to open the Internet browser.
  • Free for individual use.

Hope you find this tool as useful as I do, but if you don't, please share your comments...

See ya!

Thursday, August 23, 2012

Head First Design Patterns Book Review

Book cover from
http://www.headfirstlabs.com
I guess every software engineer should know about design patterns, they give us a way to solve design problems based on the experience of many other software engineers who have had the same or similar challenges in OO design. To be honest, I remember studying them during my B.S., applied some of them in my projects, but after years of experience in software development, is now that I realize how useful they may be. In this post I'm going to review the book "Head First Design Patterns", written by Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra and published by O'Reilly.
As others "Head First" titles, this book is well written, easy and funny to read, it has a lot of graphics, jokes, examples in the book and on the web site to be downloaded... I just loved it! Click here to know why Head First books are great.

The book covers the following design patterns:
  • Observer: Subscribe to receive updates when object's state changes.
  • Decorator: Wraps an object to provide new behavior.
  • Factory: When you want to encapsulate instantiation.
  • Singleton: Ensures one and only one of a kind.
  • Command: Encapsulates a request as an object.
  • Adapter: Wraps an object and provides a different interface to it.
  • Facade: When you need to simplify the interface of a set of classes.
  • Template Method: Subclasses decide how to implement steps in an algorithm.
  • Iterator: Allows to traverse a collection without exposing its implementation.
  • Composite: When you need to treat collections of objects and individual objects uniformly.
  • State: Encapsulates state-based behaviors and uses delegation to switch between behaviors.
  • Proxy: When you need to control access to an object.
  • Some other patterns: Bridge, Prototype, Interpreter, Chain of responsibility, mediator, etc.

Each pattern is explained in detail using an application sample in what they have called "ObjectVille". They also give you examples of its use in real life and its class diagram. Each chapter has a summary at the end (they've called it "Tools for your Design Toolbox") with the most important concepts and definitions.

Many of the above patterns were discovered by the Gang of Four (GoF), who were the first ones in writing about this topic back in 1995. Since then, new patterns have been discovered (yes, they are discovered not created), this book guides you to other reading materials where you can find more design patterns, shows you how looks the formal documentation of a pattern and describes the steps you should consider if you discover new ones.

But it is not all about design patterns, the book also explains the Object Oriented Design Principles (OODP) that every software engineer must know in order to design extensible and maintainable software:
  • Encapsulate what varies
  • Favor composition over inheritance
  • Program to interfaces, not to implementations
  • Strive for loosely coupled designs between objects that interact
  • Classes should be open for extension but closed for modification
  • Depend on abstractions. Do not depend on concrete classes
  • Only talk to your friends
  • Don't call us, we'll call you
  • A class should have only one reason to change

Something really important I learned with this book is: Always use the simplest solution that meets your needs, even if it doesn't include a pattern. So don't try to fill your design with patterns all around, first try using the Object Oriented Design Principles (OODP) then, if necessary, make use of patterns.

One more thing, the book is published in a lot of formats: printed book, kindle, PDF, so you have many options to read it. I have the kindle edition and it looks pretty much the same as in PDF. The kindle edition is available only on Kindle Fire, iPad, PC and Mac (not the portable kindle device).

In future posts I'll write about these patterns and how they are applied in the Java API.


See ya!!