I am feeling
The current mood of sweetperceptions at www.imood.com
right now.
Home  Email  Rss  PHP  Ruby

Writing good code

 June 13th, 2008

It has long been a debate on how to describe 'good code'. What are the criteria for declaring a code to be good, neat, and dry?

My advocacy is to promote writing good quality code. It is by painstaking practice and tons of reading that I get to exercise this advocacy. It is but a long journey, but little steps lead you to understanding and qualifying a code to be of high quality. So what are my benchmarks?

  • Long codes are less readable and more likely to fail.

Ruby scripts are far smaller and more compact in size compared to Java codes or C++ codes. Trust me, I've seen some and comparing them to Ruby, reading Java codes or C++ codes that are not mine would take me a longer time for understanding (even if docs and other help materials are present). Ruby has good metaprogamming (that sometimes gets abused because of monkey patching) and produce straightforward codes. Each line would end up more like real English sentences.

If you write ruby codes that take up to more than twenty lines.. hmm.. well, its doomed to fail, for sure. smile Refactor and review!

  • Codes that don't look anything like its API source is really smelly.

APIs are there for you to use as a general sitemap. It is your guide to efficiently write code with ease. Usually, APIs are well documented and even provide examples or snippets of codes to demonstrate its use. The lines of codes involved may also be present for you to inspect its process and even predict if it will pass your expectations.

It has long been a debate on how to describe 'good code'. What are the criteria for declaring a code to be good, neat, and dry?

My advocacy is to promote writing good quality code. It is by painstaking practice and tons of reading that I get to exercise this advocacy. It is but a long journey, but little steps lead you to understanding and qualifying a code to be of high quality. So what are my benchmarks?

  • Long codes are less readable and more likely to fail.

Ruby scripts are far smaller and more compact in size compared to Java codes or C++ codes. Trust me, I've seen some and comparing them to Ruby, reading Java codes or C++ codes that are not mine would take me a longer time for understanding (even if docs and other help materials are present). Ruby has good metaprogamming (that sometimes gets abused because of monkey patching) and produce straightforward codes. Each line would end up more like real English sentences.

If you write ruby codes that take up to more than twenty lines.. hmm.. well, its doomed to fail, for sure. smile Refactor and review!

  • Codes that don't look anything like its API source is really smelly.

APIs are there for you to use as a general sitemap. It is your guide to efficiently write code with ease. Usually, APIs are well documented and even provide examples or snippets of codes to demonstrate its use. The lines of codes involved may also be present for you to inspect its process and even predict if it will pass your expectations.

If you write your own method wanted to create something similar to (say "link_to"), then you must also follow the existing format of the method itself. Don't write methods that look or will work like something that's already existing in the API wherein the final script will look nothing like its ancestor method.

  • Repeatedly using a block across the whole application is not DRY, its wrong

Dubious codes are the best candidates for DRYing. Codes that appear across the application and across a method/controller are codes that should be rewritten. Exercise DRY. Always see what you can refactor. As much as possible, revisit existing methods or parts of the site that you suspect could be doing the same thing as your end goal.

Once you'll find a section/method whose output is "quite" similar to your expected result, nominate this method to a higher level and extend it. Don't create another method separate from this and create clutter. This is one road towards failure.

  • Stop reinventing the wheel.

Sure, you're great. No one is better than you. Well, you're wrong.. and chances are, if you think this way.. you're dead stuck at the bottom of the career ladder!

A responsible, mature programmer would try and see first if that something very trivial has already been done by somebody else. Research and extend what is already there. Be responsible and diligent enough to see if there is a better, faster and more elegant solution to your problem. Don't ditch the time for planning and go about writing your own code from scratch!

If you work like nothing has already been done by your ancestors or your entire community, then you're still a student. Stop writing collegiate machine problems, and get down to creating quality applications.

In line with this, I'd like to pinpoint an example. I found this code somewhere in one of our partials. At first, it wouldn't have caught my eye.. until I found this method called "cut_string". Its worth noting that we were using Rails version 1.2.6 and that not every bit of beauty found in Rails version 2.1.0 is already there. (This is one of the burdens of writing your app early, and delaying upgrades to the very last end.)

From its name "cutstring", I immediately was reminded of the "truncate" method native in Rails. The method was written in our applicationhelper. I felt the need to read and understand this uncommented code and see if its anything different from "truncate". To my surprise, it wasn't!

def cut_string(original,number_of_characters)
    truncated = original
    if original != nil
      if number_of_characters >= original.length
        max = original.length
      else
        max = number_of_characters
      end   
      truncated = original[0,max] 
      space_pos = truncated.rindex(' ') 
      if space_pos !=nil && space_pos != max
        truncated = truncated[0,space_pos.to_i] 
      end
  end
  truncated = strip_html(truncated) if truncated 
  return truncated
end

Blindly and irresponsibly rewriting it, I would've:

def cut_string(original,number_of_characters)
  unless original.nil?
    max = (number_of_characters >= original.length) ? original.length ? number_of_characters
    truncated = original[0,max]
    space_pos = truncated.rindex(' ')
    truncated = strip_html(truncated[0,space_pos.to_id]) if (!space_pos.nil? and space_pos!=max)
  end
  original
end

