Search code examples
javaoopdecoupling

Decoupling - OOP


I have a simple question (working with Java). I have two classes, one represents a Document, a second represents a Word.

The Document class needs to know some info about the words that is kept in Word. My question is, what's the best way to decouple the two classes? I have 2 options in mind:

  1. Have no connection between the classes, and each time I call a method in Document, I pass it an object of Word (so I have a third class with a main method that initiates both Document and Word).

  2. Declare a private object of Word inside Document.

One thing to note, I only have one object for Word and one for Document. I don't create a new object for every new document or word. I store a list of the entire documents in Document, and a list pf the entire words in Word.

Thanks!


Solution

  • I don't agree with your understanding of Decoupling. Decoupling is not just about which objects create other objects, it's also about which objects know about the behaviour of other objects and (crucially) what needs to change in (your example) Document if Word changes.

    However, also I really don't understand what your mean by these two phrases:

    I only have one object for Word and one for Document. I don't create a new object for every new document or word. I store a list of the entire documents in Document, and a list pf the entire words in Word

    Start from Document. What can objects of this class do? You seem to be saying that

    class Document {
    
         private List<??OfWhat??> allDocuments;
    }
    

    If class Document contains a List, what's it a List of? I think you need:

    class Shelf {
          private List<Document> allDocuments;
    }
    
    class Document{
          private List<Word> wordInOneDocument;
    }
    
    class Word {
          private String wordContents;
    }
    

    Now a Shelf could offer methods such as getRecentDocumets() findDocumentsContaining(String text) and Document could contain getWordCount() and insertParagraph(List, START); and so on.

    To have a better discussion we need to see a bit more of what you had in mind, a bit more about behaviour.

    I do agree with your general thought that there is Something other than Document and Word out there. Something that can reasonably invoke methods such as createDocument() and insertParagraph()