lundi 31 août 2015

How to implement catalog / registry while obeying immutability and "rules" of functional programming?

Folks,

what is the most appropriate way to implement a registry like

trait Registry {
  def registerComponent( name: String, obj : Any ) : Unit
  def getComponent( name: String ) : Any
  def unregisterComponent( name: String ) : Unit
}

following functional patterns. ( E.g. immutability, etc. )

What comes to my mind here is

  • State-Monad: where the state of the monad represents the registered objects (as Seq or similar)
  • Builder-(like)-Pattern but with copying the current registry context from one builder step to the next.

E.g.: A registry following builder-like pattern:

case class Registry(registered: Map[String, Any]) {
  def register( name: String, obj: Any ) : Registry = {
    copy( registered = this.registered + ( name -> obj) )
  }
  def unregister( name : String ) : Registry = {
    copy (registered = this.registered.filterKeys( !_.equals(name)))
  }
  // How to deal with return values????
  // Tuple return is quite ugly
  // 
  def getComponent( name: String ) : (Registry, Option[Any]) = {
    (this, registered.get( name ) )
  }
}

Which other solutions / patterns are reasonable or available?

Cheers,

Martin

Aucun commentaire:

Enregistrer un commentaire