Skip to main content

Use local variables and immutable data structures instead of shared mutable state

Medium
JavaClean codeAdd examplecsharp

Don't mutate a method parameter. Instead compute the result in a local variable.

Examples

Example 1:

Negative

Incorrect implementation that violates the practice.

namespace Practices.LocalVariablesAndImmutable;

public class CountNamesHelper
{
public static IDictionary<string, int> CountNames(IList<string> names, IDictionary<string, int> count)
{
foreach (string name in names)
{
if (!count.TryAdd(name, 1))
{
count[name]++;
}
}
return count;
}
}

Example 2:

Negative

Incorrect implementation that violates the practice.

package practices.java.use_local_immutable;

import java.util.List;
import java.util.Map;

public class CountNamesHelper {

public static Map<String, Long> countNames(List<String> names, Map<String, Long> countByName) {
for (String name : names) {
long previousCount = countByName.getOrDefault(name, 0L);
countByName.put(name, previousCount + 1);
}
return countByName;
}
}