Consider the following example:
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!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
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:
There is now no possibility of misusing this class.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
Of course, stateful object have their use too! But you should only add a state to your application when you have to.
Good one, Simon.
ReplyDeleteI 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.