Exposing your collections couples your solution
TL;DR: Use immutable collections to prevent unintended side effects.
Aliasing happens when two or more variables refer to the same object.
This can lead to unexpected side effects, especially when one variable modifies the shared object.
You can't change immutable collections after creation helping you prevent accidental aliasing.
Premature optimizators will argue that copying collections is an expensive operation that you should avoid.
This is a special case of Object Aliasing
public class MutableExample { public static void main(String[] args) { Listnumbers = List.of(1, 2, 3); List otherNumbers = numbers; // Aliasing otherNumbers.add(4); System.out.println(numbers); // Output: [1, 2, 3, 4] } }
public class ImmutableExample { public static void main(String[] args) { Listnumbers = List.of(1, 2, 3); List otherNumbers = List.copyOf(numbers); // Creating a copy otherNumbers.add(4); System.out.println(numbers); // Output: [1, 2, 3] } }
[X] Semi-Automatic
Several static analysis tools can warn you of aliasing abuse.
[x] Intermediate
AI code generators might not always create immutable objects by default, especially when working with mutable collections.
You can prompt them to prioritize immutable collections and wrap existing ones to avoid aliasing.
AI tools can analyze code for potential aliasing issues and suggest using immutable collections instead.
You can avoid unintended side effects using immutable collections.
This will make your code more predictable and easier to reason about.
Les odeurs de code sont mon opinion.
Photo de Martino Pietropoli sur Unsplash
Si un objet est immuable, il ne peut être que dans un seul état, et vous gagnez gros.
Josué Bloch
Cet article fait partie de la série CodeSmell.
The above is the detailed content of Code Smell - Collection Aliasing. For more information, please follow other related articles on the PHP Chinese website!