this post was submitted on 15 Jul 2023
1227 points (98.9% liked)
Programmer Humor
19622 readers
1107 users here now
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
Rules
- Keep content in english
- No advertisements
- Posts must be related to programming or programmer topics
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
I’ll shrink your example. Suppose you have an object A which has a B which has a C, which is what you need.
By writing
a.getB().getC()
, you are implicitly coupling A and C together without A noticing. All A knows is that it is coupled to B. Should B ever decide to use a different C', which would make more sense for B, it may break your code without noticing it.The solution is to make the coupling explicit. A should define a
getC
function that observes the needed contract. For the time being, it may get its C from B (which is fine, because C is under B’s immediate control), but if B changes, and wants to use C', you know to look into A (which is already explicitly coupled to B) and see if it can still function. You’d notice that it relied on B’s returning C and can find a solution to this.An example with fewer variables: You have a shopping cart, which manages items. Implicit coupling translates to knowing and relying on the fact that the items are stored in an array. Adding an item the bad way would be
shoppingCart.getItems()[shoppingCart.getItems().getLength] = item;
*The proposed solution adds the function
ShoppingCart::addItem
. Should ShoppingCart switch to a linked list, it can change the implementation of addItem accordingly. Instead of reaching through the cart into the items, you make dealing with the items the problem of ShoppingCart.I don’t have copy at hand, so I can’t check. I think this advice stems from “The Pragmatic Programmer” by David Thomas and Andrew Hunt.
* I don’t actually know Java, so please forgive if this example wouldn’t really work.