After this irresponsible rewrite, I would've saved 8 lines of code. Now what were my assumptions in this rewrite?

  • I only need this operation if original string is not blank (then I have saved some computing power)
  • I saved a whole block of "if..then..else" by using ternary operators (thereby reducing it to a one liner) since I only have to do value assignment
  • I made use of the fact that "the last assignment or code output of the last line in a method is always the return value of Ruby"

If you're the "easily satisfied programmer", you'd say that this code is already okay. But wait! There's more. wink I am not lazy, and by experience, I know for a fact that I can still reduce this 7 liner block into a mere 2 liner block! Yep, I'm not kidding.

Rails already have this "truncate" method that I can make use of. I fire up my ROR API (found online at http://api.rubyonrails.org) and check the usage of "truncate" method and I find this:


truncate(text, length = 30, truncate_string = "...")

If text is longer than length, text will be truncated to the length of length and the last three characters will be replaced with the truncate_string.

  truncate("Once upon a time in a world far far away", 14)
   => Once upon a...

[ hide source ]

    # File actionpack/lib/action_view/helpers/text_helper.rb, line 34
34:       def truncate(text, length = 30, truncate_string = "...")
35:         if text.nil? then return end
36:         l = length - truncate_string.chars.length
37:         text.chars.length > length ? text.chars[0...l] + truncate_string : text
38:       end

I read carefully and understood that what "cutstring" wanted to do was eliminate the cases wherein the sentence or string would be forcibly cut into words that are not dictionary-valid. This was the whole reason of wanting to get

spacepos = truncated.rindex(' ')
into the block. I didn't want to lose this essence, so I made this new method that will make use of my knowledge of Rails and Ruby programming. I know have this:

def truncate_string(text, length, truncate_string = "...")
  str = truncate(text, length)
  str[0..str.rindex(' ')] + truncate_string
end
  • I was able to follow Rails' method declaration for "truncate"
  • I was able to truncate the string into the desired (maximum) number of characters
  • I was able to retain the essence of words not being cut into unreadable chunks
  • I was able to maintain the dynamic use of whatever truncate_string would be preferred
  • I was able to reduce code by ~86%
  • I was able to enjoy it!

Got it? I hope you did. Happy coding!

Leave a Reply

One sweet day is coming!  I'm so happy and excited.. and so is my honey.  smile  Its a road to forever happiness and we'd like to share it with you.  Things are still cooking up, but we're excited to let you know.  Watch out for eleven8...


comments Comments »
nakakainis talaga maging empleyado lang12:02 PM pipilitin kang gawin lahat kahit na sa tingin mo mali12:02 PM sa tingin ko ito talaga problema ko ever since the world began12:02 PM ayokong gawin yung sa tingin ko eh mali12:03 PM pero kahit mali sa iba at tama para sa akin gagawin ko12:03 PM pero yun naman...


comments Comments »
Seriously, I like it when people give words of wisdom, or even share their own joys and/or sorrows.  Even those people who leave good thoughts and advices are alright.  Its okay.  But if you don't tell me who you are or if that I find that you picked my blog...


comments Comments »
Its a wonderful feeling that you are loved, and yes, its even better when you have someone to love.  In tagalog.. "kay sarap nang may minamahal.."  smile  Yep, its really great when everything seems perfect.. but then you get to ask yourself why on earth should you deserve this?  Is...


comments Comments »
If you haven't read Jules Verne's Journey to the Center of the Earth and weren't even able to watch the movie Journey to the Center of the Earth, then I hope you'll find it intriguing to watch the movie or buy the book after I relate our experience.I love Jules...


comments Comments »
Inspiration is nothing compared to Action itself.. I think so, I believe so..We should be taught not to wait for inspiration to start a thing. Action always generates inspiration. Inspiration seldom generates action.--Frank Tibolt [From MockObjects.com]&nb...


comments Comments »
I'm not a US citizen, in fact, I've never been there.  I'm not a politician or a political analyst/thinker.  But I do know a good person when I see one.  We all do right?  If I can vote for a US Presidency candidate, I'd pitch my vote for Barack Obama.Not...


comments Comments »
[video align='align-left']http://www.youtube.com/watch?v=rafEFSXVtuw[/video]While on the way home, as usual, I had to compete with a lot of people going to Quiapo.  I got a little pissed off because the drivers feel like once they have the "Derecho" sign boards they automatically upgrade their fare to 30 bucks!  They still pass by...


comments Comments »
I'm out of my league.  Hell, I didn't even know why I was there.  I knew I wanted to come because I wanted to try new things!  I don't really like gambling, and was quite hesitant to come, yet I wanted to learn how to play poker.  smile  My honey...


comments Comments »
Two days ago, my youngest sister was suddenly in the mood to watch Kill Bill again.  Well, since none at home had any violent reactions, we watched Volume 1 at around 8pm.  Supposedly, my honey and I were to discuss something very important that night, but then we opted to...


comments Comments »
  • Anti burn out = day off! 2008-11-17
  • i can only be stubborn because i have ideals and personal standards. 2008-11-16
  • working in a company means you'll do ALL of what they say. Most of the time its painful and annoying when its something you don't want. 2008-11-16
  • i just don't like being lied to. i can take a bitter truth but not a beautiful lie 2008-11-14
  • how could "a moment" take so long as 2 hours? especially if you say you're sleepy 2008-11-14
  • woohoo.. i'm happy for this weekend. smile 2008-11-14
  • nakiki-twitter lang kay Chris... buwahahahaha! - Deyey 2008-11-08
  • good to have the friendly internet always handy.. hehe 2008-11-08