Question

Let's say I have a case class with ~20 constructor arguments? This is obviously very clunky to type. What would be the best way to condense these arguments into maybe 5 or 6 arguments? There are some arguments that are related to each other enough that I could see doing:

case class myClass(myStorageContainer, myOtherStorageContainer...)

instead of

case class myClass(arg0...arg19)

Since this case class with be stored in a large list of case classes of this type I'm unsure if the overhead would be significant having to initialize so many objects to build the constructor arguments out.

Was it helpful?

Solution

Of the things you should be worried about as a programmer, initialization overhead is way, way down on the list. Your suggested grouping is a minimal first step.

The next step is to reconsider if you actually need to keep all that data together in one case class. You almost never do, and it usually hurts you to create that large of a coupling.

One thing that often works is instead of storing one massive list of myClasses, store individual lists of myStorageContainers or even args. Then re-associate them on the fly as needed using zip or map or some such.

This feels wrong for programmers trained in imperative languages, whose instinct is to protect their data from other people mutating it, and whose architectural style has developed accordingly.

Immutability means you don't need to store data in the same container in order to maintain invariant relationships between them. If I have an immutable List of arg0 and another immutable List of arg1 that are created together, then I know that the nth element of the first list always goes with the nth element of the second list. Likewise for objects stored in separate immutable maps indexed using the same key. They don't have to be physically in the same data structure.

Give it a try and see. You will probably find your modularity go way up when functions are no longer coupled to a giant case class.

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