Methods Should Do Only One Thing

Summary

Methods should do only one thing.

Details

A useful guide as to whether a function is doing only one thing is given in “Clean Code” by Robert C Martin.

“another way to know that a function is doing more than “one thing” is if you can extract another function from it with a name that is not merely a restatement of its implementation.”

Bad

  1. public void updateFooStatusAndRepository(Foo foo) {
  2. if ( foo.hasFjord() ) {
  3. this.repository(foo.getIdentifier(), this.collaborator.calculate(foo));
  4. }
  5. if (importantBusinessLogic()) {
  6. foo.setStatus(FNAGLED);
  7. this.collaborator.collectFnagledState(foo);
  8. }
  9. }

Better

  1. public void registerFoo(Foo foo) {
  2. handleFjords(foo);
  3. updateFnagledState(foo);
  4. }
  5. private void handleFjords(Foo foo) {
  6. if ( foo.hasFjord() ) {
  7. this.repository(foo.getIdentifier(), this.collaborator.calculate(foo));
  8. }
  9. }
  10. private void updateFnagledState(Foo foo) {
  11. if (importantBusinessLogic()) {
  12. foo.setStatus(FNAGLED);
  13. this.collaborator.collectFnagledState(foo);
  14. }
  15. }

You’ve gone too far

  1. public void registerFoo(Foo foo) {
  2. handleFjords(foo);
  3. updateFnagledState(foo);
  4. }
  5. private void handleFjords(Foo foo) {
  6. if ( foo.hasFjord() ) {
  7. this.repository(foo.getIdentifier(), this.collaborator.calculate(foo));
  8. }
  9. }
  10. private void updateFnagledState(Foo foo) {
  11. if (importantBusinessLogic()) {
  12. updateFooStatus(foo);
  13. this.collaborator.collectFnagledState(foo);
  14. }
  15. }
  16. private void updateFooStatus(Foo foo) {
  17. foo.setStatus(FNAGLED);
  18. }