?? Code Smell Alert: Oddball Solutions ??

?? Code Smell Alert: Oddball Solutions ??

Have you ever encountered a situation where the same problem is solved in multiple, slightly different ways across a project? That’s the Oddball Solution. This smell often occurs when different methods handle similar tasks without a unified approach.

Consider this example of email validation:

? Smelly Code:

public class UserService
{
    public void CreateUser(string email)
    {
        if (!email.Contains("@"))
            throw new ArgumentException("Invalid email");
    }

    public void UpdateUserEmail(string newEmail)
    {
        var emailRegex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
        if (!emailRegex.IsMatch(newEmail))
        {
            Console.WriteLine("Warning: Invalid email");
            return;
        }
    }
}        

Spot the oddball? We're validating emails in two completely different ways within the same class!

? A better approach:

public class UserService
{
    private bool IsValidEmail(string email) =>
        Regex.IsMatch(email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");

    public void CreateUser(string email)
    {
        if (!IsValidEmail(email))
            throw new ArgumentException("Invalid email");
    }

    public void UpdateUserEmail(string newEmail)
    {
        if (!IsValidEmail(newEmail))
        {
            Console.WriteLine("Warning: Invalid email");
            return;
        }
    }
}        

By centralizing our email validation, we've eliminated the oddball solution and improved consistency.

Key Takeaway: When you spot oddball solutions, refactor for consistency. Your future self (and your team) will thank you!

?? Have you encountered oddball solutions in your projects? How did you handle them?

#CodeSmells #CleanCode #Refactoring #CSharp #SoftwareEngineering


要查看或添加评论,请登录

社区洞察

其他会员也浏览了