lundi 17 juin 2019

How to restrict access to field setters of an object? Would achieving this with inheritance would be a bad choice?

The problem is simple, I have some business data objects that are created by the underlying services (say the data repository). These objects are created step by step. I.e (Step one only finds the image object from google, step two retrieves metadata about the image, step three downloads it to disk).

These same objects will be rendered in UI as they are being built. So the UI doesn't need to know anything about the setters and shouldn't have access to it.

But the services who are creating the instance, needs to have access to the setters.

What I have finally done is this. I created a base class which is intended to be used by the UI/client and I have extended the class with setters than the service will use to set values.

class ImmutableObject {
   protected String field;
   public String getField(){
     return field;
   }
}

class MutableObject extends ImmutableObject {
   public String setField(String field){
     this.field = field;
   }
}

Service code looks like

interface IService {
   ImmutableObject get(...);
   ImmutableObject progess(ImmutableObject o);
}

UI code looks like

ImmutableObject o = service.get(...); //Cast
render(o);
o = service.processMore(o); //Cast
render(o);

Another solution is to use the Builder pattern. But that creates a lot of boilerplate code. Also the builder will require to have getter to properties (as we'll need to render the builder on UI as well) which I am not sure if allowed in the Builder pattern.

Another solution would be to create totally different UI model objects which can be created by the object returned by the service. This again, causes are lot of more code and will have as much coupling as the inheritance method above has.

So my question is, 1. Is there a better way to do this? 2. Is this implementation is okay as far design patterns and good programming practices go? 3. Should I be doing a nested class instead to enforce better cohesion between the mutable and immutable class? I.e

class ImmutableObject {
   protected String field;
   public String getField(){
     return field;
   }

   static class MutableObject extends ImmutableObject {
      public String setField(String field){
         this.field = field;
      }
    }
}

Aucun commentaire:

Enregistrer un commentaire