Navs
Code Smells Catalog
Hidden Dependencies

Last Revision — April 19, 2022

1 Min Read


  • Also Known As

    ---

  • Obstruction

    Data Dealers

  • Occurrence

    Data

  • Expanse

    Between Classes

  • Related Smells

    - Global Data (caused)
    - Required Setup or Teardown Code (causes)
    - Long Parameter List (antagonistic)

  • History

    Steve Smith in course (2013): "Refactoring Fundamentals"

    Zhifeng Yu, Vaclav Rajlich in paper (2001): "Hidden Dependencies in Program Comprehension and Change Propagation"

Hidden Dependencies

Hidden Dependency is a situation where, inside a class, methods are silently resolving dependencies, hiding that behavior from the caller. Hidden Dependencies can cause a runtime exception when a caller has not set up the appropriate environment beforehand, which, by itself, is yet another code smell: Required Teardown/Setup Code.

Causation

Objects (which are not stateless) that require a constructor have an empty constructor - the essence of these objects should be passed on to creation, and even better if they are made immutable to avoid Mutable Data Code Smell.

Problems

Coupling

Each Global Variable is basically a hidden dependency that a tester has to mock.

Hard to Test

Mocking is required to test methods that use data outside of its closest scope (class or parameters).

Error-Prone

Changing or removing data might unintentionally break code in unexpected places.

Decreased Comprehensibility

It is hard to understand the method's behavior without looking up the functions or variables outside its scope.

Example

Smelly

class Customer:
    pass

customer = Customer()

class Cart:
    def __init__(self):
        self.customer = customer  # gets customer from global scope

cart = Cart()

Solution

class Customer:
    pass

customer = Customer()

class Cart:
    def __init__(self, customer):
        self.customer = customer  # gets customer explicitly

cart = Cart(customer)

Refactoring:

  • Inject Dependencies

Sources
  • [1] -
  • [Origin] - Steve Smith, "Refactoring Fundamentals" (2013)
  • [Parentage] - Zhifeng Yu, Hidden Dependencies in Program Comprehension and Change Propagation" (2001)