Thursday, January 24, 2013

Back to SELA and intersting issue

Hi all,
It's a long time since i posted something in my blog.
 but now after coming back to SELA i decided to renew my blog and make it much better.
I really wish to make my blog a place where programmers can find deep answers and understand better the all issue of programming.

When I browsing the internet looking for good topic to my blog I found the following question in stack overflow: http://stackoverflow.com/questions/2489701/value-object-getter?rq=1

First it looks like non important issue, however, I think this question is much more important than it looks like , I saw a lot of developers using such utilities methods or choosing the second approach and adding more methods. this issue is important since it touches the core of object oriented programming. both of the options are not good object oriented design.
the first approach creates utility methods that are not really belong to any type and it's really a procedural programming.
The second approach let's the amount of money deal also with the interpretation of the amount to specific type of coins.
The issue become more serious if you wish to support different types of coins (euro, yen, yuan...)
than you can see that both of the approaches are not so good.
Here is my object oriented solution for this issue, the UML should look like this:


1. Create abstract parent class called money with amount and factor, each type of coin will be a subclass of class money and only money will have methods of equals, hashCode and compareTo.
each subclass can implement the toString method for coin presentation. than you can write factory for it to create the right coin that also read the appropriate factor of the coin.
Now let's look how the code should look like:
public abstract class Money implement Comparable{
private int amount;
private int factor;

public Money(int a, int f){
   amount = a;
   factor = f;
}

public boolean equals(Money m){
 return (amount * factor == m.amount * m.factor);
}

public int hashCode(){
  return amount * factor;
}

public int CompareTo(Money m){
    return amount * factor - m.amount * m.factor
}

public int getMoney(){
   return amount;
}

public int getCurrency(){
  return factor;
}

}

public class Cent extends Money{

public Cent(int amount){
  super(amount, 1);
}


public String toString(){
  return Integer.toString(amount) + "C";
}

}

public class Dollar extends Money{

    public Dollar (int amount){
        // here you can also calculate the currency 
        super(amount,100);
    }

    public String toString(){
      return Integer.toString(amount) + "$"; 
    }
}

No comments: