I am trying to parse the artist.getInfo call from last.fm using Scala. The Xml API of scala is really great, however I have a question of design (and maybe personal flavour).
Currently, I am parsing the data out of the XML in a companion object and hand them to the constructor of the class like this:
class ArtistProfile (
name: String,
musicBrainzId: String,
url: String,
images: List[Image],
streamable: Boolean,
listeners: Int,
plays: Int,
similarArtists:List[SimpleArtist])
object ArtistProfile {
def apply(xml: NodeSeq) : ArtistProfile = {
val root = xml
val name = SimpleArtist.extractName(root);
val url = SimpleArtist.extractUrl(root);
val musicBrainzId = root \ "musicBrainzId" text
val images:List[Image] = Image.findAllIn(root)
val streamable = (root \ "streamable" text) eq ("1")
val listeners = (root \ "stats" \ "listeners").text.toInt
val plays = (root \ "stats" \ "plays").text.toInt
new ArtistProfile(
name,
url,
musicBrainzId,
images,
streamable,
listeners,
plays,
SimpleArtist.findAllIn(xml \ "similar"))
}
}
As you can see, these are a LOT of parameters. My question is if it would be a better style (in terms of scala’s capabilities) to pass the xml NodeSeq to the ArtistProfile constructor, so the class itself takes over the parsing instead of the companion object.
I am asking this because I am trying to write my own last.fm scala library (as an introductory project to scala) and I want things to be consistent for all objects.
- There are a few data in the call which might not be needed by everyone. With the second approach, I could use lazy vals for object lists if they are becoming larger and normal vals otherwise. To the programmer, it won’t be a difference.
- On the other side, parsing of the data needed for creating the object is now seperated from the object itself (like in the example above)
Which way is the better approach to the problem?
I’m not sure that there’s a black-and-white answer to this. You could put auxiliary constructors in the class so that you can also create an instance from an xml node, without the need for the companion object.
However, there are good reasons to favour the factory pattern.
The main disadvantage of the factory pattern (assuming you make the primary constructor private), as mentioned in Effective Java, is that the user can’t create subclasses.
I’d put them all in the companion object.