简体   繁体   中英

Circular dependencies in a Java classes with a one-to-many relationship

I've always known circular dependencies were discouraged in java, but I'm struggling to understand whether circular dependencies between objects that relate to each other are bad. For instance, if I have the classes TelevisionShow , Season , and Episode , would the following be bad practice? If so, why?

public interface TelevisionShow {
    List<Season> getSeasons();
}

public interface Season {
    TelevisionShow getTelevisionShow();
    List<Episode> getEpisodes();
}

public interface Episode {
    Season getSeason();
}

You are confusing circular dependencies with circular references. The java garbage collector can detect circular references and GC them if they have no link to the root reference.

These interfaces are not problematic by the way. This is pretty common when using JPA for example that you have a bidirectional relationship like the one you have here.

It is not a bad practice to have circular dependencies , (you are using a wrong term it is circular references) between objects, but it depends on how class model are being designed. If the design requires such circular references, then you may have this relationships.

For example, if I have two interface for file and folder,

public interface IMyFile
{
  ........
}

public interface IMyFolder
{
   ........
}

Then it is very well understood that each folder will contain list of files and folders so the IMyFolder will be

public interface IMyFolder
{
    List<IMyFolder> getFolders();
    List<IMyFile> getFiles();
}

So it is not at all a bad practice to have circular references in objects as the design demands it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM