Pages

Monday, May 27, 2013

Duplication - A bit between your teeth

I presume that pretty much everybody who has been in contact with the java programming language either in studies or professionally even for a little bit, knows that duplication is a code smell.
We all know that some consequences of duplication are: less maintainability, less readability, the code is more likely to contain bugs, performance issues... and many more.

I think there should not be need to explain what duplication is, but just in case let's write only one line to define it and also make sure that we understand it:
"Duplication is the existence of multiple copies of a single concept"


Are there any doubts until this point?...
Please go back and read once more the definition if you still are not sure about it.

So, how do we fix duplication?


But if it is so easy to understand what duplication is and also how simple it is to refactor, why do we find it all over the place, no matter what software we are looking at.

Well... there are many reasons why there is duplication all over the place:
  • sometimes we just rush to get things done and we don't care about it. 
  • maybe we think that refactoring is boring or is not profitable, so we have no patience to do it.
  • other times we think there are always more important things to do and duplication is not really affecting us.
  •  also sometimes when we want to do something about it, we just can't see it even if it is in front of us.             

 So, what do you think?... Any of this may be the reason why you are not fixing duplication?
If your reason is any of the first 3, I am sorry, but this blogpost will not be of any use to you and the best you can do is close this browser tab or surf somewhere else.

But if it is the 4th, the reason why you are not fixing the duplication, then you might find the following lines very interesting....

This is the secret why many programmers sometimes find it so difficult to deal with duplication...

There are different kinds of duplication, this are some of the most important:
  • Literal
  • Structural
  • Semantic

Literal duplication
This is a very easy to spot kind of duplication. It is basically literal values that are repeated in our code.

e.g
 public class RepeaterSpecification {  
      @Test  
      public void repeatsInput() {  
               assertThat("value",is(repeat("value")));  
      }  
      @Test  
      public void repeatsEmptyInput() {  
              assertThat("",is(repeat("")));  
      }  
     //...  
 }  

The most common way to fix this type of duplication is to create a local variable. Let's have a look at a possible refactor:

 public class RepeaterSpecification {  
      @Test  
      public void repeatsInput() {  
         String input = "value";  
         assertThat(input,is(repeat(input)));  
      }  
      @Test  
      public void repeatsEmptyInput() {  
         String input = "";  
         assertThat(input,is(repeat(input)));  
      }  
     //...  
 }  
It looks like we no longer have literal duplication. But unfortunately as you probably noticed, sometimes when fixing one type of duplication we generate another type of duplication. Keep reading to find out more...

Structural duplication
We can recognize this situation when the logic is duplicated but it operates on different data.
See this situation in the following example:

e.g
 public class RepeaterSpecification {  
      @Test  
      public void repeatsInput() {  
         String input = "value";  
         assertThat(input,is(repeat(input)));  
      }  
      @Test  
      public void repeatsEmptyInput() {  
         String input = "";  
         assertThat(input,is(repeat(input)));  
      }  
     //...  
 }  


As you can see I toke this code from the previous example. The assertThat() operation is identical, the only difference is the data that it uses. Let's have a little look at a way how to fix structural duplication:


public class RepeaterSpecification {  
      
      @Test  
      public void repeatsInput() {  
         assertThatInputIsRepeated("value");  
      }  

      @Test  
      public void repeatsEmptyInput() {  
         assertThatInputIsRepeated("");  
      }
 
      private void assertThatInputIsRepeated(String input) {  
            assertThat(input,is(repeat(input)));
      }
     //...  
 }


Now that we extracted the method that does the assertion we no longer have duplication.

Semantic duplication
This is  the situation where different code implementations represent the same functionality or concept.
The definition of semantic duplication teaches us that duplication can be invisible from the point of view of the code("The definition from the start of this post makes a way more sense now, uh? :)" ). This kind of duplication is probably one of the most difficult to spot.

e.g
public class TeamValidator {       
  
      public boolean isThereALeader(List<Members> team) {  
           Iterator<Member> iterator = team.getIterator();
           while(iterator.hasNext()) {
              Member member = iterator.next();
              String role = member.getRole();
              if(role.equals("Leader"))
                return true;
           }  
           return false;
      }  

      public boolean areThereAtLeast2NewJoiners(List<Members> team) {  
            for(Member member:team) {
                DateTime aMonthAgo = DateTime.now().minusMonths(1);
                if(member.startingDate().isAfter(aMonthAgo))
                return true; 
            }
            return false;   
      }
     //...  
 }


At first glance, when we look at the two methods in the code above we cannot really see much duplication. No matter how much we look at it, we will not see it. Semantic duplication is invisible from the implementation point of view. To spot it what we need to do is spot the behavioral anti pattern that is hidden in the code. If we think about it, basically the repetition going on is that both methods iterate one list of the same type and then apply certain criteria(Completely different implementations but one same concept).
Semantic duplication is more difficult to fix than other types of duplication and often requires a bigger refactoring effort. Here is one possible solution that helps us get rid of it using Java generics:

 public class TeamValidator {      
    public boolean isThereALeader(List<Member> team) {   
         return new LeaderVerifier<Member>().evaluate(team);  
    }   
    public boolean areThereAtLeast2NewJoiners(List<Member> team) {   
         return new NewJoinersVerifier<Member>().evaluate(team);  
    }  
 }  


 public abstract class LoopEvaluator<T> {

 public boolean evaluate(List<T> list) {
  for (T element : list) {
   if(evaluateElement(element)) {
    return true;
   }
  }
  return false;
 }
 
 public abstract boolean evaluateElement(T element);
 
}


public class LeaderVerifier<T extends Member> extends LoopEvaluator<T> {

 @Override
 public boolean evaluateElement(T element) {
  return element.getRole().equals("leader");
 } 
}



