DEV Community

Cover image for Code Smell 150 - Equal Comparison
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

3 1

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

  1. 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
Enter fullscreen mode Exit fullscreen mode

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. 
}

Enter fullscreen mode Exit fullscreen mode

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

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


This article is part of the CodeSmell Series.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay