Category Archives: Diseño

After seeing 1000 ctors

I heard it a lot of times. When I was learning Java, a flash definition about constructor methods faded away in the classroom. A “silly” definition that nobody seemed to remember a bunch of years later.

Sometimes the things that are easily forgotten are the most basic principles. We take them as a fact and we rarely reevaluate them.

One of the basics in OOP is the role of a constructor method:

A constructor method is a special method that contains ONLY the required initializations for the instance to be created in a valid state, ready to be used.

Said this, any constructor what invokes complex methods, services to retrieve data, contains lots of lines of code, or even loops, IS A MISTAKE and needs to be fixed.

A constructor has to be minimum! The instance should be created just in time and any complex initialization should be the responsibility of any other method of the instance.

This answer on Stack Overflow is very good. Be sure to read it 🙂 and keep you ctors clean!

http://stackoverflow.com/questions/1183531/how-much-work-should-the-constructor-for-an-html-parsing-class-do

ICollection vs IEnumerable vs IList

Por si las dudas, hermoso.

IEnumerable, ICollection, and IList (generally, any type with an I prefix) are just interfaces. They let you expose what your class will do, but unlike if you inherit a class, interfaces do not provide you a default implementation of any of the things they say you must do.

As far as choosing which interface, here’s a quick guide:
An IList is an ICollection that can be accessed by index.
An ICollection is an IEnumerable with easy access to things like Add, Remove, and Count.
An IEnumerable is anything that can be enumerated, even if the list of those things doesn’t exist until you enumerate it.

Some classes that you might want to extend (or keep as a private field that runs most of the logic) for your collection are List<T>, Collection<T>, (which implements IList<T>, but with easier access to overriding implementation, see Collection<T> versus List<T> what should you use on your interfaces? for the big differences between these two) ObservableCollection<T>, or collections that are not lists, like Dictionary<T, U> and HashSet<T>. For more info on any of these, look up the MSDN documentation on the class.

Translator Pattern. Know Your Patterns :)

 

image

 

This pattern is really simple. It provides a method to convert from a representation to another. The same concept can be represented in many ways. Sometimes you have to “import” and “export” representations, so you have to provide a proper encapsulation for the logic that converts from one object to another.

Why would you need to do that? In my personal experience I have used it to convert instances of “legacy” clases that are not too well designed. It happens that a lot of logic already exists in the solution that work with those clases, so redefining them would be really expensive. The brand new features use better an more robust clases. For newer parts, I use a translator to perform a one time time conversion. When a legacy part of the application needs a “new” instance, I request a conversion to the old class instance.

It can be seen as a pattern similar to Adapter or Builder. But Adapter translates interfaces and provide a “wrapper” that interacts between the outer world and the wrapped classes along all its lifecycle. Builder creates complex objects. It’s a similar pattern, but I don’t feel it’s the same as the builder doesn’t translate, it builds up an instance.

What do you think about it? Do you see a Builder here? Smile

Differences between Abstract Factory / Builder / Adapter

When it comes to patterns, it’s important to know the differences. Sometimes you have to name a class and you tend to call it “a X-builder”, or a “X-Generator”. But… are you sure you gave it the correct name?

It’s important to name things properly in our projects. From variables, to methods and classes. It REALLY matters. Even more when you are part of a team. When we are implementing a pattern we should give every entity the right now to avoid ambiguity.

In this particular case, those patterns may seem to do similar things, but they don’t. So, how to identify each one?

image

I hope somebody is kind enough to point out the differences between them. Come on, participate! Comments are welcome.

Handling selected items in a parent. Part 2.

Last time I tried to put you down to the problem: you have a container and some children. We wanted to handle the selection of items.

Until now we had to decide who will be the one that is in charge of setting the IsSelected property of each child. At first glance, we can see that the child itself is the Information Expert in which we can delegate the responsibility. After all, the children carry the  IsSelected property!

Well, I think it’s true, but that makes the design unnecessarily complex.

Why?

Imagine a Single selection mode! Just like ListBoxes have. Just one item can be selected.

I gave you a hint in the last post. It works as you should expect: Each click in a child selects it, but it also makes the previous children to be unselected.

“Wow, boy, it sounds pretty simple!”

I prepared you for the answer: it’s not the child that controls its IsSelected property… it’s the PARENT! In my opinion, it’s the only that can observe the changes and control the flow of events. If a child is clicked, the parent must know. Why? Because the it can decide if the change is allowed of not.

