Sunday, May 16, 2021

SOLID Principles, the foundation of GoF Patterns

        Robert Martin, affectionately called Uncle Bob, in many ways has been one of the towering figures in Object Oriented development methodology! He is the pioneer of the clean-code movement and has laid out some fundamental principles in object-oriented development methodology. I believe it is possible to describe most of GoF patterns in terms of the first principles proposed by Uncle Bob. These principles are immortalized by term SOLID principles.

        In the remaining article we will try to study the rationale behind few GoF patterns and examine whether the SOLID principles can explain the motivations behind each GOF pattern by first principle thinking.

        Once each pattern is broken down into set of first principles, it is left to designer’s flair and “syntactic sugar borrowed” from the programming language construct to implement or use that pattern.

Let’s revisit each of SOLID principle and connect it with the GoF Patterns!

SOLID acronym expands into

  • Single responsibility Principle
  • Open-Closed Principle
  • Liskov substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

 Single Responsibility Principle (SRP).

A class must bring only related and cohesive concepts together. It is also emphasized that “a class must have only one reason to change”. The changes might occur because the concept that the class wrapped in its definition has undergone a change or has evolved.

A direct consequence of following this principle is that this makes software maintenance and evolution easy. If a change percolates due to maintenance or software evolution, the changes will be localized in the class boundary that undergoes the change. Another benefit is the Increase of reuse of the classes. This follows as the class represents one single concept or responsibility.

"High cohesion within a module and low coupling between modules", a practice put forward in structured programming is just an extension of this principle. This principle paves way for more maintainable software with ability to evolve easily.

GOF pattern application

Factories abstract away the object creation responsibility from the class. This helps the served class (class whose objects are constructed by factory) to concentrate on the real- world concept it seeks to model. Builder and composite lend similar help for specific types of complex objects. As a matter of fact, all creational patterns abstract away the creation part of object from the served class. 

Similarly, Structural patterns take away the responsibility of representing the relation of classes (entities) among themselves. This helps the classes modelling the real entities classes to concentrate on representing the concepts they represent. For example, an Adapter takes abstracts away the difference in interface of two closely related classes. Iterators take away the traversal from collection and localize the traversal code. Mediators simplify the communication between objects and take full responsibility for brokering the communication. Memento takes away the state representation from a complex object. The Adapters, Iterators, Mediators and Memento handle single Responsibility!

Taking away one concern (such as logging, concurrency, traversal) and representing it in one full-fledged class to simplify the representation of another (entity) class better is underlying idea for several of GoF patterns. This helps the served class to narrowly focus on its core responsibility. If we were to extend the Single Responsibility principle to cover “separation of concerns” then we have a more emphatic way to cove several other GoF patterns

 

Open-Closed Principle

A module will be said to be OPEN if it is available for extension. It should be possible to extend the module with ease. A module will be said to be closed if available for use by other modules. The principle for module is extended further for defining boundaries of class.

        The basic underpinning thought is that classes should allow extensions, but it should not necessitate modifications to use it. Put simply, the interface for classes should be such defined that it allows adding of new functionality by extending (subclassing) the interface. At the same time, the interfaces should be stable enough so that modification of existing code is not needed the class code is reused.

        In object-oriented paradigm, adding code to enhance the functionality by extending the interface is welcomed. However, if code reuse necessitates adding too many branches and changing existing code, then the software design is deemed brittle. This principle makes perfect sense as changing existing code increases demand for tests and make the software fragile. Adding code by extending interfaces, however has less ripple down impact and places less demand for re-testing the delivered software.

        Software maintenance phase is true test of how well the implemented software has adhered to the Open-closed Principle! Open-closed principle enhances re-use by localising of changes

GoF Patterns Application

Bridge pattern: An interface in an inheritance hierarchy can be published, and the implementation is done its own inheritance hierarchy. This helps the library provider change implementation without impacting client code, as long as they have stable interface. The design of extensible interfaces as proposed by Open-closed principle clearly serves as a guidance in implementing this pattern.

Visitor: The main problem tackled by visitors is that there is a resistance to change existing class hierarchy of working code. However, there is a need to add functionality to all the related objects. Visitor pattern comes to rescue by introducing another visitor interface that helps us add functionality without modifying the existing working code but by adding functionality in visitor classes.

Iterator: Developers are reluctant to adapt code in each container for specific traversal mechanism. So, a full-fledged class that exposes container’s traversal mechanism called Iterators is created. This makes container’s interface more stable and extensions for different traversals techniques can be added in Iterators.

 

Liskov substitution principle

This principle emphasis careful subclassing and judicious use of inheritance. The child class inherits all the public and protected interface of the base class, so its concepts must conform to the base class characteristics.

Inheritance defines a very rigid relationship between derived and base classes (interfaces). Changes in Base classes often trickle down to the derived classes. It extends the Open/Closed Principle by focusing on the behaviour of a superclass and its subtypes. This principle together with Open-closed principle serves to provide blueprint for defining cleaner interface and class hierarchy.

GoF Patterns Application

          Abstract factory: While defining the class of related products, extra care is taken to extend the Factories of related objects. One abstract interface is exposed to client and the Concrete Factories implement the interface.

 

Interface Segregation Principle

This principle suggests that when we are faced with a complex interface then it is best advised to break it into distinct simpler, single concept representing interfaces. Doing this will save the designers of concrete classes from inserting dummy implementation in the concrete classes if the concrete classes do not have really need to implement that method

GoF Patterns Application

Segregating interface into smaller neat interface avoids bloated interfaces. Much like Single Responsibility Principle applied to designing classes the Interface segregating principle serves as a guideline to design lean interfaces.

 

Dependency Inversion principle

High level modules should not depend on low level modules but instead both should depend on higher level abstractions. Alternately, abstractions should not depend upon details but conversely details must depend upon abstractions. This aims to reduce the coupling between the classes by introducing abstraction between the layer, thus doesn’t care about the real implementation.

The idea is higher level abstraction are more stable than the lower level implementation details. The lower level implantation has to absorb much more variability. If the dependencies are on the implementation details, then very likely the software will be fragile.

Client code should write code against the interface of the classes rather than against the concrete classes. This will reduce the changes in client code should a change in the implementation of classes that provides the API changes

GoF Patterns Application

Bridge (pImpl idiom) The client is provided a higher-level interface class which provides stability to the client code. The implementation hierarchy separately absorbs all changes in implementation. It’s a classic case of Dependency inversion.

Factory method and abstract factory also recommends that client code should depend on the Factories for object creation. The factories are higher-level interfaces, defined just for object creation. This directly confirms to Dependency Inversion principle. Similarly, in prototype pattern the client code again depends on the interface class that exposes “clone” method rather than on concrete classes.


Friday, September 2, 2011

Noises, the dampening factor

It all started with one of my friends claiming that old melodies are still lively for all they are worth and that the present day music simply does not compare with the music of 60s or 70s. He went further concluding that the new songs have a "short Ear-life" as compared to the older classics because present day music has something seriously lacking.

Not that I don't love the old melodies, which are dear to me and they have the same soothing and cathartic influence on me as on most of us. But do we attribute the "short Ear life" of present day music to sloppy work done by our present day artists.

But a little thinking would reveal that it is not the complete story? How do we account for following occurrences?

The great depression of 1930s had a massive impact lasting several years and it took two US presidential tenures to restore the economy to its original health.Why did we have a typically such a long business cycle in yesteryears. The world witnessed a massive stock market crash in 2001 and the markets began to respond positively the very next year. Is it equally true that depressions earlier were the greatest ever? While it is beyond doubt that depression of 30s was a major one and it dwarfs present day's crises, it is equally true that present economic system is both more prone and resilient to all the crest and troughs of business cycles. Present day boom and busts have a shorter life too.

Here's second instance of difference between then and now.

Leaders like MK Gandhi, Lenin, Churchill impacted lives of millions of people and remained iconic throughout their life. Why do we not have leaders with such huge following these days. Today we have a bunch of professionals, who are trained in behavioural sciences, have more sophisticated speaking abilities and enjoy more media coverage to market themselves, but they fail to click. Are leaders of today as ineffective as today's music. Today's leaders have short intervals of fame and fade away into oblivion once the media decides to turn its energies on something more newsworthy..

Why do the bestsellers today have very short duration of iconic popularity? Are authors of today also slowly decaying or they do not match the originality of the classics?

Or do we wonder why in the highly networked world of today, where all information is at fingertips, being creative is more challenging than ever. In no time a really cool idea becomes bland, a witty wisecrack becomes obsolete cliche very quickly.

How do we account for all the above phenomena?

Let’s connect the rather seemingly unrelated dots and interpret these phenomena.

First lets define the key terms in the the discussion. For brevity let’s use term "pattern" to describe some recurring phenomenon. The pattern is then said to recur over a sample space, which is sum of pattern itself and a large non-recurring theme, which for brevity lets name it "noise".

A pattern is distinct or stands out only if searching for the pattern is relatively easier in its sample space. The noise essentially impairs this searching by increasing the sample space, making the pattern less discernible. Yes, by now as most of you have guessed, I blame Entropy (noise) for all above mentioned effects.

Why do we have increased noise?

Human progress, both in number (population) and the increased complexity of living has resulted in exponential growth of noise.

