KakimotOnline

July 22, 2009

Singleton (Anti-) Pattern

Filed under: programming, refactoring, software design, testing — Tags: , , — nandokakimoto @ 3:51 am

I’ve implemented my first design patterns at college, while creating a web system during the software engineer course. My classmates and I needed a facade class with a single instance of it throughout the system. So, because we’re really smart, we’ve applied the Facade and Singleton pattern. Actually, we’ve implemented the patterns without knowledge of the design patterns catalog. For us, it was just a way to get what we need.

This week, while doing my daily work, I realized how dangerous the Singleton pattern is. Well, I would have noticed it before, if I have used Test-First Programming. Even knowing the benefits of TDD, I decided to write some code in advance, since I don’t have much experience on the platform used and on its supported tests framework.

My task was to create a GPS abstraction and use it in a mobile Navigator module. My first thought was making my GPS abstraction a Singleton class. It looked very obvious for me: a mobile device has only one GPS and different GPS intances will provide the same data set. So, what I need is just a single GPS instance troughout the system.

After some minutes writing code, I’ve created abstractions similar to the Java sample below.

GPSProvider.java

import java.util.List;

public class GPSProvider implements LBSPositionObserver {

 private static GPSProvider INSTANCE = new GPSProvider();
 private Position lastCoordinate;
 private List<GPSListener> listeners;

 private GPSProvider() {
 this.listeners = new ArrayList<GPSListener>();
 }

 //retrive the class instance
 public static GPSProvider GetInstance() {
 return INSTANCE;
 }

 // perform GPS initialization
 public void initGPSService() {
 (...)
 }

 // add a new listener to the gps class
 public void attach(GPSListener listener) {
 this.listeners.add(listener);
 }

 // remove a listener from the class list
 public void dettach(GPSListener listener) {
 this.listeners.remove(listener);
 }

 @Override
 // set lastCoordinate and notify all listeners about the update
 public void positionUpdated(Position position) {
 this.lastCoordinate = position;
 for ( GPSListener listener : this.listeners ) {
 listener.positionUpdated(position);
 }
 }

 @Override
 // notify all listener about the update
 public void setStatus(int status) {
 for ( GPSListener listener : this.listeners ) {
 listener.statusUpdated(status);
 }
 }

 // return the last known coordinate
 public Position getLastCoordinate() {
 return this.lastCoordinate;
 }

}

GPSListener.java

public interface GPSListener {

 void positionUpdated(Position position);

 void statusUpdated(int status);

}

LBSPositionObserver.java – native GPS interface

public interface LBSPositionObserver {

 void positionUpdated(Position position);

 void setStatus(int status);

}

Navigator.java

public class Navigator implements GPSListener {

 private NavigatorObserver observer;

 public Navigator(NavigatorObserver observer) {
 this.observer = observer;
 }

 // start navigation by listening to gps updates
 public void navigate(Route route) {
 GPSProvider gps = GPSProvider.GetInstance();
 gps.attach(this);
 }

 // pause navigation by not receiving gps updates
 public void pause() {
 GPSProvider gps = GPSProvider.GetInstance();
 gps.dettach(this);
 }

 @Override
 // everytime the position is updated, the navigator gives directions if needed
 public void positionUpdated(Position position) {
 // navigate user through route.
 int step = this.verifyStepUpdated();
 if ( step != -1 ) {
 this.observer.StepUpdated(step);
 }

 if ( this.achievedDestination() ) {
 this.observer.DestinationAchived(position);
 }
 }

 // calculate if achieved destination
 private boolean achievedDestination() {
 (...)
 }

 // verify is have to change direction
 private int verifyStepUpdated() {
 (...)
 }

 @Override
 public void statusUpdated(int status) {
 // send status to end user.
 }
}

Now, since I’ve finished my Navigator module, I want to test it to make sure it’s working correctly. In order to test the Navigator module, I need a GPS data log and a route to walk through it, simulating a person walking and being navigated by the system. The route is not a problem because I pass it as a parameter of “navigate” method. However, there is no way to simulate a GPS log with the code above, unless I use some Dependency Injection Framework, which is not the case.

