Monday, September 2, 2013

Design Patterns - Singleton Pattern (Java)

Creational Patterns

Singleton Pattern

          A singleton pattern suggests that the implementing class does not want its instance to be created more than once (or restrict number of instances), thus making it restrictive constructor in order to avoid using ‘new’.
          In general, the singleton class has:
1.   Declares a member variable to store the class instance. 2.   Makes the visibility of default constructor for the class as ‘private’ 3.   Provides a public visibility method (generally named as ‘getInstance’), which takes care of providing the class instance.

Early instance creation vs lazy instance creation:
          In case, the class instance is created while loading the class through class loader, is known as early instantiation. In java, while declaring a member variable at class level, it can be declared as ‘static’ with initialized to the new instance of the owner class. This way, the class instance will be available at the time of application is started and classes  are loaded.
          singlInstance = new SingletonClass();singlInstance = new SingletonClass();
private SingletonClass() {}
          In this case, the ‘getInstance’ method, which needs to return the class instance would simply be:
                   public static SingletonClass getInstance(){
                             return singlInstance;
                   }

                   In case of the lazy initialization, the class member variable is declared as null and the actual class instance gets created when the ‘getInstance’ method invoked for the first time.
                   public static SingletonClass singlInstance = null;
                  
private SingletonClass() {}

public static SingletonClass getInstance(){
                             if (singlInstance == null) {
                                      singlInstance = new SingletonClass();
                             }                          
retutn singlInstance;
                   }
                  
          Making Instance Creation Thread Safe:
          To make the singleton class instance creation thread safe, there are 2 possible solutions:
<![if !supportLists]>1.   <![endif]>Create the instance of the class at the application class loading itself. This will make sure that the instance will be always available just when the application classes are loaded.
public static SingletonClass singlInstance = new SingletonClass();
So when any thread accesses the ‘getInstance’ of the class, the instance created early, will be always available and it will be returned, thus making no new creation of instance later.
<![if !supportLists]>2.   <![endif]>While with the lazy load, an instance created in ‘getInstance’ method will not be by default thread safe. To make it thread safe,
<![if !supportLists]>a.   <![endif]>Defining ‘getInstance’ method as synchronized
We can make the ‘getInstance’ method as synchronized, to make sure the first thread which gets the access, will make other threads wait. This will make sure that the instance will be created for the first time and other threads, once obtain the lock would use the same instance created in first thread.
public static synchronized SingletonClass getInstance(){
                             if (singlInstance == null) {
                                      singlInstance = new SingletonClass();
                             }                          
retutn singlInstance;
     }
<![if !supportLists]>b.   <![endif]>Making a synchronized block
The problem with synchronized method, is, it becomes overhead, once the first instance created. So every later call, which will only be getting the earlier created instance, needs to go in synchronized call. It is very much unnecessary and can be avoided using synchronized block in ‘getInstance’ method.
public static SingletonClass getInstance(){
                             if (singlInstance == null) {
                                      synchronized (SingletonClass.class) {
                                                singlInstance = new SingletonClass();
                                      }
                             }                          
retutn singlInstance;
     }
The above implementation would help in making sure that the synchronization will be applied only when the instance is not created, implying, all the calls post initialization, would go directly avoiding any cost of synchronization.
However, there is still an issue in the above implementation. The issue is mainly due to the fact that, if there are multiple threads trying to access ‘getInstance’ method simultaneously, when the instance is not yet created. In this case, all these threads will go in synchronized way, but, each one will end up in creating new instance.
<![if !supportLists]>                                                 i.    <![endif]>Avoiding faulty implementation
To avoid the fault, we need to make double check. The ‘double check’ would imply that, even if threads go in synchronized block as the instance is not created, but when they actually start the execution of the block, re-verify if the instance is still not created and then create it.
public static SingletonClass getInstance(){
                             if (singlInstance == null) {
                                      synchronized (SingletonClass.class) {
                                                if (singlInstance == null) {
                                                          singlInstance = new SingletonClass();
                                                }
                                      }
                             }                          
retutn singlInstance;
     }

Handle Cloning on the Singleton class
Cloning in java, allows by default shallow copy of an object. However, it is necessary that to have the class implementing the ‘Clonable’ interface, if it needs to clone in later stage.
In the above example, even if the user tries to get the clone on the SingletonClass instance, the java program will end up in throwing java.lang.CloneNotSupportedException.
In order to support coning in singleton, would mean allowing coning, without creating any new instance if already created.
In this case, we will need to implement ‘Clonable’ interface for our Singleton class.
public class SingletonClass implements Cloneable

and also, override the clone() method
          private Object Clone(){
                   return SingletonInstance;
          }


Avoid allowing the Singleton class extensible
 To make sure your singleton class will not be extended and used explicitly, you can make it ‘final’ class. (Note: By making the constructor ‘private’, would mean, the extensibility is also avoided. However, it is a best practice to make a class final, if you know it should not be extended)

