Some rules for functions:
- First rule for function is they are small.
- Second rule they are smaller than that.
- Lots of smaller function with better names will help you and your team because they will help you like a sign board and navigate you through your code.
- Don’t worry about function call overhead. It is overly misplaced.
- Remember making function small will save you and everybody.
- Classes hide in larger functions.
- Functions do one thing. To make sure your function do one thing is to extract till you drop. If you can extract from your function that means your function was doing more than one thing.
- Function signature should be small; they should have less than 3 arguments
- Do not pass Boolean or null into a function
- No output arguments
- Organize our method into step down principle, public methods on top followed by private method with no backward references.
- Switch statement break OO principle and doesn’t allow independent deploy ability and development ability. Replace it by Polymorphism or move it to safe independent deployable modules like Main inside of a factory method.
- Temporal coupling like file open & close operation must be in order. It can be solved by passing a block into a method.
- Command Query Separation: Command return must be void and Query must return a type.
- Tell Don’t Ask.
- Law of Demeter: Danger of too much knowledge in single line.
- Structure Programming: Program should have single input and single output.
- Complex mid loop return tends to have problem rather avoid it.
- Error Handling: Consider error handling first before we continue with any other part of function.
- It’s better to have Exception instead of returning error code.
- Exception should be scoped to our class for better understanding.
- It’s better to have unchecked exception then check exception. E.g.: derive from runtime exception
- Null object pattern or Special case pattern is often better than exception.
- Null value is not an exception.