public class NewJoinersVerifier<T extends Member> extends LoopEvaluator<T> {

 private int newJoiners;
 
 @Override
 public boolean evaluate(List<T> list) { 
  this.newJoiners = 0;
  return super.evaluate(list);
 }
 
 @Override
 public boolean evaluateElement(T element) {
  DateTime aMonthAgo = DateTime.now().minusMonths(1);
  if(element.startingDate().isAfter(aMonthAgo)) 
   this.newJoiners++;
  return newJoiners == 2;
 }
}


Duplication is not a little topic at all. The 3 types of duplication I mentioned in this post are from my point of view some of the most common but there are many more. Here a link where I found where at the bottom you can find a mention to other kinds of duplication: http://blogs.agilefaqs.com/tag/code-smells/


                                                                     
 I am the spaghetti monster, You cant get rid of me!!!! Hahahaha......

Just to conclude this post, I want to say that I have the impression that duplication many times is an  underestimated code smell that undetected grows and grows and ends up transforming systems into spaghetti monsters.

Lets get rid of it while it is just a bit between your teeth! ;)







Thursday, May 23, 2013

How to verify that void methods were called using Mockito

You can also read this article in our brand new medium space. Click here!  Remember follow Javing on medium to make sure you don't miss out on some of the great new upcoming content.

Mockito is one of the most popular mocking frameworks for java.
This post Is just little miscellaneous where I will show you how to mock and verify a void method call.

Sometimes when we test a call to a void method all we want to do is just make sure that at some point in its life cycle, another method will be called with certain parameters.
Let's see the following example:
 public class SomeClass {  
      private OtherClass otherClass;  
     
      public SomeClass(OtherClass otherClass) {  
           this.otherClass = otherClass;  
      }  
      protected void firstMethod(int value) {  
           if(value > 0) {  
                secondMethod("Yes!");  
           }  
           else {  
                secondMethod("No!");  
           }  
      }  
      private void secondMethod(String value) {  
           otherClass.someMethod(value);  
      }       
 }  

In the above piece of legacy code the most important part is a method called "someMethod()". We must make sure that it is called in a proper way, but unfortunately it belongs to a dependency to which we have no access and also to make it more complicated it is inside a private method.

Mockito framework could help us mock and verify that method call.
Here is how we can do it:
 package demo;
 import static org.mockito.Mockito.verify;  
 import org.junit.Before;  
 import org.junit.Test;  
 import org.mockito.Mock;  
 import org.mockito.MockitoAnnotations;  
 import code.OtherClass;  
 import code.SomeClass;  
 public class TestClass {  
      @Mock  
      private OtherClass otherClass;  
      //Class under test  
      private SomeClass someClass;  
      @Before  
      public void prepareDependencies() {  
           MockitoAnnotations.initMocks(this);       
           someClass = new SomeClass(otherClass);  
      }  
      @Test  
      public void is_the_value_greater_than_zero() {  
           someClass.firstMethod(8);  
           verify(otherClass).someMethod("Yes!");  
      }  
      @Test  
      public void is_the_value_smaller_than_zero() {  
           someClass.firstMethod(-1);  
           verify(otherClass).someMethod("No!");  
      }  
 }  

The most important things to highlight in this test class are:
  • The class under test is never mocked.
  • The dependencies of the class under test need to be mocked.
  • By calling a method on a mock object we will mock that method call
  • By using the verify() method we will test that at some point the method from the mock was called  with the exact same parameters.
  • The test class can access the protected method because the package name is the same.(But of course in your project structure test will be under src/test/java and production code under src/main/java)

Monday, May 6, 2013

Using transaction attributes in EJB 3.1 - Container Managed Transactions

When somebody refers to container managed transactions, what we understand is that the EJB container is responsible of managing transactionality for the methods inside EJB's deployed in the EJB container.

The theory behind transaction management in EJB 3.1 is not brief and probably my post would become to long if I tried to explain other important concepts. In this post I want to just focus on an important concept known as the transaction attribute.

To simplify this concept, I will refer to it, as a configuration given to a method/function within an EJB, that will tell the EJB container what to do with the incoming transaction when that method is called.

The thing that will determine what will occur with the transaction when a certain transaction attribute is used will be the transactional context from where the method was called. In other words, if the enterprise method annotated with a certain attribute was called from a non-transactional(e.g a web page) will manage the transaction differently than if it was called from a transactional context(e.g another EJB). And this is the reason why sometimes we have to choose wisely our transaction attributes.

To use transaction attributes in our EJB's its very simple, all you need to do is use an annotation:
 @Stateful  
 public class SomeBean implements SomeInterface {  
   @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)  
   public void someMethod(){  
    //...  
   }  
   //...  
 }  

Now that we know how to annotate the methods, lets see what will occur when each of the transaction attributes is used:

REQUIRES_NEW
When the calling method is not in a transaction: Starts a new transaction.
When the calling method is in a transaction:  Suspends the existing transaction and creates a new one.

REQUIRED

When the calling method is not in a transaction: Starts a new transaction.
When the calling method is in a transaction:  Executes in existing transaction.

NEVER

When the calling method is not in a transaction: It will execute with no transaction.
When the calling method is in a transaction:  It will throw an exception.

NOT_SUPPORTED

When the calling method is not in a transaction: It will execute with no transaction
When the calling method is in a transaction: It will execute with no transaction(No exception will be thrown)  

SUPPORTS

When the calling method is not in a transaction: It will execute with no transaction.
When the calling method is in a transaction:  Executes in existing transaction.

MANDATORY

When the calling method is not in a transaction:  It will throw an exception.
When the calling method is in a transaction: Executes in existing transaction(Execution continues because the caller was already in a transaction).




Share with your friends