Let's say that we need to produce a message as shown below.
In the above case the amount and the currency might change.
We can solve this by writing code like this.
As we have seen before this style of writing code is called "Procedural style of
programming".
Let's take a look at how to solve the same problem using "Object Oriented style
of programming". We will start with creating a class called Price
.
Currently this class has nothing. Let's move all the lines from procedural to
object oriented style.
We created a few "class methods" and moved the procedural code there.
For methods "line1" and "line2" we need to pass currency to both the methods.
why do we need to pass same currency two times. We need to do that here because
the class Price does not hold currency.
Rather than passing currency twice we will let the class hold the value of
currency and then use it when we need currency.
In Ruby when we instantiate a class then initialize
method is called. That's a
good place to pass any state level information for that class.
Now the instantiated object will hold the state called currency which can be
used by other methods. Also we need to change methods from class methods to
instance methods. After the change the class looks like this.
In the above case methods "line1" and "line2" are reaching out to "@currency".
This is not ideal. A class should be able to control what is available and what
is not.
In this case we can use attr_reader
to make currency
available to all the
methods. Note these methods need to use currency
and not @currency
.
Here is the modified solution.
So far we have been instantiating an object and on that object we have been
invoking all these methods. However we can move the call to these methods to
inside the class and have only one method from outside to call it.
Here is a modified solution.
In the above case while calling the method message
we are passing
"monthly_price" and "annual_price". We can pass on the pricing information when
we are instantiating the class. Let's do that.
Here is the modified code.