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 150 - Equal Comparison
Every developer compares attributes equally. They are mistaken.
TL;DR: Don't export and compare, just compare.
Problems
Encapsulation break
Code Duplication
Information Hiding Violation
Anthropomorphism violation
Solutions
- Hide the comparison in a single method
Context
Attribute comparison is heavily used in our code.
We need to focus on behavior and responsibilities.
It is an object's responsibility to compare with other objects. Not our own.
Premature Optimizers will tell us this is less performant.
We should ask them for real evidence and contrast the more maintainable solution.
Sample Code
Wrong
if (address.street == 'Broad Street') {if (location.street == 'Bourbon St') {// 15000 usages in a big system // Comparisons are case sensitive
Right
if (address.isAtStreet('Broad Street') { }// ...if (location.isAtStreet('Bourbon St') { } // 15000 usages in a big system function isAtStreet(street) { // We can change Comparisons to case sensitive in just one place. }
Detection
[X] Semi-Automatic
We can detect attribute comparison using syntax trees.
There can be good uses for primitive types as with many other smells.
Tags
- Encapsulation
Conclusion
We need to put responsibilities in a single place.
Comparing is one of them.
If some of our business rules change we need to change a single point.
Relations
Code Smell 63 - Feature Envy
Maxi Contieri Mar 23 '21 2 min read
Code Smell 101 - Comparison Against Booleans
Maxi Contieri Nov 11 '21 2 min read
Credits
Photo by Piret Ilver on Unsplash
Behavior is the most important thing about software. It is what users depend on. Users like it when we add behavior (provided it is what they really wanted), but if we change or remove behavior they depend on (introduce bugs), they stop trusting us.
Michael Feathers
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-150-equal-comparison-ok1
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To