首頁> Java> java教程> 主體

Code Smell - Collection Aliasing

WBOY
發布: 2024-08-30 06:01:02
原創
896 人瀏覽過

Exposing your collections couples your solution

TL;DR: Use immutable collections to prevent unintended side effects.

Problems

  • Unpredictable behavior
  • Debugging challenges
  • Data corruption
  • Violation of the Principle of Least Astonishment
  • Premature optimization
  • Unexpected Mutations
  • Concurrency problems
  • Compromised thread safety
  • Increased coupling

Solutions

  1. Use immutable collections
  2. Create immutable classes
  3. Copy the collection before modification
  4. Avoid collection getters
  5. Avoid automatic properties
  6. Favor information hiding and encapsulation

Context

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

Sample Code

Wrong

public class MutableExample { public static void main(String[] args) { List numbers = List.of(1, 2, 3); List otherNumbers = numbers; // Aliasing otherNumbers.add(4); System.out.println(numbers); // Output: [1, 2, 3, 4] } }
登入後複製

Right

public class ImmutableExample { public static void main(String[] args) { List numbers = List.of(1, 2, 3); List otherNumbers = List.copyOf(numbers); // Creating a copy otherNumbers.add(4); System.out.println(numbers); // Output: [1, 2, 3] } }
登入後複製

Detection

[X] Semi-Automatic

Several static analysis tools can warn you of aliasing abuse.

Tags

  • Immutability

Level

[x] Intermediate

AI Generation

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 Detection

AI tools can analyze code for potential aliasing issues and suggest using immutable collections instead.

Conclusion

You can avoid unintended side effects using immutable collections.

This will make your code more predictable and easier to reason about.

Relations

More Info

Disclaimer

Code Smells are my opinion.

Credits

Photo by Martino Pietropoli on Unsplash


If an object is immutable, it can be in only one state, and you win big.

Joshua Bloch


This article is part of the CodeSmell Series.

以上是Code Smell - Collection Aliasing的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!