What way, you can even have some selection modes. For example, you can have a selection mode that toggles selection when a child when it’s clicked, or one in which you always add items.

In other words, it gives you a lot of variants to choose.

This is what I finally chose in my personal designer and I think it’s the right decision. What do you think? would you have solved the situation like me? Sonrisa C’MON tell me.

Handling selected items in a parent. Part 1.

When trying to make a good design you face situations in which you have to take a difficult decision that will easily affect the whole complexity of any  further development.

“Design concerns”. That is how I call them. And some are really nasty!

From now on, I will share the troubles I stumble upon. Because not only will I annotate my current design concerns for future self-reference, but also let people participate with comments.

One of my current design issues I ran into was the relationship that a parent and its children keep in several ways, the most important of them being the selection of children.

Let’s imagine this situation:

image

We’ve got a designer surface with some items. This surface is the parent of every other items inside.  Its children are Mario, a Button that says “Hola tío” (Hello dude), and the pretty obvious TextBox “This is my text”.

Knowing that it’s a designer with some elements into it, the user will expect some specific behavior. The most important are dragging and resizing.

Now the user sees Mario into a blue rectangle, remembers the times when they jumped all the way breaking blocks and decides “I will drag Mario!”. OK, the user expects Mario to be dragged around the surface.

STOP. Before moving anything we have to know what we want to move. How will we know that we have to move Mario?

ANSWER: Oh yes. In order to move him, we will have to select it first. So we will have some items that will be selected. Selected items! Risa A common concept, uh?

OK, that sounds good.

Selected items, but what selected items? We need to select some of the children.

HOW?

Clicking on the desired item should be enough. It’s the standard behavior. Isn’t it? So we decided that we will get the clicks on each item in order to know it has been selected to do something (dragging, for example).

Let’s go!

  1. Create a boolean IsSelected property, for the class that will represent the item.
  2. Add an event handler to each child to capture the mouse click and change its state.
  3. On click, turn the IsSelected to true.
  4. Give the element the proper appearance when it’s selected.

Pretty good.

Now, click every item and observe the goodness we achieved!

image

OK, you may have noticed that not only the items are selected individually, but also they is a concept of group in the capture. Just ignore it Sonrisa it’s part of my Glass library, currently being under development.

The fact is that we have a bunch of selected items that cannot be unselected. “Woahh, simple!” you will say. Just toggle IsSelected when clicking each time.

IsSelected = !ISelected;

Neat. Now you have more options. It’s alright. You win. But this is still far from being usable.

  1. First of all, when you have selected something and you want to drag it, each click will change the selection state.
  2. It’s really annoying to select items because most of times you will only want to select a single item: the one you just clicked. The others are discarded and only the newest should be the selected one.
    I know, I know! there will be many times in which you will want to select multiple items. We definitely will have to handle those situations.

You may ask:

– Couldn’t I just intercept clicks on an item and then iterate through the rest of children in order to unselect them? In other words: each time I click one, I can unselect the others.

WRONG! If you click an item and this item and you make it responsible for changing the state of its neighbors, you’re giving it a really high responsibility. How could it be aware of each other item? That sounds like we’re breaking some very important rule.

If we have to interact with other neighbors but we’re just a little modest item that cannot say the others what to do (we don’t mind about them), who could help us to unselect the rest of the items if I, as a child, receive a click and I want to change my state?

To be continued… Sonrisa

Principios SOLID

S – Single Responsibility Principle.

Una clase debería tener una única responsabilidad, bien definida. De esta manera solamente debería haber un motivo por cambiar su implementación.

Por ejemplo, una clase Persona nunca debería ser responsable de guardarse en un archivo a sí misma. Por lo tanto, un método Persona.Save(Stream output) viola este principio. En este caso, la clase Persona no solamente tendría como responsabilidad albergar los datos relacionados con la entidad correspondiente, sino también saber cómo guardarla. Tendría, por tanto, al menos 2 motivos para cambiar:

  • si la entidad Persona cambia
  • si los detalles del guardado (por ejemplo, el formato) cambian.

O – Open / Closed Principle

El comportamiento de una clase debería poderse modificar sin tener que cambiar su implementación.

Esto significa que la clase debe ser extensible, pero a la vez, robusta: no queremos tener que andar toqueteando todos sus métodos cada vez que una especificación cambie.

L – Liskov Substitution Principle

Una clase base debe ser SUSTITUIBLE por cualquiera de sus clases derivadas sin producir ningún efecto indeseado.

I – Interface Segregation Principle

Las interfaces deben ser reducidas. Deben permitir una granularidad alta.  Las interfaces grandes y difíciles de implementar SON CONTRAPRODUCENTES.

Es preferible tener varias interfaces pequeñas que una grande. Implementarlas será mucho más fácil y el diseño tendrá más sentido. Aparte de eso, al usar interfaces pequeñas nos forzamos a definir claramente los requisitos y las dependencias de cada método.

D – Dependency Inversion Principle

Trata de depender de abstracciones, no de implementaciones.

Cuando dependemos de abstracciones, tenemos claro qué es lo que necesitamos, aunque no definimos una forma específica de hacerlo. Una interfaz, ReproductorMusica puede tener el método Play. Sabemos qué es lo que hace, pero no cómo lo hace. Esto nos brinda una gran flexibilidad y dota al código de más capacidad semántica.

How to avoid code duplication. Case 1.

As a Clean Code lover, I really hate duplicated code.

In his homonymous book, Robert C. Martin states

”duplication may be the root of all evil in software”

And I think he IS absolutely right.

You better keep your code away from clones… or they will come back to you in the shape of a muddy monster that, for sure, will eat you.

I personally came to a situation in which I find it difficult to avoid repeating myself. This is the case:

I have a method that makes some calculations in a 2D plane (for layout and runtime design). This method takes some lengths and some points and make the necessary modifications to a control in order to a 2D transform to it. Let’s see a real sample in C#:

  • This sample method is really random, but it demostrates the problem. Each version works with one dimension, vertical or horizontal. Essentially both methods do the same, and the structure is almost identical. How to simplify these 2 into ONE?

For horizontal values:

        public static Rect DoSomethingCoolHorizontal(Rect inputRect)
        {

            var multiplyHorzPositions = inputRect.Left * inputRect.Width;

            Rect p = new Rect();

            p.Left = multiplyHorzPositions;
            p.Top = inputRect.Top;

            p.Width = multiplyHorzPositions;
            p.Height = inputRect.Height;            

            return p;
        }

For vertical values:

        public static Rect DoSomethingCoolVertical(Rect inputRect)
        {
            var multiplyVerPositions = inputRect.Top * inputRect.Height;

            Rect p = new Rect();

            p.Left = inputRect.Left;
            p.Top = multiplyVerPositions;

            p.Width = inputRect.Width;
            p.Height = multiplyVerPositions;

            return p;
        }

You may notice those 2 methods are 95% the same. But each one calculates the values for each axis. Vertical and horizontal use different properties.

The duplication in these kind of methods, follow  this simple rule:  when in the first method it says “left”, in the second it says “top”. As expected, “width” is replaced by “height”. The same would have been applicable for x and y.

In the case above, the rest is exactly the same, except for the return, that reverses the order of the Point arguments). They are so repetitive that even a text search&replace would do the job in order to replicate the same calculations for the other axis.

To clarify the method, you have to take into account that the structs that carry the properties are Rectangles with 4 attributes, that actually are 2 (2 for each dimension).

I tried to keep it beautiful, but I failed miserably again and again. That’s why I asked myself to Uncle Bob. I hope he could shed a bit light on this.

EDIT

Attention: Robert Martin did his magic again! I asked him in Twitter and has been so considerate and kind that he rewrote the sample in Java with the duplication totally eliminated. He provided a link with the source code. Just see the comments section.

WOW.

The solution to this lies in making a method that swaps vertical / horizontal dimensions. The call to the Vertical derivative is the Horizontal one with 2 swaps (argument and result):

        public static Rect DoSomethingNonDuplicateVertical(Rect inputRect)
        {
            return DoSomethingCoolHorizontal(inputRect.Swap()).Swap();
        }

With the Swap method being:

        public Rect Swap()
        {
            return new Rect(Top, Left, Height, Width);
        }

The constructor of the Rect class is:

  public Rect(double left, double top, double width, double height)
        {
            Left = left;
            Top = top;
            Width = width;
            Height = height;
        }

Now IT REALLY DOES SOMETHING COOL.

Thanks, Uncle Bob. Great tip!