Temporary Field

Fields in the Class that are used only by one Method or only under certain circumstances.

Sign of Smell

When a class or object has a field (or member variable) that is only used temporarily or sporadically, it is considered a “Temporary Field” smell. This field is not part of the class's primary responsibility or purpose and is often used to store data temporarily during a specific operation or method call. Such a field can lead to various issues and can indicate a design problem in your code.

This is often an alternative to the “Long Parameter List” smell.

Reason of Smell

  • Decreased Readability: When a class contains temporary fields, it can make the code more difficult to understand. Developers reading the code may wonder why certain data is being stored or may assume that the data is important for the class's primary functionality, leading to confusion and potential mistakes during maintenance.

  • Increased Complexity: Temporary Fields can add unnecessary complexity to a class. Developers need to keep track of when and how these fields are used, which can make the code harder to reason about and maintain.

  • Violation of Single Responsibility Principle (SRP): Temporary Fields often indicate that a class is taking on multiple responsibilities. Ideally, each class should have a single responsibility, making it easier to understand, maintain, and test. The presence of temporary fields suggests that a class may be doing too much.

  • Thread Safety Issues: If a class with Temporary Fields is used in a multi-threaded environment, it can lead to concurrency issues. Temporary Fields might be modified concurrently by multiple threads, causing unexpected behavior and bugs.

  • Difficulty in Testing: Testing can become more challenging when Temporary Fields are present because you may need to set up specific conditions to ensure that these fields are correctly initialized and used. This can result in more complex test cases.

Refactoring Recipes

  • Extract Class

  • Introduce Null Object

Reference

https://refactoring.guru/smells/temporary-field

Last updated