Question

I have been struggling with this annoying problem for a while without finding an elegant solution to it.

Let's say I have such a class hierarchy :

class StatWithBounds[A](val min: A, val max: A, val currentValue: A)
class StatBetween0And20(initialValue: Int) extends StatWithBounds[Int](0, 20, initialValue)
class PositiveStatOnly(initialValue: Int) extends StatWithBounds[Int](0, Integer.MAX_VALUE, initialValue)
class UncappedPercentage(initialValue: Int) extends StatWithBounds[Int](0, Integer.MAX_VALUE, initialValue)

Copy/paste of initialValue is overly verbose. Furthermore, if I want to do something like this:

class Strength(initialValue: Int) extends StatBetween0And20(initialValue)
class Intelligence(initialValue: Int) extends StatBetween0And20(initialValue)
class Piety(initialValue: Int) extends StatBetween0And20(initialValue)

What a hell of copy/paste (and imagine I have 10 more subclass)!

Is there an elegant way to solve this cluttering problem ?

Was it helpful?

Solution

You can use traits instead if you don't need the original class:

trait StatWithBounds[A] {
  def min: A
  def max: A
  def currentValue: A
}

trait StatBetween0And20 extends StatWithBounds[Int] {
  def min = 0
  def max = 20
}

class Strength(val currentValue: Int) extends StatBetween0And20
class Intelligence(val currentValue: Int) extends StatBetween0And20
...

Alternatively, you can simply not use such long variable names!

class Stat[A](val min: A, val max: A, val current: A)
class Stat20(i: Int) extends Stat[Int](0, 20, i)
class Strength(i: Int) extends Stat20(i)
class Intelligence(i: Int) extends Stat20(i)
...

See how much less noisy that is? Long variable names are a form of boilerplate. Sometimes you need it for clarity, but not, usually, just to pass on an argument to a constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top