Today I found a nice article (actually the article found me…) written by Alexander Lucas titled Lines Of Code - Dispelling The Myths about a common project management error, which makes estimations and worse makes the evaluation of a good programmer based on the number pf lines of code he/she has written in a period.

At the end of the article Alexander presents a much bigger problem of us programmers: the usage of clever one-liners. That made me thinking of how much I hate that kind of code, even if written by me, which does something in a very clever way in one shot, but is absolutely unreadable.

Let me show you an example I have written just another day:

  1. long someValue = -1;
  2. try{
  3. someValue = (Contants.class.getDeclaredField(“NASTY_CONSTANT”)).getLong(Contants.class);
  4. }catch(Exception e) {
  5. //do nothing
  6. }

Do you know what is the result of this code, just by taking a look at it? What if the code looks like this:

  1. long someValue = 0;
  2. String[] values = new String[]{“NASTY_CONSTANT”,“MORE_NASTY_CONSTANT”,“NASTIEST_CONSTANT”}
  3. for(int i=0 ; i < values.length; i++)
  4. {
  5. try{
  6. someValue |= (Contants.class.getDeclaredField(values[i])).getLong(Contants.class);
  7. }catch(Exception e) {
  8. //do nothing
  9. }
  10. }

Thats not so clear or? Well that is what I am trying to get at…Maybe the above example is not the best, but I think it is enough to get the point that, there are limits that we need to respect and rules that need to be followed.
We need to think of the programmers that will take over the code what we have written (because this will come someday), and are we 100% sure that they will understand these clever one-liners that we have written? What if those lines need to be changed? Are they gonna be able to do that without massing up everything? Hmm…

Take another example:

  1. public String decode(String decodable) {
  2. return (decodable != null)?(decodable.equalsIgnoreCase(“aa”)?“decoded aaa”:(decodable.equalsIgnoreCase(“bb”)?“decoded bb”:“”)):“”;
  3. }

That is nice and clever but isn’t it more readable like this:

  1. public String decode(String decodable) {
  2. String ret = “”;
  3. if(decodable != null){
  4. if(decodable.equalsIgnoreCase(“aa”)){
  5. ret = “decoded aa”;
  6. }else if(decodable.equalsIgnoreCase(“bb”)){
  7. ret = “decoded bb”;
  8. }
  9. }
  10. return ret;
  11. }

Well? How many times do we chose the first version, just because we are lazy or we only want to impress the code readers? Yes I think many times, even if not for the mentioned reasons. Do we really need to write that kind of clever one-liners in case of simple codes like that?

I am really interested in your opinion about this… I am waiting for your posts…

Till next time,

Happy coding

N