What? I know how to design a single method! What can
Jeffrey Palerm possibly have to tell me about how to design a single
method?
Take a look at your product’s code base. Are any of the following true?:
* You have a method that you can’t view without scrolling.
* You have a method that takes 10 arguments.
* You have a method that not only returns a result but causes
disastrous things to happen if called more than once.
* You have a method that throws exceptions if you don’t set certain properties first.
* You have a method that has 5 nested foreach/if/try-catch code blocks.
* You have a method whose name doesn’t give you a clue as to what it does.
* You have a method that will not throw an exception because it swallows the exception without handling it.
I
could go on and on (ok, actually I’m out of ideas right now), but
chances are that you can find a method that meets one of the criteria
above. Find one of those methods, and fix it. Here are
general rules I try to live by when designing a single method:
* The name of the method should describe what the method actually does.
* A method should do one and only one thing.
* A method should either DO something or RETURN something. If it
returns something, you should be able to call the method over and over
with no negative consequences.
* The method
should be viewable without scrolling. Fewer than 10 lines of code
is desirable (my pain point).
* The method should
take few arguments. If the method needs more, refactor to require
and object that contains all the information required (parameter
object).
* The method depends only on method parameters or members passed into the class constructor.
* A method should only have one indented code block – don’t nest code blocks. Extract method first.
* Don’t try/catch in a method unless you can handle the exception or
add value. Let the exception bubble up to a point where you can
actually do something about the exception.
If you have any good points for method development, please feel free to leave a comment.