Loose Coupling in Object Oriented Design
- by m3th0dman
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 an Album 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 a Track 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 the Track.
It is actually more coupled in the second way, with many parameters. Suppose the no parameter needs to be changed from int to long because there are more than MAX_INT tracks (or for whatever reason); then both the Track and the method need to be changed while if the method would be addTrack(Track track) only the Track 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?