Because we have now added a possible
remoting boundary to the picture, I’d like to end this article by discussing
where to put code for business rules. This is a problem that crops up all
the time, but let’s assume that the main rule is to put it in the domain classes.
One specific problem I have struggled with is how to deal with code that I
think should be in the domain model, but that I don’t want to execute on the
One reason might be that I know
that a lot more data must be read from the database in order for the code
to be executed and I don’t want to send the data over a slowish wire. Another
reason might be that I want to execute the code in a secure and controlled
environment, or perhaps where certain resources are available. A good example
of this is when I want to run the business rules in a database transaction.
(Database transactions are logically dealt with by the Application layer.)
Yet another reason is that you don’t want to expose the algorithms at all
by letting the client have the code. (If you let your domain objects travel,
the client must have the code for the domain classes.)
A simple solution is, of course,
to put the code in the Application layer classes, because those classes will
never travel to the client. However, there is a risk that you will duplicate
code over time since the same domain classes will typically be used from many
different Application layer classes. The code really belongs to the domain
classes, so to speak.
still believe that some rules should be dealt with in the Data tier,
in stored procedures, for example. It depends on the nature of the rules.
See my book  for more information about putting rules in the Data tier.
I thought about subclassing the
domain model classes and have the server-side logic in the subclasses only.
I could then see to instantiating the subclass (CustomerEx
for example) at the server, upcast to the superclass (such as Customer
for example) and send the superclass to the client. When the client sends
the object back, it can be downcasted to CustomerEx and the
server-side code is available. I haven’t actually tried this, and it feels
messy, complex and not very obvious. What’s more the client must have the
code for the CustomerEx and
then can do the downcast himself.
Assume you can live with the client
having the code. You just don’t want him to call certain methods of the domain
model. One possible solution is to use Code Access Security to check where
the call is coming from. You could also add an unknown token as parameter
to the methods you don’t want to run at the client. Then you keep that token
unknown to the client, but well known to the Application layer. A good example
of security by obscurity, right? It may feel quite a lot like a hack, but
it works for some situations.