1. There is a difference between understanding the code and understanding the problem it solves. Good code should have both.
2. If you are unsure if a variable or method name fits your needs, send it to a chat and ask people what they expect from it.
3. Strings. There are no checks for strings. Therefore, if there is code like
if (order.status == 'delivering') {...}, and you decide to rename a status label, you should manually find all the places, where you've written such checks and fix them. What is a solution? Keep such checks in one place.
There are two possible ways to do it:
1) Method:
order.isDelivering()2) Enum:
order.status == OrderStatus.delivering4. Don't save on variables. Oneliners aren't cool if they prevent you from understanding the logic.
A popular example from C language:
while (*dest++ = *src++);5. One vs Many in variable naming.
If I see a variable named
attributes, then I expect it to store some collection, not an individual object.6. Semantics. Make your code meaningful.
Example:
if (!items.children) {...}
Do you have any clue of what did we just checked? Me neither.7. Null object pattern
In some cases instead of writing checks like
if (user != null && user.isAdmin()) {
user.doSomething();
}*,
you can use Null Object Pattern. "We should use the Null Object Pattern when a Client would otherwise check for null just to skip execution or perform a default action. In such cases, we may encapsulate the neutral logic within a null object and return that to the client instead of the null value. This way client's code no longer needs to be aware if a given instance is null or not."
For the example above it could be
final user = cond ? AdminUser() : Guest(), where Guest is a null object.
8. Command-Query separation
"It states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer."
Example:
user.isValid() - predicate that returns boolean. We don't expect it to change anything. If it somehow modifies our state under the hood, it'll be almost impossible to find the bug when we face some weird behavior.*This example doesn't apply to languages with null safety like Dart and Kotlin
#dev