Tuesday, March 10, 2009

The benefits of stateless objects

For my first technical post, I'm gonna talk about a too common bad practice in programming: stateful objects. This is not a simple error only novice programmers do, it's a very common error even amongst professional programmers.

Consider the following example:
class Stateful
def calculate(x)
@result = x * 2
end

def display
puts "The value is: " + @result.to_s
end
end

s = Stateful.new
s.calculate(10)
s.display

In this case, the user of the class needs to call the calculate method before the display method. This implies a knowledge of the inner working of the class by its client. This is bad. If you make the API of your class impossible to misuse, then nobody is going to misuse it. This includes you!

This is a simple example and one might think that the usage of the class is pretty obvious. But in medium size software, there are often hundreds or thousands of these nasty stateful classes. Most of them have no need for a state. This increases the complexity of the code and makes collaboration between developers harder.

A better implementation would be:
class Stateless
def calculate(x)
x * 2
end

def display(x)
puts "The value is: " + x.to_s
end
end

s = Stateless.new
x = s.calculate 10
s.display x

There is now no possibility of misusing this class.

Of course, stateful object have their use too! But you should only add a state to your application when you have to.

1 comment:

  1. Good one, Simon.

    I guess that as long as you stay in your own code, and that the application size is relatively small, this become less obvious, but I must agree that for large size application using really often a lot of these classes involving a certain pattern or "order" (despite I don't like the word order in this sense...) in order to call functions, this become really useful And ya, this is crucial when writing down an API.

    ReplyDelete