Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should every single object have an interface and all objects loosely coupled?

From what I have read best practice is to have classes based on an interface and loosely couple the objects, in order to help code re-use and unit test.

Is this correct and is it a rule that should always be followed?

The reason I ask is I have recently worked on a system with 100’s of very different objects. A few shared common interfaces but most do not and wonder if it should have had an interface mirroring every property and function in those classes?

I am using C# and dot net 2.0 however I believe this question would fit many languages.

like image 850
John Avatar asked Dec 09 '08 12:12

John


People also ask

Should every object have an interface?

It all depends... Oh yes, and if you do go heavily into interfaces - beware web services. If you need to expose your object methods via a web service they can't really return or take interface types, only concrete types (unless you are going to hand-write all your own serialization/deserialization).

Should every class have an interface?

When discussing these principles in the book, I regularly encourage the reader to add more interfaces to their classes, to make the overall design of the package or application more flexible. However, not every class needs an interface, and not every interface makes sense.

Which term is used to denote the classes and objects depend on each other?

Tight Coupling means one class is dependent on another class. Loose Coupling means one class is dependent on interface rather than class.


1 Answers

It's useful for objects which really provide a service - authentication, storage etc. For simple types which don't have any further dependencies, and where there are never going to be any alternative implementations, I think it's okay to use the concrete types.

If you go overboard with this kind of thing, you end up spending a lot of time mocking/stubbing everything in the world - which can often end up creating brittle tests.

like image 117
Jon Skeet Avatar answered Oct 02 '22 07:10

Jon Skeet