DRY benchmarking….

May 13th, 2008

Every time we try to write a benchmark for particular functionality, we habitually specify a load (max iterations), write a for-loop, set timers before and after the loop, and call the method of interest inside this loop. This typically involves copying & pasting from another benchmark and adapting the current benchmark to your needs. Why don’t we try, instead of copy & paste, to define an idiom that we could reuse for writin benchmarks? Something like this


public class Benchmark {
    private final int iters;
    public Benchmark(int iters){
        this.iters = iters;
    }

    public <T>long given(
    final Callable<? extends T> op
    ) throws Exception
    {
    	// warm things up
        for(int idx = 0; idx < 10000; idx++){}

        long time = System.nanoTime();
        for(int idx = 0; idx < iters; idx++){
            op.call();
        }
        time = System.nanoTime() - time;
        return TimeUnit.NANOSECONDS.toMillis(time);
    }
}

How can use this? This is simple….


    public static void main(
    String[] args
    ) throws Exception
    {
      System.out.println(new Benchmark(100000).given(
      	new Callable<Void>(){
            public Void call() throws Exception {
                System.out.println();
                return null;
            }
      }));
    }

Using this idiom will make the benchmarking of method calls easier…So please start using it :)

patterns, programming | No Comments | Trackback

No more downcasting via “Recursive Bounds”

May 4th, 2008

I recently coded a fairly tiny application that made use of the MVC pattern. One of the things that I noticed while I was writing it was that I was down-casting a lot. Imagine something like this:

Example


// main type
interface Model {
	void someMethod();
}

// implementation
class Mixer implements Model {
    public void anotherMethod(){
    	System.out.println("hey");
	}
    public void someMethod() {
    	System.out.println("dude");
	}
}

Now If I want to invoke both methods, I’d have to do something like this:


    final Model m = new Mixer();
    m.someMethod();
    // downcasting .
    // imagine this with more model objects
    // with unique methods...
    ((Mixer)m).anotherMethod();

I am really annoyed about this whole downcasting. It does not make my code look that pretty. So I decided to use Generics; more in specific the recursive bounds idiom which was used in the implementation of the Java 5.0’s Enums.

The solution


interface SuperClass<S extends SuperClass<S>> {
    S subclassInstance();
}

interface AnotherType {
    void print();
}

The next step is to implement the previous interfaces. Something like this:


/**
 * subclass A
 */
static
class SubClassA implements
        SuperClass<SubClassA>,
        AnotherType
{
    private final String name;
    SubClassA(){
        final Random random = new Random(19580427);
        name = getClass().getName()
                + random.nextInt();
    }
    public SubClassA subclassInstance(){
    	return this;
	}
    public void print(){
    	System.out.println(name);
	}
}

/**
 * subclass B
 */
static class SubClassB implements SuperClass<SubClassB>,
        AnotherType
{
    private final String name;
    SubClassB(){
        final Random random = new Random(19580427);
        name = getClass().getName()
                + random.nextInt();
    }
    public SubClassB subclassInstance(){
    	return this;
	}
    public void print(){
    	System.out.println(name);
	}
}

Then I can write code like this one and totally avoid dowcasting between objects:


public static void main(String... args){
 final SubClassA      		 sca  = new SubClassA();
 final SuperClass<SubClassA> sc   = sca;
 final SubClassA      sca2    = sca.subclassInstance();
 final SubClassA      sca3    = sc.subclassInstance();

 // no casting..cool huh!
 sca2.print();
 sca3.print();
}

And there you go… I’ve totally solved my downcasting problem!

patterns, programming | No Comments | Trackback

A pattern for using EasyMock…

May 3rd, 2008

Ralf Stuckert wrote a great article on EasyMock titled "Getting started with EasyMock2."  He clearly defined a pattern for using this library.

The pattern is

    1. Create a mock.

    2. Set up your expectations.

    3. Set the mock to replay mode.

    4. Call your code under test.

    5. Verify that your expectations have been met.

Believe me, knowing this pattern will save you a lot of time trying to figure out how to really use EasyMock when writing tests.

patterns | No Comments | Trackback

A live template for Java 5 Locks

April 26th, 2008

Every time I used Java 5 new locks I found myself writing the same lock.lock(); try {…} finally {lock.unlock();} over and over again. Sometimes I’ve even coded, unintentionally, a lock.lock() instead of a lock.unlock(). Because of this and other reasons which I won’t share (i.e., I don’t like to copy & paste stuff) :) I decided to automate the addition of the Java 5 locks via IntelliJ live templates. How is this going work? Simply type lock[tab] and voila you will have a new a Java 5 synchronized block written for you


$LOCK$.lock();
try {
    //tocode
} finally {
    $LOCK$.unlock();
}

p.s.,
I almost forgot. In order to make the previous live template to work for both write and read locks, you will have to set the $LOCK$ variable as a variable of the type Lock (i.e., variableOfType(”Lock”)).

toolset | No Comments | Trackback

Binding data to Java enums…

April 25th, 2008

Paul Stovell blogged about binding data to enums in C#. Here is how I would implement this technique in Java….

First, an annotation that I will use to bind data to my enum


@Target(Element.FIELD)
@Retention(RententionPolicy.RUNTIME)
public @interface Config {
	String name();
	String alias();
}

Then, here is my enum