Handle Serialization on Singleton Class
 Serialization in java will allow storing the state of the object. The state can be saved in a file. The stored state can be read using de-Serialization.
By default, if anyone tries to serialize the singleton class object, it will throw java.io.NotSerializableException   
In case if we need to make sure the singleton class state can be stored and used in case it is crashed, we may want to use serialization.
To allow the singleton class supports serialization, there are few changes will be needed. These changes are important in order to keep the singleton class not allow having multiple instances.
Below are the changes we need to make:
<![if !supportLists]>·         <![endif]>Implement the readObject method in your singleton class. And make sure to return only the existing  instance.
<![if !supportLists]>·         <![endif]>Here is the sample implementation:
private void readObject (ObjectInputStream oInstream) throws IOException, ClassNotFoundException {
                   oInstream.defaultReadObject();
                   if (SingletonInstance == null){
                             synchronized (SingletonClass.class) {
                                      if (SingletonInstance == null){
                                                SingletonInstance = this;
                                      }
                             }
                   }
          }
         
          private Object readResolve() throws ObjectStreamException {
        return SingletonInstance;
    }


Sunday, January 22, 2012

Using DECODE with Hibernate

During the development phase , we came across a challenge of using the DECODE function of oracle in a query, which will be processed through hibernate.

Original query looks like this:
SELECT ID, NAME, DECODE(CC.TYPE,'REG',C1.VAL,CC.VAL) as DECCOL FROM CUSTOMER CC, CUSTOMER C1 WHERE
CC.CUSTACCKEY = 1 AND C1.PARENTKEY = CC.KEY AND C1.CUSTACCKEY = CC.CUSTACCKEY
GROUP BY ID, NAME, DECCOL

For Pagination
String count = " COUNT(1) ";

StringBuffer orgQuery = new StringBuffer(query);
orgQuery .delete(start+6,from);
orgQuery .insert(start+6, count);
ret = orgQuery.toString();

Since we need to docodes and group by clause as well with making the query paginated, hibernate was throwing the QueryException. After reading various information on internet, we identified some useful stuffs :
1. In case we want to use DECODE in hibernate , we can define formula in the hbm.xml file, where the expected values would come through the formula. The defined name will be used in the HQL.

< property
name="propertyName"
column="column_name"
type="typename"
update="true|false"
insert="true|false"
formula="arbitrary SQL expression"
access="field|property|ClassName"
lazy="true|false"
unique="true|false"
not-null="true|false"
optimistic-lock="true|false"

/>

2. Use the inline query, to avoid the decoding directly, and use the incoming column name in the group by clause. However with this option, we can not run the query as HQL, instead , we will have to run it as SQL.

SELECT ID, NAME, DECCOL FROM (SELECT ID, NAME, DECODE(CC.TYPE,'REG',C1.VAL,CC.VAL) AS DECCOL FROM CUSTOMER CC, CUSTOMER C1 WHERE
CC.CUSTACCKEY = 1 AND C1.PARENTKEY = CC.KEY AND C1.CUSTACCKEY = CC.CUSTACCKEY)
GROUP BY ID, NAME, DECCOL

3. Not to go for DECODE, in case if you want to make the query DB independent. We can use 'Case When' to avoid the dependency from the query.

SELECT ID, NAME, (CASE WHEN CC.TYPE = 'REG' THEN C1.VAL ELSE CC.VAL END) AS DECCOL FROM CUSTOMER CC, CUSTOMER C1 WHERE
CC.CUSTACCKEY = 1 AND C1.PARENTKEY = CC.KEY AND C1.CUSTACCKEY = CC.CUSTACCKEY)
GROUP BY ID, NAME, DECCOL

We can use any of the above approaches, to make the required DECODE functionality work !

Tuesday, August 10, 2010

Change Management Process

The primary focus of Change management is on those changes that are introduced by the sponsor. Requirements changes, changes to the content of deliverable, or changes to due dates
Even in the simplest of projects, some change is unavoidable. Although changes may result in increasing costs, duration, and risk, changes can also be an important source of additional revenue or funding. Too much change, at best, impacts productivity and, at worst, can lead to the project becoming out of control with different project team members working on conflicting objectives.

The Overview
The change management process is the sequence of steps or activities that a change management team or project leader would follow to apply change management to a project. The most effective and commonly applied change processes contain the following three phases:
Preparing for change (Preparation, assessment, strategy development)
Managing change (Detailed planning and change management implementation)
Reinforcing change (Data gathering, corrective action and recognition)
These phases result in the following approach as shown below in Figure 1.



