James Carr | Rants and Musings of an Agile Developer

Archive for December 2007

Dec/07

31

Facebook Spam

Well, it was bound to happen soon enough… today a friend of mine who I know for SURE isn’t going to be online (since they are out of town) wrote on everyone’s wall to check out this “cool site” giving away free ringtones (once you sign up for about 100 pieces of spam, of course).

One wonders if this has anything to do with one of the recent facebook apps she installed. I know for a fact that one of the facebook apps (Super Wall or Fun Wall) is a spamming piece of shit… I added it and soon discovered that friends with it had comments from me I didn’t write either warning them of a hacker named Kurt Chapman or some other silly crap. I promptly removed it.

Interesting…

No tags

Recently I’ve been following an interesting thread on the XP yahoo mailing list asking the question… should we measure individual velocity?

The general response seems to be “NOT AT ALL!!!”, but I won’t repeat the discussion there when you can read it yourself, but I thought I’d pick out an interesting point from the thread that was mentioned and expand on it.

Velocity is not a team performance metric, but a planning tool that
helps the team realize how much they can commit to a given iteration.

This seems to be a general point of confusion that always seems to come up and definitely bears repeating. From my point of view, velocity is basically a way of saying “the team completed on average x number of units per iteration the last y iterations, so the customers can expect x units will be completed next week. So, dear customer, with x units to spend this iteration, what features would you like to see implemented?”

Using velocity as performance metric is dangerous imho because it assumes that a team is either doing poorly due to a decline in velocity, or that a high velocity means a team is superb and probably deserves a hefty bonus. Rubbish.

Measuring individual velocity would be a disaster of epic proportions imho… it would go against the grain of teamwork first of all, since why would individuals or pairs feel motivated to ensure that the overall team does well velocitywise? Likewise, it would be a poor metric. If pair A completes 10 1 unit cards that were freakin easy (lets say each card was doable in a session or less) and pair B completes one 3 unit card and one 1 unit card that winds up taking awhile due to external factors, you can’t really sit there and say “pair A is a lot more productive than pair B, since pair B only completed 4 units. Maybe we need to do something to get them moving!”

Velocity is not about performance… it’s about providing your customer with a close to accurate amount of “points” they can spend on features this iteration. Remember that.

No tags

Something I had a little trouble with while toying with aspects was getting a joinpoint pattern to match methods where the return type implemented some interface. I tried the following:

execution(public AnInterface *(..))

But, that only works if I am returning the explicit interface as the return type… it doesn’t match if the return type happens to implement that interface. However, according to the AspectJ Programming Guide, we’ll need to use the + operator to match a subtype. So, simply put, we just modify the above joinpoint pattern:

execution(public AnInterface+ *(..))

That does the trick…

No tags

Continuing from my last post, I decided to give a stab at making my aspect reusable in a way that I could apply it universally to any of those instances where I need to time the execution of some process and store the elapsed time in the result. It took a bit of work to get there, and I am sure I am doing it wrong (and DEFINITELY sure there are better ways to accomplish it), but it works… and it’s pretty nifty too.

At first I tried by simply making my result object implement an interface, but this didn’t feel very flexible. Likewise, I couldn’t for the life of me figure out how to construct a joinpoint pattern that matched a return type that implements a specified interface. The only way to make it match would be to have the “timed” methods return the interface, something I didn’t want since it would render the result type useless to the caller. This led me to dig in and read more about annotations and aspects, and I decided on how I wanted to be able to use a custom annotation for it.

public class TimeWaster {
	@TimedMethod(field="elapsedTime")
	public SomeResponse makeLongRequest(){
		for(long i = 0L; i < 200000000L;i++);
		return new SomeResponse("FOO");
	}
}

Basically, I just want to annotate the method being timed, and specify the field to store the elapsed time on the result object. The annotation (of course) was easy enough to make (while remembering to include the whole RetentionPolicy.RUNTIME so I could access it at runtime, I always forget):

@Retention(RetentionPolicy.RUNTIME)
public @interface TimedMethod {
	String field();
}

The heart of the aspect is, naturally, the pointcut specifying the joinpoint I want to match. Basically, match any method call with that has the annotation @TimedMethod:

pointcut makeCall(): execution(@TimedMethod * *(..));

The rest is some quickly hacked together nasty reflection code to find the setter for the field specified and invoke it with the elapsed time. So here's the mess in it's entirety, feel free to critic it as I'd like to know how I could clean it up. ;)

