A method is an abstraction

The name of a method must have a higher level of abstraction than the body for the method to be worth it. The name should explain what the method does but not how. If the name communicates exactly the same than its code, it could be a sign that the method does not pay off and should be inlined.

Whenever we extract a method from a bunch of lines of code, we are adding a little abstraction to our code. If the extraction happens too early, then we are adding wrong abstractions to the code. Those premature abstractions get in our way to a better design, often hiding duplication and deeper design problems. Lots of small methods does not necessarily mean better design.

I extract a method only when my tests are green and it's really obvious the responsibility of those lines. When I am done implementing the branch of the solution I am test-driving and it's easy to find a name for the new method.  I don't create new methods to make a test pass. Methods appear later.

Code below is an example of premature method extraction. Right after the first test passed the developer created this method:

  2. private boolean isValidArithmeticExpression(String input) {
  3. return input != null;
  4. }

The body of the method is perfectly understandable without the method. There was no duplication of the statement and there were just a few lines in the production code. Definitely too risky, too early, too complex.

An example of a wrong encapsulation:

  2. public string splitBySpace(string expression){
  3. return expression.split(" ");
  4. }

In this example the method's name says exactly what one can read in the body.

The same applies to helper methods in the tests. This is an example of a wrong encapsulation:

  2. private void conductCalculationAndAssertResult(String equation, int expectedResult) {
  3. int result = calculate(equation);
  4. assertEquals(expectedResult, result);
  5. }
Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
  • Oscar Moreno

    Hi Carlos, as you teach me, it always depends on the context, I am not totally agree with you in the first example, it’s true that the inlined method is understandable from a technical point of view but may not from a business point of view, you can read it as “the arithmetic expression exists” but the meaning in the domain is “is valid” (in that case arithmetic expression may be an object, but thats another story) so for me the rule is even when the method is one line easy readable I keep the abstraction if it add meaning or context 🙂


  • http://www.carlosble.com/ Carlos Ble

    Hi Oscar!
    The method might not be wrong if we are done with the feature at hand and specially if that line is repeated through the code. However, I’ve seen that method to be created right from the first green test. It’s too early to make the assumption that we need such an abstraction.
    Thank you mate 😉