Sponsor and subcontractor agreements often include a high-level change management procedure that provides the framework within which the changes in which they are involved must be handled.
The project manager drives the decision making process and ensures that all the stakeholders who might be impacted by the change are fully involved. Different proposed changes often need different groups of decision makers and so need somewhat different change management procedures. The project manager must coordinate the set of proposed changes as a whole and ensure that the decisions made by the different groups do not conflict with each other. Deciding which changes to make is only part of the problem. The project manager must also ensure all change management decisions are communicated effectively to those who need to know and cause the minimum amount of disruption.
It is important to note what change management is and what change management is not, as defined by the majority of research participants.
- Change management is not a stand-alone process for designing a business solution.
- Change management is the processes, tools and techniques for managing the people-side of change.
- Change management is not a process improvement method.
- Change management is a method for reducing and managing resistance to change when implementing process, technology or organizational change.
- Change management is not a stand-alone technique for improving organizational performance.
- Change management is a necessary component for any organizational performance improvement process to succeed, including programs like: Six Sigma, Business Process Reengineering, Total Quality Management, Organizational Development, Restructuring and continuous process improvement.
- Change management is about managing change to realize business results.

Changes may affect

- The technical work
- The Agreement (and any amendments) with the sponsor, a supplier, or a performing organization
- The project management plans
- The procedures

Readiness assessments
Assessments are tools used by a change management team or project leader to assess the organization's readiness to change. Readiness assessments can include organizational assessments, culture and history assessments, employee assessments, sponsor assessments and change assessments. Each tool provides the project team with insights into the challenges and opportunities they may face during the change process.
- Assess the scope of the change: How big is this change? How many people are affected? Is it a gradual or radical change?
- Assess the readiness of the organization impacted by the change: What is the value- system and background of the impacted groups? How much change is already going on? What type of resistance can be expected?
- Assess the strengths of your change management team.
- Assess the change sponsors and take the first steps to enable them to effectively lead the change process.


Change Request
Any project stakeholder (the sponsor, the delivery organization, or a subcontractor) or a member of the project team may initiate the change management process by raising a Change request containing a definition of the proposed change and a description of the rationale behind it.

Change orders
Sub-domain includes processes to:
- Decide on how to proceed with a Change request once its impact has been
analyzed.
- Monitor the progress of approved changes until they are complete.

A Change order instructs the project team to implement an approved Change request. One Change request can give rise to more than one Change order. Alternatively, one Change order can result from more than one Change request.

Friday, August 6, 2010

Project Definition

The Project Definition Document is a "living" document. It is a critical starting point in the development of any new project.

Audience and Distribution
The intended audience for the Project Definition Document consists of project stakeholders and other parties who are involved in the definition, development and/or roll out of the solution.

The objective of project definition (is to perform the minimum amount in order to):
- Establish a good business justification.
- Be ready to proceed to Planning activities on a sound basis.

Structure of Project Definition Document

- Project Overview

- Goal

- Project Description
    - Components

- Project Phases and Deliverables

- Project Benefits

- Issues to be Addressed

- Roles and Responsibilities

- Signoffs


It contains the processes for transforming a business need into a clearly defined strategy for providing a solution which meets the business need.

In this domain, the processes are mainly focused on:




Important, ideas which must always be kept in mind, carefully balanced while carrying out the processes
- Project definition is an investment. The delivery organization must minimize the time and money expended prior to initiating the Planning activities.
- Sufficient effort must be spent during project definition to provide a solid basis for the business justification and for the project commitments.
- Whether the project request comes from an internal sponsor or from a customer, the competition needs to be properly understood and addressed
o On an internal project, market and competitive analysis need to be sufficiently developed and understood by the project team.
o On an customer project, definition aims to describe the solution and combining assets, resources and time in plans able to convince the customer, and based on these plans successfully control the project, satisfy the customer and meet the financial objectives.

Project definition processes primarily address the situation where a business need is expressed by an organization and a new project must then be defined.

Input documentation

The Request for Proposal is listed only once, as an input to the first process of the domain, input documentation to the project is referred to throughout the Defining and Planning activities.

The target solution

First, it is necessary to gain sufficient knowledge about the target solution under consideration. Then, based on this knowledge and on the context of the project, an assessment is made of the unique features of this project, and how standard approaches reflected in the technical work patterns should be adapted.
Finally, based on this assessment, the overall approach to go from the present situation to the target solution is selected. This should be discussed with, and approved by, the sponsor.
This approach should identify, in a high-level Product breakdown structure, the sources of components:
- Existing offerings or assets to reuse, and the related licensing opportunities
- Products to buy and licensing constraints
- Components and enablers to build and patent potential assets.

It is the solution which is proposed to be developed and implemented in addressing the business needs expressed by the sponsor. The way from the present situation to the target solution may consist of a single project or a “road map” of multiple projects.
The overall approach is the way which is proposed for successfully going from the current situation to the situation in which the target solution is properly deployed or distributed.
Several successive Agreements with the sponsor may be necessary to develop and deploy the target solution.
The target solution may be partially implemented by the Agreement and project which are scoped during the Defining activities and supported by the project management plans.

