Loose Coupling in Object Oriented Design
Posted
by
m3th0dman
on Programmers
See other posts from Programmers
or by m3th0dman
Published on 2013-06-27T15:40:24Z
Indexed on
2013/06/27
16:28 UTC
Read the original article
Hit count: 645
I am trying to learn GRASP and I found this explained (here on page 3) about Low Coupling and I was very surprised when I found this:
Consider the method
addTrack
for anAlbum
class, two possible methods are:
addTrack( Track t )
and
addTrack( int no, String title, double duration )
Which method reduces coupling? The second one does, since the class using the Album class does not have to know a Track class. In general, parameters to methods should use base types (int, char ...) and classes from the java.* packages.
I tend to diasgree with this; I believe addTrack(Track t)
is better than addTrack(int no, String title, double duration)
due to various reasons:
It is always better for a method to as fewer parameters as possible (according to Uncle Bob's Clean Code none or one preferably, 2 in some cases and 3 in special cases; more than 3 needs refactoring - these are of course recommendations not holly rules).
If
addTrack
is a method of an interface, and the requirements need that aTrack
should have more information (say year or genre) then the interface needs to be changed and so that the method should supports another parameter.Encapsulation is broke; if
addTrack
is in an interface, then it should not know the internals of theTrack
.It is actually more coupled in the second way, with many parameters. Suppose the
no
parameter needs to be changed fromint
tolong
because there are more thanMAX_INT
tracks (or for whatever reason); then both theTrack
and the method need to be changed while if the method would beaddTrack(Track track)
only theTrack
would be changed.
All the 4 arguments are actually connected with each other, and some of them are consequences from others.
Which approach is better?
© Programmers or respective owner