mardi 5 mars 2019

How to eliminate hard dependecies on Java Beans

I've a question about DIP Principle. One of the guidelines says that we should not hold references to a concrete class (if it change then I'll have to modify all clients that use it). So, what can I follow this guideline when I use POJOs ? For Example:

I have a Bean 'Foo' with some attributes (it could represent a Domain object)

class Foo {  
   private String one;   
   private String two;

  //getters and setters
}

Multiple clients instantiate this object, for example, to persist it in the Database

   class Client1 {   

      private FooDao dao;

      Client1(FooDao dao){     
         this.dao = dao;
      }  

      public void persist() {    
         //hard coding
         Foo foo = new Foo();   
         foo.setOne("something...");    
         dao.save(foo); }     
       } 

       class Client2 {   

         private FooDao dao;

          Client2(FooDao dao){   
            this.dao = dao;

           }  

        public void persist() {   
           Foo foo = new Foo();   
           foo.setOne("something...");   
           foo.setTwo("something...")    
           dao.save(foo); 
         }
       }

If I add or change any attribute to 'Foo' class every client would have to change, so follow this guideline how can I avoid that?

Thanks!

Aucun commentaire:

Enregistrer un commentaire