Stairway Pattern

How do you feel when you invite your friend for a private family function and he brings along a dozen strangers (his friends) ?

 

Entourage Anti-Pattern

This is similar to the scenario when you want to add a library as reference and in turn ends up referring a different set of libraries which you are not directly dependent. This scenario is perfectly defined by the Entourage Anti-Pattern. The Entourage pattern also describes the (avoidable) practice of packaging the abstraction and implementation in the same assembly.

The Stairway Pattern

The stairway pattern describes a better alternative by organizing your abstractions and implementations in separate assemblies, which in turn allows both to evolve and vary independently.

It also means the references now doesn’t bring an entire entourage of assemblies along. One of the thumb rules you can adhere too is to ensure the abstraction assembly doesn’t depend on any external references.

Looking back at DRY

Continuing with our series to bring together the common design patterns and principles, we will, in this particular post, look into arguably the most famous design principle known to programmers – DRY. Don’t Repeat Yourselves – or DRY, is possibly the easiest to practice, at the same time, one that could go wrong in the ‘rush hours’ of project deadlines.  The principle, as you would be aware of, aims in reducing/eliminating duplicate software patterns in the system.  The Pragmatic Programmer describes DRY principle as follows

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system – Andrew Hunt, Dave Thomas

The evils of a non-DRY system is obvious.If you have same functionality defined in two places, and you forget to change in one of the place when the functionality changes, you are left with a system that is self-contradicting. The principle doesn’t exclusively apply to code, but rather it applies to documentation, comments in code as well. Consider a scenario when the developer changes the code, but forgets to change the comments associated with the code, the result could be a future developer banging his head to understand what is now an obsolete comment.

The duplication could be broadly categorized into four categories (again thanks to Pragmatic Programmer).

Imposed Duplication
There could be scenario’s when the Project Specifications or the technology limitations imposes duplication on the development team. Such scenarios are hard to tackle and the near perfect solution would be localize the impact of violation.

Inadvertent Duplication
This kind of duplication involves scenario when the developer doesn’t realize they are guilty of duplication. This could be resultant of a rather imperfect design.

Impatient Duplication
This is the most avoidable of the four categories of duplication and describes the scenarios when the developers are lazy or pressurized with deadlines, and end up finding shortcuts via duplicating. However, the develop team as a whole needs to remember that this tiny shortcut could lead to catastrophic impacts in latter stages of project

Interdeveloper Duplication
Most commonly seen in large disconnected teams and possibly the hardest to detect. The developer in one sub team could duplicate a functionality which was already developed.

DRY, as seen from above, is possibly the most easiest of Design Principles to master, if you are always on your toes. The key lies in keeping an eye on the bigger picture of project, refactor your code regularly.

Command Query Separation(CQS)

One of the side effect of using a method out of a library (for which you do not have source code) is that you are not pretty sure if it changes state of a related object. And if it did, when you are least expecting them to, you might have more headaches than you could imagine.  But what if the creator of library had struck with the CQS Principle ?

 

Command Query Separation

CQS, or Command Query Separation was introduced by Bertnard Meyer and it states that every method should be either a command that performs an action, or a query that returns data to the caller, but not both.

Or in other words, Bertnard Meyer wants us to separate our methods into two broad categories, Commands and Queries. Commands can change observable states of the object (and hence has a side effect), but doesn’t return a value. On other hand, Queries does not change states of the object and returns a value. It doesn’t have a side effect and can be called any number of times without having any implication.

The advantage of adhering to the CQS Principle is that the Client have a clear understanding of which methods would be causing a side-effect on the object state and which doesn’t.
Code Samples
// Queries
PersonInfo GetUserDetails(int userId);
// Command
void UpdateUserName(int userId, string userName);
However, it is not always possible to follow the CQS Principle. There are times when you would want to modify the state and return an object as well. The most noticeable example is when you work with Stacks. Consider the following code.
Stack sampleStack = new Stack();
sampleStack.Push("DummyDataString");
var fromStack  = Test.Pop();<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
As you can see from the code above, the Pop Method of Stack Object not only returns a value, but modifies the state of Object as well. The same applies to Queue as well. Likewise, there might be scenarios in our code wherein we would like to do both state change as well as return value with a method. Hence, CQS is a good principle to follow whenever possible, but one needs to be aware that there could be exceptions.

