Code Smell - Keep It Simple
Whilst it's good to write efficient code, don't do it just to make the code smaller. Do it so that the next person can more easily maintain it. Making code logic complex or over-engineering can negatively impact the team's productivity because the code is now harder to understand and maintain.
Here's an example of efficient but hard-to-read C# code:
public bool ValidateUser(User user) =>
user != null && user.Name?.Length > 0 && user.Name.All(char.IsLetterOrDigit) &&
user.Email?.Length > 0 && Regex.IsMatch(user.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$") &&
user.Age >= 18 && user.Age <= 100;
This code validates a user object by checking if the user is not null, has a non-empty name that only contains letters or digits, has a non-empty and valid email address, and has an age between 18 and 100. While this code is efficient, it may be hard to read and understand for some developers due to its use of method chaining, ternary operator, and regular expression.
Rewritten for clarity:
public bool ValidateUser(User user)
{
if (user == null)
return false;
if (string.IsNullOrEmpty(user.Name) || !user.Name.All(char.IsLetterOrDigit))
return false;
if (string.IsNullOrEmpty(user.Email) || !Regex.IsMatch(user.Email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
return false;
if (user.Age < 18 || user.Age > 100)
return false;
return true;
}
This code achieves the same functionality as the previous example but is rewritten in a more readable and understandable way, with each validation condition separated by if statements. This approach may be easier for other developers to follow and maintain in the future.