0
votes

This is more of a design and readability/maintainability question rather than a technical one.

Sometimes in Scala, you get these one liner classes (often case classes), which are typically used to hold data. They're very synonymous with Java beans, but with constructor parameters actually being val members, no need for setter methods due to immutability, and no need for toString due to the nice feature of case classes, you end up with just one line consisting of constructor parameters.

I find it wasteful to put these one-liners in a separate Scala file, and I hate to put them with other more meaty Scala classes because it starts to become confusing (even in IntelliJ IDEA it starts to pollute the project source tree).

I started a new habit of putting these single liners in the Package Object package.scala file of that package. Is there any disadvantage to this from a maintainability point of view? I am just putting them there for lack of a better place. Is there any better approach?

1
I don't see a disadvantage in putting a one-liner into a file. Could you please elaborate what you mean by "wasteful"?Madoc
It just means that you have to click on multiple files just to see one line. Even the designers of the Scala language saw this as a readability issue and removed the one-class-per-file restriction (I remember Martin Odersky himself claiming this in the Scala course on Coursera).jbx
Hmm. I would actually be delighted to open a class file and just see one line... However, I don't see a problem with putting case classes in the package object. You might also want to look at projects like scalaz, where there are usually multiple classes in a source file, all with different names, and all named differently than the file itself. It works, but I'm not sure about how maintainable that code is in a real-world project.Madoc
Yeah. I do sometimes do that (multiple classes in one file), but I find it really ugly and confusing, so I try to keep it to very small and highly related classes only. The problem with having files with just one line is that your project becomes bloated with files and you have to click multiple times just to read a line.jbx

1 Answers

0
votes

I don't think there is a disadvantage in that, but also I don't see an immediate advantage or reason to do so.

You may have a look at this question. Basically, if you use the -Xlint compiler flag, you will be told that you should not put classes into a package object.

If you want to have several classes together because of their one-line nature, you can put them still together in one file, it doesn't have to be a package object. E.g.

// utils.scala
package foo

case class FooUtil()

case class BarUtil()

Instead of package object foo { case class FooUtil() ... }