That’s the Singleton disadvantage. I can’t inject a GPS mock in my Navigator module because I always use the native gps implementation represented in my Singleton GPSProvider class. Everytime I need some GPS information, I use the GPSProvider.GetInstance() static method to retrieve the only GPS instance I have access to.

To solve this problem, I found a simple solution: not using Singleton. I removed  the Singleton pattern from GPSProvider and change every class that uses GPSProvider.GetInstance() to receive the current GPS intance. In the Navigator module, I passed the GPS instance through its class’ constructor.

GPSAbstractProvider.java

import java.util.ArrayList;
import java.util.List;

public abstract class GPSAbstractProvider {

 private List<GPSListener> listeners;

 public GPSAbstractProvider() {
 this.listeners = new ArrayList<GPSListener>();
 }

 public abstract void initGPSService();

 public void attach(GPSListener listener) {
 this.listeners.add(listener);
 }

 public void dettach(GPSListener listener) {
 this.listeners.remove(listener);
 }

 public void notifyPositionUpdated(Position position) {
 for ( GPSListener listener : this.listeners ) {
 listener.positionUpdated(position);
 }
 }

 public void notifyStatusUpdated(int status) {
 for ( GPSListener listener : this.listeners ) {
 listener.statusUpdated(status);
 }
 }

}

GPSProvider.java

public class GPSProvider extends GPSAbstractProvider implements LBSPositionObserver {
 private Position lastCoordinate;

 private GPSProvider() {
 super();
 }

 @Override
 // perform GPS initialization
 public void initGPSService() {
 (...)
 }

 @Override
 public void positionUpdated(Position position) {
 this.lastCoordinate = position;
 this.notifyPositionUpdated(position);
 }

 @Override
 public void setStatus(int status) {
 this.notifyStatusUpdated(status);
 }

 public Position getLastCoordinate() {
 return this.lastCoordinate;
 }

}

Navigator.java

public class Navigator implements GPSListener {

 private NavigatorObserver observer;
 private GPSAbstractProvider gps;

 public Navigator(NavigatorObserver observer, GPSAbstractProvider gps) {
 this.observer = observer;
 this.gps = gps;
 }

 public void navigate(Route route) {
 this.gps.attach(this);
 }

 public void pause() {
 this.gps.dettach(this);
 }

 @Override
 public void positionUpdated(Position position) {
 // navigate user through route.
 int step = this.verifyStepUpdated();
 if ( step != -1 ) {
 this.observer.StepUpdated(step);
 }

 if ( this.achievedDestination() ) {
 this.observer.DestinationAchived(position);
 }
 }

 private boolean achievedDestination() {
 (...)
 }

 private int verifyStepUpdated() {
 (...)
 }

 @Override
 public void statusUpdated(int status) {
 // send status to end user.
 }
}

Much better! Notice that I still have just one single instance of my GPS class. All I have to do is creating my GPS at the beginning of the program and pass it through classes that use it.
Doing this, testing my code became very simple. I inject my GPS mock to simulate GPS data in my tests,  just as below.

NavigatorTest.java

import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

public class NavigatorTest extends TestCase implements NavigatorObserver {

 private Navigator navigator;
 private GPSAbstractProvider gps;

 public void testNavigate() throws Exception {
 List<Position> gpsPositions = new ArrayList<Position>();
 this.addPositions(gpsPositions);
 this.gps = new GPSTestProvider(gpsPositions);

 this.navigator = new Navigator(this, this.gps);
 this.navigator.navigate(this.createSimpleRoute());

 gps.initGPSService();

 assert(...);
 assert(...);
 }

 private Route createSimpleRoute() {
 (...)
 }

 private void addPositions(List<Position> gpsPositions) {
 (...)
 }

 @Override
 public void DestinationAchived(Position destination) {
 (...)
 }

 @Override
 public void StepUpdated(int step) {
 (...)
 }

}

As you can see, I can use any GPS provider in my tests, making them much more easy and flexible.
In addition to the disavantage presented, Alex Miller discuss some points why he hates Singleton pattern.
From here, trying avoiding this pattern in situations like that. Think twice before applying Singleton in your project.

See you


Fernando

May 15, 2009

Principles of Package Design

Filed under: programming, software design — Tags: , , — nandokakimoto @ 2:39 pm

Agile Software Development is really an incredible book. After reading it, a lot had been talked about the Object-Oriented Principles on this blog (here and here). Today, I’ll be talking about another section of the book, which introduces principles used to maintain high package cohesion and a desirable package dependency, known as Principles of Package Design.

Packages are used to organize larger projects. More than this, they are containers of classes used to manage the development and distribution on software. Package’s goal is separate classes in an application according to some criteria. However, classes often have dependencies on other classes, creating package dependencies relationships. To help manage this situation, some principles were created to govern the creation, interrelationship and use of packages.

The three principles in sequence are related to package cohesion, useful in deciding how to partition classes into packages.

The Reuse-Release Equivalence Principle (REP): the granule of reuse if the granule of release

REP states that anything that we reuse must also be released and tracked. Reusability is not only the creation. It comes only after there is a track system in place that offers the guarantees of support that reusers will need. Since reusability is based on packages, if some software is going to be reused, then it must be partitioned in a convenient structure for this purpose, so all classes in a package become reusable by the same audience.

The Common-Reuse Principle (CRP): the classes in a package are reused together

CRP helps in deciding which classes should be placed into a package. This can be determined by reuse characteristics. Classes that tend to be reused together should be placed in the same package. Remember: if you reuse one class in a package, you reuse them all. Although the CRP tells us what classes put together, it also says what classes do not put in the same package. If a class depends on another class in a different package, it depends on the entire package. Every time the used package is released, the using package must be revalidated and rereleased, even the change was made in a different class that the using package depends on. Therefore, CRP also says that classes which are not tightly related to each other should not be in the same package, so every time I depend on a package, I depend on every class in that package.

The Common-Closed Principle (CCP): a change that affects a package affects all the classes in that package and no other packages.

This is the same as SRP, but applied for the packages context. Such as classes should have just one reason to change, CCP states that packages should not have multiple reasons to change. It’s preferable that changes occur in just one package rather than distributed along the whole system.

Now, we are going to take a look at principles related to package relationship and dependency.

The Acyclic-Dependencies Principle (ADP): allow no cycles in the package-dependency graph.

Package cycles create immediate problems, and the most obvious one is when you have to release a package that was modified. In order to release the package, it must be compatible with all other packages that it depends on. A cycle in your package-dependency graph makes release harder since you increase the number of packages that you have to be compatible with. For example, take the Figure 1 and Figure 2. To release package C in the first situation we must be compatible with package E and F. However, in the second case we also must be compatible with package A, B and D. Even worst, if you want to test package C, we must link and build all other packages in the system, instead of just two of them.

no-cycle

To break the cycle, two solutions are suggested:

  1. apply Dependecy-Inversion Principle.
  2. create a new package between C and A, and move the classes that they both depend on into that new package.

The Stable-Dependencies Principle (SDP): depend in the direction of stability.

Stability has nothing directly to do with frequency of change, but to the amount of work required to make the change. In software, package stability is measured in number of classes inside this package that depend on classes outside this package and number of classes outside this package that depend on classes within this package. Thus, a package is called instable if it is easy to change, in other words, just a few or none packages have dependency relationship with it. A package is called stable if it is hard to change, or a lot of classes outside this package depend on it. The book also brings a method to calculate stability metrics, but I’ll not be such detailed. Just have in mind that a good design contains some instable package and some stable package. Instable packages are on top and depend on stable packages at the bottom, just shown below.

figura1

The Stable-Abstractions Principle (SAP): a package should be as abstract as it is stable.

This principle states that a stable package should also be abstract so that its stability does not prevent it from being extended, and an instable package should be concrete since its instability allows the concrete code within it to be easily changed. Thus, stable packages consist of abstract classes and instable packages of implementations classes.

Conclusion

After some posts of OOP, we already know how to create a good class design. However, in big systems, classes are separate into packages which corresponds a very important part of the system’s release and deploy. So, a new concern is how to divide classes between packages and maintain the system’s consistency. In this post we introduced six principles explained in Robert Martin book which help us in solve a lot of package design problems. You can find a lot of more information in the book, which I strictly recommend.

See you,


Fernando

May 4, 2009

