Search code examples
javaoopdesign-patternsobject-oriented-analysis

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 changes 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!


Solution

  • The comment from @chrylis is spot on. Robert Martin covers this in chapter 6 of Clean Code: Objects and Data Structures.

    Objects hide their data behind abstractions and expose functions that operate on that data. Data structures expose their data and have no meaningful functions. (page 95)

    The definition of OOP where everything is an object, and there are no data structures, is naive.

    Mature programmers know that the idea that everything is an object is a myth. Sometimes you really do want simple data structures with procedures operating on them. (page 97)

    So what about classes that expose both data and behavior?

    Confusion sometimes leads to unfortunate hybrid structures that are half object and half data structure. They have functions that do significant things, and they also have either public variables or public accessors and mutators that, for all intents and purposes, make the private variables public, tempting other external functions to use those variables the way a procedural program would use a data structure. Such hybrids make it hard to add new functions but also make it hard to add new data structures. They are the worst of both worlds. Avoid creating them. (page 99)

    To the original question: the Dependency Inversion Principle applies to objects, not to data structures like Java Beans.