You can always write comment to your codes. But comment itself can be outdated and misleads a developer. So writing self-documented codes must our first aim to make our code more maintainable.
In my opinion a big step to achieve self-documented code begins writing if clauses.
If a developer understands if clause, he/she understand purpose of the code block more easily.
But how can we write more readable if clause?
Very easy: Don’t write logical comparisons into if clause.
if ((preprocessedFailedEmails.Count > 0) || (failedEmails.Count > 0))
{
//some code
}
Although this is a very simple if clause it’s a bit hard to get what is happening there. Let’s make it more readable.
bool hasErrors = ((preprocessedFailedEmails.Count > 0) || (failedEmails.Count > 0));
if (hasErrors)
{
//some code
}
If we move one step further:
bool hasPreprocessedFailedEmail = preprocessedFailedEmails.Count > 0;
bool hasFailedEmail = failedEmails.Count > 0;
bool hasErrors = (hasPreprocessedFailedEmail || hasFailedEmail);
if (hasErrors)
{
//some code
}
Happy coding…