Tuesday, March 15, 2016

Java vs Golang - Parameterized tests

Although I like Java, I think that with all its drawback it brings years of knowledge and optimization, I find too many times that when you "think in Java" you tend to creat complicated solutions. By complicated I mean hard for a developer to grasp and to remember.

In the following example we can see several differences that make the Java code look `old` and clumsy and not fun.
1. 7 imports  VS 1 in Golang.
2. Everything is a class. Fibonacci is a function in Golang.
3. Why hiding from the developer the fact that the test runs in a loop?
4. All these annotations.

Simplicity matter!
When you try to produce a simple code you end up with less dependency, less code, less magic, less moving parts and less things to know in order to produce quality code.
And as always, but especially in programming, Less Is More.


Simplicity Matters by Rich Hickey

The Java way from JUnit-team
 import static org.junit.Assert.assertEquals;  
 import java.util.Arrays;  
 import java.util.Collection;  
 import org.junit.Test;  
 import org.junit.runner.RunWith;  
 import org.junit.runners.Parameterized;  
 import org.junit.runners.Parameterized.Parameters;  
 @RunWith(Parameterized.class)  
 public class FibonacciTest {  
   @Parameters  
   public static Collection<Object[]> data() {  
     return Arrays.asList(new Object[][] {     
          { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 }   
       });  
   }  
   private int fInput;  
   private int fExpected;  
   public FibonacciTest(int input, int expected) {  
     fInput= input;  
     fExpected= expected;  
   }  
   @Test  
   public void test() {  
     assertEquals(fExpected, Fibonacci.compute(fInput));  
   }  
 }  
 public class Fibonacci {  
   public static int compute(int n) {  
     int result = 0;  
     if (n <= 1) {   
       result = n;   
     } else {   
       result = compute(n - 1) + compute(n - 2);   
     }  
     return result;  
   }  
 }  


The Golang way
 package Fibonacci  
 import "testing"  
 func TestFibonacci(t *testing.T) {  
      parameters := []struct {  
           input, expected int  
      }{  
           {0, 0}, {1, 1}, {2, 1}, {3, 2}, {4, 3}, {5, 5}, {6, 8},  
      }  
      for i := range parameters {  
           actual := Fibonacci(parameters[i].input)  
           if actual != parameters[i].expected {  
                t.Logf("expected%d: , actual:%d", parameters[i].expected, actual)  
                t.Fail()  
           }  
      }  
 }  
 func Fibonacci(n int) (result int) {
 if n <= 1 {
  result = n
 } else {
  result = Fibonacci(n-1) + Fibonacci(n-2)
 }
 return
}

No comments: