Question

I have an interface with only one title field:

protocol Artist {
    var title: String { get }
}

(A) Should I pass the whole object as I did here:

class Album {
    func setArtist(_ artist: Artist) {
        /// Handle
    }
}

album.setArtist(artist)

(B) Or set that only field:

class Album {
    func setArtistTitle(_ artistTitle: String) {
        /// Handle
    }
}

album.setArtistTitle(artist.title)

What is the recommended way of software design? The (A) solution looks more safer as it is restricted to the type. But the latter (B) is much more flexible. There is no need to create a concrete object, e.g if I want to unit-test my class. The code is less coupled, what we are striving for

EDIT:
All of possible duplicates consider cases with >1 parameters. For me those cases are quite obvious, since multiple parameters form a single type. In my example there is one and only one primitive parameter. The idea of the interface is guarantee existence of title, and that's it. The dilemma is where to access the title

Was it helpful?

Solution

Use A. As you say yourself it is safer and the intention of the code is clearer.

I think you may have a misunderstanding regarding coupling. An Album is supposed to be coupled to an Artist. Using a plain string rather than an Artist instance does not reduce this coupling, it just makes the code harder to understand and less safe, since you could by mistake pass something which is not the name of an artist. You can say it is more "flexible" because you can pass arbitrary stuff to setArtist, not just Artists, but that is not the kind of flexibility you want!

When talk about reducing coupling, we only want to reduce unnecessary coupling. like coupling between semantically unrelated objects, or coupling from one object to implementation details of another object rather than just its public interface.

Licensed under: CC-BY-SA with attribution
scroll top