- Proxy could be used when you want to lazy-instantiate an object, or hide the fact that you're calling a remote service, or control access to the object.
See proxy pattern with details. - Decorator is also called "Smart Proxy." This is used when you want to add functionality to an object, but not by extending that object's type. This allows you to do so at runtime.
- Adapter / Wrapper is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.
In particular Decorator looks very close to Adapter but still there is basic difference:Adapter / Wrapper Decorator Composes "origin" class True True Modifies original interface True False Modifies behavior of interfaceFalse True Proxies method calls True True - Bridge is very similar to Adapter, but we call it Bridge when you define both the abstract interface and the underlying implementation. I.e. you're not adapting to some legacy or third-party code, you're the designer of all the code but you need to be able to swap out different implementations.
See bridge pattern with example. - Facade is a higher-level (read: simpler) interface to a subsystem of one or more classes. Think of Facade as a sort of container for other objects, as opposed to simply a wrapper. So you don't have to worry about so many things, just call the facade to do all the stuff.
See Facade pattern with example.
Tuesday, 27 September 2011
Difference between Proxy, Decorator, Adaptor, and Bridge Patterns ?
Interface And Abstraction – Spiritual Explanation
Thursday, 22 September 2011
MVC Pattern Basics
The Model-View-Controller (MVC) architectural pattern is used in software engineering to allow for the separation of three common features in GUI applications:
- the data access (typically via a database)
- the business logic (how the data will be used)
- user interaction (how the data and actions will be visually presented)
MVC pattern differenciates all the 3 aspects of application in 3 difft tiers.
Modal
It incorporates following point
- Holds the business logic of the application.
- holds data sent between different. tiers like JSP to servlet and handler classes.
- One of the goals of the model is to give a presentation which does not directly refer to any specific DBMS.
View
- This represents the visible user interface, so handles presentation tier of the application.
- it knows enough about the data to create a coherent presentation, but does not actually do the work of presenting the data. Instead, it provides the ability to manipulate data outside the View through event handlers defined within.
- handles presentation logic, client side validation.
- e.g. HTML, JSP
Controller
- handles the flow of the application
- Joins the Model with the View and is the heart of the business logic.
- It is the source of activity when an event occurs and defines the event handling actions which access data (from the Model) and are presented to the user (in the View).
- e.g. Servlets, Action Class in Struts, ActionServlet is using struts-config.xml as front controller to handle each request and redirect it to appropriate destination.
Advantages
- Increases modularity of the application.
- Increases Maintainability of the application, i.e. the data presentation can be changed without any notion of how the data is obtained and conversely, the data access can be changed without any knowledge of how it is to be presented.
to be added soon
Thursday, 14 July 2011
Wednesday, 13 July 2011
Activity Diagram
Decision and Merge Nodes: Decision and merge nodes were called decision diamonds in flowcharts. This diamond shaped symbol is one of the elements that make an activity diagram reminiscent of a flowchart. Decision and merge nodes use the same symbol and convey conditional branching and merging.
Wednesday, 22 June 2011
Data Access Object ( DAO ) Pattern
A typical DAO implementation has the following components:
- A DAO interface
- A concrete class that implements the DAO interface
- Entities OR Data transfer objects (sometimes called value objects)
Entity
Order.java
public class Order{
private int id;
private String customerName;
private Date date;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getCustomerName() { return customerName; }
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public Date getDate() { return date; }
public void setDate(Date date) { this.date = date;}
}
DAO interface
OrderDao.java
Get the interface for Create Retrieve Update and Delete operations.
//holds all CRUD behaviours
public interface OrderDao {
void create(Order entity);
Order findById(int id) throws OrderDontExistException;
void update(Order entity);
void delete(Order entity);
}
DAO Implementation
OrderDaoImpl.java
This just takes the datasource object and stores all the queries related to Order object. I am just implementing finById method for simplicity.
public abstract class OrderDaoImpl implements OrderDao {
DataSource ds;
public OrderDaoImpl(DataSource ds_) {
ds = ds_;
}
public void create(Order entity) { //do something }
public E findById(int id) throws OrderDontExistException {
String sqlFindById = "select * from ORDERS where id=?";
Connection con = getConnectionFromDataSource(ds);
PreparedStatement ps= con.prepareStatement(sqlFindById);;
ps.setInt(1, id);
ResultSet rs = ps.execute();
//process result set
Order order = rs.getString("Name");
//... so on
return order;
}
public void update(Order entity) { //do something }
public void delete(Order entity) { //do something }
}
Exception class
package authordao;Using the Dao
public class OrderDontExistException extends Exception {
public OrderDontExistException() {
// TODO Auto-generated constructor stub
}
public OrderDontExistException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public OrderDontExistException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public DAOException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
OrderDao dao = new OrderDaoImpl(ds);
Order order = dao.findById(id);
//Now do some business logic
Conclusion
As this article has shown, implementing the DAO pattern entails more than just writing low-level data access code. You can start building better DAOs today by choosing a transaction demarcation strategy that is appropriate for your application, by incorporating logging in your DAO classes, and by following a few simple guidelines for exception handling.
Exception transformer pattern
class Service {
static class ServiceException extends Exception {}
void serviceMethod1() throws ServiceException {}
void serviceMethod2() throws ServiceException {}
}
Client with repetitive error handling logic
Your class as a client now has to deal with this exception every time you call a service method and also for every different method you call.
public class Client {
private Service service;
void callServiceMethod1Normally() {
try {
service.serviceMethod1();
} catch (ServiceException e) {
throw new RuntimeException("calling service method 1 failed", e);
}
}
void callServiceMethod2Normally() {
try {
service.serviceMethod2();
} catch (ServiceException e) {
throw new RuntimeException("calling service method 2 failed", e);
}
}
}
Exception transformer abstraction
However your exception handling strategy may be the same across your use of the service class only with a different message each time. Instead of repetitively duplicating your exception handling logic (try/catch) around every service call you can abstract this out as follows. The following class abstracts the logic out. Note that this class is only shown as a separate class for the purposes of incrementally describing the pattern. For best effect this class should ideally be contained within your client class as a static inner class.
public abstract class ExceptionTransformer {New client using exception transformer
abstract void call() throws ServiceException;
void transform(String message) {
try {
call();
} catch (ServiceException e) {
throw new RuntimeException(message, e);
}
}
}
Now using the new exception transformer our exception handling logic is simplified to only the logic that differs between the client methods.
class ClientUsingExceptionTransformer {
private Service service;
void callServiceMethod1UsingTransformer() {
new ExceptionTransformer() {
@Override
void call() throws ServiceException {
service.serviceMethod1();
}
}.transform("calling service method 1 failed");
}
void callServiceMethod2UsingTransformer() {
new ExceptionTransformer() {
@Override
void call() throws ServiceException {
service.serviceMethod2();
}
}.transform("calling service method 2 failed");
}
}
Variation
This pattern can be easily varied to suit your personal exception handling styles. Here’s another variation where different checked exceptions are thrown by different service methods and handled by only logging them this time.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class ClientWithVariations {
static final Logger logger = LoggerFactory.getLogger(ClientWithVariations.class);
static class Service {
static class ServiceHungry extends Exception {}
static class ServiceSleepy extends Exception {}
void hungryMethod() throws ServiceHungry {}
void sleepyMethod() throws ServiceSleepy {}
}
private Service service;
void callHungryMethod() {
new ExceptionTransformer() {
@Override
void call() throws Exception {
service.hungryMethod();
}
}.transform("method was too hungry to respond :(");
}
void callSleepyMethod() {
new ExceptionTransformer() {
@Override
void call() throws Exception {
service.sleepyMethod();
}
}.transform("method was too sleepy to respond :(");
}
static abstract class ExceptionTransformer {
abstract void call() throws Exception;
void transform(String message) {
try {
call();
} catch (Exception e) {
logger.error(message, e);
}
}
}
}
This pattern really shows its value most effectively when you have numerous methods using it and also when there are multiple checked exceptions to handle resulting in multiple catch blocks all over the place.
Do you have any exception handling API patterns of your own? I know Joshua Bloch has suggested a few in Effective Java of which one comes to mind – an exception throwing method can be transformed into a boolean via another method which just returns false in the catch block and true elsewhere that can be quite useful if you don’t want to pollute the rest of the code with knowledge of this handling logic. By the way, before anyone mentions this I’m not suggesting converting checked exceptions to runtime exceptions or suppressing them by logging them is always the right thing to do. Thanks for reading.
P.S. This pattern will be particularly nice with closures in Java 8. And the multicatch in Java 7 will certainly also help make code more concise.
Monday, 20 June 2011
Fine grained and coarse grained objects
- If object composition is based on Object references (not one for one attribute) , then its Coarse grained . If object composition is based on attributes, then its fine-grained.
- If there is one table to one object mapping, then its fine grained. If there is one object to more than one table, then its coarse grained.
- If the object holds lot of information it is coarse grained. eg. Example: A single "Account" object holds the customer name, address, account balance, opening date, last change date, etc.
Fine-grained: More objects each holding less data. Example: An Account object holds balance, a Customer object holds name and address, a AccountOpenings object holds opening date, etc. There are relationships defined between these objects.
Note:
May be I am wrong but what I was thinking, coarse object means a big object, that has much responsibility. For example, suppose we are designing a system and we have identified logical entities (business domain objects) (I am not sure, it is right term or not) and now we want to come up with java classes corresponding to those. So should we try to map one entity to one java class (coarse object) or try that one entity should include many classes (each one will be fine object). However if we have really big object, facade pattern do help by bringing infront the small object with which we have to deal with.
Tuesday, 14 June 2011
Repositories vs DAOs
- DAOs are strictly tied to the underlying representation on a DBMS. The original specification is more generic, allowing for file-based persistence and the like. But the vast majority of DAOs are pointing to a DBMS. Moreover, commonly used persistence frameworks, such as Hibernate help a lot in managing database portability, so this is a smaller issue nowadays, than it used to be. As a result the DAO concept eventually downsized, to a "database access point" while Repositories are still intended to be generic.
- Repositories provide a more abstract view over the underlying data model, providing an interface strictly coherent with the domain. DAOs might be implemented basically in many ways, but frameworks and code generation tools tend to put the focus on the data structure rather than on the domain model. This is sometimes a tiny issue, sometimes just a matter of style, but in large systems can degenerate in a severe maintenance problem.
- Repositories enforce access to the persistence layer on a one-repository-per-aggregate basis, while DAOs are normally developed one-per-entity or one-per-table. So, repositories are more tied to the DDD concept of Aggregate Root and have a different granularity than DAOs. This definitely makes the most significant difference.
Repository Pattern
Example
Lets take an example. There is a big basket of toys. Toys contain Soft toys, wooden toys, miniature toys. If a kid wants miniature toys, he has to spill all the toys from the basket and separate the needed ones. Kid’s dad doesn’t want him to do that. He separates the miniature toys, that becomes a miniature toy repository, and gives it to child. Goal is never allow the kid to put hands on the basket.
Kid’s dad does the job of maintaining toy basket. Once the kid is done playing, he puts the toys back into the basket. When kid wants to play he gives the kid whatever toy he wants. When dad brings a new toy for the kid, he is going to put that in the toy bag. In general, dad maintains the toy repository.
Implementation
Repository pattern, as described in Domain Driven Design, in a typical java environment backed by frameworks like Hibernate and Spring.
Child.java
public class Child {
public void Play(ToyRepositoryBase toyRespository) {
//Gets all the toys seperated by Dad
List<Toy> toys = toyRespository.GetToys();
//Now child starts playing
System.out.println("Child is playing with " + toyRespository.GetType());
//Child is done playing. Now dad puts back the toy into the bag
toyRespository.PutToysBackIntoBasket(toys);
}
}
Get all the toys
//Toy is a abstraction of miniature toy or soft toy or wooden toy
public abstract class Toy
{
}
//Miniature toy is concrete class.
public class MiniatureToy extends Toy
{
}
Similarly we can have wooden toys, metallic toys and so on.
Get the toy repository
//This toy repository is abstract of miniature toy repository, wooden toy repository or soft toy repositoryI have omitted other sub classes like WoodenToyRepository for brevity here.
public abstract class ToyRepositoryBase {
//Child calls this to get toys before starting to play
public abstract List<Toy> GetToys();
//One child is done playing, dad puts the toys back into the basket
public abstract void PutToysBackIntoBasket(List<Toy> toys);
}
//Concrete class of miniature toy repository
public class MiniatureToyRepository : ToyRepositoryBase {
//Consider this as action performed by dad,
//who gives the miniature toys to child
@Override
public List<Toy> GetToys()
{
List<Toy> miniatureToys = new ArrayList<Toy>();
return miniatureToys;
}
//This is action performed by dad. Once child is done playing,
// he puts back the toys into bag
@Override
public void PutToysBackIntoBasket(List<Toy> toys)
{
//Here you can use cache or database
}
}
We are not allowing the kid to put hands on the toy bag. Same way, business logic has no knowledge of database and related implementation logic. All that business logic knows is how it can get the needed entity from repository, and how it can give the entity back to repository. It is the responsibility of repository to interact with the data source.
Advantage
This pattern has several advantages.
- No duplicate codes needed. If you got another child who wants wooden toys, same logic works.
- Business logic is simplified, since its interactions is only with repository and repository entities.
- Less scope for errors
- Strong typing, since Miniature toy repository gives miniature toys.
- Easy to test.
A cyclical dependancy anti-pattern: Identity Theft
Anti-patterns:
In software engineering, an anti-pattern (or antipattern) is a design pattern that appears obvious but is ineffective or far from optimal in practice.Or as I like to think of it, the type of code that makes you want to rip your eyes out, like in that movie Event Horizon…
Identity Theft
Here’s a pattern that I have seen many times in a previous codebase, which I believe suffers from some design flaws:Description
FooListing is a repository-type object that holds a list of Foo objects, which it populates from the database using its populate() function. The Foo object also has a populate() method, but this method instantiates a FooListing, and uses the FooListing populate function with its key – so now the FooListing contains the desired Foo object.Our original Foo object now contains a reference to the Foo object that it wants to be. So it does what anyone would do, steals its identity and hides the body.
Foo.populate() looks something like this:
public void populate() {
FooListing listing = new FooListing()
// Set up FooListing
FooListing.setSearchKey(id);
if (listing.size > 0) {
Foo foo = listing.get(0);
this.setBar(foo.getBar);
// continue to copy over properties
// ...
} else {
LOG.warn("Foo not found for key: " + id);
}
}
Why this is bad?
Firstly, apart from the questional morality, it is duplicated code. FooListing already has the capability to create and populate a Foo object from the database. Two locations for this code means twice the maintenance if something changes, (more than) twice the possibility of bugs, etc.Foo and FooListing have become tightly coupled and dependant on each other under this design – there is a cyclic dependancy which is a code smell, and may cause headaches when writing unit tests.
There is also a waste of resoures creating the uneccesary FooListing and Foo objects inside of Foo.populate(), at least some of that could be avoided by client code accessing instances of Foo via FooListing.populate
It also doesn’t make sense that a data access object like Foo should be concerned with information about how it is created. Foo should act more like a bean, or an immutable class.
Another dangerous aspect of this design is the implication that client code accessing Foo cannot be certain that Foo has been instantiated correctly. If the client code has a faulty key for Foo that does not exist in the database, when it creates new Foo(key) there is no way to know that Foo.populate() has failed to find the correct value, and instead they are left with a faulty Foo instance which was not what they requested.
Solution
The best solution for this isolated pattern is to completely remove (or deprecate) the Foo.populate() method, and replace calls to it with FooListing instances.If FooListing fails to find a matching Foo, the client code should realise this when FooListing returns them a null object. The client code can handle and recover from this case in context.
Implementing a getFirstResult() function in FooListing could be beneficial if there are many cases where the code with otherwise be calling get(0).
We could also simplify the calling code so that retrieving a result is a one-line operation – i.e. get() calls populate() if the list has not already been populated.
public final class FooListing {
private List<Foo> _listing;
private int _id;
public FooListing {
}
public FooListing(int id) {
_searchId = id;
}
public void populate() {
_listing = new ArrayList<Foo>();
// Query the database and add to _listing
}
public Foo get(int index) {
if (_listing == null) {
populate();
}
if (_listing.isEmpty() || index >= _listing.size()) {
return null;
} else {
return _listing.get(index);
}
}
public Foo getFirstResult() {
return this.get(0);
}
public List<Foo> getList() {
return _listing;
}
public void setSearchId(int id) {
_id = id;
}
}
And the client code would only need to call
Foo foo = new FooListing(id).getFirstResult();
References:
1. http://en.wikipedia.org/wiki/Anti-patternsSunday, 12 June 2011
The new Builder Pattern
I like to create immutable objects, especially after reading Josh Bloch's excellent "Effective Java" book. If an object is immutable, it has only one possible state and it is a stable one, so once you successfully build an object, you don't need to care about state transitions that can make your object unstable or corrupted. And immutable objects can be shared even in a multithreaded application. There are many other pros of immutability (you can read some of them here).
There is a classical way of making immutable objects in Java which consists of making all fields final (and private, of course), using only constructors to modify them (so that the only moment when a field is modified is during its construction) and making the class final (to avoid adding "setter" methods to subclasses). When you only have a couple of fields, that's fine, but when you have many of them you end up with a constructor with many arguments, which is ugly and difficult to use. If you have optional parameters, you can have a constructor with all the parameters and some other shorter constructors that have the mandatory parameters and some optional ones, that invoke the big constructor, like this:
public class Foo {
private final String mandatoryOne;
private final String mandatoryTwo;
private final String optionalOne;
private final String optionalTwo;
public Foo(String mOne, String mTwo, String optOne, String optTwo){
this.mandatoryOne = mOne;
this.mandatoryTwo = mTwo;
this.optionalOne = optOne;
this.optionalTwo = optTwo;
}
public Foo(String mOne, String mTwo, String optOne){
this(mOne, mTwo, optOne, null);
}
...
}
This can be a bit messy when you add more optional parameters, you end up with a lot of constructors like these and it has a lot of boilerplate code.The use of setters for the optional parameters is not an option, because this leads to non immutable objects (some object can change the state of your object with one of those setter methods).
Some time ago, thinking about this problem, I thought a solution could be to use a Javabean object, with one setter per field (even for the mandatory ones), but with a kind of "seal" method, that would "mark" the object as built and since that moment, an IllegalStateException would be thrown if a setter was called. Nevertheless, I wasn't very satisfied with this approach, because the setter methods that sometimes can be called and sometimes not would be confusing for the caller.
So one solution to this is chained invocation of setters in java. This method is used in the New Builder pattern, explained by Josh Bloch in this PDF presentation, which is different from the original GoF Builder pattern. This pattern uses a public inner static class as a builder. The constructor of the original class is made private, so the only way to build objects is with the inner builder class. The builder has a setter method for each optional parameter and uses a fluent idiom that allows chaining of these method calls. I like this pattern a lot, because it solves the problem elegantly and effectively.
Implementation of the New Builder pattern
In Josh Bloch's presentation there wasn't a detailed implementation of the pattern, although it was very clear the idea and the intention so I have searched for it in the Internet.
Static Builder - the builder is a static nested class of the class from which it has to make instances, the builder's constructor is public (so you invoke the builder with 'new'), and the builder has the same fields as its enclosing class. The 'build()' method copies the content of the builder's fields into a new instance of the enclosing class. What I don't like about this implementation is this duplication of fields (for each field in the original class you have a duplicate field in the builder).
public class ID3Tag {
private final String title;
private final String artist;
private volatile String album;
private volatile int albumTrack;
private volatile String comment;
public static class Builder {
private boolean isBuilt = false;
private ID3Tag id3tag;
public Builder(String title, String artist) {
id3tag = new ID3Tag(title, artist);
}
public Builder album(String val) {
if (isBuilt){
throw new IllegalStateException("The object cannot be modified after built");
}
id3tag.album = val;
return this;
}
public Builder albumTrack(int val) {
if (isBuilt){
throw new IllegalStateException("The object cannot be modified after built");
}
id3tag.albumTrack = val;
return this;
}
public Builder comment(String val) {
if (isBuilt){
throw new IllegalStateException("The object cannot be modified after built");
}
id3tag.comment = val;
return this;
}
// ... a lot more optional parameters
public ID3Tag build() {
if (isBuilt){
throw new IllegalStateException("The object cannot be built twice");
}
isBuilt = true;
return id3tag;
}
}
private ID3Tag(String title, String artist) {
this.title = title;
this.artist = artist;
}
}
The usage of this class would be:
ID3Tag tag = new ID3Tag.Builder("My Title", "My author")
.comment("Great song").build();
There is a similar pattern, called the Essence pattern, here by Dr Herbie. This pattern uses direct access to the fields of the builder (like in a C++ structure) instead of using "setter" methods and it doesn't use "chaining" of modifications like in the New Builder Pattern ("...builder.option1(value1).option2(value2)...").