We have greater number of singers and more music is produced than ever. Also we have easier access to music. No wonder a really rocking-happening song turns bland in matter of days.

Increasingly complex economy which resulted from globalization and use of technologies has made the business cycles short. Our boom and bust phases (business cycles) are short. Gone are the days when we will see increased sustained growth for decades. Also gone are the days when man and his government will toil for decades to endure a bad phase. The reasons for shorter cycles are increased business activity and increased sophistication in the way business is transacted. We have ideas that are cool make billions in a few months and we see giants collapse in short span. Alarming is the growth of noise in business sphere too.

Leaders have an uphill task these days to have increased following as the dissension creeps in easily. It is not difficult to explain that unbridled reign and brute majority is secured by a government only in those places where noise is less. By less noise in political sphere I mean a weak ineffective opposition, low penetration of media or a repressed society all of which sum to give less political activities and hence less political noise. In mature democracies people mostly have mixed opinions.

People have increased access to books, ideas and information. The data generated these days is more than ever and is still increasing at an exponential rate, and social networking sites have had only a multiplier effect. A witty or a serious thought-provoking idea is only seconds away before a social networking site makes it so public so as to be unoriginal.

Same applies to the book authors who have to battle to maintain the creative space and be original and popular.

I have not much fair idea how much maths is used in social sciences. however a persuasive argument can be built as follows.

The term derangement in combinatorial maths refers to number of ways you could place an object in incorrect position, which is essentially the noise. The derangement function grows very fast with increase in number of objects (factorial function). When we increase the sample space we are blurring the pattern very rapidly.

Thursday, November 11, 2010

Sea of change

Politics presents a grim picture everywhere and in Bihar its even worse. We have caste equations, communal issues, strongmen and their henchmen ( list is pretty endless). However there's a ray of hope and not everything whats going on is wrong.

I boarded the train from Calcutta and then one of my companions started heaping praises on Nitish administration. Mostly all agreed and gave him a thumping yes. He quoted the popular incumbent chief minister saying "30 years of mediocrity cannot erase thousand years of excellence !!". It might be noted that during last three decades has seen Bihar plunge in deep recess.

Also state secretary Mr NK Singh won applause from everybody sitting around.It was argued that first time voters from Bihar had talked about development issues rather than caste loyalty. Statistically speaking mostly a huge voter turnout always benefits the ruling government, an indication of people showing confidence in the administration.

With lots of positive vibes in air I got down in Bhagalpur on Nov 1, which was a polling day. Elections in Bihar are different from the rest of the nation. Anticipating trouble the markets are closed, educational institutions are shut sine die, and even private vehicles are seized for movement of security personnel. 6 phase of polling in Assembly elections might seem security overkill, but owing to Maoist challenge, private armies and local goons this was a necessity.

This time I also got a chance to travel by roadways extensively and this is when I could sense some real change. Its surprising that so far Bihar lacked a functional state transport corporation and people were happy to see BSRTC back on roads afer a decade of non existence. Law and order situation has considerably improved and prosecution rate has gone up tremendously. People were relieved that even dreaded places like Siwan, Jehanabad and Munger guns are silent. The autowallahs took pride in saying that roads were excellent travel time is drastically reduced.

Nitish has his share of critics too and people in Bihar are very observant when it comes to political subtleties. I want to quote here another self proclaimed political analyst. "Law and order is fine as the major bahubalis are busy minting money on road contracts and over two lakh unemployed youth have been pulled in for "sarva siksha abhiyaan" or state police". Thus the state has gone ahead with mantra "if you cant fight them join them". This observation is rather simple, direct and hard to contradict. The trickle down theory that everything falls into place if there is good governance at top, does not entirely hold true, as corruption permeates all levels.

However people take respite in the fact that for the first time in over two decades plan money is actually being disbursed. With the mammoth level of state expenditure corruption in backward state of Bihar is inevitable. The gains made in last five years are hard to ignore and the new government which will assume power after Nov 24 will have large shoes to fill in. Regardless of which political party gains control, it should be able to build on these achievements and hopefully next five years will be dedicated to installing proper checks and balances while keeping the growth story intact.

Thursday, June 10, 2010

Nuclear liability bill : Liability thrust on Indian masses

What minimum sentence do you award to individuals who by their negligence kill 25000 people and leave many times over crippled with multiple disabilities. The negligence was not ignorance but it was under full cognizance of management who would rather save money than save lives. The commision report clearly indicts the top exectives of ecouraging and even driving the cost cutting measures. It reminds of a famous quote in Fight Club where a top executive rubbishes recall of cars, which was quite accident prone, on the grounds that the cost of out of court settlement times the probability of accident and death of people was lesser than the cost of recall (A very valid economic justification indeed!!)

