Be a Developer, not a Blender

Do not Pass Over the Layers

We use layers in a project to isolate responsibilities in a project. Take a look below at a MVC classic representation:

mvc - w3schools

mvc – w3schools

MVC means Model, View and Controller. It is easy to find developers that affirm that they always use and apply this pattern in their projects, but several developers do not apply it. A code snippet was posted in the first page with this problem:

@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();
        }
    }
}

Why is the Controller annotated with @TransactionManagement when we know it handles the database connection? With this annotation with are using the Controller to affect the model.

We could say that:

  1. ManagedBeanOne has a behavior set by JSF
  2. ManagedBeanOne is using a method that will control the transaction
  3. ManagedBeanOne will define the method flow
  4. ManagedBeanOne will need to handle any kind of business exception, needing to do a rollback if needed

Why wasn’t the transaction delegated to another class, responsible only for that?

Notice that by adding a simple annotation envolving very  simple transaction management, the ManagedBean now has a responsability overload.

Pay Attention to the Packages

An easy way to see if our classes are passing over layers is looking at the packages import of our class.

If we see a DAO/Repository class imported in a Controller we can suspect that our code is not respecting the layers.

Imagine that we have the classes below:

  • DogController
  • DogService (will keep the business rules)
  • DogDAO
  • PersonService
  • PersonDAO

What I propose is:

  • DogController will “see” only the DogService
  • DogService will “see” only DogDAO or any other class in the “service” package
  • DogDAO will only “see” other classes in the DAO package
  • If PersonService need to search any Dog information, it will only “see” the DogService class and no the DogDAO class. With this kind of approach we will be encapsulating the Dog data access behind the DogService. Any update in the Service or in the DAO would be automatically reflected in the project.

Conclusion

Do not pass over your layers. Your Controller should only be allowed to handle the request flow: set the page that will be displayed, loading properties file texts, formatting values to be displayed in the response, etc.

2 thoughts on “Be a Developer, not a Blender

Leave a Reply to Luiz Ricardo Cancel reply