Understanding Open/Closed Principle

Open closed principle is an important rule in software design, which we need to follow when designing a software system. It states “A Software code should be open for extension but closed for modification”.

What does that mean? Let’s take a very simple example from day to day life. We all use TV remotes. Say, we have created a very simple software code for remote operations like on/ off, vol increase/ decrease, channel change etc. Now what should be my design considerations

1. Any one should be able to extend the code to add new functionality, for example, for advanced TV’s one should be able to add functionality for subtitle language selection, operator specific options etc.
2. At the same time I need to make sure that no one should be able to alter existing core functionality like vol increase/ decrease, so that it does not break down the functions which are working fine perfectly.

Point 1 is what we say open for extension and point 2 states closed for modification principle. The open/ closed principle helps maintainability of code perfectly, by making sure we do not break what is working fine with flexibility of adding new features at the same time.

Composite Design pattern

When I first tried to understand composite design pattern, I came across this UML explanation

composite_pattern

Image source : wikipedia

To start with, I was not able to make any sense out of this, so I tried to look for simpler example, and came up with this

composite2.

Think of a scenario where we need to support a tree format data structure. Where every node can be composed of more similar nodes, or a leaf node. For example in above scenario, at leaf level we have juniors, to whom no one report. At non-leaf level we have managers, to whom, juniors and other managers report, and these managers themselves report to some senior manager. To help us structure this kind of complex relationship, composite design pattern comes into play.

Proxy Design pattern

Proxy design pattern is one of the simplest design pattern. The name explains it all, we place a proxy class between the client and actual implementation. An example is EJB’s home and remote interface implementation. Or think of a webservice call, where we are trying to fetch Employee details from webservice. Instead of calling the webservice directly we bring in a proxy class, which is called by client and it call’s the actual webservice later. The advantage it gives us is that if the webservice call changes, say url for the call changes or pattern of input/ output xml is modifies, we just need to make change at one place, rather than changing calls at multiple clients.

proxy

Bridge Design pattern

When I first tried to understand Bridge pattern, I got it confused with Adapter pattern and then Abstract Factory pattern. In my defense, these patterns do have features overlapping. But when I got into depth of bridge pattern, the advantages got clear i.e. decouple an abstraction from its implementation so that the two can vary independently.

Bridge pattern allows an abstraction and implementation to change independently whereas an Adapter pattern makes it possible for incompatible classes to work together

Adapter design pattern

Adapter design pattern is probably one of the simplest, yet very useful design pattern. Let’s take and example, you have a device which runs on Direct Current (DC), but in your home you have supply of Alternate current (AC). What will you do? Go to an electronic shop and explain the problem, the guy in shop will give you an AC to DC ‘Adapter’. What it does is basically takes AC as input and provide DC as output for your device.

Similar problems are faced at times by developer, especially when they are using API from third party or legacy code. Say you are using a Tax class API (you do not have code) which takes integer to calculate tax in its getTax method, whereas your code stores the data in int. One way is to convert the format at every place in code where ever you are using getTax. A second and simple ‘Adapter’ way will be to create a TaxAdapter class which will have a getTax in it, which further calls getTax of Tax class. The only responsibility of TaxAdapter is to convert the data into a format which is expected by Tax class(double to int, AC to DC).

Builder Pattern

You must have used DocumentBuilder or StringBuilder classes if you have worked with core Java. Buider pattern is simple object creation pattern, which helps handling of creation of complex objects by breaking the object building exercise into multiple easy steps.

A simple example will be- let’s say we have a car object with many complex properties- Engine, top speed, boot_space, seating arrangement, air_conditioning etc. A CarBuilder class can help in creation of the objects

Class CarBuilder{

public void setEngine(Engine e)
{
//..
}

public void setSpeed(String s)
{
//..
}

public void setAirConditioning(String temp, String cooling, int avgtemp)
{
//..
}

public Car getCar()
{
//This will finally create the car object and return
}

}

The calling method

