Favor immutability by converting attributes to sets
TL;DR: Using sets for attributes simplifies your code and makes state management easier
Problems Addressedhttps://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-vii-8dk31x0
https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-vi-cmj31om
StepsThis refactoring is safe when your attributes don't rely on specific indexing behavior.
\ Since sets don't maintain element order, check if your logic depends on order.
Why is the code better?Entities are immutable in the essence.
\ Using sets ensures uniqueness and simplifies logic.
\ You no longer need to check for duplicates before adding elements.
\ Operations like union, intersection, and difference become straightforward, making your code more maintainable and flexible.
LimitationsSets don't preserve element order.
\ If your logic depends on sequence, converting to a set may not be appropriate and you should use an Ordered Collection or Array
AI RefactoringYou can prompt your AI assistants to make this refactoring for you.
Try Them!| Without Proper Instructions | With Specific Instructions | |----|----| | ChatGPT | ChatGPT | | Claude | Claude | | Perplexity | Perplexity | | Copilot | Copilot | | Gemini | Gemini |
Tagshttps://hackernoon.com/refactoring-remove-setters-codesmell?embedable=true
See also CreditsImage by Angelo Giordano in Pixabay
This article is part of the Refactoring Series.
https://maximilianocontieri.com/how-to-improve-your-code-with-easy-refactorings?embedable=true
\
All Rights Reserved. Copyright , Central Coast Communications, Inc.