Be a Developer, not a Blender

Hello, how are you?

We live in a “frameworks that are easy to use” age that helps us to create our projects. One thing that a lot of teachers say is: “Just use this annotation and it will be ok”.

Annotations have the objective of making frameworks easier to use and identify their behavior, but some developers get lost with this feature and and they forget about some of the OO basics.

CRUD, JMS queues, Beans, transaction controls can be created in minutes, but what about the Object Orientation? What happened with the good practices that took a long time to be correctly forged? Why are they being abandoned?

Mixing Concepts

To understand better what I am trying to say, let us see below some code snippets  that we find in development sites. In the first sample we can see a code with JPA and JSON mixed:

@Entity
@XmlRootElement
@JsonAutoDetect
@DiscriminatorColumn(name = "animal_type")
@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = Dog.class, name = "dog"),
        @JsonSubTypes.Type(value = Cat.class, name = "cat"),
        @JsonSubTypes.Type(value = Bird.class, name = "bird")
})
public class Animal {
 
    @Id
    private int id;
 
    @JsonSerialize(using = JsonDateSerializer.class)
    private Date birthday;
 
    @JsonView(ToothView.class)
    @OneToMany(mappedBy = "animal")
    private List<Tooth> teethList;
 
    // other stuff
}
 
@Entity
@JsonRootName(value = "Dog")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Dog extends Animal {
 
    @JsonProperty
    private String name;
 
    @Convert(converter = JsonAttributeConverter.class)
    private Double weight;
 
    @JsonIgnore
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "dog", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Bone> boneList;
 
    public Dog() {
    }
}

What is the problem with the code above? Why would someone mix JSON annotations (VIEW) with JPA annotations (MODEL)? If we need to edit an attribute only to display it in a different way in a VIEW, this update will affect the same class that is used to persist the data. We will increase the risk to input a bug when persisting the data.

No Respect for the Layers

Let us see another example:

@ViewScoped
@ManagedBean
@TransactionManagement(TransactionManagementType.BEAN)
public class ManagedBeanOne extends SuperManagedBean implements Serializable {
     // attributes
    public String doSomething() {
        try{
            transaction.begin();
            // do something
            transaction.commit();
        }
        catch(Exception ex){
            transaction.rollback();
        }
    }
}
 
 
@ManagedBean
@WebService
@ViewScoped
public class ManagedBeanTwo implements Serializable{}

Should the class be defined as a JSF ManagedBean and an EJB? The worst part of this code is: Why is a JSF class managing a transaction? What do we gain by giving this ManagedBean so many responsibilities?

Huge Code Blocks Do Not Help

A code that I could not post here is a class with more than 1k lines. The worst part of a huge class is that the some developers start to make jokes about it, or sometimes the class is considered to be a huge bad monster that should never be touched because any update would break the code.

How long will developers keep adding just one if statement to this kind of classes without doing small refactorings?

Exception that Dictate the Rules

A terrible practice is using an Exception to handle the request flow. Take a look below:

try{
    myObject.doSomething();
} catch(MyExceptionOne one){
    sendErrorSmsToCustomer();
    defineOldPlanToCustomer();
    sentToScreenOne();
} catch(MyExceptionTwo two){
    sendErrorEmailToCustomer();
    defineNewPlanToCustomer();
    sentToScreenTwo();
}

What would happen with the database data if an error is thrown at the first line of the exception block? What would happen if a developer invokes “myObject.doSomething()” in another class but without the correct catch code like above? What if the line code that handles the user plan is not executed?

What comes next?

It is an easy task to say if code looks good or bad, but I believe that one thing that is needed is to always to show a solution. What we will see in the pages to come is not something created by me, but are good practices and design patterns that you will find in several development books.

What we will see:

  • Page 2: Do not Pass Over the Layers
    • Pay Attention to the Packages
  • Page 3: Increase your Cohesion
  • Page 4: Loose Coupling
    • Facade is a Good Call
  • Page 5: Let us Return to the DTOs World
    • How can I easily pass the Entity data to a DTO?
  • Page 6: Small Classes and Methods
  • Page 7: How can we use Exceptions Correctly?
  • Page 8: The Broken Window Theory
    • Keep your build working
    • Do not leave your tests breaking
    • Do not comment/ignore your tests
  • Page 9: Good practices that helps
    • KISS
    • DRY
  • Page 10: It does not matter if you have a huge amount of tests without quality
    • Use Test Tools
    • Did you find a bug? Create a test for it
  • Page 11: Conclusion

