Required Setup or Teardown Code — Code Smells Catalog Skip to content

Required Setup or Teardown Code

Bloaters Responsibility Code Smell Between Class

Close the socket when you're done. Check the environment variables before you start. Reset the state after every call. The object could handle all of this internally. Instead, it made it your problem.

2 min read 1 source

Overview

If, after the use of a class or method, several lines of code are required to:

  • set it properly up,
  • the environment requires specific actions beforehand or after its use,
  • clean up actions are required,

then there is a Required Setup or Teardown Code code smell. Furthermore, this may indicate improper abstraction level.

Causation

Some functionality was taken beyond the class during development, and the need for their use within the class itself was overlooked.

Problems

🧲
Lack of Cohesion

Class can't be reused by itself - it requires extra lines of code outside of its scope to use it.

Example

1class Radio:
2    def __init__(self, ip, port):
3        socket = socket.connection(f"{ip}:{port}")
4
5    ...
6
7radio: Radio = Radio(ip, port)
8...
9# Doing something with the object
10...
11# Finalizing its use
12radio.socket.shutdown(socket.shut_RDWR)
13radio.socket.close()
14...
PYTHON

Refactoring

  • Replace Constructor with Factory Method
  • Introduce Parameter Object

Sources

Browse All 56 Smells