I'm creating a .NET MVC solution that will have two web projects, one for API and for Web. Some models, such as customer, will be the same between the two projects.

Is it best to have them kept in a common web library and referenced from the two web projects, or keep them unique to each project?

  • 2
    The most applicable principle here is probably DRY. – Robert Harvey Jul 6 '16 at 6:05
  • 1
    if you put it in a library you still will be able to create derived classes when required. So I guess that's more flexible because you can avoid duplication and allow extension. – derloopkat Jul 6 '16 at 11:55

It's tempting to ruthlessly eliminate duplication in our systems, and for very good reasons, but we must always ask ourselves whether this is real duplication or apparent duplication.

What I mean is that we'll sometimes have code that looks identical, but each will have their own reason to change, independent of each other. If you think the view model for the App will always change in tandem with the view model for the API, then they should share the same view models. However, you'll likely soon find that the view model for your app needs a property that the API doesn't need, due to needing some ephemeral UI element (like, say... a drop down list that contains data from some external system you'll be "borrowing" in your app).

I see the app and the API as two different front ends to the same business models. They should absolutely share the same business models (logic/dtos), but sharing view models is iffy at best IMO. If things are identical now, you could share the code, then inherit from your shared classes later, if you run across a situation where you need to extend the base models. Maybe the best of both worlds.

  • Since view models do not (or should not) contain logic, the only thing you are duplicating is the code required to get and set values for the object's private fields. This is so trivial that there is no benefit to sharing the class between two projects. +1 – Greg Burghardt Sep 27 '18 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.