package org.jamescarr;
public aspect ElapsedTimeLogger {
	private static final StopWatch TIMER = new StopWatch();

	pointcut makeCall(): execution(@TimedMethod * *(..));

	Object around():makeCall(){
		TIMER.start();
		Object resp = proceed();
		TIMER.stop();

		Signature sig = thisJoinPointStaticPart.getSignature();
		if (sig instanceof MethodSignature) {
			Method method = ((MethodSignature) sig).getMethod();
			if (methodHasTimedAnnotation(method)) {
				TimedMethod annotation = getTimedMethodAnnotation(method);
				setElapsedTime(resp, annotation, TIMER.getTime());
			}
		}
	return resp;
	}

	private TimedMethod getTimedMethodAnnotation(final Method m) {
		TimedMethod annotation = m.getAnnotation(TimedMethod.class);
		return annotation;
	}

	private boolean methodHasTimedAnnotation(final Method m) {
		return m.isAnnotationPresent(TimedMethod.class);
	}

	private void setElapsedTime(Object resp, TimedMethod annotation,
			long elapsedTime) {
		try {
			Method m = getElapsedTimeAssigner(annotation, resp.getClass());
			if (m != null) {
				m.invoke(resp, new Object[] { elapsedTime });
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private Method getElapsedTimeAssigner(TimedMethod annotation, Class clazz) {
		Method m;
		try {
			m = clazz.getMethod("set"+StringUtils.capitalize(annotation.field()),
					new Class[] { long.class });
			return m;
		} catch (SecurityException e) {
			throw new RuntimeException("Target method should be accessible", e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException("'field' attribute of annotation should specify a field of type long with a provided public setter.",e);
		}
	}
}

Seems like it does the trick. Although it does seem complex (and I wouldn't say it was a good idea if I only had one instance of such a thing going on), it is 100% reusable and saves both the tedious code duplication and the SRP violation of including timing functionality inside of each and every method that requires it. I'll probably refactor it a little, but you get the picture.

As an aside note, I was curious if perhaps my approach would actually increase the elapsed time, so I ran a few unscientific benchmarking tests... on average the aspect approach performed close to the local method approach... and the increase in time was only off by a few milliseconds at best (nothing to die over). Fun stuff.

No tags

Recently I’ve been knee deep in some legacy code doing a fair bit of refactoring, and one of the patterns I keep coming across is processes that need their elapsed time measured. You know what I’m talking about… a procedural mess shock full of primitive obsession all over, something like the following (except imagine that the for loop is some time intensive process):

public class TimeWaster {

	public SomeResponse makeLongRequest(){
		long start = System.currentTimeMillis();
		for(long i = 0L; i < 200000000L;i++);
		SomeResponse resp = new SomeResponse("FOO");
		long end = System.currentTimeMillis();
		resp.setElapsedTime(end - start);
		return resp;
	}
}

Of course, the knee jerk response will be to hide the primitive long values manipulated all over behind some kind of abstraction, such as:

	private static final StopWatch TIMER = new StopWatch();

	public SomeResponse makeLongRequest(){
		TIMER.start();
		for(long i = 0L; i < 200000000L;i++);
		SomeResponse resp = new SomeResponse("FOO");
		TIMER.stop();
		resp.setElapsedTime(TIMER.getTime());
		return resp;
	}

A little better... but there's still something fishy here... why does my class (despite the fact I selected the random name of timewaster) need to know about a timer? It has two roles now... generating the SomeResponse (again, remember the for loop is an assumed time intensive process of generating SomeResponse) and timing the time it takes to generate that response.

To solve this problem, we can move the timing process to an aspect, measuring the execution of the makeLongRequest using an around advice, which allows us to invoke the target method as well as modify any input and output values before returning (this is also ideal for contraint checking). So to begin, and especially since aspects can be a little tricky, we construct a very simple aspect... containing only a pointcut and a sysout in an after advice (which is called after the method finishes):

public aspect TimeWasterTimer {
	pointcut makeCall(): call(SomeResponse TimeWaster.makeLongRequest());

	after(): makeCall(){
		System.out.println("Pointcut worked..");
	}
}

I run the tests and see that yep.... that worked. So, to start small, we'll make an around advice that simply returns the return value and run the tests to make sure they pass.

public aspect TimeWasterTimer {
	pointcut makeCall(): call(SomeResponse TimeWaster.makeLongRequest());

	SomeResponse around():makeCall(){
		SomeResponse resp = proceed();
		return resp;
	}
}

Tests pass, so let's remove the timing code completely and run tests.

public class TimeWaster {
	public SomeResponse makeLongRequest(){
		for(long i = 0L; i < 200000000L;i++);
		return new SomeResponse("FOO");
	}
}

Now all of our tests related to elapsed time fail... perfect. Now to finish things off, we simply move the timing code to the aspect and set the elapsed time on the response before it's returned.

public aspect TimeWasterTimer {
	private static final StopWatch TIMER = new StopWatch();

	pointcut makeCall(): call(SomeResponse TimeWaster.makeLongRequest());

	SomeResponse around():makeCall(){
		TIMER.start();
		SomeResponse resp = proceed();
		TIMER.stop();
		resp.setElapsedTime(TIMER.getTime());
		return resp;
	}
}

Rerun tests, and everything is green. Sweet! ;)

In this case, we were able to split out the responsibility of measuring execution time to a separate module by using an Aspect, allowing for a better separation of concerns. We could take this a step further an make it generic enough to be used in all cases that elapsed time is measured, perhaps by having an interface for classes that record elapsed time and a pointcut with some complex joinpoint matching magic. I'd also be interested in any alternative solutions others have come up with to solve this problem (I know Spring AOP is another way of tackling it).

Stay turned for more posts on Aspect Oriented Programming. :-P

No tags

Dec/07

10

OOP with Javascript (framework free)

I thought these two lessons on OOP in javascript bear repeating, even though they’re quite old (2003? 2004?)

No tags

Dec/07

10

Google Reader’s Recommendations

Today I noticed a little feature in Google Reader that I hadn’t noticed before, “Recommendations.” It’s a simple green box in the top right corner of the page that lists some recommended blogs and boy, is it right on the money!

  • PragDave was listed, which was really no surprise as I already read Dave’s blog… I just hadn’t subscribed to it.
  • Likewise, SpringSource Team Blog also came as no surprise due to my latest interest in Spring (Stay tuned for an in progress tutorial I’m working on that describes how to use SpringBatch for batch processing).
  • you’ve been HAACKED is a blog I hadn’t heard of, but a quick glimpse of it looks like it’s very TDD oriented, so it’s added. ;

There’s several more, with many of the recommendations being blogs that I already read, I’ve just been to lazy to add it to reader. One thing’s certain… I don’t know whether I should praise Google for a job well done or feel a but frightened that their software can figure out my interests so easily. ;)

No tags

Theme Design by devolux.nh2.me