public enum Role {
@Config(name="James Bond", alias = "Agent 007")
AGENT;

// static attribute that will allow us to
// config the enum only once.
private static boolean isConfigured = false;
static {
if(!isConfigured){
    configureRole();
}
}

private RoleValue value;
Role(){
}

public RoleValue getValue(){
    if(value == null){
        throw new IllegalStateException();
    }
    return new RoleValue(value);
}

private static void configureRole(){
    final Field[] declaredEnums = Role.class.getDeclaredFields();
    for(Field eachField : declaredEnums){
        final Config placedConfig = eachField.getAnnotation(Config.class);

        final boolean isValuesField     = eachField.getName().equals("$VALUES");
        final boolean isRefreshedField  = eachField.getName().equals("isConfigured");
        final boolean isValueField      = eachField.getName().equals("value");

        // ... we want to igonore the VALUES, isConfigured, and value fields.
        // ... we care only about the Role's enum instances.
        if(isValuesField || isRefreshedField || isValueField){
            continue;
        }

        final String name           = placedConfig.name();
        final String alias          = placedConfig.alias();
        final Enum<Role> actualEnum = valueOf(eachField.getName());

        final RoleValue enumValue   = new RoleValue(name, alias);

        try {
            final Field field = actualEnum.getDeclaringClass().getDeclaredField(
                  "value"
             );
            field.setAccessible(true);
            field.set(actualEnum, enumValue);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

        isConfigured = true;

    }
}

/**
 * a updatable value
 */
public static class RoleValue {
    private final String name;
    private final String alias;
    public RoleValue(String name, String alias){
        this.name   = name;
        this.alias  = alias;
    }

    public RoleValue(RoleValue value){
        this(value.getName(), value.getAlias());
    }

    public String getName(){
        return name;
    }

    public String getAlias(){
        return alias;
    }
}
}

interesting way to play with Java 5.0’s enums…. cool :)

programming | No Comments | Trackback

Debugging windows services in .NET

April 19th, 2008

The other day I was trying to test a Windows Service that I implemented for a friend. I thought to myself that this was going to be an easy endeavor. I just needed to install the service, run it, set some breakpoints, then attach its process to the debugger and that was it. Oh boy… I was SOOO wrong. It was not as easy as I thought it would be.

I cannot remember how much time I spent trying to make it work using the above approach. It was until I decided not to rely on this “supposedly clean” way for debugging .NET Windows Service applications that I was able to complete my testing, so I could tell my friend “here is the service.”

Here is what I wrote to solve my debugging problem:


static void Main()
{
#if (!DEBUG)
    System.ServiceProcess.ServiceBase[] ServicesToRun;
    ServicesToRun = new System.ServiceProcess.ServiceBase[]{
         new MyService()
    };
    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#else
    // Debug code: this allows the process to run
    // as a non-service.
    // Put a breakpoint on the following line
    MyService service = new MyService();
    System.Threading.Thread.Sleep(
      System.Threading.Timeout.Infinite
    );
#endif
}

I know, I know, this is not pretty, but It works. At the end that’s the only thing that matters :-)

programming | No Comments | Trackback

Sharing Class names: a bad, bad practice….

April 19th, 2008

I consider sharing class names (in design or implementation) a bad, bad practice. In my opinion, it is a practice that will lead to confusion among developers, will eventually cause problems, and will promote software entropy.

You don’t have to go that far to find an example of this bad practice. You can find it right within the Java’s core API


public class Arrays {

// ... some code goes here

public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}

// ... some code goes here

}

Hmm, this method returns an ArrayList. You’d think that you could do the following and get no errors.


public class Gotcha {
    public void whatsWrongWithThisA(){
        final String[] args = {"a", "b", "c", "d"};
        final List<String> luckyList = Arrays.asList(args);
        for(Iterator<String> itr = luckyList.iterator();
            itr.hasNext();)
        {
            final String next = itr.next();
            System.out.println(next);
            itr.remove();
        }

        Assert.assertTrue(!luckyList.isEmpty());
    }

}

You are wrong! You will definitely get an error if you run it.

java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:144)
at java.util.AbstractList$Itr.remove(AbstractList.java:360)
at com.gotobject.clearance.Gotcha.whatsWrongWithThisA(Gotcha.java:28)

First of all, the ArrayList that you think is being returned by the Arrays.asList(…) is not the java.util.ArrayList that you and I are so familiar with. This one is a private static nested class that shares the same name as the one in the Collection framework. This nested class uses AbstractList.Itr class as its main iterator. If you examine its code you will notice that this iterator’s remove method invokes the AbstractList’s remove method, which returns an UnsupportedOperationException. I don’t know if this name was intentionally given by its designers, but it does not seem right. Maybe it should have been named FixedArrayList or something like that. Do you think of a better name?

p.s.

Here is the entire code. I’ve include both the test that shows the problem and the test that shows a temporary fix.


public class Gotcha {
    @Test(expectedExceptions =
            UnsupportedOperationException.class)
    public void whatsWrongWithThisA(){
        final String[] args = {"a", "b", "c", "d"};
        final List<String> luckyList = Arrays.asList(args);
        for(Iterator<String> itr = luckyList.iterator();
            itr.hasNext();)
        {
            final String next = itr.next();
            System.out.println(next);
            itr.remove();
        }

        Assert.assertTrue(!luckyList.isEmpty());
    }

    @Test
    public void whatsWrongWithThisB(){
        final String[] args = {"a", "b", "c", "d"};
        final List<String> luckyList = new ArrayList<String>(
                Arrays.asList(args)
        );
        for(Iterator<String> itr = luckyList.iterator();
            itr.hasNext();)
        {
            final String next = itr.next();
            System.out.println(next);
            itr.remove();
        }

        Assert.assertTrue(luckyList.isEmpty());

    }
}

programming | No Comments | Trackback

 

July 2010
M T W T F S S
« Apr    
 1234
567891011
12131415161718
19202122232425
262728293031  

Categories

Archives

Tags