3

I have on my controller a Create and an Edit action.

I have for each action a viewmodel. Both viewmodels have approximately 15 properties. 10 are common for both models and the rest differs.

My question : Should I create some base model with the common properties (keeping DRY) or should I dont care here ?

4 Answers 4

4

This is almost certainly going to come down to the actual situation you are in. The most important question to ask yourself is: do these shared properties form some kind of base entity? If the answer is yes, you are probably safe having a base class. If not, I would stay away from it and just put the properties on the individual models.

If you are leaving out some properties in the create view model that become editable in the edit view, the shared properties probably do not make up some type of base class, and you should avoid the base view model approach. If the extra properties are just helper properties, like select lists, then you can safely have a base model that has the common properties.

Sign up to request clarification or add additional context in comments.

Comments

1

You should definitely care. Writing good, clean code is good for the soul, besides we all know every time you write bad code, God kills a kitten. :( And we don't want that.

Move the common code / properties to a base class and then have two descendants, it's nice, clean and makes maintenance a lot easier.

Comments

0

Personally I would go the base class option so that your having to repeat data annoation attributes in multiple places.

1 Comment

You can reuse data annotations by declaring them in a separate class and using the MetadataType attribute on each view model.
0

My view is that if I am creating or editing something, it is essentially the same thing. Really there shouldn't be any difference in the core data structure.

But assuming there are differences, I would use a base class to share the common properties as you would anywhere else.

3 Comments

If you are creating or editing something, it might not be essentially the same thing. For instance you could create something by importing values from an external service, in which case your create model has enough properties for you to access that service and locate the object you would like to import. Once imported, your edit model would almost certainly have nothing to do with your create model.
Hmmm not sure I agree completely Nick, if I have a Car model it's properties are the same whether I create it OR edit it, it has a number of doors, number of wheels, seating capacity etc. The mechanics for how I get data to create a Car instance are irrelevant to the actual implementation of the model.
@SimonLee: The question specifically asks about view models, not the entity model itself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.