YAGNI Principle

We developers have a common problem – We tend to overthink and over engineer. We tend to over think into the future attempting to foresee some of the features that we might require in the project. But most often than not, those features might require a lot of changes resulting in technical debt, or not used at all.

YAGNI

This is the issue YAGNI or You Aren’t Gonna Need It intends to resolve. The YAGNI Principle states that we should implement features only when we actually need them, and never when we foresee that we might need them.

YAGNI is the crux behind XP’s (Extreme Programming) Practice of “Do the simplest thing that could work” and Emergent Design which encourages developers to design only for the features that is actually needed, unlike Big Design Up Front (BDFU). This reduces a large amount of unwanted work, and avoids feature creep, resulting in avoiding cost of delay.

Think about it, if you are including features that you don’t require now, there is additional cost of delay due to additional development and testing. And to think you might never actually need that code might have you banging your head cursing your assumptions which resulted in writing the code.

YAGNI discourages developers to work on features based on assumptions that you might require it later on. In fact, YAGNI aligns with the Occam’s Razor (modern interpretation for Software Development) which states among competing hypothesis, choose one with the least assumptions. This is what Lean Software Development teaches us as well, to delay the decision making as much as possible so that decisions can be made based on facts rather than assumptions.

Fail Fast Principle

There are 3 keys ways a developer usually approaches error handling in code.

  • Ignore
  • Fail Safe
  • Fail Fast

We have, at different point of writing code, used all three approaches. There are times when have good reasons to ignore a particular exception scenario, while at other times, we are opt for Fail Safe approach.

Fail Safe approach never hides the exception, but rather, delays it until it is safe to raise it. This is a reasonable approach, considering we are now swallowing an exception. But there is a huge problem with this approach. Most often than not, the Fail Safe approach makes the application to fail slowly, resulting in the system to continue working smoothly when the exception occurs and then fail later on. This, as a developer, inevitably leads you to spending hours debugging your code to trace a bug. What would have been a better approach ?

Fail Fast Principle

Fail Fast Principle that has its heart in Defensive Programming, encourage developers to fail fast and visibly when an exception occurs. The biggest benefit of this approach is a faster feedback loop. In early days of adhering to this principle, you might end with a lot frustrating moments as you might think your have build a fragile software, but remember, it is always better to fix the bugs upfront, than to have the customer face them. The Fast Fail Principle does exactly that for you and aids you in building a robust application.

That doesn’t mean that you should completely ignore the first two approaches. This is the guidelines I keep for myself.

  • Use Ignore, only when having really specific reasons.
  • Use Fast Safe, when it is a critical piece of code, and Failing Safe is a better approach
  • Any other times, Use Fail Fast.

 

Patterns,Principles and Programming.

Have been thinking about putting together a collection of Jump Start Tutorials on some core concepts on Programming, finally getting everything together

Design Patterns

Design Princples

Code Smells and Refactoring Techniques

 

SOLID : Open / Closed Principle

The Open / Closed Principle focuses on one basic requirement, the classes should be Open for extensions, but closed for modification.

The better way to explain the principle would be to first express the issue in hand. Consider the below class.

image

The class itself looks good, but what if in future one needs to add another Shape, say Circle. This would raise need to modify our existing class which is violation of OCP.

The solution to problem lies in achieving extension by deriving from abstraction. Let’s rewrite the code.

image

As you can see in the above implementation, we have created an abstract class with the function we might require extension. The corresponding classes, Square and Circle, implement this abstract class and extend its functionality. So when the requirements changes, and you need to extend, you needn’t change the existing classes. This means the classes which are properly tested needn’t be touched again and thereby reduce chances of introducing bugs in existing classes.

The Chain Of Responsibility Pattern is yet another way of achieving Open Closed Principle