Design Patterns #9: Composite

Design patterns episode 9 – Composite

With unexpected delay but patterns are back! In this episode – composite.

The composite is generally used to model tree-like structures in a way that classes that are using the composite can handle its elements in one particular way without having to distinguish whether an element has children – a composite, or hasn’t – a leaf (in other words, whether we can go further down the tree or element is a dead-end).

The first thing that comes up when thinking about that kind of structure would be a directory tree where folders are composites and files are leafs. Or any other structure alike: corporate structure (managers and subordinates), online shops (categories and concrete items) and many many more.

DEFINITION
Let’s see how the Head First book defines this pattern:

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets client treat individual objects and composition of objects uniformly.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004) 

So, in other words we have tree structure of objects and collection of objects and the client doesn’t need to care about if it’s a leaf or a composite. This is the key feature of this pattern. For instance, let’s think about file system where we have files and directories. Both of them are elements of file system and should be treated the same: the client can perform the same operations on both – rename, delete, get size etc. But obviously we can do more things with directories (as this is a collection of files and directories), therefore composite pattern isn’t applicable here (of course you could use typecasting to make it work but that’s a different thing).
The diagram shows what discussed above – both concretions are treated the same, nothing different can client do with one or the other type. The diagram presented here is different than what’s in the book. The book adds further methods: add()remove(),  getChild(). But isn’t that inconsistent with the definition? How can you add a further child to a leaf? You could throw an exception but wouldn’t that violate the Interface Segregation Principle? That kind of issues have been greatly discussed here by the guy who I quoted on multiple occasions.
So, to conclude this aspect of the pattern – my opinion is that we should stick to ISP and not force any class to implement something that the class doesn’t use. Period. Let’s move on to code example.

EXAMPLE

In our code example we’re going to build a store’s menu. Let’s start with the abstraction:

Our IStoreElement consist of name property and a method to list self in the menu: there will be different implementations of this method for leaves and composites. This method can take optional argument as we want to nicely format the menu by indentation of sub-components.
Now the leaf class:

Leaf’s implementation of ListOut() method works that it returns a string with given number of dashes and its name.
And finally composite class:

This class is equipped with private list of objects that implement our base interface. This list can be set in constructor.
The ListOut() method starts with the same thing that counterparting method in leaves but before returning the value recursively invokes the same method for all IStoreElements that the composite holds in its private list. This invocation takes indent parameter increased by 1. This way we achieve that nice formatting of the list once requested in the topmost component.
Now, let’s see how it work all together:

We generate the list and then print to the console the string returned by ListOut().

To sum things up: he Composite Pattern is used to represent tree-like structures where all their elements can be treated uniformly, where single components are called leaves and collections of components are called composites. The pattern can be equipped with methods to modify the content but this lead to violation of Interface Segregation Principle.

Next week: the State Pattern. I hope that this time without any delay. Check the links and source code below. Thank you!

Composite pattern by Christopher Okhravi: link [YouTube]
Composite vs. Decorator by Christopher Okhravi: link [YouTube]
Composite pattern by Michael: link [YouTube]
Source code: TXT file

GetNoticed IT#7: S-O-L-Interface Segregation Principle-D

Hello there!
Today the last ‘episode’ of my SOLID series. The only only that is left for today is Interface Segregation Principle.

Clients should not be forced to depend upon interfaces that they do not use. [see here, page 5]

In practice, this means that implementing an interface should force a class to implement only those features that the class actually uses. Nice example is give by Piotr Zieliński here after oodesign.com. But let me add a pinch of my own imagination here. Let’s think about workers. A worker is someone who does some work and gets paid for it.

Nice and clear. No problems. But we live in 21st century, a brave new world! We can use robots to do some work. But the problem is that a robot doesn’t need to get paid. So, you either throw an exception or leave implementation of this method blank. But that’s not a right approach.

Chris Klug even brought up an example of MembershipProvider (which is an abstract class not an interface to be precise, but that depicts a problem with complex interfaces in a pretty good way.) in ASP.net where it was almost impossible to implement all features!

