Since you posted this under the backbone.js
tag, let's get the obvious answer out first: You're not violating the DRY principle, because you don't have to define the fields for Backbone.Model
. Your model, at its simplest, can look like this:
var FooModel = Backbone.Model.extend({});
If today your service returns {foo:1}
, and tomorrow {foo:1, bar:2}
, Backbone will quite happily use the new property.
Let's assume you were using a framework that required you to define your client model's properties, the question becomes more debatable...
<opinion>
The best you could do would be to codegen the client-side model properties from the server models. If you wanted to stretch it, you could possibly even generate simple validation code, but that's about it. Is it worth it? With the additional complexity added by code generation tools, I would say that unless you have hundreds of model types, the answer is a resounding no.
Consider what happens when you change a server model, in each of the following cases:
- You add a property to the model
- You remove a property from the model
- You change a property of the model
Whether your client-side model is automatically generated or not, each of the changes will most likely require you to change some code on the client. Removing and changing a property are breaking changes: your application will most likely break or fail in unpredictable ways if it expects a certain property to be there, and it's not. Addition is more harmless, but unless you do some client-side code changes, a new property will not be very useful. You'll have to write code that uses the new property.
Now, if you're making changes to the client-side code anyway, the price of having to change the model definition is absolutely tiny. Any amount of quasi-theoretical DRY compliance can't make it worth your while.
I would go even one step further, and actually try to avoid directly mapping your server-side model to your client-side model, because it creates a tight coupling between them. There are numerous occasions when you may need to change the model in either end without changing the other, but if the models are expected to be directly equivalent, the change will propagate unnecessary change in its counterpart. Because in ORM-backed, "Active Model" type patterns the model is a participant in both persistence and business logic, there will be plenty of changes like this.
Instead you should write/generate Data Transfer Objects (DTO
) for your server-side models. The DTO should contain a minimal necessary subset of the server model's properties, which the client needs. The DTO defines the interface between the server and the client. If the client model needs to change, you can change the DTO. If the server model changes, you can change the DTO.
</opinion>