Showing posts with label Soft Design. Show all posts
Showing posts with label Soft Design. Show all posts

Wednesday, November 2, 2011

Request, Response, Request, Response

In a layered application (not tiered) we usually have an UI layer, a business layer, communication layer and DB layer (the most common applications are distributed this way, it seems natural). This obviously leads to calls between layers, for example, the user clicks in the UI to get a report of the clients, the UI asks a "service" in the business layer to get that report, and probably the business layer ends up calling another "service" from DB or Communication layer.

So far so good, but what I want to talk about today is how this is implemented. I really don't know why, but I usually see a lot of Requests and Responses classes going through layers. Meaning that each service receives a request and returns a response, so each client layer needs to create that request and process that particular response. In our example it would be something like this:

In the UI:


This is the usage of the Service, as I commonly see it in legacy codes. But what about the interfaces of these classes?, well they usually tend to be something like:


And the "Service" usually looks like:

So if we want to get a report of  Clients by year and city we call the first constructor of the ClientRequest class and then the first method of the ClientBusinessService. If we want Clients by Country, we only set the country in the request and call the second method of the service.

Which are the things I don't like?

  1. Request and Responses are Data classes.
  2. Requests and responses end up having lots of attributes that are not needed
  3. Requests end up having service configuration attributes
  4. Interfaces are not representatives of the functionality. We loose readability
  5. We always need translators
  6. Code overhead


1. Requests and Responses are data classes.

Data classes are not good, a class is represented by its attributes and methods, so if a class only have attributes then it is probably not needed. On the other hand, Data classes promote feature Envies from other classes that need the information that they contain, leading to maintenance headaches!. Another thing to consider is that the request will probably have setters, which will make your life a complete nightmare.

2. Requests and responses end up having lots of attributes that are not needed

The country is an example of this point. Of course my example is quite simple, but take under consideration the in real world the services are more complex but for my simple example some questions come into my mind:

shall I write one constructor per service method? Obviously the request depends on the Service call, we need to make sure that we call the constructor needed when we call the service. This is not ideal.

shall I write only one constructor for the request and pass null if the attribute is not needed?. This is horrible, we should never pass null to a constructor, this leads to a lot of problems (one is the continuous null checking in all the services that use that request)

shall I leave the default constructor and set the attributes  I need?. You still have the problem of nulls and setters are always a nightmare, I would recommend no to add setters in your class (as a general rule), they are the seed of side effects.

 for the year and city request, do I need the country or not?. This is the main key that I haven't discussed. YOU NEED TO KNOW WHICH ATTRIBUTES ARE NEEDED FOR THAT CALL, the interface does not define that clearly, you need to know how the service is implemented in order to create the request!, by calling getClientsByYearAndCity you don't know if the country is not needed, that's only your assumption.

3. Requests end up having service configuration attributes

Maybe this is not entirely related to Requests and Responses, but something I find associated to this pattern is that the request does not only have domain specific information. As it is easy to add new members into the Request class, people start adding things that are needed to configure the Service, for example, connection Ports, URL, session information. This is horrible because the service might vary the implementation (you can have to classes that implement the service interface, let's say one goes through a web  service to get that information, and another goes through the database), you probably don't need some information for both implementations. The Service interface must reflect the Service responsibility, not its implementation.

4. Interfaces are not representatives of the functionality. We loose readability

This is related with what I already said, you don't know for sure the parameters that you need to send to the Service in order to make it work. It is not clear what a request represents, it is not clear by reading the interface which is the expected result. I've been nice and wrote some clear methods but you may not find that in real world.

5. We always need translators

Instead of returning domain objects we return Responses, but responses are plain objects that does not have any function, so or you need an utility class (hate that names) that reads the response and provides you with the information you need completely processed, or you read the response and create a new object with that information.

6. Code overhead

You need a lot of lines, for translating the request and the response,  for null checking, constructors, request and response classes. This makes the code unnecessary complex.


These are the reasons I can think right now,  probably I'll find more, but I'll leave them for another post :-)






Wednesday, October 12, 2011

Complaints

Do you have the perfect job?, do all your fellows work as you expect?, is your work environment great?. If the answer of all these questions is "YES" then you need to change your job.