So, the  general rule is smaller but more rather than complex and few. Benefits we get from following that approach are multiple. First of all, if we break code to smaller pieces it is easier to get it, it keeps the code clean. Secondly, you don’t need to worry about something you don’t need, you don’t have to write empty methods or build properties your class will never ever use.
Let’s update and expand our example little bit to follow the principle. I’m going to split IWorker interface into three separate interfaces: ICanWork, IHuman, and IRobot. Additionaly IRobot will get PowerConsumption property.

That seems to be written better than the initial code, doesn’t it? But now, our factory needs to keep track of how a robot is performing. In order to do that we need to log all the work it is doing and count its total power consumption. That leads to a problem. First thought is to write a new class and inject a RoboWorker. But that would result in the Dependency Inversion Principle broken. We could do that or inject RoboWorker twice: first as IRobot and second as ICanWork; or else inject it once and then use “ICanWork as IRobot” statement.

But that is terrible, terrible idea as there is no way to be sure that object you will inject into PowerCounter implements IRobot interface. So, don’t even think about it as there is a better way – some call it super-interface. You simply create another interface which inherit all required interfaces and make our RoboWorker class implement that interface instead of two separated. In our case it’s going to be ICanWork and IRobot.

[edited 24-04-17]
I have been thinking about that solution given above and I couldn’t get rid of this feeling that it’s not the best way. And in fact it isn’t. First and foremost, in our example we had first written our class RoboWorker so it implemented two interfaces and then we replaced them with one interface that combines the former two, and that is violation of Open/Closed Principle – once a class is done it’s done. So better solution for PowerCounter needed here – generics to the rescue. PowerCounter will take generic-type parameter T which implements both interfaces implemented by RoboWorker.

In the above code PowerCounter class has one T type field which holds reference to an object supplied in the constructor. Usage of this would be as follows:

Now, it is nice and clean.

That’s it. Seems that I have now covered all SOLID principles. Hope you enjoyed!
Cheers, Michal

Sources:
https://www.youtube.com/watch?v=MrvwDLEBIjo
http://www.pzielinski.com/?p=424
896isp.pdf by Robert Martin
https://jeremybytes.blogspot.ie/2013/09/applying-interface-segregation.html

Me about SOLID:
Single Responsiblity Principle
Open/Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle

 

GetNoticed IT#6: S-O-Liskov Substitution Principle-I-D

Greetings!
It’s time of next part of my SOLID series. It is one but last and it’s going to be about Liskov Substitution Principle. The principle states:

If a type ‘T’ is a sub-type of type ‘S’ then objects of type ‘S’ must be fully replaceable by objects of type ‘T’.

This means that if any class is inherited from a superior class then it must be possible for any object of superior class to be replaced by any object of a sub-class without introducing any unwanted behaviour of the code.
The simplest example could be class Rectangle and a sub-class Square. Rectangle has two properties: Height and Width – with getters and setters. Square is derived from Rectangle but its properties are written in that way that changing one dimension also enforces change the other dimension. Now, if we run the below code:

The area of a rectangle 5×10 should obviously be 50. However, result given by our code will be 100 which is doubtlessly incorrect (more on this example here).
Now, the question: how to follow the principle? There are some conditions your code must meet to ensure that the LSP is followed.

Contra-variance of arguments in sub-type methods, co-variance of types returned by sub-type methods: this means that (a): overridden methods in sub-class must accept more generic arguments, and (b): types returned by those methods must be more precise. However, C# does not allow for that so it is necessary to stick with return types and arguments defined in base method’s signature.

No new exceptions thrown in sub-class unless exception types are derived from exception types in base class.

Pre-conditions for a sub-type method are not stronger than for counterpart method in base class: this means that conditions that must be met to successfully invoke a method must be less or equally conservative in sub-class than in base class.

