1

Is this a correct summation?

If a class instantiates another class and stores it as a local variable, that's a dependency.

If a class instantiates another class and stores it as a class attribute/field, then it's an association.

I can't find any resources that address this distinction specifically.

Josh Bond
  • 1,719
  • 4
  • 17
  • 26
  • I think some distinctions in OOD don't show up in actual programming. Implementing association can be either by instance fields, class fields or local variables (local creation, I assume, or dependency injection in some cases). And implementing dependency can be the same. It all depends what the code needs. – markspace Jun 19 '18 at 17:19
  • Another answer here: https://stackoverflow.com/questions/1230889/difference-between-association-and-dependency Note that the first accepted answer starts with "In general..." These are not hard and fast rules, and implementations in code vary. – markspace Jun 19 '18 at 17:23
  • @markspace Thanks for that. The "no hard and fast rules" and code implementations vary is what I'm getting from in person discussions as well. – Josh Bond Jun 19 '18 at 17:37

2 Answers2

2

You are right!

Association - if class A holds a class level reference to class B. (Permanent relationship)

class Account{} 
class Customer{
  private Account account; //permanent
  Customer(Account account){
     this.account = account;
  }
}

Dependency - Class A is dependent on class B. Dependency indicates that you may invoke one of the APIs of the received class (B) reference and any modification to that class may break your class as well. (temporary relationship)

 class Account{
    public void deposit{}
 } 
 class Customer{
    public void makeDeposit(Account acc){
        acc.deposit(); //temporary
    }
 }
Murad Hajiyev
  • 121
  • 1
  • 10
1

Not really a correct definition. First: "local variable" and "class attribute" are the same thing. Any class attribute referencing another class will (in any language I know) be stored as a pointer to that instance - just from a physical perspective.

Now, the difference between dependency and association is that the latter is more specific. When you model a dependency from A to B it means: "beware in A when something is changed in B". Often you use a dependency when you have operations that use the referenced class in parameters or so. Whenever you model an association it really means A knows about B (and has some reference).

qwerty_so
  • 35,448
  • 8
  • 62
  • 86