Reputation: 465
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();
}
Upvotes: 0
Views: 250
Reputation: 30538
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.
Upvotes: 2
Reputation: 6276
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.
Upvotes: 0