views:

84

answers:

1

Thinking about avoiding code replication, I got a question that catches me every time I start developing a new system:

Let's say we have a system where I have a customer, have to CRUD it in a repository and show it as a resource in a webservice.

Thinking about the classes related to the customer, we would have (Okay, I will never use these names for real):

  • CustomerEntity, representing the entity used for doing the system's logic;
  • CustomerRepositoryEntity, representing the table row where it will be stored;
  • CustomerXMLEntity, representing the XML node 'customer';

It seems that I will have three entities and all the customer's attributes will be in each class. I was wondering if isn't there a way, or a pattern to consolidate these three classes inside the same entity, called simply "Customer".

This way, every time I need to create a new representation of "Customer" (for example, If I want to represent it as a Json element), i don't need to create a new class for it. I know it's a very particular issue, but I was just wondering if it couldn't be easier (and better looking) than how I am doing now.

+1  A: 

Assuming you're using the same languages in your different applications...

Build a proxy class, and a backend class.

The backend class runs close to your data, and exists only to serve up data to your proxy.

Your proxy runs on any client and takes the location of the backend endpoint as an initialization parameter. When a get/set is called on your proxy object, it handles your validation and business rules, then hands the request back to your backend class, which handles the implementation details of persisting your data.

You'd have two layers of abstraction: one for data persistence, and one for business rules.

>>>>>  Nathan
Nathan