Saturday, 20 December 2008

Self Documenting Code – Gimme Just One Less Line

I was in a technical interview a good while back and it was review your answers to the tech quiz time.

INTERVIEWER: OK, that’s a good answer. That would work but can you do it in less lines of code
ME [chewing pen]: Errmmm –OK that’s it in two lines
INTERVIEWER: OK – but I’m sure you can do it in one line
ME [scratching head]: Oooooo – Errmmmm – that’s one line
INTERVIEWER: Well Gee – that does it. But I’m sure you can do it in maybe 10 characters
ME [Weeping real tears]: Ahhhhhhhh !!!!!! Please let me out.

OK – maybe the end of the interview went a bit better but I must have spent a good 20 minutes frantically trying to trim down my code to the size of an atom. I retrospect I think it was a fair enough way to grill me – but in the day to day work of chipping away at in the salt mines of computer code do you ever want to trim your code down to the bare minimum?

Consider this code
private static string RemoveTrailingTag(string input, string tag)
{
if (input.Length >= tag.Length && input.Substring(input.Length - tag.Length) == tag)
{
input = input.Substring(0, input.Length - tag.Length);
}
return input;
}
OK – it’s trimming tags from strings. But what on earth is the 'if' statement doing. The revised code tells us
private static string RemoveTrailingTag(string input, string tag)
{
if (HasTrailingTag(input, tag))
{
input = input.Substring(0, input.Length - tag.Length);
}
return input;
}

private static bool HasTrailingTag(string input, string tag)
{
return input.Length >= tag.Length && input.Substring(input.Length - tag.Length) == tag;
}
OK – the ‘if’ checks for the trailing tag. Admittedly I’ve expanded the code but I’m a big believer in more is less (confusing). Of course self-documenting code isn’t new (Steve McConnell etc..) but there does seem to be a real mind set of trimming code down to the smallest, most elegant (i.e. unreadable) fragments. It’s as if we’re developing assembler code to run on the chip of a washing machine. Except most of us aren’t and never will be.

No comments: