11 November 2009

Time Flies

I've just published tempus-fugit 1.0-SNAPSHOT to java.net's public maven repository with a view to synchronising it with Apache's uber-repo. Download here, or point your pom at it to enjoy all the fanciful goodness inside.

oh, I should mention... tempus-fugit represents two things to me
  1. A focal point to a lot of thinking done by a lot of very smart people I've been fortunate to work with (along with my own special kind of magic) themed around concurrency and time.
  2. An attempt to consolidate this thinking into a single place that can be easily reused before finally being discarded with mild disdain*.
What it actually is, is
  1. a dozen or so classes that capture key abstractions we've found are frequently shared across domains.
  2. a even smaller number of wrapper or helper classes that we've found can help using concurrency in Java that little bit nicer.
  3. all with an underlying theme of testing and improving testability.
* more specifically, in collaborative projects, it represents a move away from collaboration into a more socially introvert culture whereby collective code ownership becomes uncooperative code ownership. Eat my JAR and don't dare dream of refactoring it. Bad, robot.

Thawte claim I'm not to be trusted...

...well, not quite, but they have recently announced that they'd be discontinuing the Personal E-mail Certificates and Web of Trust. These were free services and it comes as bit of a blow as I've been using them to sign my JARs for WebStart deployment. As Thawte are the root authority, it meant no annoying prompts from WebStart claiming I was a would-be terrorist. Looks like I'm back to hiding in shadows.

A couple of useful links below.

http://ciardhubh.de/node/4
http://www.dallaway.com/acad/webstart/


31 October 2009

Performance Monitoring (Part 1)

Keeping an eye on the performance of your applications is something that it easy to neglect. We all know that we should be regularly recording key performance indicators and regularly leaning on the profiler to spot dangers early, but how often is the dust actually blown off?

I've been doing a fair bit of this lately (blowing off that is) and thought it might be a good idea to capture a few thoughts in a mini-series of posts that will be rivaled in drama only by the likes of Dynasty and Dallas. Enjoy...


Part 1. The Beginning


It's probably a shrewd move whatever your application to setup performance measurement early. I'm usually interested in two areas, the real-time performance and the resource usage.

Performance


What you define as "performance" is completely down to you and your application. It may be in the request / response world, the time taken to process a request and return a response. It may reflect the ability to handle thousands of requests within a SLA agreed time or it may be around reliability and up time, scalability or accuracy. Whatever. Some things that are usually constant though are an emphasis on time, correctness and robustness of system under load. This is all about measurement and optimisation.

  • Response times - of your critical path
  • Throughput - typically the number of requests / transactions / operations per second
  • Load - the number of request / transactions / operations being observed.
  • Success / failure counts - it's no good being quick if you're always wrong!
  • Garbage collection profile - you'll probably be more interested in this if your system is already highly performant. In these cases you can potentially see dramatic differences in critical path processing times when excessive or inefficient GC is taking place. Tuning is a specialist skill, good luck. Google Sun's G1 for renewed hope.

Resources


The section on resources is more open ended, I mean hear both hardware resources and software resources (including the resources available to the JVM). Of course, taking into account the resource usage of interrelated external systems may also be of interest to the happy tuner and its all about avoiding resources starvation and spotting bottlenecks.
  • CPU
  • Memory - The JVM can theoretically allocate only 2GB to the heap on 32 bit machines and 16GB on 64 bit machines. In practice, hitting this upper bound with -Xmx can be tricky. Either way, you'll want to understand the memory characteristics of your application and how it behaves if you start to reach the upper bound of the heap.
  • IO - I mean here things like handles, database connections, physical network connections and other tasty bites. Without these, all is lost and managing these to avoid resource starvation can be of primary importance.
  • Threads - there is a relationship between the number of threads your software requires and hardware resources available to you, threads are not unbounded in your application so the prudent coder will seek insight into the affect creating lots of threads will have. See a previous post.

Statistic Gathering


Once we have an idea of what we want to measure, the next step is to think about how to capture and represent the raw data. We need to capture the raw data and turn it into information that's useful. It turns out that turning this data into information will influence how we capture it...

