An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
Code Smell 133 - Hardcoded IF Conditions
Hard coding is fine. For a short period of time
TL;DR: Don't leave a hardcoded mess on IFs.
Problems
Testability
Hardcoded values
Open/Closed Principle Violation
Solutions
- Replace all IFs with a dynamic condition or polymorphism.
Context
Hard-coding iF conditions is great when doing Test-Driven Development.
We need to clean up stuff.
Sample Code
Wrong
private string FindCountryName (string internetCode){ if (internetCode == "de") return "Germany"; else if(internetCode == "fr") return "France"; else if(internetCode == "ar") return "Argentina"; //lots of elses else return "Suffix not Valid";}
Right
private string[] country_names = {"Germany", "France", "Argentina"} //lots moreprivate string[] Internet_code_suffixes= {"de", "fr", "ar" } //moreprivate Dictionary<string, string> Internet_codes = new Dictionary<string, string>();//There are more efficient ways for collection iteration//This pseudocode is for illustrationint currentIndex = 0; foreach (var suffix in Internet_code_suffixes) { Internet_codes.Add(suffix, Internet_codes[currentIndex]); currentIndex++;}private string SendUserName(string internetCode) { return Internet_codes[internetCode];}
Detection
[X] Automatic
By checking If/else conditions we can detect hard-coded conditions.
Tags
- IFs
Conclusion
In the past, hard-coding was not an option.
With modern methodologies, we learn by hard-coding, and then, we generalize and refactor our solutions.
Relations
Code Smell 36 - Switch/case/elseif/else/if statements
Maxi Contieri Nov 28 '20 1 min read
Code Smell 102 - Arrow Code
Maxi Contieri Nov 15 '21 2 min read
More Info
Credits
Photo by Jessica Johnston on Unsplash
Don't be (too) clever. My point was to discourage overly clever code because "clever code" is hard to write, easy to get wrong, harder to maintain, and often no faster than simpler alternatives because it can be hard to optimize.
Bjarne Stroustrup
Software Engineering Great Quotes
Maxi Contieri Dec 28 '20 13 min read
This article is part of the CodeSmell Series.
Original Link: https://dev.to/mcsee/code-smell-133-hardcoded-if-conditions-53bi
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To