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

Github: https://github.com/mickaj/SheetMetalArranger

 

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

 

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

GitHub: https://github.com/mickaj/SheetMetalArranger

 

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!

GetNoticed DEV#1: Updates in Guillotine implementation

Greetings!
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 (https://github.com/mickaj/SheetMetalArranger). I encourage also to view other repos in my GitHub account. I would much appreciate your comments, suggestions and criticism.

Thanks and good luck!