You could capture all the data about every single request but it's unlikely that this is the information you'll need without doing some form of manipulation. Instead, I prefer to capture information, manipulating and aggregating the data from each request as we go.

For example, typically you might be interested in the means, samples or percentile based information.

Mean values are probably the simplest to get started with, recording figures like mean response time are useful but not always the full picture. Average figures can be skewed by extreme results or extreme results may be lost in the mean. Supplementing with unmodified samples can help give a fuller picture.

Percentile based reporting gives more insight than a smoothed average figure. For example, if most of the requests are sub-second, it can be hard to spot the small number of slow requests. By reviewing at a particular percentile you can gain visibility of these and help determine what's an acceptable level. For example, the mean response time at the 95th percentile will likely be noticeably different than the mean.

Another option is to implement a sliding view on the data. Here, you record information for, say, an hour and as time progresses beyond that hour, you start to loose past data and include new data. At most, an hour of data is available. This can be useful as rather than cumulative counts, the sliding window is visually more responsive to changes (in particular, drops). For example, once charted, a drop in a cumulative chart will show as a slow in accent of the series where with a sliding window chart, it will show as a clear drop. A subsequent post in the series will talk in more detail about this sliding window approach.

Implementing


There's plenty of ways you can as statistics to your application. Instrumenting the code at key points through decoration is a good option. Using something like AspectJ is another option and both free your code from any clutter that would otherwise pollute and distract from your classes real responsibilities. Logging is a good example of instrumentation polluting things. Typically, the act of logging has nothing to do with the role of the class doing the logging.

The instrumenting code will likely be modifying objects in memory that collect and manipulate the raw data. You'll almost certainly want to make sure this memory object is thread safe and performant, it should be light weight and non-obtrusive.

What happens to the memory object is up to you, but you'll need to output it for analysis at some point. I prefer to publish the objects via JMX, that way you can setup a separate 'collector' to periodically read the values and have it's wicked way with them. With this approach, its even more important to keep the object lightweight - the MBean will always be in memory (the MBean server will see to this) and so if it contains rogue references to big objects, they'll never get garbage collected. The other tip is to create one of these such objects per request type, don't create a new one per request for example.

In the next exciting post in the series, I'll talk about interpreting the results you get. Hope that wasn't too dull.

1 August 2009

Java source for Mac OSX

Grrrr arrrrh Apple, grrrr...

See here for a more balanced view.

Abstracting ReentrantReadWriteLock

All locks in Java are reentrant, they have to be in case the owner of the monitor ends up calling a method that needs that monitor. So, it a thread requests a lock that it already holds, it'll be given it. Without this, a subclass couldn't override a snynchronised method and then call the superclass method without deadlocking.

Java's ReenstrantReadWriteLock is about acquiring seperate read and write locks for efficiency. For example, in the case where you may have infrequent writes but frequent reads, it may be more efficient to not synchronise all access with just one lock. Instead, ReenstrantReadWriteLock can allow all read access to only block when a write is taking place. You'll end up with multiple simultaneous reads but synchronised writes and all the reads will have guaranteed visibility of the writes.

How to know when to actually use the ReenstrantReadWriteLock is going to have to be the subject of a followup post, but as you'd expect, profiling is going help you make decisions against your specific situation.

With all Lock implementations, you specifically acquire the lock and are politely asked to release the lock within a finally block. Makes sense but it always bugs me that we're forced into Java's verbosity trap, yet again.

So, vanilla Java would have you;

Lock l = ...;
l.lock();
try {
// access the resource protected by this lock
} finally {
l.unlock();
}
So why not wrap the boiler plate code up in a micro-DSL and pass a closure-like thing to execute? Any implementation must call both lock and unlock and re-throw any exceptions. The following test shows this to be true.

@RunWith(JMock.class)
public class ExecuteUsingLockTest {

private final Mockery context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};

ReadLock readLock = context.mock(ReadLock.class);
WriteLock writeLock = context.mock(WriteLock.class);

@Test
public void readLock() {
setExpectationsOn(readLock);
execute(something()).using(readLock);
}

