4

I have one question that I can't seem to get answered anywhere. It's in regards to decoupling your code with interfaces. The question is - should ALL objects inside other objects (being created and used) be refactored into an interface to follow the dependency inversion principle of S.O.L.I.D.? What about new'ing up objects inside an even driven method?, ex. a method called when I press a button. Should the object be passed in through, say the constructor? Of course this all applies to my objects and not in the BCL right?

chuckd
  • 13,460
  • 29
  • 152
  • 331

1 Answers1

5

millimoose gave a great answer. It's especially good because it's the right answer for any programming problem :)

I would just like to elaborate a bit. When dealing with scenarios like this, the following conditions hold:

  1. Decoupling comes with its own cost.
  2. No code will be perfect since you likely won't get all the time you want to work on it.
  3. It's not the end of the world if your code is more coupled than it could be.

So don't look at it in terms of an all-or-nothing proposition and instead look at it like a score. How much coupling are you willing to put up with? How much are you willing to pay for decoupling? At some point there's a balance between design time and perceived maintainability -- keeping in mind you don't even know how your code will change anyway.

Have you heard of the book "Event-Based Programming: Taking Events to the Limit"? It's all about coupling: http://books.google.com/books?id=9CL446IzhuAC&pg=PR21&dq=taking+events+to+the+limit&hl=en&sa=X&ei=bcfLUMzRMcWLqgHi-oHoBw&ved=0CDUQ6wEwAA

The author claims that you can't eliminate all coupling, but you can transform it, and coupling should be shifted to simpler classes. Perhaps you can use that as a guide for your efforts.

RonaldBarzell
  • 3,822
  • 1
  • 16
  • 23
  • "How much are you willing to pay for decoupling? At some point there's a balance between design time and perceived maintainability -- keeping in mind you don't even know how your code will change anyway." It seems that if you start with a philosophy that you will keep all things decoupled from the beginning, that no overhead would be added to your project, therefor you wouldn't need to justify spending any additional time decoupling. you would just automatically do it as you designed. – chuckd Dec 15 '12 at 00:54
  • I think if you plan to be decoupled at the outset, then it will be cheaper to do so, but it may still cost more than a (partially) coupled design. It depends on a lot of factors. Also keep in mind I'm just taking the cost of the initial release; not knowing where long-term maintenance will lead, I can't say whether a particular decoupling will "pay off". – RonaldBarzell Dec 15 '12 at 01:00