I’m currently learning about various application design approaches and there’s one thing I can’t really get my head around.
Let’s say I have a physical device in my network, an IP surveillance camera. I need a model that represents ‘IP surveillance cameras’ to work with them in my application, which might look like this:
public class IPCamera {
public string Token { get; set; }
public IPAddress IPAddress { get; set; }
public string RtspUri { get; set; }
}
Now, if I want to store the IPCamera into a database (e.g. with Entity Framework), I need maybe another properties and thus, another model with:
public int Id { get; set; }
Oh.. I want to access my application with via a WCF service. I can’t use the object “IPAddress” here because it’s not very serialization friendly, hence I need another model with a custom IP class that stores the IP address as string.
And last, an Android clients wants to access my data. I design a RESTful API using WebApi2. The client isn’t interested in the cameras RTSPUri, but wants to know about the current state (is online, is offline).
I’m wondering: How to name all these models that they don’t come in conflict? Should I design a model per each purpose/layer/service? And how to link/map them? With the adapter pattern?
0
Now, if I want to store the IPCamera into a database (e.g. with Entity Framework), I need maybe another properties and thus, another model with…
No, you just need an ID property in your IPCamera class:
public class IPCamera {
public int ID { get; set; }
public string Token { get; set; }
public IPAddress IPAddress { get; set; }
public string RtspUri { get; set; }
}
I can’t use the object “IPAddress” here because it’s not very serialization friendly, hence I need another model …
No, you just need a ToString()
method in your IPAddress class.
The client isn’t interested in the cameras RTSPUri, but wants to know about the current state (is online, is offline).
Add an isOnline()
method to your IPCamera class?
2
You could use inheritance as in
public class StateFullIPCamera : IPCamera {
public bool isOnline { get; set; }
}
public class IPCamera : EntityBase {
public string Token { get; set; }
public IPAddess IPAddress { get; set; }
...
}
public class EntityBase {
public int Id { get; set; }
}
Be careful though, if there are properties in the base classes which clients do not need, you should be returning them a different model. Never only populate some properties.
I upvoted Robert’s answer because it is simple and makes sense.
As I commented there, I would suggest another api method specifically for getting the state of the camera and leave it off the model entirely.