@Test
public void writeLock() {
setExpectationsOn(writeLock);
execute(something()).using(writeLock);
}

@Test (expected = Exception.class)
public void readLockThrowingException() throws Exception {
setExpectationsOn(readLock);
execute(somethingThatThrowsException()).using(readLock);
}

@Test(expected = Exception.class)
public void writeLockThrowingException() throws Exception {
setExpectationsOn(writeLock);
execute(somethingThatThrowsException()).using(writeLock);
}

private Callable<Void, RuntimeException> something() {
return new Callable<Void, RuntimeException>() {
public Void call() throws RuntimeException {
return null;
}
};
}

private Callable<Void, Exception> somethingThatThrowsException() {
return new Callable<Void, Exception>() {
public Void call() throws Exception {
throw new RuntimeException("bad robot");
}
};
}

private void setExpectationsOn(final Lock lock) {
context.checking(new Expectations() {{
one(lock).lock();
one(lock).unlock();
}});
}
}
The implementation is fairly straight forward with a couple of interesting points to note around generics.

public class ExecuteUsingLock<T, E extends Exception> {

private final Callable<T, E> callable;

private ExecuteUsingLock(Callable<T, E> callable) {
this.callable = callable;
}

public static <T, E extends Exception> ExecuteUsingLock<T, E> execute(Callable<T, E> callable) {
return new ExecuteUsingLock<T, E>(callable);
}

public T using(ReentrantReadWriteLock.WriteLock write) throws E {
try {
write.lock();
return callable.call();
} finally {
write.unlock();
}
}

public T using(ReentrantReadWriteLock.ReadLock read) throws E {
try {
read.lock();
return callable.call();
} finally {
read.unlock();
}
}
}

Having the micro-DSL pass in the generic Callable on the static constructor meant that I couldn't make just the using method generic and instead had to link the types by making the class definition generic. You might also notice that the Callable used isn't Java's Callable, as Sun saw fit not to have the Exception as a generic type. By creating the new Callable interface below, I was able to neaten up the micro-DSL so that we're not forced to throw Exception from a method that uses the ExecuteUsingLock class. Instead, you define your closure-like function to throw RuntimeException.

A real world example might be something that updates a status probe where the variable lock below is an instance of ReentrantReadWriteLock.

public void setStatus(final Status status) {
execute(settingStatus(status)).using(lock.writeLock());
}

public String getStatus() {
return execute(gettingStatus()).using(lock.readLock());
}

private Callable<Void, RuntimeException> settingStatus(final Status status) {
return new Callable<Void, RuntimeException>() {
public Void call() {
EnclosingClass.this.status = status;
return null;
}
};
}

private Callable<Status, RuntimeException> gettingStatus() {
return new Callable<Status, RuntimeException>() {
public Status call() {
return EnclosingClass.this.status.toString();
}
};
}
All this to avoid the boiler plate code! Fresh.

29 July 2009

is(not(instanceOf(smell)));

For some reason, common perception is that using instanceof is a bit of smell. I think its fallen in with a bad crowd and isn't really as bad as its cracked up to be.

For example, given the following, what's clearer in the following exception handling code?

try {
...
} catch (InvocationTargetException e) {
if (RuntimeException.class.isAssignableFrom(e.getCause().getClass())) {
throw new ApplicationException(...);
}
throw e.getCause();
}
or

try {
...
} catch (InvocationTargetException e) {
if (e.getCause() instanceof RuntimeException) {
throw new ApplicationException(...)
}
throw e.getCause();
}
There seems very little difference in the semantics of the two calls, both handle class hierarchies and both handle interfaces. I think the legitimate use for Class.isAssignableFrom is around scenarios where reflective-type checks are more suited (for example, where the class to check against is only known or may change at runtime). Using Class.isInstance is a similar alternative. The other point that the API documentation points out is that isAssignableFrom works with primitives whereas instanceof can not.

I wonder if the bad reputation instanceof suffers from is more due to often being seen in the company of strange conditional logic than anything else. The kind of stuff that seems to go against your Mumma's good advice. It may just have fallen in with a bad crowd but is itself a good kid at heart...

I suspect instanceof, being around since forever, is seen as a bit antiquated but given the example above using Class.isAssignableFrom seems to just obfuscate things. The example needs to find out why a dynamic proxy throws an exception and because the InvocationTargetException wraps the underlying cause, it kind of breaks checked exception handling and it feels like we need to do some conditional check. If there is a smell here, that's it. The above is trying to hide the symptom of the smell (instanceof) but the smell is still there, its just harder to see. I often catch similar whiffs when catching ExecutionException.

More conventional cases where instanceof is a genuine smell may be around conditional logic making decisions based on class type where using polymrphism would be the obvious solution. It's this kind of thing that your Mumma warned you about and I suspect its this is the real smell that's rubbed off on poor downtrodden instanceof.

29 May 2009

Convert a Callable to a Runnable

Everytime I come accross it, it bugs me.

The Executors class has helper methods to convert from a Runnable to a Callable, presumably so you can submit an old school Runnable task to an exectuor, but I can never find the counterpart helper. Something to convert a Callable to a Runnable.

I seem to keep finding myself needing one and you might think me silly for doing so but it's because I'm into the habit of coding as Callables now. I tend to think of Runnable as simply something that can run, not in terms of a Thread or concurrent task. I like the way I think about Runnable.

Callable is like the new cool kid, with its funky return value and the ability to throw an exception. Wow, why did I ever bother with Runnable in the first place? Callable, like Runnable, however is still just something that can be called, it just so happens to fit in nicely with the executor framework and kind of looks all bling.

I digress... back to jusitifying why I think I'm always needing to convert from Callable to Runnable. As I say, if both interfaces represent something that can be called, I favour Callable becuase its more powerful. I can return useful things and catch useful exceptions. I'm in the habit of using Callable.

Often then, I'll have utility classes, useful nuggets of functionality dressed up as a Callable, and if I want to schedule them with an executor with a fixed delay or fixed rate, I can't. The interface wants a Runnable and only a Runnable. Most likely becuase it doesn't really make much sense to schedule a fixed rate execution of a task that returns something when it would take quite some thinking to actually do something with the return value.

None the less, I'd like to schedule something at a fixed rate (ignoring the result) that I also schedule elsewhere and actually do something with the result.

Starting with the tests, any helper must delegate to the Callable and handle any exceptions.

@RunWith(JMock.class)
public class CallableAdapterTest {
private final Mockery context = new Mockery();
private final Callable callable = context.mock(Callable.class);

private static final Object RESULT = new Object();

@Test
public void delegates() throws Exception {
callableWill(returnValue(RESULT));
runnable(callable).run();
}

@Test(expected=RuntimeException.class)
public void exceptionBubblesUp() throws Exception {
callableWill(throwException(new Exception()));
runnable(callable).run();
}

private void callableWill(final Action action) throws Exception {
context.checking(new Expectations() {{
one(callable).call(); will(action);
}});
}
}

To get a green light, the implementation is fairly trivial.

public class CallableAdapter {

public static Runnable runnable(final Callable callable) {
return new Runnable() {
@Override
public void run()
try
callable.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
};
}
}

Let me know if you've got any comments, great ideas on the subject or can improve on the implementation above.

15 March 2009

SWTBot vs Window Licker

The title is a bit misleading because these guys arn't really squaring off like Gozilla and Gigan, the projects aren't competing and this blog isn't really a full or fair compairison. For a start Window Licker doesn't yet support SWT and as its name suggests SWTBot, er, does.

My comments are really based on having a go at implementing some basic SWT support in Window Licker and adding some features to SWTBot so it shouldn't be taken as authoritative. This entry is more of an experience report after trying to contribute to both projects. I'll try to follow up with an API usage report when I've used both more with my applications.

The Code


