20 Tips for becoming a better programmer

1. There should be only one single exit point to each method (use if-else whenever needed).

2. When using if-else, make sure to place the shorter code snippet in the if:

if (cond) {
else {


3. Do not throw exceptions if you can avoid it, it makes your code much slower, if you feel like throwing something and then catching it – go play ball with your dog. If you don’t have a dog get one – they’re awesome!

4. Do not try to do many things on the same line – when you’ll get an error – it will be harder to debug, example how to NOT write your code:

String result = hasInformation()? getState() : (hasMoreInformation() ? getOtherState() : getState());

5. Look for code pieces that look the same and if you find any – refactor!

6. Meaningful names are a must. If you’re not sure, meditate on it for another minute. Still not sure? ask your colleagues for their opinion.

I’m still shocked everytime I find out that the following is not common knowledge:
7. Whenever you can use HashMap instead of List/Queue – use it!

And on the same note:
8. If you can use caching instead of I/O (usually DB) – use caching

9. If a nice and simple regex can do the job – use it!

10. Do not use regex for parsing (for example: HTML/XML/json) – there are special tools for that in every language, for example in Ruby, Java etc.

11. Print to Log. You should have at least two levels of logging: DEBUG and ERROR. The latter should be the default. Nice tip: you can send your self a text when a critical error occurs, by sending an email to your_mobile@your_carrier – look here for more details.

12. Use stackoverflow – not only for asking questions: Take a few minutes, every day, and try to answer questions – you’ll be surprised how much you’ll learn from it!

13. A rule of thumb: if your method is over 50 lines – split it. If your class is over 500 lines – split it. If you think you can’t split it – you’re doing something wrong. This recommendation is a “language dependent” and shouldn’t be taken “as is”: while 50-line method feels natural in Java/C# – it will be considered very long in more expressive languages such as Ruby & Python.

14. Writing a code which is “self explanatory” is great but also very hard, if you’re not sure how “obvious” your code is – use code-comments.

15. When writing code comments always assume that the reader doesn’t know what you’re trying to do. Be patient & explain. No one is going to *bug* you because your comment was too long…

16. You want to improve? read books, blogs, technical online newspapers join relevant groups on Linkedin, update yourself with the latest technologies, go to conferences, got the point ?

17. Practice makes perfect: solve code-challenges, join hackathons, go to meetups etc

18. Experiment with different IDEs until you find the one that “feels right”, study it carefully and make sure you know the major features (including plugins). Tune-up the keyboard shortcuts – it will make your workflow smoother.

19. Whenever you find a bug, before you fix it, write a unit-test that captures it. Make sure it does.

and my favorite:

20. Don’t get lazy – RTFM

We’ll finish with two quotes:

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”
– Brian Kernighan

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”
– Rick Osborne

Many thanks for Jeff Grigg, Tom Burton and Keith M. O’Reilly for their feedback which helped me improve this post – cheers!

20 Tips for becoming a better programmer

Playing with Ruby

Ruby is a wonderful programming language, and when I say wonderful I mean that basically it just makes you happy. As a Java programmer, there are so many things that I need to check and be careful about, and Ruby just makes it easier for you, taking care of you, and if I have one more glass of wine I might get carried away and say that it almost spoils you, makes you lazy – cause now when I have to implement an algorithm, I’d rather do it in Ruby rather than Java, or even PHP, which is still easier, but with all the ugly $-signs (yes, I am lazy when it comes to hold the shift key and press ‘4’, who’s the dumb-a$$ that came up with that stupid idea anyways, ha ?)

One of the things I first do when starting to learn a programming language is implementing a few basic stuff, for example, the famous Tower of Hanoi:

def hanoi(disc, src, hlp, dst)
    if disc > 0
        hanoi(disc-1, src, dst, hlp)
        puts "moving disc #{disc} from #{src} to #{dst}"
        hanoi(disc-1, hlp, src, dst)

hanoi(3, 'src', 'hlp', 'dst')

It’s so beautiful to define factorial in one line:

def fact(n) (1..n).inject{|r,i| r*i } end 

And then I usually continue to merge-sort:

# sorting the array from _start index to the _end index
# using merge sort
def mergesort(arr)

    # stop condition
    return arr if arr.count == 0 || arr.count == 1 
    # split the range
    mid = arr.count/2

    # sort recursively both parts
    arr1 = mergesort(arr[0, mid]) 
    arr2 = mergesort(arr[mid, arr.count-mid])

    # and merge
    merged = []
    max_i, max_j = [arr1.count, arr2.count]
    i = j = 0
    while i < max_i && j < max_j
        if arr1[i] <= arr2[j]
            merged << arr1[i]
            i += 1
            merged << arr2[j]
            j += 1

    # continue copying the rest:
    while i < max_i
        merged << arr1[i]
        i += 1
    while j < max_j
        merged << arr2[j]
        j += 1

    # return

arr = [2,3,4,5,6,1,7]
puts mergesort(arr)        	

and if we didn’t have enough, let’s implement quicksort as well:

def quick(arr)
  return [] if (arr.size == 0)    
  pivot = arr.pop
  left = Array.new
  right = Array.new
  arr.each { |i|
    if i < pivot
      left << i
      right << i
  return quick(left) + [pivot] + quick(right)

a = [5,3,9,8,7,2,4,1,6,5]
p quick(a)

The downside of coding in an unfamiliar language is that your’e still captured in patterns that are perfect for other programming languages, only that in this one – you can do things in a more elegant & efficient way.

Until next time…ta-ta!

Playing with Ruby