0

Lately I was wondering if it is a bad practice to use variables in your code that are related to each other (e.g. a = 2 * b). A concrete example would be euro and dollars. Let's say we have a Person class who has some balance in euros and dollars (coded in java for demonstration):

class Person {

    float balanceInEuros;
    float balanceInDollars;

    public Person(...) { // Problem 1 (see down below)

    }
}

Problem 1: What do you need to put in the constructor arguments? Both variables are float so we can't differentiate between to distinct constructors (java can have multiple constructors for a class, as long as they have a different type of arguments). To solve this we can make two separate methods to return a Person, for example:

public static createPersonWithEuros(float euros) {
    Person person = new Person();
    person.setEuros(euros);
    return person;
}
// Similar for dollars...

Problem 2: Now we have no value for the dollars, so a method person.getDollars() would result in an error. Of course this can be fixed again by adding a single line in the createPersonWithEuros() method: person.setDollars(Person.EXCHANGE_RATE_EURO_DOLLAR * euros) or something along those lines.


Arguments for

  • It feels more natural to use dollars and euros instead of a so called 'balance' which has no concrete meaning.
  • It makes more sense and thus enhances the readability of the code

Arguments against

  • By using a universal 'balance' with functions to calculate to euros/dollars etc., it results in cleaner code (less functions/bulk code...)
  • You need more memory to store essentially the same thing, which could be bad

What is better and why?

EDIT: Another thing I am concerned with is that I programmed this particular example in an OO language. What if this was written in javascript for example?

Dacaspex
  • 669
  • 7
  • 15

1 Answers1

1

By creating a separate class Balance which has an amount and a currency, you can use a single constructor with a 'balance' parameter and use euros, dollars, pounds and so on as you like. All conversion goes to the Balance class and Person can use balances regardless of currencies, conversion rates and so on.

JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27
  • I'll wait a day or two to accept this as an answer. Maybe others will come up with a different answer – Dacaspex May 17 '16 at 20:04