If you don't have complaints about your job then there is nothing important to do there, there is nothing to fix. Complaining is a need, an exercise, try to make the complaints a daily thing in your team, list all the problems that people find and try to fix them. Create new tools, talk with your boss, do trainings, try to make your office a better place to work ... so at the end it will became harder and  harder to complain.

Complaining is the key exercise of team's evolution. If you implement complaining as an exercise in your team you will find that at first that the problems are quite trivial, very simple to fix (one or two days of work), but then you'll see that people find more complex things to do.

Try the same experiment I did some time ago, ask your devs about the compiling time of the application, write down all the complaints, get their ideas, reduce the compiling time (as much as you can). Then ask again in a couple of months about the compiling time, you'll get a lot of complaints about it and you'll try to fix them, you will find that doing that is hard, but will make your development times faster and faster, you evolve!. On the other hand, let's say you don't get any complaint about the compiling time, you get another complaint, let's say xUnit coverage, you still evolve because the xUnit coverage was a problem that was hidden by the compiling time problem which everyone was more worried about, now that you solved that you are prepared to fix other issues, as your see, you still evolve!.

Hearing complaints all the time is boring and awful, so try to implement a weekly session of complaints get all your team together and ask them about their problems, talk about them, you'll see everyone will have one!




Thursday, September 8, 2011

What is and WHAT SHOULD NEVER BE!

Is quite late now, I'm sitting in a silent room of the public library near my home. A few minutes ago I was reading a bit about Taxonomy Expansion but I got bored :-s. As I always say, I live like a rock star, so to wake me up a little bit I began to look at the source code of the application I'm supposed to maintain.Yes!, Jagger must be so jealous of me!

At the precise moment I was reading the classes of the DB module, the song "What is and what should never be" of Led Zeppelin (2nd song, disk 2, album: How The West Was Won, 1972) started to sound in my computer. I believe it was a message from God because I inmediatly found something like this:


public class BaseHandler
{
    public BaseHandler(Command command)
    {
        command.addContext(this); // WHAT IS, BUT SHOULD NEVER BE!!!!
    }
    ....
}

And this is incredible because after looking and analyzing that class the song changed (1st song, disk 2, album: How The West Was Won, 1972), the title ... "Dazed and Confused", that's exactly how I felt. It was like the rock gods Robert Plant and Jimmy Page where talking directly to me!.

Let's leave the drugs for a moment :-) ....What is the main problem of the class?. Well, "this" is not fully created, check this short example (try to run it, it prints "null"):

public class BaseHandler
{
    public BaseHandler(Command command)
    {
        command.addContext(this);  // the instance is not fully created!!!!
    }

    public void doSomething()
    {
        System.out.println("Im Base Handler");
    }
}

public class Command
{
    public void addContext(BaseHandler handler)
    {
        handler.doSomething();
    }
}

public class Handler extends BaseHandler
{
    private String message;

    public Handler(Command command, String message)
    {
        super(command);
        this.message = message;
    }

    @Override
    public void doSomething()
    {
        System.out.println(message);
    }

    public static void main(String [] args)
    {
        Handler handler = new Handler(new Command(), "Im Handler not  Base Handler");
    }
}


This is not obiously the code was looking at, it was more complex and fortunately didn't fail (no attribute was used from the constructor), but it is a good example of java class initalization. (Before a class or interface is initialized, its direct superclass must be initialized, but interfaces implemented by the class need not be initialized. Similarly, the superinterfaces of an interface need not be initialized before the interface is initialized.)

Moby dick is sounding now, I'm moving my feet as an epileptic drummer, beliving that I'm so great that I can follow the rithm (yeah! in my dreams!). Everyone have already left the room by now, I think they
are about to close the doors so I should be running out.

Have a great night!

Tuesday, May 24, 2011

Dependency injection - a practical approach

What do we want to achieve when we are coding? I mean, which are the quality attributes of a code that define it as a GOOD piece code? Well … we all know that the response to these questions is: “it depends, it depends on the problem”. Despite of the fact that this is actually true (it is a correct answer, we should define out software quality attributes before coding), we usually want our code to be at least extensible, testable and readable:

  • Extensible because we think that our code will be reuse in the future (yes, right :-s).
  • Testable because we are force to create unit tests for our classes (nowadays committing code without test is unacceptable) , and
  • Readable because we might think that our code will be read in the future and we want it to be understood (actually, you don’t want to be bother in the future with questions about things we wrote and don’t remember)

Ok, but … why is it related to dependency injection? Well … dependency injection is a design principle that would help us to achieve these goals. To make it clear, dependency injection defines that “your class should be configured with its collaborators by using constructors or setters”. This is the most practical and simple definition I could think of.


Let me show you a common example of code,




And the usage of the class would be:



Let’s first analyze readability. When we see the code of the class Service we can say that “Service builds a Report for a particular country BY READING INFORMATION FROM THE DATABASE”. But, when we read the usage of the class what we know is that “Service builds a Report for a particular country”. Do you see the difference? When we use the class Service we don’t know if we are going to connect to the database or if the information comes from a web service or whatever. This becomes a problem when we read the code because we are forced to go into the Service class and look into its implementation just to realize that it actually reads information from the database. Hmmm … but isn’t it what encapsulation is all about? …… NO, encapsulation is not hiding information, it just hiding implementation and prohibiting the direct manipulation of the internal state of the class from the outside.


This readability issue may be seen as stupid for this particular example, because Service class is quite simple, short and easy to read. But is different when we are working with some real code in real applications where you don’t have one class, you have thousands! When we read code we want it to be as much as expressive as we can, we want to have all the information of what that class does, maybe not how it does it, but we want to be aware of things like database connectivity, for example.

Now let’s check extensibility. The responsibility of the class Service is to “Build a Report for a particular country by reading the database information”. Hmmm … there is something that seems to be wrong, right?, if we look at the code of service there is nothing that connects the Service functionality with the database. I mean, from my perspective the Service class creates a report. To achieve this, it needs the clients and the accounts. In the particular case of out example, we see that the Clients and Accounts come from the database, but this should be a detail of implementation only. Do you see where I’m going? With the implementation of Service as it is, we have a strong relation between the building of a report and the database connectivity. We shouldn’t have this, because we don’t have a good separation of concerns in our code. If we want to change the information resource (let’s say a web service) we will have a problem with our service implementation. Or we will have to create another service class that uses a web service to create the Report. This is an example of poor extensibility; the service class can only be used to create a Report from the database.

Finally, let’s take a look at testability. How do we create a unit test for Service? Focus on the word UNIT, we only want to test Service and not the database connectivity, it seems very hard to do because of the new instruction inside the constructor of Service. If we want to mock the Database connectivity we have a problem and we need to do a lot of ad hoc things just to avoid going to the database. Testability is very important because with a test we can establish the expected functionality of the class (doing Test is not testing).

A few lines and a lot of problems, hug? Let’s see the same implementation with dependency injection:



And it’s usage,




Now our class is more readable, extensible and testable.

It is more readable because we have more information when we use the class than when we see its code. When we see the code we know that “Service creates a Report using an external resource to gather information”, but when we see the usage, we know that “Service creates a Report using a Database connection to gather information”.

It is more testable because it is easier to mock the database connection, we can test what service does without worrying about the database connectivity, we just mock it.
It is more extensible because it is quite simple to change the behavior of the class service, if we want it to connect to the database we inject a DBConnector, however, if we want it to connect to a web service, we just create an ExternalResource implementation that connects to a web service and retrieves the clients and accounts.

Of course we can talk about other benefits of dependency injection like coupling reduction or interface programming, but these are much related to the extensibility of a class. I wanted to show a real example of the gain of using dependency injection in our code. I didn’t want to write a lot about all the theory behind it in this post, but I could write something more specific in the future without sounding like a book.




I hope this helps to understand!



Friday, March 4, 2011

Shortest Path

New simulator, now: A js implementation of Dijkstra's algorithm. I might refactor it in the future (I will probably use a priority queue instead of two arrays), but it works now so I would like to share with you. 


For the ones that don't know what Dijkstra's algorithm is check this.


I keep using my graph generator so the interface is the same. This script will generate a random weighted graph and find the beth path between two nodes. The path will apear in a pop up in your browser.


Vertex number:
Max edges number:
Path between: and







Wednesday, March 2, 2011

Big Brother groups simulation

Most people in the world heard about the tv show called Big Brother, for the ones who have no idea what I'm talking about, it is a TV show where a bunch of people live in the same house for a couple of months while they are filmed 24x7. Now that I write the concept of the show it seems quite stupid :-s.