I hope that this posts helps you. (:

I am really thankful for the Rodrigo Sasaki’s (http://cv.rodrigosasaki.com) help, this guy rocks!

Design Pattern – Observer (Part 02)

Hello, how are you?

Let us keep talking about the Observer pattern. If you did not read the first post about this pattern, read it before reading the Part 2 about this pattern (Design Pattern – Observer (Part 01) ).

How could we loose coupling of our classes? (Questioning of the last post Design Pattern – Observer (Part 01) )

A good way to loose this coupling would be: the class Listener receives a reference to its Notifier class. It is a very simple solution.

Our Notifier class will only “tell” to a Listener that something happen through the “update” method, and the Listener will decide which attributes will be needed.

The class YahooPattern will need a password to send the email, it will access the Notifier the get this information. Let us begin the refactoring?

First of all we need to refactor the “update” method. Let us use another kind of super class? Let us update our UML and use an abstract super class (instead interface like we did in the last post).
Design Pattern - Observer (Part 02)Design Pattern - Observer (Part 02)
We updated our interface Notifier, now it has methods that will be visible to our listeners. The listeners now will be able to get the information that it is needed to send an email. The class that sends the email (EmailPattern) has a reference to the Notifier.

The Notifier reference will enable the emailSender to get all the needed data, instead the older version where the Notifier has the responsibility to know each of its listeners. If each listener change the needed parameters to send an email, the update method from the Notifier class will remain intact. If you had to change any email class to get another data, you only need to change the “collectData” method that is an abstract method which every subclass will implement.

If a new requirement comes to the HotmailPattern class, like add a specific image to the text, you would need to add the get method to the Notifier interface and update the HotmailPattern class to get and use this value. Notice that our class Notifier has been changed by adding a get method only, and the Notifier does not need to know whom/how will use this data.

Let us see our implemented code:

public class EmailSender implements Notifier {

    private List listeners;
    private String emailText;
    private String emailSubject;
    private String password;

    public EmailSender() {
        listeners = new ArrayList();
    }

    public void addListener(Listener listener) {
        listeners.add(listener);
    }

    public void removeListener(Listener listener) {
        listeners.remove(listener);
    }

    public void createEmails() {
        emailText = getNewEmailTextFromDataBase();
        emailSubject = getNewEmailTitleFromDataBase();
        password = getPasswordFromDataBase();
        notifyListeners();
    }

    public void notifyListeners() {
        for (Listener listener : listeners) {
            listener.update();
        }
    }

    // Getters and Setters
}
// Our superclass EmailPattern. All Emails patterns will extend this class
public abstract class EmailPattern implements Listener{
    protected Notifier emailSender;

    public EmailPattern(Notifier emailSender){
        this.emailSender = emailSender;
    }

    public void update(){
        collectData();
        sendEmail();
    }

    protected abstract void collectData();
    protected abstract void sendEmail();
}
// This is our implementation. The class will get the password and any other data that it needs
public class YahooPattern extends EmailPattern {
    private String emailText;
    private String emailSubject;
    private String emailPassword;

    public YahooPattern(Notifier emailSender) {
        super(emailSender);
    }

    @Override
    protected void collectData() {
        emailText = emailSender.getEmailText();
        emailSubject = emailSender.getEmailSubject();
        emailPassword = emailSender.getPassword();
    }

    @Override
    public void sendEmail() {
        System.out.println("Sending email subject: " + emailSubject + " with the text: " + emailText + " with the password: " + emailPassword);
    }
}

And here comes a new Design principle:
“Always try to loose the coupling between classes that communicates.”
We loose the coupling when we updated our Notifier class to only provide the information, instead of knowing the need of each listener; now our Notifier just calls the listeners without worrying which parameters it should pass. And by updating the listener so it might be able to collect all the data it needs.

A briefing of the design patterns seen so far:

    Design Pattern: Strategy
    Studied Principles:

  • Identify everything that changes and isolate it from what does not change.
  • Program to an interface.
  • Give priority to composition rather than inheritance.

Design Pattern: Observer
Studied Principles:

  • Always try to loose the coupling between classes that communicates.

If you have any doubt or question, just ask.

I hope you liked this post, see you soon.

Design Pattern – Observer (Part 01)

Hello, how are you?

Today we will talk about another Design Pattern, “Observer”. If you want to see the first design pattern that we studied you can see it here (Strategy). Let us do a fast review about all design pattern subject that we have studied so far:

      Design Pattern: Strategy

 

    Studied Principles:

  • Identify everything that changes and isolate it from what does not change.
  • Program to an interface.
  • Give priority to composition rather than inheritance.

Let us work with the following user case:
“Mail4Usted is a company that sends emails to the clients that are recorded in its database. The company has a system that applies specifics configurations to each email server, there are a specific configurations for emails like Gmail, Hotmail.


The Mail4Usted is requesting a refactoring in its system. The problem is that the last company that was doing the maintenance of the company system has disappeared; everything that the Mail4Usted can do is to send the last version of the software code.

The system sends email only to two email servers: Gmail and Yahoo. The Mail4Usted wants its system to send email to the Hotmail customers; if the Mail4Usted likes the job new requests will be done.
Our newest customer also explains that this division for the email servers is needed because of the specific configuration that it is applied for each email server.”

The code that we received is written bellow:

public class EmailSender{
    public void sendNewEmails(){
        String emailText = getNewEmailTextFromDataBase();
        String emailSubject = getNewEmailTitleFromDataBase();

        sendEmailToGmail(emailText, emailSubject);
        sendEmailToYahoo(emailText, emailSubject);
    }

    //Others methods
}

A very simple and pour solution would be, to write the method that sends email to the Hotmail and we would be happy:

public class EmailSender{
    public void sendNewEmails(){
        String emailText = getNewEmailTextFromDataBase();
        String emailSubject = getNewEmailTitleFromDataBase();

        sendEmailToGmail(emailText, emailSubject);
        sendEmailToYahoo(emailText, emailSubject);

        // Our new method
        sendEmailToHotmail(emailText, emailSubject);
    }

    //Others methods
}

Imagine if every time that an email server had to be added or receive some maintenance in the system, our main class will be edited. Our main class would be long, hard to maintain and with none cohesion.

To make our code better we could apply two design patterns: starting with Strategy and then the Observer.

What always change in our code that we could isolate? Notice that we have a behavior that is always changing and every refactor that we have to do will affect our main class; this is something that does not need to happen.

Applying the concepts of the Strategy pattern we will isolate the behavior that always changes. But to do things more interesting, what if we understand a little bit about the Observer pattern so we might apply the two patterns together? Let us see a little history that will give us the idea of how the Observer pattern works:

“Imagine that you subscribed in a store to receive its announcements about some products with discounts. Even if you do not have any idea of when you can buy these products with discounts, you will receive the announcement.
Notice that you will be like a “target” of these notifications even if you are busy with others occupations. You will receive the announcements no matter if you are reading the news paper, watching TV or walking with the dog.”

What if we apply this “announcement” idea here? We could write the code isolating all send email behavior (Strategy). After we isolate the code that varies into a class, this class will receive like a notification informing that it already has the needed data (working like a Listener). We will be applying the Observer pattern that works like this: “The class A notifies to the class B needed information, the class B will work with this information”.

We could define the Observer pattern by:

“Defines a dependency relationship “One to Many”. When this objects state changes, all others objects with this relationship will be notified about this changing.”
To apply this concept in our user case we will use the class EmailSender to notify each class EmailHoster that a new routine to send email will be able to begin.

First let us take a look in how our interfaces will be (remember to always code to interfaces, and interfaces means a super type!):Design Pattern Observer Parte 01
With this interfaces we will have a code more flexible to refactoring, with good design patterns applied.

The Listener will be notified that some changing has happened (update(…) method) in the stated of our object “Notifier” (that it is the responsible to notify). After the object Listener receive this notification, it will send the emails (sendEmail() method).

Our classes of the type Listener and EmailPattern:Design Pattern Observer Parte 01

Our class Notifier:

Design Pattern Observer Parte 01
We have isolated all behaviors that changes (Strategy). We removed the code from the principal class, we have now a class that will send the email (EmailPattern classes); this “send email” code will be inside the class EmailPettern. We also have a class to set up the info and give to the EmailPattern classes (EmailSender).

Take a look how our classes will be coded:

public class EmailSender implements Notifier {
    private List listeners;
    private String emailText;
    private String emailSubject;

    public EmailSender(){
        listeners = new ArrayList();
    }

    public void addListener(Listener listener){
        listeners.add(listener)
    }

    public void removeListener(Listener listener){
        listeners.remove(listener)
    }

    public void createEmails(){
        emailText = getNewEmailTextFromDataBase();
        emailSubject = getNewEmailTitleFromDataBase();

        notifyListeners();
    }

    public void notifyListeners(){
        for(Listener listener : listeners){
            listener.update(emailText, emailSubject);
        }
    }

    //Others methods
}
// All classes would have almost the same implementation with their own peculiarities.
public class GmailPattern implements Listener, EmailPattern {
    public void update(String emailText, String emailSubject){
        // apply class peculiarities
        sendEmail();
    }

    public void sendEmail(){
        // send the email
    }
}

I only wrote above the code of the GmailPattern to do the reading easier. All others classes like HotmailPattern, YahooPattern would have the same methods with not equal behaviors.

You can see how cleaner our code is, with more cohesion and functional. No matter which kind of email we are working with (GmailPattern, YahooPattern or HotmailPattern), our class of the type Notifier will notify to its Listener that some changing happened in its state. Our class Notifier does not need to know anymore which kind of email server (Gmail, Yahoo, Hotmail …) it is working with. Can you see how our class EmailSender still working with the emails in a “cleaner” way?

Notice that if we need to change the method that configures the Hotmail html, our class EmailSender will not receive any edition. Isolating this behavior we are allowing our software to be more flexible to changes.

You may be thinking: “What is the advantage of the Observer pattern? Where can I apply this?” I will write some samples below:

  • Every time a car passes through a Stop light without stopping, some machine will take a picture and send it to the system. There is “somebody” that “saw” this car passing and notified to the system what happened.
  • An application that sends online messages. Let us to study some messenger: the old ICQ (but work the same with the messengers of our days) where you need to have the app in your pc. You can send a message by selecting a buddy, typing some text and sending it. The ICQ notifies the server delivering this message. Or the ICQ of your buddy will search for undelivered messages there or the server will notify the user ICQ in his PC. One thing is for sure, no matter what your buddy is doing: “reading soap opera news”, or “watching Tom & Jerry cartoons on Youtube”, he will receive this message.
  • One simpler sample to finish: a TV remote control. There is an application waiting for the stimulus that comes from the control. When you push the button the application understand the action you requested and execute it.

But we still having a strong coupling between our class EmailSender and its Listeners (GmailPattern…). Take a look at the code above and try to figure it out…

To let this coupling easier to see, let us take a look in a new user case:
“Image now that more than the subject and the email text (body text), it will necessary to inform which Yahoo account we will use. With this new user case, we will have a Listener with different behavior of the others.”
Every time we need to change the amount of parameters to send to a Listener, like YahooPattern, our Notifier (EmailSender) will have to change too.

How can we work in this coupling? The ideal is when you edit one class, this editing do not affect any other.

We will see in the next post about Design Patterns a solution to louse this coupling.

See you soon! o_

Design Pattern – Strategy

Hello, how are you?

I will post here some design patterns of the study I am doing about this subject. The base book to this study will be Head First – Design Patterns. I will describe in here the same patterns that we can find in the book, but I will be using different samples and adding more material about this subject as soon it is possible.

Let us use this user case: “An internet site that sells toys cars is receiving a lot of customer visitors every day and becoming more famous. Its investors want more; they want that the site provides to the customers the simulations of the toy car actions.”

Check below our class model (there are others sub classes of ToyCar that are not described below):

Design Pattern - Strategy

The investors want that the car perform the action of starting the engine, to the customers may hear the engine sound. To accomplish this, the solution that it is “the most useful, fastest and quickest” may be to apply some changing in the super class. What of bad could come of using this solution that the Java gives us? Any change in the super class ToyCar will be reflected to all sub classes, and all sub classes will have the same behavior! We just have to create a method to start the engine (“startEngine()”) and our problem will be solved:

Design Pattern - Strategy

The team was very happy with the result of this new functionality that was delivered on time. Now the customers can hear the engine sound. BUT, after a phone call it was possible to see that something bad happened. One of the investors saw something in our application that should never happen, a wood car starting its engine. Why this happened? Let us see our model:

Design Pattern - Strategy

Our wood car, that also has ToyCar as super class, received the method to start the engine when a wood car does not have an engine. What could we do to solve this problem? We could just override the method:

    @Override
    public boolean startEngine() {
        // Do nothing
    }

Would the above code be the best solution? Let us suppose that we have a sub class of ToyCar, a metal car (“MetalCar”) where we would have to override the method too. By doing this method overriding in all classes methods we are increasing our project complexity. And each time, that a new ToyCar sub class is created and this sub class should not have the method startEngine() implemented, we would have to override this method also.

So, which solution would be the best one here? Let us apply the first pattern principle of this study:
“Identify everything that changes and isolate it from what does not change.”
What is the meaning of this? Think about an engine behavior that will be present in one class and other different engine behavior that should be present in another class; we could isolate this behavior from our ToyCar class. Instead of letting our class ToyCar handling this behavior, why do not delegate it? Here it come our second pattern principle:
“Program to an interface”
This principle is nothing more than: use all benefits from super class. Imagine if we have an interface with a visible method, our class will not care with which behavior the interface method has. Let us create an interface to handle this engine behavior:

Design Pattern - Strategy

Bellow you can check how our classes will be implemented. First the class ToyCar, then Mercedes and WoodCar:

// Interface and Engine Behavior implementations

public interface EngineBehavior {
    public boolean startEngine();
}

public class NoEngineBehavior implements EngineBehavior {

    @Override
    public boolean startEngine() {
        System.out.println("No engine to turn on");
        return true;
    }
}

public class RegularEngineBehavior implements EngineBehavior {

    @Override
    public boolean startEngine() {
        System.out.println("Engine On");
        return true;
    }
}

public class PowerfulEngineBehavior implements EngineBehavior {
    
    @Override
    public boolean startEngine() {
        System.out.println("Powerfull Engine On");
        return true;
    }
}

// Our Classes Implmentatioins
public class ToyCar {
    private int doorTotal;
    private int maxSpeed;
    protected EngineBehavior engineBehavior;
    // Others attributes
    
    public ToyCar(){
        engineBehavior = new RegularEngine();
    }
    
    public void startEngine(){
        engineBehavior.startEngine();
    }
    
    // Others methods
}

public class Mercedes extends ToyCar {
    
    public Mercedes(){
        engineBehavior = new PowerfulEngineBehavior();
    }
    
    @Override
    public void startEngine(){
        engineBehavior.startEngine();
    }    
}

public class WoodCar extends ToyCar {
    
    public WoodCar(){
        engineBehavior = new NoEngineBehavior();
    }
    
    @Override
    public void startEngine(){
        engineBehavior.startEngine();
    }
}

I know that we could change the way that our interface is receiving its implementation (“engineBehavior = new NoEngineBehavior();”) and another “upgrades” about patterns, but this refactoring is subject to another posts.

You may think: “Wait a minute, even if I do comment the method startEngine() or put the code engineBehavior = new NoEngineBehavior(); I still have “duplicated code” in my system!” Think with me about this next investor requirement: “When we call the method startEngine() in a type of ToyCar that does not have an engine, we would have to register this action in a log”. If you notice how our classes are implemented now (WoodCar, and all others MetalCar, BambooCar), we would have to change only the method startEngine() in our class NoEngineBehavior. All classes that do not have an engine behavior would be with a correct functioning.

Final considerations:

  • The class name should indicate a noun. Things like: “Car”, “House”, “Computer”, etc. In the user case that we simulated today this behavior is like our noun. It is a class that handles a behavior pattern.
  • Program to an interface – this principle does not necessarily means that we have to create an Interface, but it means always program to a super type. You should always program to a super type like a regular Class (POJO), Abstract Class and Interface. You must decide the best type for your system and implement it. In the book Head First – Design Patterns the authors make this explanation very clear. Do not mistake this principle that says: “always code for a super type” with “always create an interface”. A super type will be the best solution to your design problems in like 99% of the situations.
  • We just studied another project Principle:
    “Give priority to composition rather than inheritance”.

As we saw in our user case today, we used an interface to create the composition. Using composition in our system will make our job easier.

    Design Pattern: Strategy
    Studied Principles:

  • Identify everything that changes and isolate it from what does not change.
  • Program to an interface.
  • Give priority to composition rather than inheritance.

I hope this post might be able to help you.

If you have any questions or ideas to share just leave your comment.

See you soon.