Imperative vs. Declarative

I came across this beautifully detailed post, Imperative vs. Declarative by Philip Roberts, and wanted to share my thoughts on the Ruby-way of things (and hopefully get it right).

So as Philip explains it:

  • Imperative Programming: Telling the “machine” how to do something, and as a result what you want to happen will happen
  • Declarative Programming: Telling the “machine” what you would like to happen, and let the computer figure out how to do it

(Where ‘Machine’ is Computer/database/programming language/etc)


Imperative

Suppose, you have an array of numbers and you want to double every value. If you have recently started Ruby, you’ll probably try doing things the old way; i.e. Iterating over the array, and doubling each value:

1
2
3
4
5
6
nums = [1,2,3,4,5]
dubs = []

for n in nums
    dubs << n * 2
end

or maybe if you already know about each, you’ll go about doing it this way:

1
2
3
4
5
6
nums = [1,2,3,4,5]
dubs = []

nums.each do |n|
    dubs << n * 2
end

Declarative (The Ruby Way)

Now, the Ruby way of doing things is different (which also happens to be Declarative BTW):

1
2
nums = [1,2,3,4,5]
dubs = nums.map { |n| n * 2  }

I on the other hand would take this a level higher to show how cool I am:

1
2
3
4
5
6
7
8
9
class Integer
    def double
        self * 2
    end
end


nums = [1,2,3,4,5]
dubs = nums.map(&:double)

Conclusion

  • Loops are Imperative
  • Map is Declarative
1
Ruby ROOLZ, Java DROOLZ

Also this: