Thursday, 11 December 2014

Picture with a celebrity

Happy to have the priviledge to take a picture with one of the celebrities of the world of software development, R.C Martin. The event was held once more in central London in one of the many fabulous skyscrapers at "The sun" offices. Great atmosphere, drinks and pizza to make the huge crowd of IT professionals comfortable. Martin in a great speech counter attacked recent critics that were made to the Test Driven Development approach by David Heinemeir Hansson. Once more a great talk by one of the most important figures of modern software development.

Myself with R.C Martin(a.k.a Uncle Bob)

Monday, 8 December 2014

Tip for quicker coding in IntelliJ

Did you know that with IntelliJ you can use Live Templates, to quickly insert predefined snippets of code. This can speed up your coding...

All you have to do is create templates for anything that you want, assign an abbreviation to it and the editor will do the rest for you just by typing the abbreviation.
Here an screen that shows, where in the IDE you can find this feature:

  

This is a cool one I like very much. You just type 'test' then hit tab and you will get a cool fresh test method :)

 @Test  
 public void $END$() throws Exception {  
 }   

Fore more detailed info about live templates, you can read this nice article at JavaCodeGeeks.com

Wednesday, 29 October 2014

Indaface!



Recently my team leader gave me an S.L.A.P, hehehe...
Don't worry this is not a case of bullying, it just a way of refering to an important Object Oriented Principle known as the Single Level of Abstraction Principle.
As Usual at the office paring on an story, when we got to the refactoring bit, I was told to improve a method that had some ugly conditional logic on it, and also some duplication.
Instead of removing the duplication, I just delegated all the problematic part to another method, so the original method would look smaller and cleaner, but...
He said to me: Do you think that code you just delegated is located now at a different level of abstraction?... Indaface! Violation of S.L.A.P
Below, an example that somehow recreates todays funny situation :P Sorry, can't show you the real code(Dont wanna get in trouble :) ).

 /*  
     We have a vault that its being populated and categorized but there is a little 
     duplication issue when populating the vault with CAT-3 items. Items withGrook() 
     are definitely CAT-3, but those withTrook() are only categorized as CAT-3 if 
     klop.isHigh().   
 */  
    public Vault stuff(Klop klop, Vault vault) {  
     vault.include("CAT-1", azra());  
     vault.include("CAT-2", khy());  
     vault.include("CAT-3", things.stream().filter(withGrook()).
     map(toSponge()).map(toPlik(klop)).collect(toList()));  
     if(klop.isHigh())  
       vault.include("CAT-3", things.stream().filter(withTrook()).
       map(toSponge()).map(toPlik(klop)).collect(toList()));  
     return vault;  
     }  
 /*  
     At the beggining we may feel tempted to extract that vault.include, to its own
     method which will be specific to CAT-3 items, regardles that the stuff method looks
     shorter, the problem is that we did not remove the duplication plus we are disrespecting
     the S.L.A.P principle.  
 */      
      public Vault stuff(Klop klop, Vault vault) {  
           vault.include("CAT-1", azra());  
           vault.include("CAT-2", khy());  
           includeCat3Items(vault,klop);  
           return vault;  
        }  

   private void includeCat3Items(Vault vault, Klop klop) {  
           if(klop.isHigh())  
             vault.include("CAT-3", things.stream().filter(withGrook()).
             map(toSponge()).map(toPlik(klop)).collect(toList()));  
             vault.include("CAT-3", things.stream().filter(withTrook()).
             map(toSponge()).map(toPlik(klop)).collect(toList()));  
   }  
  
  /*If we want to respect S.L.A.P, in this case what we need to extract, is just the 
    changing part, and delegate the condition to check if klop.isHigh, to the delegate
     method.  
  */  
     public Vault stuff(Klop klop, Vault vault) {  
     vault.include("CAT-1", azra());  
     vault.include("CAT-2", khy());  
     vault.include("CAT-3", things.stream().filter(ook(klop)).
     map(toSponge()).map(toPlik(klop)).collect(toList()));  
     return vault;  
   }  

   private Predicate<String> ook(Klop klop) {  
     return klop.isHigh() ? withGrook(): withTrook();  
   }  

 /*  
     The final refactor could even go one step further by extracting implementation 
     detail into a plu(Klop klop) method  
 */      
   public Vault stuff(Klop klop, Vault vault) {  
     vault.include("CAT-1", azra());  
     vault.include("CAT-2", khy());  
     vault.include("CAT-3", plu(klop));  
     return vault;  
   }
  
   private List<Object> plu(Klop klop) {  
     return things.stream().filter(ook(klop)).map(toSponge()).map(toPlik(klop)).collect(toList());  
   }  
   private Predicate<String> ook(Klop klop) {  
     return klop.isHigh() ? withGrook(): withTrook();  
   }  