Even petty theft are met with harsher punishment than these white collar executives who walk away with 2 years sentence and are in fact granted immediate bail. The entire state machinery has let us down. First it was legislators and executive who cheated us by inviting Union carbide without adequate safety laws and letting the perpetrators escape. Then it was judiciary's turn to deal final blow and make mockery of victims by letting the guilty walk away while, hundreds of thousands, waited for over two decades for justice.

Does our government really value Indian lives? The state which gets a fair share of royalty and taxes from the corporations have relieved themselves from their most fundamental responsibility of protecting her citizens. To add insult to injury we have a monstrous nuclear liability bill which seeks to set upper limit on a firm's liability in case of major mishaps. Perhaps nowhere in the world the state seems to have connived with few foreign players against her own citizens.

Well a small bit of digging should reveal very outrageous clauses which are bluntly rude and discriminatory. The bill indirectly lets the manufacturing corporations (read finely it is the Westinghouse, Generic electric, ABB corp.) free from any financial of legal liability in case of mishaps. The only entity which shoulder have limited liability are the operators (read finely it is the state owned NPCIL) to an extent of 500 crores. The state (taxpayers) are left with unlimited liability. Such is the doublespeak that in this case the victims (common people by virtue of being taxpayer) are held accountable for lack of due diligence or simply some ruthless cost cutting measures for profits by these Western manufacturers.

The bill doesn't just stop here. It goes to the extent of disallowing the victims a legal recourse against the manufacturing corporations. The only entity which can hold these corporations accountable are the operators and all they have is period of 10 years to settle all claim after which it lapses. Considering the pace of judiciary world wide this virtually reduces it to a no ops.

What is shocking is the manner in which the clauses were added to the bill as it openly flouts all standard norms and canons. What is even more shocking is the haste manner in which our "Dumb Manmohan Administration" tried to table the bill in parliament. People by now must have serious doubts over saneness of Indian interlocutors who claim to have clinched a win-win deal.


Does this bill gives India any tangible gains.... however remote it may be??
The answer is a big NO.

The fact that US froze all major R&D programme in civilian Nuclear program after 3 mile incident is well known. France which meets over 90% of her energy needs through nuclear plants is way ahead of US in this arena and is willing to help India without these severely limiting bills. Thanks mostly to Bhabha's efforts Indian nuclear establishment, totally indigenous, is perhaps unique in the world as it harnesses abundant and cheap Thorium. Strategists foresee cheap electricity, increased R&D footprint and more jobs on Indian soil, only if the Government is ready to rely on the home grown technology.

What I fear is that we will see offensively priced power produced by three decade US technology being subsidised by Indian taxpayers, who will also have to brace for all mishaps on their own.

We have not forgotten the Dabhol episode, when the government was held ransom by few private players and was asked to subsidise their reckless way of operation. We seem to be incapable of learning from failures. Just two years back three major Indian companies won bid for cheapest cost per unit of electricity for four mammoth power plants. We seem to be incapable of learning from our successes too.
The situation here reminds me of British era of "drain of wealth", when we subsidised British merchandise at the cost of Indian industry. Even today it seems law governing Indians are being drafted by US interlocutors. Colonialism is back in a new garb and we are not complaining, but the Government is taking pride in embracing it.


















Manmohan Sir, Sure We do need FDI for development but not at the cost of selling out the entire nation.
































Friday, May 14, 2010

"Hello World"

The term "Writers block" for an amateur as myself would be by no means an exaggeration but it helps to highlight my present state of mind. Writing is something that i would be starting
after a long pause....pause significant enough to seriously slow down not just keystrokes,
but also put you in a jinx and then you start treading cautiously what to pick to write about.
Well.. despite a few concerted efforts, I was never a regular blogger.


Long back i had read about various quirks people adopted to counter writer's block.
There was a once a poet who immersed his feet in cold water to overcome his mental block.
Poets and Painters often turn to their "MUSES" to seek inspiration.
Philosophers trust their eccentric companions or totally isolate themselves to counter it.
Then there are people whose creative juices flow once when they have imbibed enough spirit.

I belonged to none of the above group so I took a bit different path..
I took a walk..and a cup of tea. None of these actually helped. So i figured out was mental block
was something that cannot be cleared by some standard operating procedures.


Well we always have a hitch before we start something new or revisit something that has gathered moss for a significant period of time.

I had a hard time deciding to pick topic to break that jinx. There was another realization in queue... waiting to be discovered ..
Selective elimination of options does not necessarily result in selection of one.
So here I sit waiting for a something interesting to write about.
So Stay tuned and suggest me some of your worthy inputs, ideas and shape my writing :-).