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:
- Is this discouraged?
- If yes, why and what is the alternative
- Should the solution be adding some sort of cache instead?
- 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 aBar
explicitly. As a setter, it shouldn’t really need to return anything. Then either exposeexpensiveGetBar()
, or exposegetBar()
and have it cache the result ofexpensiveGetBar()
.