Code smell: Don't talk to strangers
“Don’t talk to strangers” can be a useful rule of thumb for identifying code smells when writing code.
Consider the following snippet of python code:
state.getSubState().getSubSubState().doThing(args)
The goal is to execute the doThing
method. However, this implementation is accessing the internal structure of state
to get to it. Both getSubState()
and getSubSubState()
are exposed internal implementation details that should have remained hidden. When these internal structures are public, it becomes much harder to refactor or change them because it will break the code.
This is where the "Don't talk to strangers" rule of thumb comes in handy. From the perspective of the code invoking state
, the subState
and subSubState
should be considered strangers — they are not part of the public interface the caller should be concerned with.
Instead, you should delegate the responsibility of calling doThing
on subSubState
to the state
object:
state.doThing(args)
Internally, state
can then decide how to handle the request. It could for example do the same trick on subState
:
subState.doThing(args)
This approach keeps the internal structure encapsulated and reduces coupling between modules. It’s especially helpful to apply this principle right after writing new code, as that's often when it's hardest to recognize these kinds of design smells.