11 March, 2013

My views and experience with Design patterns - Part 1

           
As it is said in almost all design pattern books, any real time problem can't be solved with just one design pattern. All are intertwined.

Assume we are producer. May be say we are developing an SDK.
Lets see what all patterns can be present.

1) Always have a factory which manufactures objects ( Factory pattern )
           some function like getInstance() or getFactoryObject()->createA() , getFactoryObject()->createB() is fine.

2)  Expose API's to consumer which is simple ( Facade pattern )
          The API's should be simple for the consumer to fill values hiding the underlying complexity of the system.

3) As most of the systems being developed are distributed in nature, try having proxies in your code.
            Say. For example we have n processes (services) sending/receiving messages and processing the request and these process rely on our SDK.

Now we shall have design's like

a) Having a recvBufferQ which receives the message and a thread keeps on polling this Queue to take this message to put in some other Queue based on type of message or any criteria.

b) The other way we could think of is identifying each message as new session and subsequent requests belong to same session if it comes from the same user.

To be more clear on this lets define something called a Service and Session.

Service : A service is one which does a particular job. For example : Order processing , Payroll processing, Query processing, Call Processing. It is a single object.

Session : A Session is one which is associated with this service. There can't be any session without service. It can be correlated to users who are performing those operations. So lets associate each user to one particular session.

For example : If A orders something or searches something using amazon.com or google.com or anyother sites, his query goes to a particular service which in turn gets a unique session object for this user and he is permitted/not permitted to do operations based on session state.

For persons who have done
a) Theory of Computing course, visualize it to an Automata or Turing Machine.
b) Probability & Queuing course, visualize it to M/M/N/K system.


Once the user logs out, the session is no longer associated with the user and is deleted. May be we can dump the object state to DB for charging him in case of call processing system / auditing him later / placing ads based on previous session history etc etc.

So now as we said each user is treated as a new session. Now we can't handle all those requests using a single class implementation. It will obviously lead to adding locks, processing delays leading to performance bottleneck and dropping of messages leading to 503 Service Unavailable. This can be visualized in a different way where attacker keeps on creating N number of sessions and not releasing those sessions causing the server to overshoot its memory leading to 503.

Lets get back to design patterns. As a single class implementation can't handle all requests we have to delegate the requests to a different person. We can either use the queue method to give it to each process based on some factor or we can go with something called proxies.

Lets define new terminologies called Service Proxy and Session Proxy.
A session proxy is one  which handles the requests on behalf of the session.
A service proxy is a client side proxy of a service.

If you are interested more try understanding http://msdn.microsoft.com/en-us/library/windows/desktop/dd430452%28v=vs.85%29.aspx.

So how many sessions do we create ?
Ans : Here comes the concept of Object Pool.

Ideally it is based on the load of the webpage / server or based on some heuristics.
We can initialize huge sessions and place it an object pool and mark it idle. Every time a request arrives the session is used and returned back. Before returning back to the object pool, the user state may be recorded in DB. There can be a separate service which uses some API's to analyze this session object and use that information to display Ad's or get the user email ID and spam him :P and what not :).

How long should we maintain a session?
May be we can run a timer which is done in most of the systems and erase it once the timer fires.

Should we create more sessions on-demand?
Of course yes. Say if 90% of object pool are in use, there is a potential chance of it to reach 100%, so may be the service can add some more new sessions to object pool.

How can we add new sessions to an existing object pool?
Think of it as a linked list. There is Node1 which points to the 1st object pool. Now we can create node 2 and initialize with another chunk and keep on repeating this.


I talked about exposing cool API's, hiding the complex implementation to consumer.
Now these API's usually have an input parameter and output parameter.
Input param should be some structure where customer fills some values and may be a system call happens based on those and the guy who receives the call fills the output param with values.

Customer may/may not fill all values. For example consider a job portal where there are lots of fields which are mandatory and fields which are optional. Any programmer(who doesn't sleep while coding :P ) would initialize all the member variables in constructor thereby ensuring values for optional params also.

What if we need to modify this API future? Are we permitted to add new variables or new structures?

DEFINITELY NOT.

Why?
The size of the object changes. To illustrate more, lets say customer one uses your library builds his application. Later he needs some updated feature version of the library. Now if you modify an existing API, the newly built application would work fine.

What happens to applications which are already running?
when that call is made for the API which is modified the app COREDUMP's  :) similar to my mind right now :)

So how do we solve this problem?
1) The API defined initially should not have an object as parameter. Instead we can define it as an AutoPtr.

2) If some new features needs to be added instead of adding new objects we shall define something called Extension Ptr.

class A
{
       // mandatory features.

       // Extension
       ExtensionAutoPtr B;

};

Now this class B can be used to add new features.
The API exposed to customer can be Func(AutoPtrofA,RetAutoPtrofA)

Now how do we decide whether some variable is set by user or not?
Naive approach would be to check by comparing the values with the initialized values in the constructor.

Is there any other way?
Think of it. Variable storage differs based on type. For ex : char occupies 1 byte, structures occupy the size of it, union occupies the max value defined it.  So to decide whether an object has  a value set or not we can use char which occupies 1 byte or may be a boolean with each variable/object initialized to false instead of iterating through all variables inside a complex structure or checking with initial values.

When the objects value is set by the consumer this boolean variable associated with the object has the value true which means consumer has set it else not.

Lets conclude it for now about my view on design patterns - part 1 .

I hope readers understood something about design patterns.

Kindly do read my other blogs and give feed back so that i can improve :)





1 comment: