Want better code? Write less of it.
There are various statistics related to the average defect density (i.e. how many defects one can expect to find in a code base); suffice to say, the numbers point to unhip ranges like
20 to 30 bugs for every 1,000 lines of code
and even
100–250 defects per thousand lines of code
Given this amazingly horrible data, what is one to do about it? There are a few possible answers, including:
- Write a lot of tests
- Write better code
- Write less code
The first choice is rather noble; however, it turns out to be a Herculean effort (to say the least) and therefore, few teams actually do it. Writing more hip code is a great idea– there are tons of resources related to writing better code (Robert C. Martin’s “Clean Code: A Handbook of Agile Software Craftsmanship” comes to mind) and I highly recommend teams strive to embrace the craft of coding. In spite of that, I have an alternate suggestion: write fewer lines of code.
If the average application has anywhere from 2 to 25 bugs per 100 lines (oh my goodness that’s an enormous number!) doesn’t make sense to write fewer lines of code? Of course! The question then becomes, how do you write less code? As it turns out, the answer is simple: you borrow code.
Borrowing code is certainly not new, yet I’m continually astonished to find corporations maintaining their own logging frameworks, web frameworks, UI frameworks, the list goes on and on. Why would you write your own logging framework in this day and age? Why not use log4j? Why write a web framework when you can borrow any number of wildly successful ones, such as Rails?
Of course, these frameworks have code in them too– but the beauty is that you end up leveraging the The Wisdom of Crowds; that is, you end up leveraging a community of focused smart people with varying backgrounds maintaining the code and usually a wealth a users providing feedback in multiple environments and situations– making the code more stable.
Aside from borrowing open source libraries to handle commodity issues (i.e. logging, ORM, web frameworks, etc) there are other techniques too. If you write Java code day in and day out, languages like Groovy offer manifold opportunities to lessen your lines of code.
For instance, need to read the contents of a file? If you write this requirement in Java, you could write something like this:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class ReadFile {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(
new FileReader(new File("/Users/aglover/temp/myfile.txt")));
String output;
while ((output = reader.readLine()) != null) {
System.out.println(output);
}
}
}
Note, the above Java code isn’t perfect nor am I trying to bash Java! But, it took 12 lines of code to print the contents of a file.
In a language like Groovy, for instance, I can achieve the goal with one line of code.
println new File("/Users/aglover/temp/myfile.txt").getText()
The above code isn’t magic– in fact, it is using essentially the same code from earlier (it’s all Java!). It’s just that someone else wrote it and scores of people are using it and making sure it works day in and day out. Ergo, using 1 line of code means I have 11 fewer lines of code to maintain (smarter people than me are maintaining those other 11 lines, baby!).
If it’s your bag to write better code, man, then I suggest you try writing less of it. Instead, focus on writing the minimal amount of code that serves a business need and borrow everything else. Can you dig it, man?
| Related odds and ends | ||
|---|---|---|
19 comments Saturday 08 Nov 2008 | Groovy, Languages, Software Development
19 Responses to “Want better code? Write less of it.”
Less code + Wisdom of crowds + open source, got it
I’ve been following your blog for some months. This post made me want to say hi.
Simply is always the best way to program, agreed.
Also, I’m digging the new (?) blog design!
Ah…but by bringing, say, Hibernate into your project to avoid writing JDBC code, you immediately inherit all their bugs into your system. Sure, you’re not writing the bugs, but you’re sure as hell supporting them.
Additionally, you have more surface area to deal with. Everywhere there’s a coupling point is a potential for bugs and defects, and the more frameworks and third party tools you incorporate into your system, you have more API’s to learn and call correctly.
Finally, when you bring in third party tools into your system, you have issues of friction between the components. Not all components play nicely together.
Don’t get me wrong, I agree in general with your thesis, but there are no silver bullets. Your friend Ted Neward’s article about Hibernate being the Vietnam of computing makes the point far better than I ever could.
Indeed, Matt– you do bring in a lot of code that other people wrote; however, the bet is that they’ll (that is, the authors and their manifold users) find the bugs before you do (and they’ll fix ‘em!). Put it this way– would you rather write your own version of Hibernate or borrow it? Borrowing Hibernate isn’t a silver bullet (I agree w/you 100%); however, I’m betting that the authors of Hibernate are smarter than me when it comes to ORM. Vietnam or not, no?
Thanks for commenting– indeed, no silver bullets!
Thanks for dropping by, Leo! Hello to you, man and thanks for readin’!
Thanks, Eric! It’s quite hip and copasetic, no?
Doesn’t the Bugs/LOC depend on the language?
What about K?
http://en.wikipedia.org/wiki/K_programming_language
“A function to determine if a number is prime can be written as: {&/x!/:2_!x}”
In my opinion the Bugs/LOC metric depends on the language you use, especially the density of “thought points”. Each time a developer needs to think (compare {&/x!/:2_!x} with println “hello”) he can create a bug. This is not depending on lines of code. In Java the the metric is very low (few Bugs/LOC) because Java has very few “thought points” (if (a==3) { ) whereas other languages have a lot of “thought points” per line ({&/x!/:2_!x}).
Coming back to your post: Groovy is much more dense than Java and I assume more Bugs/LOC in Groovy therefore. Someone would need to look into this and do some experiments.
Peace
Stephan
Interesting premise, Stephan. Indeed, some hip languages are harder to learn than others…Lisp comes to mind as a language that might be difficult for developers to embrace; consequently, does that mean there are increased chances for defects in, say, Clojure?
On the other hand, in your example,
{&/x!/:2_!x}might be somewhat esoteric to understand; however, it is only one line of code– how many lines of code would you need to determine if a number is prime in Java?You definitely are on to something interesting with your point; however, you said that “Groovy is much more dense than Java and I assume more Bugs/LOC in Groovy” and while I don’t necessarily disagree with you, my point is that because Groovy is used by so many different people that those defects will surface quickly (and accordingly fixed quickly). Thoughts?
Thanks for your input, friend!
Ah, less code. Yes! Very important.
one line API’s are nice. But it doesn’t stop there. Frameworks are part of the problem. Every application succumbs to “rounding errors” of the framework. In other words working around the framework limitations.
Entire teams of developers forget how to write code because they are nurse maids to frameworks of which they only desire in a given situation 5% of its functionality.
Everyone I know in the BIZ is sick of “call me” frameworks that have no internal description for the behavior expected and which require copious amounts of hacking to build decent apps. (Not to mention 100 MB of open source out of synch jar files)
No. No.
You dont have to go “deep” or “wide”. The key to LCITOM. (Less code is the ONLY metric) is to give up frameworks, and use well written APIs.
But where does that leave us given that frameworks have been in vogue so long?
Ill tell you where! Starting from scratch.
Ditch frameworks in favor of well thought out APIs and your code base will melt to the bare minimum and will serve your precise purpose.
Otherwise explain to your boss why XYZ-bernate didn’t work or didn’t scale. Times ten.
You could also write:
println new File(“/Users/aglover/temp/myfile.txt”).text
I’m sorry, I couldn’t help myself
To the point: it’s definitely true, that you should try to use existing libraries, but a more expressive language (like Groovy) can bring a lot more bugs to your code. For example, people like me, when confronted with all this Groovy goodness get this urge to write everything in one line (seriously I have a problem). The code that’s perfectly readable to me, can be a real mess to someone else. Because it’s hard to read, you can introduce new bugs, and not even know why. The other thing is the dynamic nature of Groovy. This could introduce a whole new class of runtime errors, that in Java would be spotted at compile time. I love Groovy, but a great power comes with great responsibility:) More powerful language is not a silver bullet.
You bring up a very good point, but if you had followed your own advice and borrowed code from somebody else you could have written this in one line of Java as well
System.out.println(org.apache.commons.io.FileUtils.readFileToString(new java.io.File(“/Users/aglover/temp/myfile.txt”)));
“Why write a web framework when you can borrow any number of wildly successful ones, such as Rails?”
True, but I’ve found that writing a thin layer on top of existing frameworks to narrow them down to exactly the use you want to make of them (the 5% another commenter mentioned) can be useful. I’m currently doing this for a client with Struts 1 (sic!) and am writing a blog post about it.
[...] how the range effectively lessens the amount of code one has to write to achieve iteration; that is, a range’s sequential-ness enables me to drop [...]
[...] Disco Blog: menos código, mejor código.Categoría: Geek, Software libre| Hace unos días leí un interesante comentario en el blog de Andy Glover sobre cómo el software libre ayuda a mejorar la calidad de los [...]
[...] baby! The fewer lines of code, the better! James goes on to suggest a new metric, Spag, which is a convenient way to count executable lines [...]
I am a groovy fan boy so I love the GDK method addition to java.io.File getText(), but you don’t need to use Groovy to take advantage of the “wisdom of crowds.” I am amazed how many people will write file reading code like what was shown above when there is a perfectly good class called org.apache.commons.io.FileUtils that does it for you. Another one is problematic Java string code, how is it in this day and age that people don’t know about org.apache.commons.lang.StringUtils?!!
So I guess to summarize my real point, people please don’t forget about the Jakarta commons library! Seriously, if you don’t know about it and you are a Java developer that writes stuff that you intend to keep around for more than oh, a couple of hours, go to commons.apache.org and be amazed… please please don’t write another line of code before you do.
Indeed, James — the Apache commons library is a wealth of code that easily enables people to write less code! Thanks!!
[...] lines of code can result in a quicker time to market with fewer defects. But reuse is important not only because it means writing less code, but also because it means [...]
[...] saved by TheSecretLover2009-04-22 – I think, therefore I crave saved by mlaaker2009-04-20 – Want better code? Write less of it. saved by TrendyTots2009-04-16 – :: cheap and chic invites :: saved by mattpao172009-04-03 – [...]