mardi 15 mai 2018

Immutability with inheritance design pattern

I'm implementing some code in Scala, following a tutorial in Java.

The tutorial has a piece of code that can be minimized into the following:

public abstract class A {
    private int id;

    public A(String name) {
        id = Helper.getId(name);
        fetchAllAttributes();
    }

    protected abstract void fetchAllAttributes();

    protected int fetchAttribute(String attribute) {
        Helper.getAttribute(id, attribute);
    }

    public class B extends A {
        int volume;

        public B() {
            super("B");
        }

        @Override
        protected void fetchAllAttributes() {
            volume = super.fetchAttribute("volume");
        }

    }
}

And this is what it looks like when you translate it into Scala:

abstract class A(val name: String) {
  private val id = Helper.getId(name)
  fetchAllAttributes()

  protected def fetchAllAttributes(): Unit

  protected def fetchAttribute(attribute: String): Int = {
    Helper.getAttribute(id, attribute)
  }

  class B() extends A("B") {
    var volume = 0

    override protected def fetchAllAttributes(): Unit = {
      volume = super.fetchAttribute("volume")
    }
  }

}

And here I'd like to ask two questions:

  1. Is there a name for this pattern, where you call an abstract method in the abstract class' constructor and provide a method for the child classes to use in their implementation?
  2. As a Scala developer, I really don't like mutable objects and variables. Is there a good way to implement this in an immutable fashion, using only vals?

Aucun commentaire:

Enregistrer un commentaire