Last Updated: February 25, 2016
·
1.298K
· austinkeeley

Avoid the word "and" in your method names

When writing code, look out for methods that contain the word and. For example:

public void doThisAndThat() {
    ....
}

Someone on StackOverflow pointed this out to me once (I wish I still had a link to the question to give them credit). This is code smell. It says that your method does 2 things. This is bad because

  1. It's not good API design. It's not exactly clear what you're doing with this method or why this and that are connected.
  2. You are most likely tightly coupling functionality within the method.
  3. There must be some reason why you want code to be executed in a set order. To me, this makes me feel like you're concerned about the state of your objects (which is good), but you're doing it wrong. Take a moment to consider the design of your classes and their lifecycle.

2 Responses
Add your response

Agreed for the most part. What about:

public void doThisAndThat() {
  doThis();
  doThat();
}

I write methods like this sometimes to provide a shortcut.

over 1 year ago ·

I agree, with a qualification. There are times when you want this; for example, an atomic operation. Also, if your method is doing too much, the solution is of course not to be less explicit, but to fix it. In that sense, the "And" is a smell but not a bad thing in itself.

over 1 year ago ·