Generic DAO with NHibernate and Autofac

Filed under: C#, hibernate, programming, software design — Tags: , , , — nandokakimoto @ 2:20 am

Data access is one of the most important design decisions in software development. Depending on how you design your data access classes, every single modification causes cascading changes throughout your project. Imagine you have a lot of persistent data objects to manage and, for example, you have to change your database. This transition must be done without modifying the source code of your persistent classes. Other problem happens when you add more persistent data collection classes to the system. Of course, you won’t be happy if every time a new basic class is added, a new CRUD class is needed. The last point is programming in respect with the OOP, in other words, programming for the abstractions and not for implementations, with low coupling and high cohesion.

To solve those problems, the project that I’d worked for the last 8 months (Onibus Recife) used a combination of 3 technologies, and this post is about them.

NHibernate

NHibernate is an Object-relational mapping (ORM) solution for the Microsoft .NET platform: it provides a framework for mapping an object-oriented domain model to a traditional relational database. NHibernate’s primary feature is mapping from .NET classes to database tables. NHibernate generates the SQL commands and relieves the developer from manual data set handling and object conversion, keeping the application portable to most SQL databases, with database portability delivered at very little performance overhead.

NHibernate was used exactly for this purpose: create SQL commands and provide database portability.

Generics

Generics is a programming feature added in the .NET Framework 2.0 which allow you to define type-safe data structures, without committing to actual data types. This results in a significant performance boost and higher quality code, because you get to reuse data processing algorithms without duplicating type-specific code.

Using Generics, our team was able to use one, and just one, repository class for all of the simple persistent entities. Every time a new entity was add to the project, nothing more than its corresponding .hbm file was needed.

Autofac

Autofac is a fresh approach to IoC in .NET that fits well with C# 3.0.

The Autofac framework enabled us to inject all classes’ dependencies in just one place. So, when dependences changed, just a few lines of code were modified in a single source code file.

To illustrate those techniques, I’ll use them in a sample and small project.
Imagine a simple Contacts project used to keep your friends’ address, phone number and birthday. The abstraction of a contact is shown below.

Contact.cs

contact

In order to persist the Contact class in my SQL Server database, I used NHibernate framework. Due to that, I need an .hbm file for the Contact class and a NHibernate session manager, responsible to manage database access. Because it’s a small and very simple project, I created a simple session manager, shown below.

NHibernateSessionManager.cs

sessionmanager

Now, it’s time for the repository class. Actually, I implemented a repository interface and its implementation. Remember: program for abstractions, not for implementations. Note that they are generic. I did this to provide a single persistent implementation for more than one entity and simplify my life as a programmer. The code of them is listed below.

IRepository.cs

irepository1

NHibernateRepository.cs

nhibernaterepository1

Now, let’s test our code reading data from the database. For that, I used the following piece of code.

TestReadContactById

getcontact

The test passed, so everything is working.

Now imagine that we need another entity class, for example, a User, to restrict the program access with a username and password. All that I have to do is creating the User.cs abstraction and the User.hbm.xml file. I don’t need a new CRUD class for it. I just use the same generic repository that I used for Contact class, saving me a lot of time. Below is the code that I used to retrieve a user from the database.

TestReadUserById

getuser

Note that we must instantiate a new NHibernateRepository with a NHibernateSessionManager as parameter every time we need a new IRepository instance. Probably, in a big project, this line of code will be scattered in a huge number of files and, if that instantiation change for any reason, a lot of files will be modified. That’s what we don’t want. We like when changes are made in just one place and that is the work of Autofac framework.

Take a look of how the same tests are made using Autofac.

AutofacRepositoryTest.cs

autofactest

The framework will inject all classes’ dependencies in the beginning of the program execution. Later, to instantiate an object, we ask the framework to resolve its type. If its instantiation changed, just the line of code where Autofac register is changed.

Conclusion

In this post, I’ve introduced a combination of NHibernate, Generics and Autofac. With these technologies in hand, I was able to create an extensible persistent layer in a low coupling and high cohesion way as shown in the sample project created.

For more information about this technologies see Hibernate and Autofac documentation.

See you.


Fernando

April 6, 2009

C# Extension Methods

