I was looking at some code and a simple rule just occurred to me. If you’re creating an object oriented system, any time you start writing a method that accepts an instance of a class that you created as an argument, you should ask yourself whether that method should really be a member of the object being passed in as an argument.
I’d also recommend that any time you’re asking a question about an object (in a loop condition or an if
statement, for example), it’s worth considering whether that logic should be encapsulated as a method of the object as well.
For example, you might have code like this:
if (person.getAge() > 18 && person.getCountryOfBirth().equals(Country.USA)) {
// allow person to vote
}
It should probably be written like this:
if (person.isEligibleToVote()) {
// allow person to vote
}
The second example is easier to read and makes it easier to avoid keeping the voter eligibility conditions in more than one place. For example, I know that someone is going to file a bug noting that my expression doesn’t account for naturalized citizens. Keeping that logic in its own method will make it easier to fix that bug.
A simple rule of thumb
I was looking at some code and a simple rule just occurred to me. If you’re creating an object oriented system, any time you start writing a method that accepts an instance of a class that you created as an argument, you should ask yourself whether that method should really be a member of the object being passed in as an argument.
I’d also recommend that any time you’re asking a question about an object (in a loop condition or an
if
statement, for example), it’s worth considering whether that logic should be encapsulated as a method of the object as well.For example, you might have code like this:
It should probably be written like this:
The second example is easier to read and makes it easier to avoid keeping the voter eligibility conditions in more than one place. For example, I know that someone is going to file a bug noting that my expression doesn’t account for naturalized citizens. Keeping that logic in its own method will make it easier to fix that bug.