Tuesday, 27 September 2011

Difference between Proxy, Decorator, Adaptor, and Bridge Patterns ?

Proxy, Decorator, Adapter, and Bridge are all variations on "wrapping" a class. But their uses are different.
  • 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 interface
    False True
    Proxies method calls True True
     
    See Adapter pattern and Decorator Pattern with examples.
  • 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.

Interface And Abstraction – Spiritual Explanation

“What is the difference between interface and abstract class?”, a typical interview question . Answer is so obvious, and we can list at least 3 differences. Here is an attempt to correlate Object Oriented world with spiritual world, and explain abstraction and interface.

“Soul is an abstract notion realized by concrete living being”. So as per OO world, if you got “Soul” as abstract class, you got to have a concrete class “Life”. Soul can not operate without Life.
Just like I said object is an entity with an objective to live, abstract class can live through concrete class. Inheritance is the only mechanism for an abstract class to live. Spiritually, Soul operates through life. Life is an object with a process thread running in it.

In Spiritual world, it is said that “Soul carries the karma (good or bad actions) from previous life, which has influences in the new life”. If you consider this statement, karma is the action log recorded into the abstract class.
Body is an interface to life (and hence interface to Soul) and real world. so IBody can be implemented by body of human, bird or any living creature. Once the objective is complete in this real world, destructor is called on life object. However actions are kept recorded (like log files) in the abstract class through out this new life.
In every new life actions recorded in abstract class is not revealed, as it is private declaration . Only the ultimate object builder (God)  has access to it. Object builder reads this private variable, and makes the decision of choosing a new interface for Soul. Dispose method is programmed to be called in a timer function. When timer event fires, dispose is called, and the Life object is disposed terminating the process thread.

After thread is terminated and Life is disposed, Object builder reads the record log from Soul class. Based on the karma recorded in the log, a new object with the suitable interface (body) is created, and Life is induced into it with a process thread. And a timer is started in the Life class, which when fires Thread Abort is called.

Thursday, 22 September 2011

MVC Pattern Basics

Definition
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. 
Example
to be added soon

    Wednesday, 13 July 2011

    Activity Diagram

    Activity diagram help to discribe visually the sequence of action that leads through the completion of a task. Activity diagrams are good analysis diagrams for developers, users, testers and managers because they use simple symbols, plain text and a style that is similar to the familiar flowchart. Activity diagrams are good at helping you to capture, visualize and describe an ordered set os actions from a beginning to an end.
    Activity diagrams are a technique to describe procedural logic, business process, and work flow. In many ways, they play a role similar to flowcharts, but the principal difference between them and flowchart notation is that they support parallel behavior.
     
    Symbols used in Activity Diagrams
    Intial Node : Every activity diagram have on initial node symbol. This is a solid circle. We can provide a name and some documentation for the initial node (but generally not provided).
    The initial node can have one transition line exiting the node. The transaction line is called a Control Flow and is represented by a directed arrow with the arrow pointing away from the initial node
    Control Flow/Edge : A control flow is a directed arrow. A control flow is also referred as just flow or an edge. The control begins at the symbol losing focus and points to and is connected to the thing gaining focus.
    Guard Conditions : A guard condition is shown as text between in the round bracket on the control flow. Guard condition can be think of as a gatekeeper to the next node
     Connector Node: The connector node is a good way to simplify overlapping flows or flows that span multiple pages.
     
     

    To use a connector node, draw a flow exiting a node and transitioning to a connector. Where the connection is made to the next node, draw a connector with a flow exiting the connector and transitioning to the next node in the diagram.
    Connector nodes come in pairs. Make sure that connector pairs have the same name; naming connectors will help you to match connection points when you have multiple connector pairs in a single diagram.
     Pins: Pins in the UML are analogous to parameters in implementation. The name or value of a pin leaving one action should be thought of as an input parameter to the next action. 

    Actions: Action nodes are the things that you do or that happen in an activity diagram, and an edge represents the path you follow to leapfrog from action to action
    Actions are permitted to have one or more incoming flows and only one outgoing flow. If there is more than one incoming flow, then the action will not transition until all incoming flows have reached that action. Actions can split into alternate paths using the decision node or transition into parallel flows using the fork node but only a single flow actually should be attached as an outgoing flow for an action.
    Actions also can use preconditions and post conditions to indicate the necessary conditions before and after an action occurs. Preconditions and post conditions can be added to a model using a note—the stereotype symbols with the word precondition or the word post condition in between and the name of the condition. The note is attached to the action to which the condition or conditions applies.
    Note: Insteaded of using the pre and post condition, we can use guard condition or we can make use of decision node to convey the same message.
    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.
    When the diamond-shaped symbol is used as a decision node it has one edge entering the node and multiple edges exiting the node. When used as a merge node, there are multiple entering edges and a single exiting edge. A decision node takes only one exit path, and a merge node doesn't exit until all flows have arrived at the merge node. A merge node marks the end of conditional behavior started by a decision node.

    Transition Forks and Joins:
    A fork exists to depict parallel behavior, and a join is used to converge parallel behavior back into a single flow. Forked behavior does not specify whether the behavior is interleaved or occurs simultaneously; the implication is simply that the forked actions are occurring during a shared, concurrent interval.

    When multiple flows enter an action, this is implicitly a join, and the meaning is that the outgoing flow occurs only when all incoming flows have reached the action. 


    Partitioning Responsibilty with Swimlanes:
    Sometimes we want to show who or what is responsible for part of an activity. We can do this with swimlanes. Modeling tools typically show swimlanes as a box with a name at the top, and place whatever nodes and edges belong to that thing in that swimlanes. We can have as many swimlanes as it makes sense to have, but boxy swimlanes can make it hard to organize our activity diagram. UML version 2.0 supports vertical, horizontal, and grid like partitions, so the swimlanes metaphor is no longer precise. The actual terminology is now activity partition, but the word swimlanes is still employed in general conversation and used in modeling tools.

    Signals: A signal indicates that an outside event has fired, and that event initiates the activity. There are three types of signal, these are –

    ·         Time signal
    ·         Send signal
    ·         Receive signal
      
    The hourglass shape of the time signal is used to specify an interval of time. The receive signal symbol is a rectangle with a wedge cut into it, and the send signal symbol is a rectangle with a protruding wedge.
    Terminating Activity: There are two terminating symbols to end the flow or activity, there are –

    ·         Activity final node : When we reach the end of an activity, add an activity finanl node
    ·         Flow final node : When we reach the end of a flow and nothing else happen, add flow final node. This indicates the end  of one particular flow, without terminating the whole activity

    We can have more than one activity final node and flow final node in a single activity diagram



    Wednesday, 22 June 2011

    Data Access Object ( DAO ) Pattern

    A data access object (DAO) is an object that provides an abstract interface to some type of database or persistence mechanism, providing some specific operations without exposing details of the database. It provides a mapping from application calls to the persistence layer.

    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)
    Seeing all the components with the Example

    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;



    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

    }


    }
    Using the Dao

    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

    Checked exceptions are widespread in Java. Imagine the situation where you are calling numerous methods on a class (say for the sake of serving as an example: a service class) each of which throws a checked exception (say ServiceException).
    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 {

    abstract void call() throws ServiceException;

    void transform(String message) {
    try {
    call();
    } catch (ServiceException e) {
    throw new RuntimeException(message, e);
    }
    }

    }
    New client using exception transformer

    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.