GetNoticed DEV #5: Slowly but forward

Good evening!
Slowly, but still – the project is moving forward. I’ve been rewriting my DLL following the plan (or as modern politician would say – road map). And of course during the process the plan has been amended. Most changes are cosmetic, the biggest change is that I introduced a sub-class inside Panel class – its responsibility is merging boxes in the panel. It is highly possible that available space would become highly fragmented during the execution of the Guillotine algorithm and some of the free boxes could be merged. The below picture illustrates the most simple case.

This is what Merger class will do. It is a sub-class within Panel class because I don’t see any other place where it may be useful.

Another thing that is worth mentioning is presence of singleton classes. I am aware of the fact that it may be considered as an anti-pattern but here I use them deliberately. The reason for that is my singleton classes don’t have any fields or properties, only methods therefore I do not fear any loss of data, unwanted instances or inheritance. I tried to implement that in most simple and safest way possible. I will probably write a general post about advantages and disadvantages of singleton, but here and now is no time and place for this.
Cheers, Michal

SheetMetalArranger on GitHub
Design sheet (*.xlsx)


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

896isp.pdf by Robert Martin

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

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:

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


GetNoticed DEV#4: Better late than never – A Plan

Hello there!
It’s time to write an update what’s going on in my project. My project is (or was) a a hastiness. I just sat down, launched VS and started typing. And this is not a good way to manage projects, not matter how small they are. I have written some code, I have first results, it can do some calculations and if I really wanted to I could build a user interface and present a demo. Maybe if circumstances are not auspicious I will be forced to do that and that would be a sad end to my project. But I still have some time so I will try to organise the project a little bit. Main reason for that is I’m getting lost. In order to achieve at least some level of order I prepared a spreadsheet with descriptions of all classes. If you compare it to code I have written so far they may be slightly different (not only names). But that’s another advantage of having that plan – it gives you an overview on the project which in turn makes you see that there are some areas where you can improve it. You can preview that spreadsheet by clicking here.

Before I decided that I need that plan I had written some more code. To those who are not familiar with what I am doing here’s brief explanation: you have big rectangle and you want to fit into that rectangle other rectangles. Biggest remaining rectangle is places in bottom left corner, container-rectangle is cut according to one edge of just placed rectangle and that gives you two containers. You take next biggest rectangle and place it into one of the containers you got by cutting. And you repeat that until all items are placed. There is a scenario where you can have two containers arranged in that way so one is extension the other. So it would be natural to merge them. And that is what I have written. No point in showing the code here, nothing interesting in that. But you wanted an update, that’s the update 🙂
Cheers, Michal



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:

Here are some more examples of how to follow the open/closed principle:

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 DEV#3: Going in circles is not always a bad thing

Nau mai!
I am a bit stuck. I have this feeling that I am going in circles. But I wouldn’t say in this case that it is actually a really bad thing. It’s more like going in circles but with each circle its radius is growing so the perimeter is also growing.
What I mean in that a bit literary sentence above? It means that in terms of functionality, efficiency or feature-wise (or whatever it’s supposed to be called) I didn’t achieve anything new. As it was mentioned in my previous dev post I have restarted the project. At this point I have rewritten everything I had before the restart. Only better. Still far from perfection as I am trying to take a leap into SOLID but way better that it initially was.

Here’s what it is all about:

  • as mentioned in DEV#2 all classes in the library are abstracted by interfaces
  • class ItemNester introduced to make it a bit cleaner to handle multiple sheets. Now it is only required to create an instance if ItemNester, give items to it and we’re good to start calculating
  • the most important thing: unit tests! Most of the methods are covered by unit tests. The class wasn’t built in TDD but the tests were a great aid for debugging

To enrich this post a bit I will also write here a bit of my approach to unit tests. Of course, I am using xUnit installed as a NuGet package. All tests are stored in a separate project (class library) and each class file handles tests for one class from the main project. Each test class has private execute() method and multitude of test cases.

Sometimes execute() method may return a value and may take arguments, it depends how your test is going to work. That is so-called preparation phase and it is optional. Although some may say that a well-written test should include that. I don’t know, I only know that it is possible to write a test without that (and I actually did in my project).
Now, we can move on an actual test case. In xUnit it is nothing more than a public method that is void but inside it’s body calls some specific methods. This method should be preceded with [Fact] or [Theory] attribute. So far, I’ve used only facts and I don’t know how theories work. That test method should check something. To do that we use Assert method.

That test above will compare 4 and result of 2+2 and if these values are equal report as passed. Of course, Assert.Equal is not the only thing you can check. You can check multiple things, for instance if a collection contains or doesn’t contain an item, check types, or if something is null. There are broad range of conditions you can check. Maybe someday (when I become more proficient) I will write something more about that.
That’s enough for today. I regret to say that but I’ve expected that to be easier and smoother but what can I do… No one ever said it was going to be easy. The good thing in that is that I don’t fell like I am wasting time. It’s a win win situation.
And in this positive attitude I’m saying goodbye 🙂