In my code base, I want to refractor away from vars
. The code base structure follows the format:
class Animal {
var name : Option[String] = None
var owner : Option[String] = None
}
case class Dog(breed: String) extends Animal {
//Dog logic
}
The main reason for this design is that information is not available all at the same time.
So, from service A
, which deserializes a json, I receive an Animal
(either Animal
, Dog
)
val animal = new Animal
animal.name = "My little animal"
and then
def update(animal: Animal) : Unit {
animal match {
case a : Animal => a.owner = Some("Joe") // call to service B
case _ => //handle dog
}
}
update(animal)
The question is: How can I redesign it to avoid mutable state in Animal
?
Write a
copy
method inAnimal
? There are a bunch of fields, which might generate some boilerplateComposition?
Making the two classes case
?
case class Animal (...)
case class Dog(animal: Animal, breed: String)
Edit
- Animal as a
trait
I still need a concrete implementation of Animal
, as I will have Dogs
and Animals
(which are really Animal
and no subtype)
- Problems with copy
The built in case class copy method, does NOT update the values of the Animal
class. So defaults values will be used - not what I want. - yes, it is possible to create a case class with all the fields, but is it practical if we have 100+ fields?