The sponsor’s concept about a project tends to lie somewhere between two extremes:
- The sponsor has a clear perception of the solution, of the project to implement it, and of the role of the delivery organization in the project. This precise view may be reflected, for example, in a Request for Proposal (RFP). In this situation, the solution is more or less defined and the sponsor and the delivery organization are soon able to agree on the scope of the project.
- The sponsor understands the business problem which is to be solved, but has little idea about how to solve it. They expect the delivery organization to devise the target solution, to select the overall approach which will implement the target solution, and to scope the first project to be undertaken. In this situation, the delivery organization’s response depends on its experience in similar situations. The two cases are:
o The delivery organization has a solution which is available “off the shelf” and so is able to propose a project to deliver this solution.
o The delivery organization has no “off the shelf” solution.

Here the sponsor and the delivery organization must work together to devise the target solution and to imagine how to develop it in sufficient detail so that a project can eventually be clearly defined and the related Agreement can be created. In many cases, the scope of the first project to be agreed upon and undertaken would be to design a solution rather than to build and implement one.

Depending on the situation, the freedom of access which the delivery organization has to the sponsor can vary tremendously.
- At one extreme, the delivery organization may be expected to respond to a formal RFP with no access to the sponsor organization at all
- Sometimes the sponsor may respond to written questions only and share all the questions and answers with all of the competitors.
- At the other extreme, access to the sponsor may be more or less unrestricted.

Project management must use all possible access to the sponsor in order to eliminate misunderstanding as soon as possible, and preferably prior to finalizing the proposal for the Agreement.

The processes to assess situation and to select the approach, may be applied twice:
- Once to sketch out the overall approach which goes from the present situation to the target solution.
- Once when determining the project scope, which may be a subset of the target solution, on which the Planning activities will then focus.

Overall approach
- Managing the work to refine the description of the solution.
- Understanding the project context, by identifying and evaluating the relevant situational factors.
- Selecting an approach to move from the present situation to a position where the business need is met.

Monday, April 19, 2010

The Characteristics of Agile Software Processes

- Yogesh A Sakurikar (yogesh_skr@yahoo.com)


Agile software processes are very popular and is practiced by many software organizations. It helps improving the delivery of the real system into small units and hence increasing the business value.

Lets take a look at the characteristics for Agile software process


  1. Modular
    1. Processes broken down into small activities, these activities are capable of transforming the software vision into reality.
    2. Activities are used as good tools in Agile
  2. Iterative
    1. Agile focuses on shorter cycles for set of activities; with each cycle certain activities will be completed.
    2. Generally these are as small as 4 to 6 weeks
    3. Since 100 % work is not completed, these cycles are repeated.
  3. Adaptive
    1. Risks can be introduced during the cycles (iterations), these needs to be addressed and planned to mitigate.
    2. Agile process helps adding those risks under the logs, which would be then handled either in same cycle or next, based on priority.
    3. Some of the activities can be discarded if the risk turned down.
    4. Activities can be back logged and handle in next cycles
  4. Collaborative
    1. Communication is the vital part of the agile processes
    2. Understanding the process of fitting developed pieces together
    3. All the teams integrate and work closely
  5. Quality of life
    1. Agile processes emphasizes on work balance.
    2. Self-organize teams gives the distinctive feature to achieve work balance
    3. Teams are more alive.
  6. Convergent
    1. As the iterations repeated, the system becomes closer to reality
    2. Teams have more control over the success with repeated increments.
  7. Parsimony
    1. Minimum number of activities per cycle to minimize risks
    2. By minimizing the risks, developers can deliver quality system.
  8. Incremental
    1. Agile does not build whole system at once, instead breaks it down in small cycles with manageable set of activities.
    2. The partitions of nontrivial system increments which may be developed concurrently at different times.
    3. Each piece unit tested independently
    4. With each piece completes unit test, integrated into system.
  9. Time Bound
    1. Small cycles are good for software developments
    2. Each cycle has a time span (around 4 – 6 weeks)
    3. All the activities are not taken; instead activities which can be done within the fixed pan will be taken to achieve the goals.
    4. Functionalities might be reduced to manageable limit of the cycle, rescheduled for next cycle if needed.
  10. Inverted Pyramid
    1. Developers are empowered; they self-organize to accomplish the task at hand.
    2. Coaches and team leaders work for the team; they are in charge of resolving the issues that the developers can't solve for themselves.
  11. Better Liberty
    1. People in an Agile Software project feel more liberated
  12. Constant Learning and knowledge sharing
    1. People in an Agile Software project are constantly learning, and sharing knowledge, in an ad hoc way, because by definition agility is based on continuous short feedback cycles of inspection