Well, that's the main concept of the show, but the most probable thing is that if BB has audience success then other TV shows appear on the screen, for example one called "The debate" or something similiar (depending on the country), in this other show another bunch of people talk about the guys that are in the house (it is incredible stupid, right?), the things that you can hear on this other TV show are like: "it is a strategy!" or "different groups has been formed inside the house".


Well, the last phrase made me think about which groups can be formed inside BB house?, and... I created a simulator :-). Bassically, I used the code of the previous post (1) in order to generate a random simple graph, then find all the connected components of it.


Vertex number:
Max edges number:






Monday, February 28, 2011

Javascript random graphs

I'm not an expert in Javascript so I decided to practice a bit. I've done a random graph generator using HTML5 canvas functionality and I would like to share with you.


Here is some explanation:


1) Vertex Number is the numer of nodes you want.
2) Max edges numer: is the maximun number of edges of the graph (the graph may have less)
3) If an edge is an reflexible edge it will appear as "*". 
4) In a direct graph the end point of the arc is marked with a rectangle (if not directed it has no sense)
5) The weight of the edge is in the edge (if not weighted it has no sense)
6) The weight is between 20 and another number I can't remember now (I could check the code but I don't want to).
7) If you receive a message saying that the graph couldn't be created then it is because the Max edge number is to high for that particular graph.
8) I haven't done any check of empty values or text or whatever because it is boring. :-)
9) I only tested on Chrome which is my default browser (I'm not QA :-) ).
10) If "Directed Acyclic" and "Non Directed Simple Graph" are checked, then it is consider as "Directed Acyclic"


cheers!


Vertex number:
Max edges number:

Non Directed Simple Graph
Directed Acyclic
Weighted





Friday, December 31, 2010

Looking through my dog's eyes (first approach)

Hello, it's been a long time, but I didn't have something interesting to tell, I've been reading about ontological Engineering which is not something very exciting for everyone. 

I did this last month, and never improved it, so I decided that I could show you something without being completed. I was kind of boring and was thinking about how my dogs can see (as you can see, I live like a  rock star). I mean, do they seen in black and white?, do they see colors? how is their perspective of the world?, well, I participate on a forum about dogs (I have a bullmastiff) and one guy talked about this topic once. He posted these images.

The first one is the human vision, and the second one is the dog vision. If we consider that this is true.... Let's start doing a first analysis (this is a very simple analysis, I'll do some frequency analysis in the future to complete this) ... Let's separate all the color channels:


For the humans:


For dogs:


The first interesting thing is that the Red channel is quite similar to the Green channel for the dogs.
This is the comparison between human channels and dog channels, (red, green, blue respectively)

  

As we can see, the dog curve for the green channel is quite similar to the human curve.


These are the frequency comparison (red, green, blue):




So with this first analysis (a very simple one), I wrote a js script that converts any "human" image into a "dog image".

NOTE: I repeat, this is a first approximation, I need to improve the filter for the red and green channels. You need a brower that supports HTML5 (chrome, Firefox, IE 8). I tested it with PNGs, JPGs and bmps. Other format might not work.














Tuesday, September 14, 2010

Interfaces and behavior

This is a very simple post (easy to read), for the ones that know something about object oriented programming is quite stupid, but I want to talk about something annoying I usually find in code. One common mistake I see in software development is the confusion between an object interface and its behavior. Basically what I see is that developers don't understand polymorphism. I'll try to define polymorphism in a very simple way: "Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. "


With that being said, I'll present an example of what I commonly see:


The idea is quite simple, let's say that we want to calculate taxes based on the sale of a product. So we create a class called TaxesCalculator (for example) in order to calculate the taxes based on a sale (I'll simplify the domain model just to make the idea very simple is not my intention to give a real example).


So TaxesCalculator will have a method called calculate that receives a sale and returns a list of taxes


So far so good, the class seems to be OK and everyone is happy. But then we realized that there are to ways of calculate taxes (for example, based on the country), let's call them Reg1001 and Reg1002. It seems to be a problem where the use of polymorphism seems to be suitable. I don't know why but I do not often see this kind of problems fixed using polymorphism. I usually find something like this:

List calculate(Sale sale, boolean useReg1002)
or
                                                        List calculateUsingReg1001(Sale)
                                                                                         List calculateUsingReg1002(Sale)
or even worst
                                                        List calculate(Request)
where request has these methods:
                                                        Sale getSale()
                                                                                          boolean isReg1002()

Which is the main problem with these implementations?, well the it's quite obvious that we tied the implementation with the interface, and this is  a problem because the code of the TaxesCalculator is harder to maintain (too many ifs and conditionals, low code reutilization, etc). And we make the TaxesCalculator client harder to maintain also, this class needs to know how we need to compute our taxes (something the TaxesCalculator should know), why does it need to know that?, well, it's very easy, because it needs to know which method to call and how to call it.


For me the easiest way to do this is by having:



We need to differentiate the interface from the behavior of the class, the interface needs to represent a business behavior (the act of calculate taxes) by doing this we will be able to modify the code easily. With this implementation we have a very simple client code that we won't need to modify if we need to add a new way of calculate taxes.

On the other hand, If you need to modify the behavior of an existing class based on some configurations you can still maintain the same interface by configuring the class using its constructor (so you create the class with its configuration, so the class factory is aware of the implementation and not the client).


Well, I'm kind of tired of writing, it's a very simple idea and we learn it at school, but sometimes people follow their dark instincts and write some awful things that other people unfortunately need to read :-)

Thanks 



Sunday, August 29, 2010

The need of doing things right

There are several steps to follow in order to do re-engineering. I've read different books that teach us how to work with legacy code and how to refactor it, but theory is nothing more than an ideal world. Those that work in a company will understand what I'm talking about. However, in the case of re-engineering there are some basic steps that we should follow to achieve success that are so obvious that we don't pay attention to them and we fail.

For example, in order to refactor a legacy code, we have:

1) Define your goals!. 

It is silly, right?, if we don't have goals to focus on, how are we going to define a design?. Well, think about the times you've done a refactor and asked your architecture lead to put in black and white all the goals and objectives you needed to achieve. Where you objectives the same as your manager, architecture lead or client?

2) Having an initial understanding.

If you need to modify code, you'd better understand it!, again, it's obvious, but some common thing among developers is that after understanding what we need to do we start thinking about the design. We say, "ok, this code is a piece of crap and we need to do it all over again!", we are focused on one problem only and we start what we think is the best design ever. Please ask yourself how many times, you asked your colleges about the code you are about to modify, how many times you asked a technical analyst about all the functionalities that you need to cover. 

3) A detailed model 

Not talking about your design yet. Before doing a big refactor, we need to understand the complete functionality of the code you are about to modify, and that means doing a detail model of it. Why this is important?, it is important because it may or not be broken!, we may think that the code is old and useless but after you understand it and analyse it, you might find that despite of the fact you wouldn't do that way, the design is not actually wrong, and doesn't need to be fixed.

4) Your design.

Now that you are sure about what are your goals and that you need to modify the code, go to the fun part. Do your design. Again, ask everyone to review it!, you are not as important as you think you are!, and worst, YOU ARE NOT THE  GREATEST DEVELOPER IN THE WORLD!. Once you are sure that your design fit, COMMUNICATE IT AGAIN!, ask your architecture to review it, make sure everyone understood and agreed on it. Do a prototype of your idea, it will help a lot!

5) Modifying the code.

Now it's time of the real fun, but first you have to answer yourself, have I detailed all the steps to do the refactor?, developers don't like to write documents but they are very useful, we need to communicate our ideas a bit more. After you have your plan in black and white, DO YOUR UNIT TESTS!, again, YOU ARE NOT THE GREATEST DEVELOPER IN THE WORLD!. After your tests are complete, be incremental (despite of the hard work)

6) Communicate the changes

You've worked a lot, but the rest of the teams don't know about it. Communicate your effort and how the things must be done in the future. Explain your design or it will die.


Again, these are silly and very obvious steps, but we don't follow them every time. We need to focus a bit more and leave the time pressure away :-)

Cheers!

Wednesday, August 25, 2010

Number of paths - acyclic graphs

This is a quick post (I should be working now). Yesterday, I heard a college of mine asking: "how many paths are between these two cities?". The guy next to me looked for an answer in Google (as we always do), and found a very interesting forum that solved his problem.


I personally read it, and I didn't like what I saw. I mean, if you have a problem like this one, please, read something about graph theory.

If you have an acyclic graph things are much simpler, I'll explain how to do this with an example:

Let's say you have the following graph (It also works with undirected graphs):


The length of the longest (possible) path in an acyclic graph is equal to the number of vertices minus 1 (in this case 3) . The adjacency matrix gives us a lot of information. If you multiple this matrix twice, you get:


This new matrix shows the number of paths of length 2 between two vertices, for example, the number of paths of length 2 between v1 and v3 is 1. So if you want to get the number of possible paths you only need to do:



It's not my intention to say that this is the best solution, but I would like to point out that there are other possibilities than algorithms taken from a forum :-).

Then we can talk about graphs with cycles, but I should get back to work!

Cheers!



Sunday, April 26, 2009

Creational Patterns

Hi everyone!, today I'm going to talk about creational patterns, again, these are only my ideas regarding to this topic. I'm basically going to talk about the most used creational patterns: Abstract Factory and Factory Method and I'm going to describe the most important differences.

Ok, let's start with Abstract Factory and Factory Method (I've already talked a bit on the previous post, so let's reuse some diagrams J .

Let's say we want to create a simple car object, but we have two kinds of Cars (Compact and Premium), if we want our code to be independent of the Car construction so we could implement a Factory Method. The main idea of the factory method is that we create an abstract interface and let it's implementations to create the specific object. Basically, Factory Method is to creating objects as Template Method is to implementing an algorithm. Let's see the car example:




So CompactCarFactory creates a CompactCar and PremiumCarFactory creates a Premium Car but for the Factory client doesn't know about which type of car is being created. In my opinion, this is the most important quality of the Factory Method, the independence of the car type in the client class gives us a great decoupling between objects which is something that developer should be considering constantly while coding. 

Let's go a bit deeper in implementation, other intent of the Factory Method is that we want to avoid the construction of the objects in other parts of the code, maybe because we consider the new operator harmful for our problem, in this case,  object must have a protected constructor and the factory classes should be in the same package of the object. This is quite good, I think it is OK, however, I do not always find the need of avoiding the object construction with the new operator in other part of the code. I consider that other programmers are grown up people and would use the factory instead of the new operator. So having the factory in a separate package don't smell so bad for me, (we'll probably need to create a car in a fitnesse for example where is no need to be so elegant and so the factory could be unnecessary).

On the other hand, the implementation of createCar() method should not have any logic inside. If you see that the method is growing you should consider a Builder pattern instead of a factory Method (I'm talking in the design phase). As we shouldn't have any logic Unit test should not be very difficult to do, right? (and probably unnecessary J).

One final comment about this pattern, a method inside your class that creates an object is NOT a factory method J, you might think it is silly, but I've found several peaces of code where a class method is documented as a "Factory Method" without being a Factory Method.

So, let's move on with Abstract Factory, let's suppose we have the following:




Is it a Factory Method or an Abstract Factory?, I've found this example in some books a Factory Method, however if we read the intents of the Abstract Factory method in the same books, we find something like "families of objects are involved", well, for me it is kind of tricky right?, I have a redefinition of a factory Method but in each overriding we are create different type of objects which extends of an Abstract Object. In my opinion, it is a Factory Method because we cannot create with the CarFactory multiple families of objects. Abstract Factories can be used as an alternative of facade to hide platform-specific classes, so an Abstract Factory might look like this:



Most of the things commented for the implementation of the factory Method can be applied to Abstract Factory, so I don't want to be redundant on this and point out some useful topics:

  • Abstract Factory is more general that a Factory method. Sometimes creational patterns compete with each other, however they sometimes complement each other. An Abstract Factory might store a set of factory methods or Prototypes, for example.
  • Generally, we often start with a Factory Method and then evolve toward Abstract Factory.
  • While a Builder is used to create complex objects, Abstract Factory emphasizes a family of product objects (either simple or complex).

One final comment, despite of the fact that Factory Methods and Abstract Factories are quite similar they intents are different, consider an Abstract Factory as class that makes us able to create families of product objects and a Factory Method as more specific object factory.



Class Names and Patterns

We could talk years and years about name conventions and design and don't arrive to a concrete solution. That's why you should only consider this post as a opinion and nothing more than that.

Names seems to be a serious problem for some developers. I worked with C++ several years and me and my fellows didn't talk about this topic too much, but now that I'm working with JAVA it seems that names are important!. One of the things I would like to talk today is about patterns and names. How do we call a class that is implementing a pattern?, for example, a Strategy class, should be called, for example, "calculationStrategy"?, as in everything related to design there are multiple opinions. Some people think that it is unnecessary because if a developer is reading your code he should know how a strategy pattern is implemented and is redundant to specify the implemented pattern in the class name. On the other hand, some people think it is right!, they consider that being redundant in this case is a benefit for the reader because it makes code easier to read. 

Before continue, we should also consider the difference between the pattern's intent and it's implementation. The most important thing when we need to analyse of a pattern is it's intent: what it is suppose to solve and what is useful for, we should decide whenever to implement a patter or not based on these intentions. The implementation is secondary, you could implement a pattern the way you want, there are different ways to code a pattern and achieving the same result. However, if you decide to use the implemented pattern's name in your class name try to make a standard implementation of it, it is a way to avoid readers confusions.

Let me show you some examples, 

An abstract factory is not a factory method. These patterns are quite similar but they are expected to do different things. The factory Method is similar to the abstract Factory without the emphasis on families. If you call a Factory Method as an abstract Factory you may leading to confusions. Consider the following,




If another developer reads "CarAbstractFactory", instead of expecting what I've showed before, he will be waiting to read something like:





Which is not the same. in this case you should reconsider the name of your class, and named it as "CarFactoryMethod" or "CarFactory".



Strategy is different from polymorphic. When you have to implement a strategy pattern consider that the class that is implementing the Strategy Pattern is injected to a client or Director. Something like this:



and not something like this:




What I'm trying to say with this examples is that you can use pattern names in your class names, but if you do it, be sure that the implementation of the pattern corresponds to the name of your class and it is implemented in a standard way so everyone can understand it without having problems.


Singleton Pattern

What we should say about the singleton pattern???, the usage of this pattern is completely abused. Why? because it is easier to think in processes and methods than thinking in Objects. Singleton pattern gives us the possibility of formalizing statics methods and this is NOT a good practice.

There are a lot of blogs and discussion forums about this issue and you can find some really crazy comments and recommendations. But when do we use a singleton pattern??, in my opinion you have to consider these points (they all should happen):

1) You NEED only one instance of the class. For example, you need to synchronize the access to a shared resource
2) The singleton class might be used by the whole application in the same way
3) It is a FINAL class
4) Should the clients of this class be unaware of the application they are part of?

