Question

This is a design question.

We have magazines that have copies; copies are made of articles. In order for a copy of a magazine to be published, each article needs to be verified; when all articles are verified the copy itself can be published.

So we have a Copy class and an Article class; the Copy class has a "publish" method and the Article class has a "verify" method.

Here are my questions:

  1. How do I design the Copy class so that it is composed of Articles?

  2. Do I need to instantiate articles separately from the instantiation of the Copy class (and if yes, how do I make the articles part of the copy), or can the instantiation of articles be done by the Copy constructor? Every tutorial deals with "composition versus inheritance" but I was unable to find one that describes instantiation in this case.

  3. (Optionally), is there a non-procedural way to write the Copy.publish method so that it only runs if each article has been verified? In my mind there should be some kind of equality of state / simultaneity between the status of each article and the status of the copy (the state of the copy is "can_be_published" when each article has been successfully verified -- but I shouldn't have to check the status of every article, every time one tries to publish a copy).

I'm fairly new to Java and trying to write this little app "by the book" instead of simply writing each operation in a procedural manner, but there's surprisingly little info on composition that I could find.

Was it helpful?

Solution

1.

class Copy {
  private List<Article> articles = new ArrayList<Article>();
  public addArticle(Article article) {
    this.articles.add(article);
  }
}

2.

Yes, you can have an addArticle method like above. However, if you want to enforce the Copy having all the articles initially, then you can pass a list of articles into it's constructor instead.

3.

class Copy {
  public boolean canPublish() {
    for (Article a: articles)
      if (!article.isVerified())
        return false;
  }
  return true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top