0

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.

2
  • possible duplicate of Many Arguments in Case Classes
    – gnat
    Commented Feb 6, 2015 at 17:05
  • @gnat: That's a "best practices" question. Yes, it does ask if there's a way to fix the problem, but nobody volunteered an answer to that part of the question. I've fixed the titles of both questions to clarify what they are actually asking. Commented Feb 6, 2015 at 17:07

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.