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

@since Monday, September 19, 2011

Factory Pattern

@throws 0 exception(s)
Continuing my series on Design Patterns (builder, strategy), I'll focus on one of the most commonly used patterns in object oriented programming - the Factory Pattern. 
In fact, there are actually 3 different patterns named factory (in some form): Factory Class, Abstract Factory, and the Factory Method. Each pattern has a different intention or use case but all handle the same problem of creating object instances during application runtime. Factories usually hold some creation logic and don't have much purpose if the object created can be easily constructed outside the factory.

Factory Class
Used to create an instance that is difficult to construct in normal initialization. Such difficulties may involve wrapping our instance with cache or other AOP operations. Some frameworks, such as Spring Framework use BeanFactory to initiate Beans by integrating with Spring's application context and provide the framework features on newly created Beans. A simple use case may be as follows:
Usually, it's good practice to hide your class construction from being accessed through different flows. A better way is to replace new with a factory class.

Abstract Factory
Next level of hiding our class initialization after the Factory Class. Here we're creating a hierarchy of factories that construct a super object (interface). We select the specific Factory Class to invoke during application runtime.
Factory Method
We've manage to hide the construction of objects from our use case flows but still our factories use new to construct the object. It is perfectly OK to initialize some objects with their constructor. There are times, however, when this isn't the best practice. For example, the constructor is too complicated, or we want to create a default instance with a particular set of arguments. In Java's Locale, such behavior is perfectly described in the Locale.getDefault() method, which constructs an object after reading system properties, without the user interacting with the object's constructor.
To summarize, it's good practice to hide your object construction in order to enhance your application modulation. Factories are perfect for that purpose but don't over use them or you'll end up having an empty layer around a simple object construction. Factories can also help in your clients' use cases by providing them with helpful construction methods (such as Factory Method or methods of a Factory Class).

Comments / Suggestions are welcome.

@since Thursday, March 31, 2011

Event Driven Programming With Event Roaster

@throws 0 exception(s)
Often, in a multi layered, structured application it is sometimes required to notify several services on a system state change. Such change could be of some user interaction with our application, exception thrown from a specific layer or new client registered with our publishing service. These operations can be handled in a variety of paradigms, but for today's lesson: Event Driven Programming.


Recently I faced a problem with our ever growing application of knowing of a network topology change and notify several modules. The initial approach we took was to send important events to a centralize service, which knows almost the entire application structure, that can modify modules state based on the called method. Over time this service got larger and larger, complexity level rose and the maintainability efforts went to the roof. Searching for a suitable solution I broke the behavior to small strategy methods to which I could call from the original method. These strategies are actually event handlers for the state change. Looking around for event handling framework that will suite my needs I came across GWT's HandlerManager, Java's beans implementation, EventBus, ELF and even SpringSource event multi caster. Most, if not all of the above frameworks follow the same guidelines and principals with their provided solution, some are a lot easier to configure than other but what most of them lack is the (poor) support of configuration by annotations.

That's where my github.com account went in handy - I decided to write an event handling framework of my own. Named the project - Event Roaster. The framework is fully annotation configured and if you're working with IoC container like Spring it even provides you with EventServiceFactoryBean. So, here's what you need  to know before you can start working with it:



The snippet above demonstrates how simple the configuration really is and layout for event publishing and handling. Objects you wish to pass around as events are annotated with @Event (no need to implement anything, any object will do) and handler methods are annotated with @EventHandler, each method declaring which event it handles. Handlers can set their priority when called and (future versions will include the ability to) block further event processing. Publishing (a.k.a Firing) an event is as simple as calling the fire event in a matching event service. The event broadcasting is done asynchronous using a multi-threaded executor service. That's all there is to it, implement your handling methods and you're good to go.

Event Roaster is an open source project and as such it requires some attention and assistance by its users and contributers. Future versions are waiting release to Maven's Central repository using Sonatype OSS repository (project can't go to Central unless one of its dependency will move to Central as well). Feedback, feature requests and any general assistance will be appreciated. 

@since Wednesday, February 16, 2011

Strategy pattern as replacement to instanceof if statements

@throws 0 exception(s)
Let's begin with a simple rule: instanceof is an ugly pattern.



To add to this ugly pattern you might not notice a fault in such pattern (what if Bar extends Foo?) and the maintenance for it can go sky high as your system evolves. You will end up adding more ugly code and keep trying to rearrange those switches so that class hierarchy wouldn't collide with your logic.

The literature tells us that this type of design can be replaced by using the visitor pattern and make each class responsible on how it should be invoked by others. To me, that sounds awkward to force my domain objects to be familiar on their interaction with services, DAOs or other delegating classes. I prefer the use of strategy pattern and leave my code clean from coupling. The following is a slightly modified strategy pattern with a corresponding holder which enables re-use of strategies in a Dependency Injection environment. The very basic interface might looks as follows:



For the re-use part, we hold our concrete strategies in a holder in a simple Map (HashMap in the following example). If you're using some dependency injection framework you can inject all known implementation to the holder below and then inject the holder to clients use code.



To quickly go over the abstract implementation: the map holds our strategies by their declared discriminator/key. The holders uses generics to support using the holder with any extended type of strategy without casting. Another point to mention is the abstract method getDefaultStrategy() which enables our concrete implementation to use a default strategy (obvious) or throw some state exception if no strategy was found. You can simplify this implementation by using interfaces but with this added generic flexibility I managed to replace different strategies with the same basic holder abstraction.

The following is an example on how the holder and strategy above can be used in real life scenario.



As you can see, ExampleStrategy is simply extending the Strategy interface and provide a single execute() method. By injecting all known implementation (your IoC container should do it for you) and passing them to our AbstractStrategyHolder we're ready to use our strategies in our designated flows. Small note: I wouldn't recommend using the class type as discriminator but sometimes it's our best option.

We managed to clear our ugly instanceof switch with a single call to a strategy holder and invoke the matching strategy - cleaner code, easy maintenance. Need another reason why this is better? Testability! With this design implementation we can better test our code and write small, individual tests to our flows. Need another?! Extensibility! Need new strategy to perform another action? Add a new strategy and let our IoC container inject it to our current holder implementation (I've seen this happen so many times I believe that alone should convince you to use the strategy pattern).

The code examples (and for the builder example in earlier posts) can be found here.

@since Tuesday, February 1, 2011

Builder Pattern for Persistence Objects

@throws 0 exception(s)
Usually, when dealing with persistent entities we would like to keep records at the same state they are stored in the database and keep the newly created entities unmodified until we are persisting them to a database. The first requirement is quite easy to accomplish when using interfaces. For instance, our data access layermight export the following as its domain objects:


Notice that our domain object interface doesn't expose any mutators (setters). Client retrieving these records is unable to change their state. If your services are read only - we're basically done. We hide our concrete implementation by declaring those classes as private package visible (I would also add final to be even stricter) and initialize them anyway preferable (constructor, setters). Easy, right?

Now, let's say our service enables CRUDoperations. We present our clients with the option to persist entities by passing a DTO/ VOimplementing the same interfaces as shown above. First ( Lazy) option: the client can have its own domain hierarchy implementation based on our published interfaces. Hmmm, nice option, but we don't want to force our clients to have unnecessary code when we can provide it with some assistance. Second option, publish our DTO and force the client to create the object by passing alldata values to the constructor (no mutators) - better, but what if our constructor has 5-6 (or more) fields? [ code smell] Third option: expose a default constructor and mutators and have the client initialize the object with multiple invocation lines, one-per-setter (we can have a mix mode of the 2 ndand 3 rdoptions but it's still the same). But, leaving mutators exposed might damage our requirement of keeping our entities unmodified until we reach the actual persist part. So, what should be a better option (I don't think it's the best, since any solution should fit the desired requirements)?

Here comes the builder pattern - we offer the client easy initialization of DTOs but prevent it from changing it once it's done. We add an inner  private static class called Builder which will allow easy initialization of our domain objects. Why inner class and not FooBuilder ? That's simply a flavor, I prefer having a class called Builder for each of my domain objects. Both options (inner or external) will give us the same result and have the same structure. Let's say we have the following DTO as our Foo implementation:


I won't go into details describing the DTO itself, simply say that I'm using Hibernateas an ORMand added some Hibernate Validatorsto give it a more realistic look and feel. Notice the default constructor is not available to client interaction (Hibernate can easily interact with it) and so does our mutators (private package scope). Another thing to notice is the special care we give collections: we never return the actual field or use the parameter given to us (collections are mutable [ 1, 2]). So, how can our clients initialize the above DTO? By using a Builder!


This example is what the general design should be like. For each mutator method we expose on our builder we can add validation logic or validate the entire object in the build() method. Notice we added 3 static factory methods to our original DTO to support 3 operation types: creatinga new instance, updatingan existing one or mergingvalues from existing one to a new instance. Another point to notice is that our builder returns itself from each mutator and that the build()method returns the interface (blocking any future changes to the instance). For ease of use we can add helper mutators to create complex objects by passing parameters to our builder to create (e.g. class holding IP and port - add  setIpAndPort(IP ip, int port)  and  setIpAndPort(IpAndPort ipAndPort)  to our builder)

With this approach we get the requirements we asked for when offering our clients CRUD operations. This design guideline might look as an overkill but the maintenance benefits and ease of client usage is what we're really looking for. With modern IDEs (like Eclipse, IntelliJor NetBeans) we can simply create a coding template to auto-generate builder implementation for our persistence objects. This design is not limited to persistence layer. Every time you need to create an object with too many constructor arguments (and you prefer not to refactor that class) - use a builder. Builder pattern - another tool in your clean code toolbox.