Post-conditions for a sub-type method are not weaker than for counterpart method in base class: this means sub-class method must be more or equally conservative on its results than a counterpart method in base class.

Invariants from base class must be kept in sub-class: his means that if a certain method in a base class does not inflict a change in one property, the same property cannot be changed by counterpart method in sub-class.

Pre-conditions and post-conditions are explained in a clear and simple way in the video below around 42:17 (or click here).

History constraint: this means that what’s immutable in base class must stay immutable in sub-class and what’s mutable in base class must stay mutable in sub-class. So, (a) the sub-class cannot introduce methods that allow change of what’s unchangeable in base class, and (b) if a base class provides ways to modify a member within itself it must be possible to change that in sub-class with use of those ways.

And that’s it. I have to admit that so far the L was the most mind-cracking part of SOLID. I hope that my explanations are clear enough for you. Apologies for no examples this time but I find those given in the video above are better than those I would invent. So, thanks for your time and good luck!

Links to resources used to write this post:
https://www.youtube.com/watch?v=Whhi1C2PpaA
https://www.youtube.com/watch?v=bVwZquRH1Vk
https://www.infragistics.com/community/blogs/dhananjay_kumar/archive/2015/06/30/simplifying-the-liskov-substitution-principle-of-solid-in-c.aspx
https://en.wikipedia.org/wiki/Liskov_substitution_principle
http://stackoverflow.com/questions/11331964/what-are-the-differences-pre-condition-post-condition-and-invariant-in-computer
http://serebrov.github.io/html/2016-02-18-oop-solid-l-liskov-substitution-principle.html

Links to previous posts related to SOLID:
Dependency Inversion Principle
Single Responsibility Principle
Open/Closed Principle

 

GetNoticed IT#5: S-Open/Closed Principle-L-I-D

Good evening!
The time is high to write new post. I’m continuing about SOLID principles. Today it’s “O” which stands for Open/Closed Principle. According to Wikipedia this rule was first defined by Bertrand Meyer in his book Object-Oriented Software Construction (1988). The rule states:

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

Or as others say:

Once a class is done, it’s done!

The idea behind those statements is that if we have a class and it is needed to extend it or modify we create new class which inherits either from our existing class (with use of overridden methods) or from abstractions.
Seems pretty easy, right? However, I still had a bit of a struggle to figure it out and comprehend it in my own way. It would be the best if I explain it on an example. My project for GetNoticed2017 contest is based on rectangles so let us consider an example with rectangles.

Our program has to perform some simple transformations of a rectangle. In order to do that we have a static Transformations class which consist of two methods that take a rectangle as an argument and return transformed one.

Currently our Transformations class can only rotate a rectangle by 90 degrees and scale it. And that would work perfectly fine up to the point where we want to add new transformation. In order to do that we need to modify Transormations class and that is clearly violation of OCP.
Let’s now rebuild our little system to be consistent with OCP. Key to that is abstraction – in our case that simple interface:

Now, we’re going to write separate classes for our two methods we’ve already had in Transformations class.

So, now we have everything we had before but the difference is that we now follow the OCP. Of course, way of use of these classes will be different that one static class. Let me show you that using unit tests:

As you can see our test class has a field of type ITransform which holds objects of our new transformation classes. Changing value of it we can freely shuffle with what operation we can perform (for example, instances can be supplied by an IoC container).
At this point adding new transformation is quite easy. But let’s introduce another type of transformation just for its own sake. Let it be cutting in half along vertical axis:

And that’s it. Open/Closed principle is followed. At this point you may ask question why. The example presented here is very simple, not to say primitive. But in real world classes are bigger and a little bit more complicated. So once a class is tested and running in production environment any change may inflict a bug. Not changing existing classes eliminates that risk. Obviously you can create a bug in your new class (inheriting from an existing class or from interface) but that is yet to be tested. There is no risk that you could break already tested and working code.

As a conclusion to this post and two previous related to SOLID I have one observation: ABSTRACTIONS are extremely important and useful.