This post is dedicated to L.K, thanks for the patience :)

Tuesday, 23 September 2014

The Add-Delete ratio as a metric of code quality

Recently after reading some articles about software quality metrics, I started thinking a lot about what would be for me a metric that really could reflect the quality of the code in the system I am working in.

I am not a big fan of numbers but in the same way of an altimeter is a useful thing you want to look at when you are driving a plane, a good code quality metric could give you warning signs about system that you are building.

In page 15 of the book "Clean Code" by R.C Martin, it says that the only valid measure of code quality is, "What The Fucks per second".



Couldn't agree more, but the only problem with this metric is that is not easy to reflect in a chart so all others can see it and therefore have an idea of how bad the system really is...

Time ago while talking to a colleague here in London, we came to the conclusion that a really good metric to reflect the quality of the code we write, is the "Added-Removed code ratio".

So this is basically the ratio of added to removed lines of code in your system. 
To measure this, what you do is:

1 - At a point in time, take your system as a whole and count the amount of lines of code, of the target language, lets say Java(Just java, dont take xmls and other configuration files...).

2 - At a future point in time, take again the same system, and count the lines again.

3 - Write down the ratios and take note of the percentages the amounts of line are increasing, or decreasing and present the data in some chart.

 This metric if tracked often, such as the altimeter, will warn your department about when you need to invest more time in technical debt, and when your system is sustainable and you can keep pushing features.

I guess you wonder, how do I know this is right? 
Well, it is very simple, we just need to understand the definition of re-factoring which is:

"a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior."

Re-factoring its very important, because the more understandable the system is, the better quality it will have. So it is not about just the smaller your code is, but about tracking the amount of effort you expend in adding and removing(specially removing) stuff from it.
- In a system where we see that the remove ratio numbers across time are going in a down trend(smaller gap between added and removed lines), it means that the developers are taking care and the overall  quality is improving.

- In a system where we see that the remove ratio numbers across time are going in an up trend(big gap between added and removed lines), it means that the teams are not investing enough time in improving the quality of the software they make.

I hope you liked the post, I appreciate feedback, this is just my opinion.



Monday, 14 July 2014

Helping methods indentify their calling threads with ThreadLocal class

In multi threaded applications in occasions we want to identify the thread that called certain method.
We could pass some additional parameter for that purpose to the method we are calling, but that wouldn't be very elegant.
The class ThreadLocal allows us to manage an object within the current Thread scope.

Let's have a look at an example...

The class below called sample Thread, uses some service and that service has interest in knowing who called it.
So What we do is create some context with come kind of unique identifier(e.g ThreadName,UUID...) and then we give that context to the class ThreadLocal to handle it(We will create an special wrapper class to hold ThreadLocal).

 public class SampleThread extends Thread {  
   @Override  
   public void run() {  
     ThreadContext threadContext = new ThreadContext();  
     threadContext.setId(getName());  
     ContextManager.set(threadContext);  
     new BussinessService().bussinessMethod();  
     ContextManager.unset();  
   }  
 }  

The context could be anything we want, but in this example I will be using the Thread name.

 public class ThreadContext {  
   private String id = null;  
   public String getId() {  
     return id;  
   }  
   public void setId(String id) {  
     this.id = id;  
   }  
 }  

The class ContextManager will act as a container that will allow us to access and modify the context of the Thread.


 public class ContextManager {  
   public static final ThreadLocal threadLocal = new ThreadLocal();  
   public static void set(ThreadContext context) {  
     threadLocal.set(context);  
   }  
   public static void unset() {  
     threadLocal.remove();  
   }  
   public static ThreadContext get() {  
     return (ThreadContext) threadLocal.get();  
   }  
 }  

With this infrastructure in place, the Service can identify the calling thread.

 public class BussinessService {  
     public void bussinessMethod() {  
       ThreadContext threadContext = ContextManager.get();  
       System.out.println(threadContext.getId());  
     }  
 }  