Filed under: C#, programming, software design — Tags: , — nandokakimoto @ 1:29 am

I’ve been talking about Object-Oriented Principles for a while, and this post will not be different. Here and here, I’ve introduced OOP and described an elegant solution to comply with Open-Closed Principle using Visitor Pattern, respectively. Today I’ll be talking about a C# 3.0 feature called extension methods. Maybe you’re now asking what extension methods and OOP have in common. That is what this post is about.

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

Therefore, extension methods are an optional technique to extend classes functionalities without modifying it. This makes me remember the Open-Closed Principle which states that software entities should be open for extension, but closed for modification. By using extension methods, your software tends to be less difficult to change, to not impact in dependent modules and even more important, changes are achieved by adding new code, not by changing old code that already exists.

Extension methods are defined as static methods in static classes, but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. The following example shows extension methods for C# string class.

StringExtension.cs

em1

Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive. They are used as if they were instance methods and are visualized in VS intellisense, as show below:

em2

Here is the test class for StringExtension.cs class showing how to invoke extension methods in C#.

TestExtensionMethods.cs

em3

As you could see, this feature enables you to extend the string class, which is a sealed class, same as final class in Java, and implossible to inherit it. This helps you to extend and maintain code in a really elegant way. So, remeber using extension methods when find similar problems in you code.

See you,


Fernando

March 28, 2009

Visitor Pattern and the Open-Closed Principle

Filed under: programming, software design — Tags: , , — nandokakimoto @ 3:55 pm

A few weeks ago, I described here the Open-Closed Principle, which says that software entities should be open for extension, but closed for modification. Now, imagine you are facing with the following design problem:

You need to add a new functionality to a hierarchy of classes, but the act of adding it will be painful or damaging to your design.

I’ll use here the example of Robert C. Martin’s book: suppose you have a hierarchy of Modem objects. The base class has the generic methods common to all modems, and the derivatives represent the drivers for many different modem manufactures and types. Suppose also that you have a requirement to add a new method, named configureForUnix, to the hierarchy. This method will configure the modem to work with the UNIX operating system, corresponding to a different implementation in each modem derivative.

The real problem is not adding the new configureForUnix method, but what about the others operating systems? Must we really add a new method to the Modem hierarchy for every new operating system? Adding methods to the hierarchy of classes obviously violates the OCP because we’ll never be able to close the Modem interface.

The VISITOR pattern helps solving this kind of problems. As it definition says: VISITOR lets you define a new operation without changing the classes of the elements on which it operates. To do that, VISITOR use a technique called dual dispatch, which evolves two polymorphic dispatches.

The figure below shows the UML diagram create by VS2008.

uml

Now, let’s create the code necessary to implement the VISITOR pattern in the Modem problem.

Modem.cs

modem

ModemVisitor.cs

modemvisitor1

HayesModem.cs

hayes

ZoomModem.cs

zoom

ErnieModem.cs

earnie

UnixModemConfigurator.cs

unixmodem1

And here is the test code.

TestModemVisitor.cs

testemodem1

Having built this structure, new operation system configuration can be added just by creating new derivatives of ModemVisitor without changing the Modem hierarchy. Another pattern that accomplishes this is the DECORATOR pattern, but this is a talk for other post.

See you,


Fernando

March 8, 2009

The Principles of Object-Oriented Design

Filed under: programming, software design — Tags: , , — nandokakimoto @ 3:33 pm

At this moment, a lot of source code are been writing by thousands and thousands of programmers all around the world. Most of them uses an object-oriented language, but probably just a few have knowledge of the ODD, which I consider crucial for a reusable and extensible project.

What are The Principles of Object-Oriented Design

In March of 1995 UncleBob wrote an article that was the first glimmer of a set of principles for OOD. These principles expose the dependency management aspects of OOD. When dependencies are well managed, the code remains flexible, robust, and reusable. So dependency management, and therefore these principles, are at the foudation of the -ilities that software developers desire.

The first principles are about class design, which are:

  • The Single Responsability Principle (SRP): a class should have one, and only one, reason to change.
  • The Open-Closed Principle (OCP): software entities should be open for extension, but closed for modification.
  • The Liskov Substitution Principle (LSP): subtypes must be substitutable for their base types.
  • The Dependency-Inversion Principle (DIP): depend on abstractions, not on concretions.
  • The Interface-Segregation Principle (ISP): make fine grained interfaces that are client specific.

