Home > Back-end >  Are generic types coupled to the type of their generic type parameters?
Are generic types coupled to the type of their generic type parameters?

Time:11-30

Given class A

public class A<T> where T : B{
  ...
}

Is A coupled to B? Or is is more useful to think of this as a type restriction?

I was making a class diagram and was wondering how to represent this type of relationship when planning out a system's architecture.

CodePudding user response:

I'm not sure what you mean by coupled, but where T : B is a generic type constraint. So T must implement B.

CodePudding user response:

"Coupling" is a fairly abstract concept. In this case A would have at least some coupling to B, since a change in B could require a change in A.

A "type restriction" would be a more specific, but should probably called "generic type constraint" since that is the term commonly used in the documentation. But all constraints imply some amount of coupling, if A did not use any methods or properties of B there should be no reason for the constraint to exist.

If the goal is to write a class diagram the important thing is that whoever reads it understand the idea. If in doubt, add some comment or text to make it clearer. But in my experience, class diagrams are not commonly used in professional environments, since they tend to get obsolete fairly quickly. Source code is usually a better source of truth about how things work.

  • Related