Skip to content

Latest commit

Β 

History

History
113 lines (66 loc) Β· 3.24 KB

File metadata and controls

113 lines (66 loc) Β· 3.24 KB

Code Smell 111 - Modifying Collections While Traversing

Code Smell 111 - Modifying Collections While Traversing

Changing a collection while traversing might lead to unexpected errors

TL;DR: Don't modify collections while traversing them

Problems πŸ˜”

  • Unexpected Results

  • Concurrency problems

Solutions πŸ˜ƒ

  1. Avoid altering the collections

  2. Make collection copies

Context πŸ’¬

We over-optimize our solutions with the prejudice that copying collections is expensive.

This is not true for small and medium-size collections.

Languages iterate collections in many different ways.

Modifying them is generally not safe.

Sample Code πŸ’»

Wrong 🚫

// here you add elements to the collection...
Collection<Integer> people = new ArrayList<>();
  
for (Object person : people) {
    if (condition(person)) {
        people.remove(person);
    }
}
// You iterate AND remove elements, elements,
// risking skipping other candidates for removal

Right πŸ‘‰

Collection<Integer> people = new ArrayList<>();
// Here you add elements to the collection...

List<Object> iterationPeople = ImmutableList.copyOf(people);
    
for (Object person : iterationPeople) {
    if (condition(person)) {
        people.remove(person);
    }
}
// You iterate a copy and remove it from the original

coll.removeIf(currentIndex -> currentIndex == 5);
// Or use language tools (if available)

Detection πŸ”

[X] Semi Automatic

Many languages provide control both in compile and run-time

Tags 🏷️

  • Fail-Fast

Conclusion 🏁

This is something we learn in our first courses.

It happens a lot in the industry and real-world software

Relations πŸ‘©β€β€οΈβ€πŸ’‹β€πŸ‘¨

Code Smell 53 - Explicit Iteration

Code Smell 134 - Specialized Business Collections

More Information πŸ“•

Credits πŸ™

Photo by Christine Roy on Unsplash


Bugs are bugs. You write code with bugs because you do. If it’s a safe language in the sense of run-time safe, the operating system crashes instead of doing a buffer overflow in a way that’s exploitable.

Ken Thompson

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of Your Code