Why we should be extremely sure about using a Singleton??, 

1) One of the main things is the Liskov Substitution Principle

Let see it with an example, let's suppose you have the following class structure:



Let's also say that A is a helper (or utility class). Some common thought it to implement the helper as a singleton so we don't have an instance for each client so the code gains in performance (which is not very good, we should not consider performance in our design unless performance is our problem). Now, someone comes in the future and realizes that the way A should act depends on the business logic, so  he decides to implement a new class that extends from A so he'll have something like:



His idea is quite good, but what's the problem he is facing right now?, he can't inject B or C to the client!! (we are violating LSP). As A is a Singleton, every time you do A.getInstance() you get a class of type A and nothing more, we cannot use LSP with Singleton pattern (this is something we agree to loose with this pattern, see point (3) ). Despite of the fact that we can't think about future changes while we are coding (one of the agile laws), when we implemented the helper as a singleton we didn't consider the first intention of the Singleton Pattern and this is when we made a mistake. 

2) Let's think about unit test now, testing the client will be harder if we use a singleton as a Supplier. First of all, if you want to use a Singleton supplier, please, do it as the class diagram showed before. The cliente should have an instace, sorry..... THE instance of the Singleton Class. The client code should be like this:

public class Client
{
    private A singletonA = A.getInstance();

    public void useA()
    {
            singletonA.act();
    }
    
    public void setSingletonA(A singletonA)
    {
        this.singletonA = singetonA;
    }

}

IT MUST NOT BE LIKE THIS:

public class Client
{
    public void useA()
    {
        A.getInstance().act()
    }
}

Why?, well the first option can be tested with a mock, the second one doesn't.


Final comments

Singletons are good for they where created for, we shouldn't try to create a Singleton just because we think it should be there. We should think about the preconditions of the pattern, what it is supposed to solve?. Basically, we must consider if we NEED a single instance of the class. We must NOT consider if we THINK there should be a single instance of the class or if we THINK it would be better. Differencing this is the key part while we decide to implement a Singleton Pattern.


Thanks!