The Single Responsability Principle

In the context of the SRP, responsability is defined as a reason to change. Therefore, when the requirements change, that change will reflect in all classes that assume that responsability. If a class assumes more than one responsability,  then there will be more than one reason for it to change. In addition, this responsabilities becomes coupled and software is all about low coupling and high cohesion.

A good design is to separate two responsabilities in two completely different classes.

The Open-Closed Principle

This principle is about Rigidity, which is the tendency for a software to be difficult to change, even in simple ways. A design is rigid if a single change causes a cascade of subsequent changes in dependent modules. The more modules that must be changed, the more rigid the design.

The OCP advises us to refactor the system so that further changes will not cause more modifications. If OCP is well applied, then changes are achieved by adding new code, not by changing old code that already exists.

Modules that conform to the Open-Closed Principle have two primary attributes:

  • Open for extension: this means that the behavior of the module can be extended. As the requirements of the application change, we are able to extend the module with new behaviors that satisfy those changes.
  • Closed for modifications: extending the behavior of a module does not result in changes to the source or binary code of the module. The binary exacutable version of the module remais untouched.

How to be conform with this principle? Abstraction. This topic is covered by ICP.

The Liskov Substitution Principle

The LSP is one of the prime enablers of the OCP. It is the substitutability of subtypes that allows a module, expressed in terms of a base type, to be extensible without modification.

This principle is about inherintance and polymorphism. It exposes that base and concrete classes must be substitutable in all aspects and behaviors. Let’s take the Square and Rectangle example. In math, a Square is a Rectangle and this is the reason why many programmer design a Square as a derivate of a Rectangle. However, this is a really poor design. Look at the code below, assuming that a Square class extends a Rectangle class.


void f (Rectangle r) {
     r.setWidth(5);
     r.setHeight(4);
     assert(r.getArea() == 20);
}

The f functions is able to accept Rectangles and Squares object. With that in mind, the first problem is a Square does not have, in its concept, the attributes width and height. But, this should be acceptable. The second problem is  the need of overriding the setWidth and setHeight methods of Square object to maintains the object integrity. The final, and the real problem is that this function works just for Rectangle and not for Square. Since, for these function, Square is not substitutable for Rectangle, which violates the LSP.

The LSP makes it clear that in ODD, the IS-A relationship pertains to behavior that can be reasonably assumed and that clients depend on.

The Dependency-Inversion Principle

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend on details. Details should depend on abstractions.

More traditional software developers methods, such as Structured Analysis and Design, tend to create software structures in which high-level modules depend on low-level modules, and in which policy depends on detail. The dependency structure of a well-designed, object-oriented program is inverted with respect to the dependency structure that normally result from traditional procedural methods.

However, considering the implications of a high-level module that depend on a low-level module you will see that changes to the lower level modules can have direct effects on the higher level modules and can force them to change in turn. This is not a good idea at all.

The modules that contain high-level business rules should take precedence over, and be independent of, the modules that contain the implementation details. High-level modules simply should not depend on low-level modules in any way. In contrast, they should depend on abstractions. In that way, you are able to change concrete implementations with no changes to its clients.

The Interface-Segregation Principle

This principle deals with the disavantages of fat interfaces. Classes that have fat interfaces are classes whose interface are not cohesive. In other words, the interfaces of the class can be broken up into groups of methods, each one serving a different set of clients. So, some clients use one groups of member functions, and others clients use the other groups.

The ISP acknowledges that there are objects that require noncohesive interfaces. however, it suggests that clients should not know about them as a single class. Instead, client should know about abstract base classes that have cohesive interfaces.

Conclusion and References

This is just the beginning of Object-Oriented Design. Remeber to not apply those principles and patterns to a big, up-front design. Rather, they are applied from interation to interation in an attempt to keep the code ,and the design it embodies clean.

You can read more about OOD principles here or in the book Agile Software Development, Principles, Patterns and Practices, in which this post is based on.

See you


Fernando

Older Posts »

Blog at WordPress.com.