So, I started working on a new project this week and, after exploring the code a bit, I noticed something that I find keeps popping up in .NET code. There is an overabundance (and misuse) of interfaces. Everywhere. Even to the point that the action methods are taking in IModels and the such. After talking to one of the leads who had to rescue the code base, the lead developer stated that the "new" keyword was bad. So, to that person, everything had to be an interface and decided that dependency injection should be used everywhere. I mean, everywhere. And, nothing is programmed against a concrete object—not even in the tests! To give an idea of the types of objects and interfaces, here is an example:
public interface IPerson { string FirstName { get; set; } string LastName { get; set; } int Age { get; set; } } public class Person : IPerson { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } }
And then this class is used in controllers:
public class PersonController : Controller { public ActionResult AddPerson(IPerson person) { if (ModelState.IsValid) { /* Add the person */ } // Do something else } }
Well, for those not familiar with ASP.NET MVC, this use of interfaces in the action method (public ActionResult AddPerson) causes a whole lot of extra work. The model binder can't create an arbitrary object, so it can't bind the incoming data to an interface. Instead, a concrete class is required so it can be initialized and then bound. So, to make MVC not choke, you have to create a model binder. (A topic for a different approach.) So, instead of using the built-in goodness of ASP.NET MVC and its model binders, we're giving ourselves so much more work with absolutely no value added.
The other complete abuse here is that interfaces should describe the behavior and capabilities of an object, not to describe what it is. Interfaces usually describe the verbs available on objects, and classes describe what the object is. Sure, there are edge cases and other tricks that utilizing an interface allows one to do, but this is definitely not a good use of them.
No comments:
Post a Comment