Sobes.tech
Junior — Senior

Violation of the principle of low coupling in a three-tier system

livecode

Task condition

The system implements three levels: view, controller, and model. In the current version, the view layer directly calls controller functions, and the controller immediately interacts with the model. This interaction violates the principle of loose coupling: the levels become dependent on each other, which complicates replacement, testing, and scaling of components.

To fix this, an intermediate service layer should be introduced or the 'Facade' pattern should be used so that the View depends only on abstractions of the controller, and the controller depends on abstractions of the model.

An example of the current code (with renamed functions):

# View
@app.route("/user/<user_id>")
def fetch_user(user_id):
    return ctrl_fetch_user(user_id)

# Controller
def ctrl_fetch_user(user_id):
    ...
    return model_fetch_user(user_id)

# Model
def model_fetch_user(user_id):
    return session.query(User).filter(User.id == user_id)

After refactoring, the view layer will work with a service, and the service with the model repository, which will completely decouple the levels.