Source code for this example: https://github.com/mickaj/OCPdemo

Here are some more examples of how to follow the open/closed principle:
http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/
https://www.youtube.com/watch?v=Z_VuxB5guuA

Links to my previous posts related to SOLID:
#1: Dependency Inversion Principle
#2: Single Responsibility Principle

Hope you’ve enjoyed reading this post and it will be somehow useful for you.
Good luck!

 

GetNoticed IT#4: Single Responsibility Principle-O-L-I-D

Hello!
It’s time to continue about SOLID. Last time I started from the last letter in the abbreviation so this time we’re going to go to the opposite end and talk about S.

A class should have only one reason to change.

Sounds simple? But what a responsibility is? Let’s think about database access class which handles extraction of data from DB and saving data to DB. So it can be said that this class has two responsibilities, right? That is why the principle sounds as above, not “A class should have only one responsibility” as the name of the principle suggest. Martin himself explains that very well here: youtube.com/watch?v=Gt0M_OHKhQE
I like to say that this principle means that there should be only one source of possible changes to a class. This is almost exactly as the formal definition but somehow when I said it this way the principle became clear for me.
The principle is also explained as below:

The single responsibility principle states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility. (Wikipedia)

So, to sum things up: the SRP inclines to create simple and cohesive classes that can only be changed by changing one requirement.

Now, let’s move on to an example. I don’t know how clear it is going to be but I can’t think of anything that is better and a the same time simple enough.
We have an Item class that is described by its name and its value. It also stores information how many items of a type we have available. An item can be sold, we can calculate its value after tax, shipping cost and our sell margin, and we can generate an invoice line for the transaction.

One glance at the code above and it’s obvious that the SRP rule is violated. First of all an item should not hold information of quantity available. It is store responsibility not item itself. Why? For instance, we we may want for certain items to implement auto-replenish feature. That’s definitely storage responsibility not the item. Or even better: we may want to calculate how many items of different type we have in store. How to do that if each item holds its available quantity?
Okay, so let’s remove storage responsibility to separate class. That class should be able to store different items and its available quantities. As we don’t want to create thigh coupling between storage and items we’ll start from creating abstractions of item class and storage class (which we’re going to built in a minute).

What Item can do has already been described above. Storage must make it possible to add and remove items, and check if an item is available. Let’s implement Storage class:

That’s done. So let’s move on to selling an item and calculating its value. Our case is simple and it might seem to be an overkill but I think that there should be separate classes to deal with selling (or maybe it’s better to say ‘processing order’) and calculating item’s value (after tax, with shipping costs added etc). The reason for this separation is in the principle. Why I want to separate selling an item: its requirements may change independently of calculating the value. For instance shop management decides to introduce extra discount. That changes only the way the value is calculated. It has nothing to do with the processing of sale. So, let’s begin with ValueCalculator.

ValueCalculator takes item, tax rate, margin rate and shipping cost in its constructor and makes available properties as follows: NetValue, TaxValue and GrossValue. That’s the responsibility.
Having the above done we can move on to separating GenerateInvoiceLine and creating new class InvoiceGenerator.  Its only responsibility is to return a line that can be pasted into an invoice:

Now it’s finally time for order processing (or SellItem method in initial Item class). It has to ask Storage if there is required quantity of ordered item available, and if affirmative it orders Storage to remove required quantity of item from stock and the asks InvoiceGenerator for a invoice string that is going to be handed to InvoicePrinter.

So, that would be it. Our example now follows the SRP. After all these changes our Item class now in fact has only one responsibility: to describe an item.

You can download final version of the code written above here. I hope that it is for anyone in anyway helpful. I also encourage to check the first post about SOLID here. It is about Dependency Inversion Principle. That’s it for today, thanks for reading and come later for more!

 

GetNoticed IT#3: S-O-L-I-Dependency Inversion Principle

