Code should be necessarily verbose to describe it’s intent, but no more so. Boilerplate and other code that describes the same behavior over and over again makes your program more work to read and understand, and increases the risk of errors.
- Copying similar logic over and over again leads to needing to read more code to understand what the program is doing.
- When updated, copy and pasted logic must be updated in many places which are easy to miss and cause large change sets.
- Having similar but slightly varied code hides the deviations, forcing you to read over nearly identical code just in case there might be a difference.
A better approach is to write generic code that can serve in the place of boilerplate. When you find yourself repeating some boilerplate ask yourself “Does the behavior of this deviate far enough that making it generic would make it overly complicated? If the behavior does not deviate now, will it likely in the future, or do both blocks of code resolve to the same conceptual idea?”. Each logical construct should be given only one definition within a code base.
For instance, is it useful in a web application to specify for each endpoint individually that it uses HTTP, that it accepts and returns JSON, that it returns a 200 HTTP status code when successful, a 422 when there is a validation error, a 500 when there is a server error, or would it be better to declare that all endpoints have those attributes unless specified otherwise? Is it useful to specify for each endpoint that it logs the request and result, that it performs database changes in a transaction, and that the request is processed through a half dozen layers, each with unique method names, or would it be more useful to put all the unique logic of a request together in one place and abstract away all the other layers to the request pipeline?
In short, most of your code should describe a default for your program or a deviation from the default. Specfying the same behavior over and over again is an antipattern that can slow down inital development and will increase the cost and risk of maintenance thereafter.