Window Licker supports Swing and Html (including Ajax) very elegantly and uses the Java java.awt.robot package to take control of the mouse and keyboard and generate native events. SWTBot simulates events using manual notification. That is to say it calls the SWT widget notifyListeners method directly where as Window Licker fires native GUI events. This wouldn't necessarily be much of a distinction but it does mean SWTBot doesn't always behave exactly as expected (for example, it doesn't handle text caret movement or clearing text fields). An application under test from Window Licker behaves much more like an application driven by a user whereas SWTBot doesn't always have to wait for visual ques to move along.

Window Licker feels like a more mature framework, its nicely componentised and test driven where as SWTBot seems more evolutionary and although there are plenty of nice abstractions in common with Window Licker, it is harder to test due to the lack interfaces/mocks. SWTBot's code base is sprawling and covers a lot of ground, Windows Licker feels more focused on the problem it tries to solve. Having said that, its much more straight forward contributing to SWTBot, I was able to contribute (and understand) more of the SWTBot code base upfront.

SWTBot's project hosting presents itself as a confused, capricious old boy, shuffling papers and smelling mildly of pee

The other slight gripe I have with SWTBot is the project structure, its more suited to Eclipse than IntelliJ as its dependencies are provided via plugins rather than raw Jars. Window Licker comes with Eclipse and IntelliJ project files which is always nice. SWTBot also has several projects that make up the software, the build process isn't as obvious as others and it uses some generated code that you'll probably won't spot but still need to know about.

The Project Hosting


SWTBot has recently moved to its new home on Eclipse.org but the team lead hasn't deprecated the old site and resources. Consequentially, it can be a bit confusing for a new user to follow when there are two subversion repositories, two sets of bug tracking instances, lots of mailings lists and so on. Window Licker is much more low key, at the time of writing there is no pre-packaged release to download, it has a minimal site on Google Code that invites you to just download the source and get stuck in! In lots of ways I prefer this approach.

SWTBot has lots of broken links on the site and presents itself as a confused, capricious old boy, shuffling papers and smelling mildly of pee. Window Licker on the other hand, portrays itself confidently, most likely wears a monocle and speaks in a concise and authoritative tone. Even though some of what it has too say seems to go over my head.

Conclusion


For me, SWTBot really lets itself down is how it's being run. We all realise that open source software often has to take a back seat to your day job but if you're going to release something open source and encourage participation (say by hosting it on Eclipse.org) you should really be able to take the helm and support your community. As such, I had a bit of a bad experience with SWTBot trying to get a feature committed. In short, I did a whole bunch of work after explicitly being asked to do so in order to get it committed, then when it was done, the team lead ignored it and committed a previous version I'd submitted! The previous version works fine, it did the job but i was asked to re-jig things to better fit in with the project's standards, yet it got dumped. See the Bugzilla trail less I waffle even more.

It's a shame because experiences like that just lower confidence in a project, I'm unlikely to want to push any changes back now. I guess though in summary, SWTBot's code was easier to contribute to (although I was working in one small area of a large project structure). Window Licker is probably the superior technically and in terms of code quality but was harder (for me) to work with. I was working on essentially cloning some of the core Licker functionality to work with SWT and found that I didn't fully understand all the abstractions and mechanisms. I suspect that in a pairing environment, it wouldn't be a problem but contributing via email and patches is unlikely to get the most out of collaboration.

26 February 2009

Less is More

Dirty and Jim were trying to convince me the other day that less is more when it comes to maximum heap size in Java. After I finally got the point, I was aghast! Shock, horror... creating threads in Java takes up non-VM managed memory!
After running a few tests I confirmed that the lower the max heap size is, the more threads I could create. I can easily get a OutOfMemoryError when allocating memory for threads way before any real heap space is used.
The helpful message you'll get is.

java.lang.OutOfMemoryError: unable to create new native thread

I ran a simple loop that would create dozy threads (they sleep a lot) and watched how many threads could be created before the out of memory error above. I repeated this after setting the maximum heap size. Check out the results below, you can see that no real Java heap is used, still I get an out of memory error and am limited on the number of threads I can create. As a caveat, these results should in no way taken as representative on any other environment than my laptop running Java 1.6. Your mileage may vary.






I'd always considered OS native threads or light weight processes to be effectively unbounded with the restrictions being on the resources they are associated with. I don't think this is really the case though as clearly, the act of creating a thread that does nothing and has no real resources associated with it (other than any native voodoo) requires OS memory allocation in my tests.

I thought this was really interesting as it demonstrates how small decisions can have a big impact on the run-time characteristics of a system. Being able to tune your application to suit your production requirements is always tricky. Large memory models and data manipulation can often require large heap sizes but if in addition, you then want to create large numbers of threads, you might get into the murky world I've touched on here. Of course, thread pools are generally the way to go if you want to manage your resources properly, but that's another story all together.

I'm sure Google can tell you more, but see this random blog for another description.


23 February 2009

Infering the Type in a Micro DSL

In a recent post, I was talking about a micro DSL to create a simple "find x in a list" service. The key thing here is that it defines how to look for x in the list. So the list can be a list of anything, not just a list of x's.

Just to recap then, to find something in a list, the original client code (using a static import) looks like this.

find(needle).in(haystack)

The class (in this case NeedleFinder) implements the DSL and specifically decides in the in method how to compare a Needle object to whatever is in the haystack list. I wanted to create a more generic class so started to implement the ListFinder to use generics and a couple of interesting things came out.

The generified class looks like this.

public final class ListFinder<T, L> {
private final T target;
private List<L> list = new ArrayList<L>();

private ListFinder(T target) {
this.target = target;
}

public static <T, L> ListFinder<T, L> find(T target) {
return new ListFinder<T, L>(target);
}

public ListFinder<T, L> in(List<L> list) {
this.list = new ArrayList<L>(list);
return this;
}

public L using(Comparator<T, L> comparator) {
for (L item : list) {
if (comparator.equals(target, item)) {
return item;
}
}
return null;
}

public interface Comparator<T, L> {
boolean equals(T target, L item);
}

}

With the following test case showing its usage (the Needle and Bale class aren't show for brevity).

public class ListFinderTest {

private final Needle needle = new Needle("Bob");
private final Needle missing = new Needle("Billy");
private final Bale bale1 = new Bale("Christian");
private final Bale bale2 = new Bale("Bob in disguise");
private final Bale bale3 = new Bale("Kelly");
private final List<Bale> haystack = asList(bale1, bale2, bale3);

private final ListFinder.Comparator<Needle, Bale> comparator = new ListFinder.Comparator<Needle, Bale>() {
@Override
public boolean equals(Needle needle, Bale bale) {
return bale.name.contains(needle.name);
}
};

@Test
public void needleFoundInHaystack() throws Exception {
assertThat(find(needle).in(haystack).using(comparator), is(bale));
}

@Test
public void needleNotFoundInHaystack() throws Exception {
assertThat(find(missing).in(haystack).using(comparator), is(nullValue()));
}

private static ListFinder<Needle, Bale> find(Needle value) {
return ListFinder.find(value);
}
}

Here we're defining the equality of a Needle in a list of Bale objects to be when the name of a Needle is contained in the name of the Bale. A silly example I know but it illustrates that we redefine what we mean by equality for the list finder by implementing the ListFinder.Comparator. The concrete example that spawned the idea was when searching for a Race object inside a list of Event objects; two completely different entities.

Anyway, what I thought was interesting about this example was the type inference going on in the static find method. I originally wanted to just use ListFinder.find method directly as in the following.

ListFinder.find(needle).in(haystack).using(comparator)

Where ListFinder is statically imported. Usually, I'd rely on type inference here to work out that needle means T and therefore T is of type Needle. However, in the case above, the compiler will complain as the haystack parameter is not of type Object. The trick is that the generic method find in ListFinder needs to infer two types (T and L) but only has enough information for T. So it defaults L to type Object. grrr damn Java indisputable logic.

The alternative is to use the full notation as follows.

ListFinder.<Needle, Bale>find(needle).in(haystack).using(comparator)

Or (as I've done in the test) use an internal method who's return type gives the compiler enough information to infer both types. I prefer this approach as it makes the DSL expression to find a needle much more readable.

So, Java can't chain methods to infer the types. I didn't really expect it to be able to so, its a bit much to ask for. Although it would be pretty sweet if it could.

One last thing, Papa Ray was showing me a Jedi alternative to the finder. If we're lucky, he might blog about it. It seems Jedi offers some measure of insurgency against the proliferation of anonymous inner classes in lieu of closures but in all honestly, I just wanted to get in some big words in before signing off. TTFN.


16 February 2009

More on Micro DSLs

I was recently talking about what I call micro DSLs and I thought I'd follow up with another example.

So, another example of a micro DSL I found myself writing is one of finding some object within a collection of differently typed objects. In my example, I want to find a Race object inside a bunch of calendar events objects, the finder micro DSL looks like this.


final class RaceFinder {

private final Race race;

private RaceFinder(Race race) {
this.race = race;
}

static RaceFinder find(Race race) {
return new RaceFinder(race);
}

CalendarEventEntry in(List<CalendarEventEntry> events) {
for (CalendarEventEntry event : events) {
if (race.getName().equals(event.getTitle().getPlainText())) {
return event;
}
}
return null;
}
}
The way the class is built, it forces the client to use it such.

CalendarEventEntry event = find(race).in(events);

Where find is statically imported and race and events have been pre-populated.

The original version had a method in the class to do the find, in the context of this class it was harder to test the find. I had a bunch of mocks and I was testing the find function amongst other behaviours of the class. The search line looked something like this.

CalendarEventEntry event = searchForRaceIn(events);

Why I term this a micro DSL is that it has a very specific usage (to find a race within a calendar) and it has a private constructor and public static construction method to ensure strict usage. The real thing though is the method names don't really do what they imply they're going to do. The 'in' method actually does the search, but the 'find' method doesn't do any such thing, it creates an object.

How do you feel about this? When its used in a tiny domain like this and when it expresses the conversation more concisely than the alternatives, I feel pretty good about it. It makes me realise its not the words (method names) that are important, its the sentences they put together. So I'm compromising on realistic method names for more expressive sentences. The fact that the class prevents you from constructing invalid sentences just makes the warm feeling grow.

Micro DSLs are recognisable by their tiny-domain, the way in which construction is done to ensure they can only be called in an order that makes sense to the domain and badly names methods.

Micro DSLs are starting to spread in my code like jam on toast but I know I have to check myself and really justify their use before I go mad. I also had fun trying to turn the finder above into a generified class which I'll talk about in my next post. I bet you can't wait, you lucky people.



12 February 2009

I blog, therefore, I am

Just because I blog, it doesn't mean I'm important. Just because I use commas, it doesn't mean I can grammatically correct others. Just because I use the word 'grammatically', it doesn't mean I can spell. Just becuase I can spell, it doesn't mean I can grammatically correct others spellings.

Also, Twitter is shit and exists solely for the purpose of fulfilling its own wet dream.

24 January 2009

Inheritance vs Composition

When interviewing, I often like to ask a candidate to discuss inheritance vs composition using Stack as an example.

Example 1.




public class EvilStack<T> extends Vector<T> {
public T pop() {
// ...
}
public void push(T item) {
// ...
}
}


Example 2




public class Stack<T> {
private Vector<T> items = new Vector<T>();
public T pop() {
// ...
}
public void push(T item) {
// ...
}
}

Extending Vector as in example 1 weakens the encapsulation of the class. Suddenly, methods to get and insert elements at specific positions are available to clients of the stack. We move from trying to create a well behaved LIFO stack to creating a socially irrisponsible monster: an EvilStack.

So I was surprised when looking at the Java implementation to see that java.util.Stack extends Vector! Bad robot.

22 January 2009

Deprecated Annotation

Why didn't Sun add a value property to the @Deprecated annotation? Instead of

@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Deprecated {
}


which kind of implies we should do the following.

@Deprecated
/** @deprecated use {@link Foo} instead */
public class GoneOff {
// ...
}


why can't we have

@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface MyDeprecated{
public abstract String value() default "";
}


which means we can use

@MyDeprecated("use Foo instead")
public class GoneOff {
// ...
}