CarBuilder cB=new CarBuilder();
cB.setEngine(e);
//.so on
Car myCar=cB.getCar();

To make it more useful in handling higher complexity, we can create the CarBuilder as Abstract Class or interface, which is implemented by HatchBackBuilder, SportsCarBuilder etc.

Prototype pattern

Prototype is a creational design pattern. When I first read about it, I got it a bit confused with Factory pattern. If you look at Car Factory example, where the factory helps us create a “new” car at run time, and we can choose whether we want a Sedan or Hatchback while the car creation. Prototype pattern differentiates itself from factory pattern, by providing prototypes of objects beforehand, and creating a copy at runtime.

Extending our Carfactory example further, lets say now we are not limited to 2 set of cars, but we have ready prototypes say a car called Swift, Ritz, Figo, Scorpio, all with their specifications already defined. At runtime, we will just create a copy or clone of the car which user needs. Note that we can actually build our prototype pattern on factory pattern, but for simplicity of this example we will stick to a simple implementation of car by these objects.

public class CarPrototype{

Car swift=new Car();
swift.setMaxSpeed(200);
swift.setMileage(20);
swift.setFuel(Diesel);

Car figo=new Car();
//set properties

//more cars

//we will also override clone method if required

public Car getCarFromPrototype(String str)
{
switch(str)
{
case ‘FIGO’: return figo.clone();break;
case ‘SWIFT’: retrun swift.clone();break
//so on
}
}

}

One important difference between factory and prototype is that prototype pattern creates a clone and factory pattern create a new object. When a new object is created using a new keyword, it makes sure that user get a object with fresh state. Whereas in clone (prototype), we are making sure that we are also copying a particular state of object. This also helps us understand when to use factory and when prototype should be preferred.

Abtract Factory Pattern

Abstract Factory pattern is another creational design pattern in the league of Factory, Singleton, builder and Prototype patterns. The term has some resemblance to Factory pattern and so does implementation. I tried looking around the internet to figure out some good explanation, but unfortunately they are too complex. This will help though- http://www.oodesign.com/abstract-factory-pattern.html

In my attempt to over simply things, I will try to go back to factory pattern and the example I used for CarFactory, http://kamalmeet.com/2013/06/factory-pattern/. The idea was simple with CarFactory, that user knows he wants a car, but which car is to be created is decided at runtime.

factory

AbstractFactory Extends the idea a bit further, it gives us a factory of factories.

AbstractFactory

To understand the above diagram, lets extend our CarFactory example, lets say we know that we need a vehicle to start with but we do not know if it will be a car or a bike (decided at runtime). So we will have 2 concrete factories-  CarFactory and BikeFactory. CarFactory is responsible for creating Sedan or HatchBack as previous example and BikeFactory is creating SportsBike and NormalBike. On top of the concrete factories we will introduce a AbstractVehicalFactory which is implemented by CarFactory and BikeFactory.

concatenate strings in different rows of a recordset

How to concatenate strings in different rows of a recordset, using a common id?

Example

I have a table (test123) like this

IdValue DataValue
———————
1 aaaaa
2 bbbbb
1 ccccc
2 ddddd

Desired output

IdValue Data_Concatenated
———————-
1 aaaaa,ccccc
2 bbbbb,ddddd

Solution 1: Using sys_connect_by_path

SELECT idvalue ,
SUBSTR(MAX(sys_connect_by_path(datavalue, ‘,’ )),2) data_concatenated
FROM
(SELECT idvalue ,
datavalue ,
row_number() over (partition BY idvalue order by datavalue) row#
FROM test123
)
START WITH row# = 1
CONNECT BY prior row# = row#-1
AND prior idvalue = idvalue
GROUP BY idvalue
ORDER BY idvalue;

Solution 2:

SELECT idvalue, RTRIM (EXTRACT (XMLAGG (XMLELEMENT (“X”, dataVALUE || ‘,’)), ‘/X/text()’),’,’) VALUE
FROM test123
group by IDvalue;