cover-img

Code Smell 67 - Middle Man

Remove the Intermediators

4 May, 2023

8

8

0

TL;DR: Remove the Intermediators

Let's break Demeter's Law.

Problems

  • Unnecessary Indirection
  • Empty Classes
  • Readability

Solutions

  1. Remove Middle man.

Sample Code

Wrong

public class Client {
Address address;
public ZipCode zipCode() {
return address.zipCode();
}
}

public class Address {
private ZipCode zipCode;

public ZipCode zipCode() {
return new ZipCode('CA90210');
}
}

public class Application {
ZipCode zipCode = client.zipCode();
}

Right

public class Client {
Address address;
// client now has to expose its address
public address() {
return address;
}
}

public class Address {
private ZipCode zipCode;

public ZipCode zipCode() {
return new ZipCode('CA90210');
}
}

public class Application {
ZipCode zipCode = client.address().zipCode();
}

Detection

Same as its opposite smell, We can detect this small using parsing trees.

Tags

  • Coupling
  • Declarative
  • Readability

Conclusion

This is exactly the opposite to Message Chain. We make explicit the message chain.

Relations

Code Smell 08 - Long Chains Of Collaborations

Code Smell 114 - Empty Class

More Info

(Refactoring Guru)[https://refactoring.guru/smells/middle-man]

(Refactoring.com)[https://refactoring.com/catalog/removeMiddleMan.html]

(C2 Wiki)[https://wiki.c2.com/?MiddleMan]

(JetBrains)[https://www.jetbrains.com/help/idea/remove-middleman.html#remove_middleman_example]

(Wikipedia)[https://en.wikipedia.org/wiki/Law_of_Demeter]

Credits

Photo by Dan Counsell on Unsplash


Whenever I have to think to understand what the code is doing, I ask myself if I can refactor the code to make that understanding more immediately apparent.

Martin Fowler


Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code

8

8

0

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.