Hi there!
One day I want to be professional dev. In order to do that I need not only to write something that works but also is written in proper manner. What that means? Every time that matter is discussed conclusion is always the same: properly written code is simple, testable, easily maintainable and expandable. Some time ago ca. 2000 a set of rules was established to achieved that. These rules were defined by Robert Martin and Michael Feathers and are called SOLID.

S – Single Responsiblity Principle
O – Open/Closed Principle
L – Liskov Substitution Principle
I – Interface Segregation Principle
D – Dependency Inversion Principle

Some say that the last one is the most important (for instance, founder of Get Noticed contest here: https://youtu.be/SnsIw3cZR5k?t=4m5s) as it allows developers to write loosely coupled (internal dependencies-wise) applications. For that very same reason I will start this short series of posts about SOLID principles.

High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.

It would be best to explain that using an example. Assume that we’re building an application to handle purchase orders. Let’s consider this small piece of code:

In our application we have two classes: Item which describes items we have to sell; and OrderHandler which handles an actual order by adding tax and shipping cost. In this case class OrderHandler depends on class Item. That is DIP violation. To fix it we need to abstract Item class.

In the code above there is ICanBeSold interface defined which has only one get-only property. That’s enough for our OrderHandler as it has only one method that returns total cost of ordering an item. That creates loose coupling between items and item orders. Changes in Item class would not inflict errors in OrderHandler (of course as long as it implements ICanBeSold interface). Another benefit of that is the fact that you can create multiple classes which can be used in OrderHandler.

Dependency Injection
Neat and nimble way to follow the DIP rule is dependency injection. This pattern is about designing your classes in a way that they use abstractions instead of concrete classes and whenever you need a concrete object to be used you hand the object to the class through class constructor, a method’s parameter or through property.

Injection through constructor
Let’s rebuild our application so different rules of discounting can be applied. For instance, we need to allow free shipping sale and abroad shipping. In order to achieve that we’ll create new class called PriceCalculator.

Take a look at the code above. Now OrderHandler class can be used to sell anything that implements ICanBeSold interface by rules set by anything that implements IPricingRules interface. What is that going to be is now passed to OrderHandler in its constructor.

So, actually there are two dependencies injected through the constructor.

Dependency injection through a method
If our OrderHandler is going to be used to do something more than perform one-time action it might be better to consider injecting a dependency through its method. It is very similar to what I have described above. The difference is that the dependency is given as a parameter to one of methods available in high level class. Let’s rebuild our OrderHandler again:

In the example above IPricingRules is injected to ProceedeSale method. That allows us to use different rules every time we want to do the sale. The example above has been simplified slightly by replacing item injection by simply giving its value in OrderHandler constructor. Now, take a look a the code below:

We’re proceeding with the sale twice but each proceeding has its own rules defined by IPricingRules implementation.

Injecting through property
Another way to inject a dependency is through property. In this case we simply create a IPricingRules property with both getter and setter. Now, every time we want to change pricing rules we simply set value of this property. Our rebuilt OrderHandler would look like that:

And here’s its usage:

Other means
However simple Dependency Injection is and, I presume, most common way to follow the DIP it isn’t the only way. For example, a delegate can also be considered as a way to achieve dependency inversion since a delegate is also form of abstraction. Let’s again rebuilt our OrderHandler class and equip it with a delegate to use for custom sales:

And its usage:

In the above we’re using Lambda expression as a delegate but here we could set whatever method we want including one from different class.
So, these are basics of Dependency Inversion Principle and Dependency Injection. Here are some recommendations where to look for further information about the topic:
http://plukasiewicz.net/Artykuly/DIP_IoC_DI
https://www.codeproject.com/Articles/159800/Inversion-of-Control-Practical-usage-of-Interface

In my next posts I will continue about SOLID principles and plausibly at some point I will write a post also about dependency injection containers.
So, thanks for reading today. In my case SOLID principles redefines how I should write code. This means that I need to restart my project again. But, as I see it, it is better  to write good code and maybe finish the project with delay or in impoverished version than to write something that works but is crap.
Good luck!