Coding Standards – Naming Convention for Methods that Set and Get

coding-standards

Let's say we have a method setFoo that sets a flag in a Bar object e.g.

class Baz { 
    public void setFoo(String foo)(
       ...
    }
}

inside setFoo, the method is doing some expensive load of the Bar object from the database.

class Baz { 
    public void setFoo(String foo)(
       Bar bar = expensiveGetBar();
       ...
    }
}

To avoid the need to get the Bar object again, the developer changes the method to return it.

class Baz { 
    public Bar setFoo(String foo)(
       Bar bar = expensiveGetBar();
       ...
       return bar;
    }
}

Questions are:

  1. Is this discouraged?
  2. If yes, why and what is the alternative
  3. Should the solution be adding some sort of cache instead?
  4. How would you prefix the method? set? get? seget? geset?

Best Answer

A function should serve one purpose. That’s part of the reason it’s called a function. If you find a method hard to name because it’s doing more than one thing, then split it into more than one method. Readable method names can often be made from just one verb and one noun.

In your example, you could change setFoo() to take a Bar explicitly. As a setter, it shouldn’t really need to return anything. Then either expose expensiveGetBar(), or expose getBar() and have it cache the result of expensiveGetBar().

Related Topic