?? Code Smell Alert: Oddball Solutions ??
Mehedi Hasan
SWE L2 @Vivasoft| Trainer @Edge.gov.bd| C#, .NET, Python, AI, LLM, Docker, CI/CD| Top 5% ranked on LinkedIn assessment of C# and OOP| Problem solver
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