Finally just to demo the concept we could just create a couple of Threads and run them to see how they are identified by the services via their context.

 public class Main {  
   public static void main(String args[]) {  
     SampleThread threadOne = new SampleThread();  
     threadOne.start();  
     SampleThread threadTwo = new SampleThread();  
     threadTwo.start();  
   }  
 }  

Friday, 20 June 2014

Creating an executable jar file with maven

It happen to me recently that I wanted to pack a little app with maven and run it from the console, but I always forget what is the config that I need to add to maven in order to make sure the manifest pointing to the class with the main method is included.

After wasting precious half hour around the internet and after I did what I wanted to do, I thought... What better place to write this config once and remember it forever, than my blog ;)

To do it just add the following to your pom.xml and make sure you write the correct path to your main class.


 <build>  
     <plugins>  
       <plugin>  
         <artifactId>maven-assembly-plugin</artifactId>  
         <configuration>  
           <archive>  
             <manifest>  
               <mainClass>com.djordje.tips.Main</mainClass>  
             </manifest>  
           </archive>  
           <descriptorRefs>  
             <descriptorRef>jar-with-dependencies</descriptorRef>  
           </descriptorRefs>  
         </configuration>  
         <executions>  
           <execution>  
             <id>make-assembly</id>  
             <phase>package</phase>  
             <goals>  
               <goal>single</goal>  
             </goals>  
           </execution>  
         </executions>  
       </plugin>  
       <plugin>  
         <groupId>org.apache.maven.plugins</groupId>  
         <artifactId>maven-compiler-plugin</artifactId>  
         <version>2.5.1</version>  
         <inherited>true</inherited>  
         <configuration>  
           <source>1.7</source>  
           <target>1.7</target>  
         </configuration>  
       </plugin>  
     </plugins>  
   </build>  

When the maven package gets executed two .jar files will be created.
The one with the text jar-with-dependencies on its name, will contain is the one we should run. To do it, just go to the terminal, navigate to it(inside the target folder) and type the command:

 java -jar myapp-jar-with-dependencies.jar  

Tuesday, 25 February 2014

paranoia testing

Somebody told me once a funny story about a woman who day after day kept arriving late to work, because once on her way to the office, she kept having the need to go back home again and again just to check that she unplugged the iron from the wall socket. Her unfounded fear was such that one day she finally decided to take the iron with her to the office in her handbag.

A common unfounded fear that some developers sometimes have when working with the database, is that they will fail to query it for whatever reason and they feel the need of testing that the database is returning them the expected values. It is common to see horrible tests like this one:

   @Test  
   public void whenAddingANewUserTheUserIsSavedToTheDatabase() {  
     //Tell hibernate to add this user to the database   
     ormAdapter.add(userFactory("djordje", "123"));  
     //Find the user and check its values  
     User savedValueInDatabase = adapter.find("djordje");  
     assertThat(savedValueInDatabase.getName(),is("djordje"));  
     assertThat(savedValueInDatabase.getPassword(),is("123"));  
     //Delete the test data  
     ormAdapter.delete(savedValueInDatabase.getName());  
   }   

The above test has many problems, not just it is slow, also it is wrongly aimed because is not testing the functionality of the application, it just testing that some third party framework(hibernate in this case) is working properly.

Developers who do this, don't understand that the database is just a detail/add-on of the application.
It is fine to perform a smoke test to ping the database if they want(just to verify that the configuration of the ORM framework was correctly done), but testing that the HQL or the hibernate criteria are returning some values is wrong.
"Hibernate, MySQL, Oracle... all are just vendors, their solutions will work, you don't need to test them again!"

Focus on testing the functionality by mocking the dependencies you have with the database.
The only thing that counts at the end of the day is that the inputs and outputs to the service layer are processed correctly. If the data comes from a database, a file, a socket... doesn't matter at all.
Here an alternative test that will mock a dependency to the database and will check that the data is processed correctly:

   @Test  
   public void loginTest() {   
     PersonManagementAdapterORM adapterORM = mock(PersonManagementAdapterORM.class);  
     when(adapterORM.find("djordje","123")).thenReturn(new Person("djordje","123"));  
     LoginService service = new LoginServiceImpl(adapterORM);  
     boolean authorized = service.login("djordje","123");  
     verify(adapterORM).find("djordje","123");  
     assertThat(authorized,is(true));  
   }  

Now tests main concern is the functionality and not how the data is added to, or retrieved from the database.
I trained the mock to behave as expected and I verified that its behavoir was executed as expected.
The database was not at all a concern.