DEV Community

Cover image for Code Smell 67 - Middle Man
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

1

Code Smell 67 - Middle Man

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();
}
view raw middleman.java hosted with ❤ by GitHub

Right

public class Client {
public ZipCode zipCode() {
// Can also store it
return new ZipCode(’CA90210’);
}
}
public class Application {
ZipCode zipCode = client.address().zipCode();
}
view raw nowhereman.java hosted with ❤ by GitHub

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

More info

%[https://refactoring.guru/smells/middle-man]

%[https://refactoring.com/catalog/removeMiddleMan.html]

%[https://wiki.c2.com/?MiddleMan]

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

%[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



This article is part of the CodeSmell Series.

%[https://dev.to/mcsee/series/9470]

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more