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

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:
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 DEV#2: Restart!

Hi there!
Those of you who read my post already know that I started writing a cycle of post about SOLID. As I mentioned in the first post of that cycle (here) I’m going to follow these principles (at least to extent I understand them). But I want to write less amount of good stuff rather than sh*t load of crap. Not saying that from this point no crap will come from my keyboard. It will but at least chances are smaller.
Let’s cut to the chase now. As I said the project has been restarted. I rewrote Container and Item classes which are now based on respective interfaces. Container class has one method that test if an item can fit inside. That method is covered by simple set of unit tests. Not much, but as they say: Rome wasn’t built in a day.
I hate to do that but again I have to make excuses. Progress I have made since last week is embarrassing. Majority of time I spend on my project is during the weekend. Friday I get home a little bit earlier from work and this evening I start working on my project. But last Friday was different. It turned out that Bus Eireann (Irish coach service) is on a strike – indefinite. So my whole weekend I spent on arranging alternative way to commute this week, which turned out to be buying a car. And here in Ireland it’s not that simple. You can’t just buy a car and just drive off as you are. First you need to get insurance, road tax and in some cases test the car. So that occupied me for the recent period.
I hope that was one-time only and all further weekends will be fully available.
Thanks, Michal.



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: 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:

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!

GetNoticed DEV#1: Updates in Guillotine implementation

It’s Sunday evening so it’s time to share updates on what has recently happened in my project.
I have to admit that progress isn’t as significant as I wished. This post is not to make excuses but I have to say a word or two to whitewash myself a bit. I started new job somewhere in the middle of February. The office is around 60 km from Dublin so I have to commute every day. To make long story short: I wake up at 4.30 am and I back home around 9 pm. That’s a long day…
Now, let’s get back to business. I want to follow the Guillotine algorithm in my project. Some may say that it’s not the best I could do. I agree, but for the time being that’s my decision. Who knows, maybe if I have some time to spare I will go for something better. We’ll see.

New things implemented from last week:
1) ArrangerResults class introduced. That allows items to be distributed into multiple sheets in case if one is not enough;
2) Calculate method in Arranger class can now check against an item being to big for declared sheet and exclude it from calculation
3) Item sorting is now achieved with classes that implment ICompare interface, which is instantiated by Arranger class
4) Checking if an item can fit into container and sectioning of remaining part of container after placing an item into it are now moved to separate methods in Arragner class (respectively method CheckIfFits and DoSection)
5) ArrangerResultsPNG class introduced which allows to create PNG file for arrangement

All the code I have written so far still needs some serious tweaks and refinements. However I am hoping to be finished with ArrangerLibrary by the end of this month. I’m sure that some updates will be required after this deadline has passed. But my plan for the application is that it’s going to be more expanded: more or less it will be possible to manage sheet cutting projects, store them and edit. This is still kinda blurry vision.

So, that’s it for today. Thanks for your attention. The code can be viewed on GitHub ( I encourage also to view other repos in my GitHub account. I would much appreciate your comments, suggestions and criticism.

Thanks and good luck!

GetNoticed IT#02: User controls in WPF

I’m continuing learning WPF. Recently, I’ve put my focus on user controls. As I did not spend too much time mastering WinForms I didn’t do anything in this matter so far.
Default controls library offers basic set of controls you can use to build a WPF user interface. It’s easy to find a case where the same set of controls will be used frequently in your UI. First thing that comes to my mind: a tabbed interface which display some data. To make it efficient it would be reasonable to create a pattern of how those basic controls will be used in our data tab, so once user open new tab it will contain this pattern. And a user control can be understood as such.
In this presentation I will prepare an application that display a person’s details. It will consist of list of users, buttons to show details of existing person and to add new person and a tabbed panel where the application will show details of selected (or new person).

The model will consist of two class: both public; one is Person class which describes one particular person some basic details, the second one ListData contains a list of all persons and some properties used to bind them with the UI. ListData can be more or less considered in this case as a view model.

To start building your customised control you simply need to add new item to the project and select WPF user control – that’s easy to find, no need to explain.
And here’s XAML and code-behind for the control:

The control consists of text blocks which display properties of person bound to the control. In the code-behind you can see a dependency property declared. It is of type Person (more on dependency properties here). That allows us to bind an object of this class directly to the control. What also needs to be mentioned is that the control is given name x:Name=”this”. That in turn is required to internally (in boundaries of the control itself) bind a dependency property to a certain text block in XAML <TextBlock Text=”{Binding ElementName=this, Path=ThisPerson.Balance}”/> .

As mentioned earlier class ListData would be our view model.  It implements INotifyPropertyChanged interface and shares two properties: PersonIndex and SelectedPerson. The first one is bound to SelectedIndex property of a combo box with list of all available persons and the second one is bound to our custom control.

What’s interesting is that setter for PersonIndex also changes SelectedPerson property. That works in that way that switching an item in combo box (which is bound two-way with PersonIndex) will also inflict a change in SelectedPerson.
That’s pretty simple way to build controls specifically for displaying data from custom objects. I would much appreciate if anyone smarter than me is reading that and thinks that it is not a good practice (as it is actually coupled with the model but I think it could be easily improved by introducing some abstractions).
Source code available on GitHub here:

So, that’s it for today. My plans for the weekend is to improve a bit the Guillotine algorithm I wrote implementation last week.
And here’s a goodbye riddle: in the demo you can find three persons defined. The last one is Pierre Aronnax. Who is he?

Cheers, Michal

GetNoticed DEV#0.5: Bin packing problem and Guillotine algorithm

First weekend of working on my application is almost gone. So the time is high to write a short report.
General thought: I am LOUSY mathematician. Not a mathematician at all!
During my student days I had never been good at it. Add the time that passed since then and you have the outcome.
But let me cut to the chase. Here’s short explanation for those of you who haven’t had a chance to read what my application is going to be. My plan is to write a program that will help engineers to optimise utilisation of sheets used for cutting flat items from steel plates. It is common activity in fabrication companies and multitude of software is now available on the market. So it’s not going to be any innovation or breakthrough.
Packing as many items as possible in given space is called bin packing problem. And there is multitude of its varieties (1D, 2D, 3D) and algorthims to solve it (shelf, guillotine, max-rectangles).
Currently, I am convinced to use guillotine algorithm. It is not the one that gets most optimal results but its implementation is quite simple and achieved results (despite that not the efficient) can be described as acceptable. So, that’s the current choice but I am not saying that it’s final.

Guillotine algorithm
Entry point for this algorithm are set of rectangles to be packed (height and width) and size of available sheet (again height and width). Rectangles are stored in a list. They will be attempted to be placed into available containers. Available spaces are similarly stored in a list. Each container is described by its height, width and bottom-left coordinates (X and Y). Initial list of containers contains only one item based on available sheet – the container has width and height derived form available sheet and bottom-left coordinates equal to 0,0.
First item from rectangle list will be placed in that only one container. After that is done the remaining space must be divided into two containers as shown in the picture below.
Decision how to split the remaining space can be based on various factors: arbitrary decision that we’re going to cut vertically or horizontally; by shorter cut-line; which cut generates a rectangle of bigger area; which cut generates a rectangle which is closest to square or which cut generates a rectangle which is most suitable for next item to be placed. It practical application it would be best to consider all options and take best results.

Next step is to place another rectangle from the list. We check which of available container can accommodate the item and which does that most effectively area-wise. And that continues until all rectangles are allocated.
To distinguish which rectangle is allocated and which container is taken I used separate lists. At the very end of each iteration I simply move the rectangle that has just been placed into a container to that second list and the same thing happens to the container – it is moved to second list.
There are also different strategies how to set the order of rectangles to be allocated. They can be sorted by area, by height or width, or by longer edge. Similarly to decision how to cut remaining space after placing a rectangle this strategy also generates different results. We choose the most optimal.
So, that’s basically it. If you wish you can check my first implementation on GitHub. But I have to warn you: the code is dirty as hell. But for the time being that’s just playing around. It will get cleaner and nicer 🙂

That’s it for today!
Regards, Michal.

GetNoticed IT#01: LQA tester episode


Despite the fact that ever since I finished high school I’ve been working in mechanical design (and fabrication as well for a period of time) I had a chance to taste the IT business. Sometime between November last year and February this year I worked for a game testing company. I was employed as a LQA Tester which stands for Localisation Quality Assurance tester. My role was to look for all localisation bugs.
The work itself was quite enjoyable even that I’m not a die-hard gamer (FM doesn’t count). So here are my reflections from that time.
Generally, it’s not a job a professional adult could do for a longer period. At least at the position I was employed on. The reason is simple: wage. I was employed on a project basis meaning that  I worked only when there was a project for me. I was able to step into this job because I had saved a bit of funds in my pre-LQA job. But if I had to pay full bills, eat and commute to the office without that backup money it would not have been possible. So in my situation it was like having a break from serious job.
What I enjoyed the most was that geeky-fell in the office. The crew members were mostly youngsters with real passion towards games and they were a bit odd in comparison to the rest of society. At least I had that impression. Thanks to that it you couldn’t feel that you’re working in a big international corporation. Tell me which major company would allow their employees to come to work with vividly coloured hair, ear plugs, tattooed fore-arms not covered with a shirt sleeves and wearing a Pikachu tee.
Now, let me say few words about the job itself. Basically, localisation testing is about finding all language mistakes and error in all localised content (that includes audio and graphics). Games that I was working with were in quite advanced stage so I had not much to do but all had to be double checked so I still needed to complete a game to the very end, exploring all possible options and features (there usually was a debugging tool that allowed to speed up the process, for instance a shortcut to instant kill of an enemy).
The issues I was finding were mostly some minor spelling errors, extra dot or comma. I had maybe on or two major bugs reported.
During my training days a lot of focus was put on cultural context. This means that localisation is not only 1:1 translation but actually porting a game to another culture. For instance, Japanese people are sensitive to issues related to atomic bombs (for instance. Fallout 3 and Megaton case); or it wouldn’t be acceptable to put nudity in Arab version.
To sum things up it was a great experience for me but I didn’t see any future unless progressing to a full-time. But all in all it wasn’t wasted time. I only regret that I didn’t have a chance to work on bigger project and in earlier stage of development.

Thanks, Michal.

GetNoticed/DajSięPoznać #00: Intro

While travelling to work today morning I decided to participate in this year’s Daj Się Poznać/Get Noticed competition. It is a coding contest where you need to do two things: built your individual project and blog about the project and IT.
The contest is demanding but no matter if I manage to reach the finish line or not it is a motivation and a kind of a whip that makes you work! As written in contest’s website: there’s nothing to lose. So, why not give it a try?
My project will be a program that arranges items in a sheet to maximise sheet’s utilisation. This is an issue that I often encounter in my job. I don’t know yet what algorithm I am going to use and how big the application will be. If you think about such program you can make it really light-weight with only base utility or go big and implement project management, catalogue of items, multitude of options. We’ll see what comes of it.
Here’s link to Daj Się Poznać website:
And this link leads to list of competitors:
So, that’s it for now and stay tuned!