Showing posts with label Software Design. Show all posts
Showing posts with label Software Design. Show all posts

Oct 30, 2010

Semantics only works in a context

I am a believer of semantics. What is why name the domain as semanticsworks.com. But let me take a step back to explain what I mean semantics here. You may find the definition in Wikipedia, but what I mean semantics here is the true intention or need to do something. For example, when I say " I need a car to go to work", the true intention is "I need get to work", "a car" is just a means, or an implementation. If I work at home, I wouldn't need a car at all. As a software developer, I can easily apply semantics into programming. For example, I would prefer writing semantic html rather mix presentation html, I would focus on abstraction(interface) rather on implementation(class) and so on. When I study a a new technology, a new programming language, I will first think what problem it is trying to solve, then I focus how it solves the problem more efficiently and elegantly. When I want to propose my solution or design to my client, I would raise the what the existing problem is, and how my solution solve the problem in a better way. Semantics seems to work. But one important thing shouldn't be forgotten, that is a context. Here is what javascript guru Douglas Crockford said in his Loopage presentation


A little while ago I was talking to a friend of mine — a really bright guy, one of the smartest programmers I know – about what we should do next with JavaScript. I suggested to him that we should get the tail recursion thing going, we should get that fixed. Why do we want to do that? Well, I said, among a lot of other things it would allow us to do continuation style passing. I think that would be a useful option for us to be able to provide within the language, and if we don't optimize the tail calls then we don't get that. His answer was: I've never used continuation passing, so I really don't see the value of it, which I immediately recognized as a really stupid answer.

The way I was able to recognize it so fast is that I have used that same argument myself, and I've been hearing that same argument throughout my entire career. Basically, the core of that argument is: "I'm not qualified to make a decision about that. The onus is on you to educate me deeply about this thing that I'm not even interested in." There's no way to overcome that kind of requirement, nobody can win that argument. But it turns out that usually that reasoning is wrong. I've heard that argument about why we shouldn't have to worry about closure. I've heard it about why we shouldn't use recursion. I've heard it about why punch cards are better than timesharing. You can go all the way back to 'it's better for us to be programming with digits, I don't understand why we need compilers'. It's been going on from the beginning. That's why software development is so slow, because basically we have to wait for a generation to die off before we can get critical mass on the next good idea.

Semantics does not always works as we expect. Seemingly, Crockford forgot his friend's context. He should have let his friend buy in his context in the first place. When you try to propose a solution to solve a problem, which your client does not think as a problem, or does not see a need to solve it immediately, then your semantics will not work in your client's context. So here is what you can do.


  1. Think in the context of your client, don't propose a solution to solve a problem that your client has not interest in solving, only propose the solution in your client's context
  2. Think in the context of your client, guide your client to think in your context and make him believe that it is a problem, then propose your solution. Sometimes, this can be very hard, if the contexts collide heavily.
  3. Ignore your client and move on

There are lots new technologies coming, like Domain Specific Language, Cloud computing, Service Oriented Architecture etc. How soon they will be adopted will depends on how people can accept the contexts in which their designer think, and how soon people can accept these context will somewhat depend on the result the early adopters achieve.


A friend of mine asked me recently, what versioning control system should be used. I said "Git". He asked why? I said it is distributed versioning control system and it is scalable. Then He said, "We don't need it to be distributed.". You know, I made the same mistake, I lost the context of friend.

Oct 4, 2010

Static class vs Singleton

Design pattern question is often asked in interview for developer. In an interview, I was asked to describe one design pattern that I am familiar, except singleton. Maybe the interviewer think that Singleton is too easy to answer. Yes singleton is a very simple, a sample is as follow.


class Program
{
 static void Main(string[] args)
 {
  Printer.Instance().Print();
 }
}

class Printer
{
 static Printer _printer;

 public static Printer Instance()
 {
  if (_printer == null)
  {
   _printer = new Printer();
  }
  return _printer;
 }

 protected Printer()
 { }

 public void Print()
 {
  Console.WriteLine("printing...");
 }
}

Although Singleton pattern is simple, it can be also used to test applicant's understanding of object. Let's say, if someone writes the following code some code argues that design pattern is useless, structured procedure is better. In some case, structured procedure is just as good. Can you write some code demonstrate in what scenario Singleton solve problem that static method cannot solve? (Don't think of mullti-threading, it is not an issue here.)


class Program
{
 static void Main(string[] args)
 {
  Printer.Print();
 }
}

static class Printer
{
 public static void Print()
 {
  Console.WriteLine("printing...");
 }
}


My answer

Although two solutions look similar, but it reflects different thinking. One of book affect me most in my programming career is Object Thinking. In this book, it says


The essential thinking difference is easily stated: “Think like an object.” Of course, this statement gets its real meaning by contrast with the typical approach to software development: “Think like a computer.” Thinking like a computer is the prevailing mental habit of traditional developers.

The singleton solution is reflection of "think like an object". When you think like an object, you are also an object, the other objects will be your buddies. You will interact with printer buddy by his interface. As long as your buddy expose the your printer interface, you know how to communicate with him. It doesn't matter who your buddy is, what matters is you know what kind of service your buddy provide you. You scenario will be, I see a Printer guy, he is the only printer guy, I don't care who he is, but he says he can print, so I ask him, "Print, please". If you think this way, you can write the following code. This is fundamental feature of object-oriented technique, polymorphism.


class Program
{
 static void Main(string[] args)
 {
  Printer.Instance().Print();
 }
}

abstract class Printer
{
 static Printer _printer;

 public static Printer Instance()
 {
  if (_printer == null)
  {
    Type pritnerType = GetPrinterTypeFromConfiguration();
    _printer = Activator.CreateInstance(printerType) as Printer;
  }
  return _printer;
 }
  public abstract void Print();
}

class LaserJetPrinter : Printer
{
   public virtual void Print()
   {
      Console.WriteLine("hhhhhhhhhhhh");
    }
}

class InkJetPrinter : Printer
{
   public virtual void Print()
   {
     Console.WriteLine("kakaka");
    }

}

If you think like a machine, your mindset will be like, I am the master of the printer, I want feed it with some instructions. Ok, I have menu of the machine, one of instruction is "print", let me feed it, and it prints. If you think like this, you will write the static method like above. This is not necessary bad practice, in fact it is even the best practice(please check CA1822: Mark members as static, if you never want to have differently print behavior. Until then You have much less flexibility, and OO is your friend.

Sep 4, 2010

Defensive programer , code analysis, and code review.

I was born in China, English is not my native language, and I still have difficulties in writing in English. Once, I sent an email to my boss. In his reply he highlighted my typo and grammatical error. At first I felt embarrassed, but I immediately appreciated his effort of doing so. I am sure sometimes my email is confusing, but nobody has ever done that to me before. I guess it is because they don't want to hurt my feeling or save the time to correct me. I do use spelling check and grammar check functions of email app, and I never felt embarrassed, isn't that strange?


I have been a programmer for years, I have made all the programming mistakes that can be made, and I still make, but less. Some developers correct my error, some don't. I felt embarrassed in early time, but I gradually accept the fact that my code sucks and appreciate their effort. Compilers also correct my mistake, I was frustrated in earlier time, but I never felt embarrassed by compilers.


As I got more experience, I found that it was never easy to tell my fellow developers about their mistakes in coding or design. I was working in a software company. One of the senior developer resigned for a new job and my boss asked me to take over his project which I never touched. Firstly, I reviewed his code, I felt sick and wondered how a senior developer can write such crap. During the later knowledge transfer, I asked lots of critical question, I knew I hurt his feeling and he was unhappy. Personally, I think he is nice and funny guy, and I regret about that. From then, I try to be careful about my words when I express my opinion of others' code. Even then, it is still inevitable to hurt someone's feeling some time, if my opinion is too radical to him.


Is this just my unique experience. In the book Debugging Microsoft .NET 2.0 Applications, author John mentions his experience in Chapter 3, "Assert, Assert, Assert, Assert". He argued with his boss about a section of code, which misused "Assert", and he said "Whoever wrote this needs to be fired! I can't believe we have an engineer on our staff who is this incredibly and completely stupid!". His boss got very quiet, grabbed the paper out of his hands, and quietly said, "That's my code." . And John resigned from the company later.


Although it is not so new book, I find that it is still very useful. The author discusses some proactive tools to improves code quality, one of them is code analysis, and a chapter 8 is dedicated to topics "Writing Code Analysis Rules". I think code analysis is quite effective, because no matter how defensive you are as developer, you seldom can be embarrassed by a machine. Machine always reports the warning or error if you break the rules.


For a while, I suspected the effectiveness of code review. My previous experience tells me that developers tend to be defensive for themselves. Why? If there is a large gap in coding quality and experience between the author and the expectation of the reviewer, the reviewer may ask the question like "How can a senior developer write such crap?", this make the author looks incompetent, so it is natural to for him to be defensive. In such case, code review will not be necessary. Maybe it will be more effective for the company to send the author for some crash course to close the gap, or the recruitment process needs to be reviewed to to find out why this gap is not caught in the first place. If the gap is small, generally, the code review is powerful software quality tool. It has been adopted by many good software companies. It is said that some company go to the length that code developed by junior developer can not be merge into trunk until it has been reviewed by senior developer. I am not sure if that is true, but code review not only improve quality but also transfers knowledge, and it can become an company culture that attract people. However we developers are still human, we should be very clear that, code review is review of code, but not performance review of employee. And we should not use words that target for people but not code. One senior developer once reviewed my code and said "You don't understand what object oriented programming is." I was upset for a while. Am I too vulnerable? Maybe, I am a human.

Feb 15, 2010

The semantics of c# interface

We all use interface construct in c#. Recently I came across the Haack's blog Interface Inheritance Esoterica, I decided to find out more. So I write a very simple example like below

public interface IAnimal
    {
        void Walk();
    }

    public interface IBird : IAnimal
    {
        void Fly();
    }

    public class Bird : IBird 
    {
        void IBird.Fly()
        {
            throw new NotImplementedException();
        }

        void IAnimal.Walk()
        {
            throw new NotImplementedException();
        }
    }

Then I use ILDASM to examine the IL generated, the Bird class actually implement two interface,


//Bird IL
.class public auto ansi beforefieldinit DemoInterface.Bird
       extends [mscorlib]System.Object
       implements DemoInterface.IBird,
                  DemoInterface.IAnimal
{
} // end of class DemoInterface.Bird

//
.class interface public abstract auto ansi DemoInterface.IBird
       implements DemoInterface.IAnimal
{
} // end of class DemoInterface.IBird


We can see that the Walk is not a member of IBird, the semantics here is the class that implement IBird, should also implement IAnimal. So I change my code to be the following

public interface IAnimal
    {
        void Walk();
    }

    public interface IBird //: IAnimal
    {
        void Fly();
    }

    public class Bird : IBird , IAnimal
    {
        void IBird.Fly()
        {
            throw new NotImplementedException();
        }

        void IAnimal.Walk()
        {
            throw new NotImplementedException();
        }
    }

This time the generated IL for Bird is exactly the same as previous code. The only difference is that IBird does not "implement" IAniaml. In the first example, the semantics of Bird implementing IBird is as following


  1. The class is an IBird (or we can say it has gene.) Even the IBird interface has no member it still has semantics, System.Web.UI.INamingContainer it is an example.
  2. The Bird class is an IAnimal
  3. The Bird class implements IBird member Fly()
  4. IAniaml's member is not the member of IBird, but IBird support IAnimal's memeber
  5. The class that implements IBird, also need to implements IAnimal.
  6. The Bird class implements IAniaml member Walk(), because of previous semantics

The the original intention of interface is contract, and a contact can be a composite, which means a contract can be a combination of other contract(s).

Jul 12, 2009

Naming in Entity Framework

When using the entity framework designer, you create you entity model with a naming convention. For example, a table "Customer" will map to a entity type "Customer" and entity set "CustomerSet" . It is very tempting to change the name of "CustomerSet" to to Customers. But what about Criterion, its plural forms is Criteria, what about Equipment, it is plural forms is also Equipment. I feel that the default naming convention is good enough, because it tells you it is a set and also my configuration is kept to minimum, isn't this the spirit of convention over configuraiton?

Jan 17, 2009

Value object and Persistance

It is confusing to mixed value object with its persistence. We know value has has no identity. How about primary key in database. Every table in database has an primary key. Isn't that key the identity of value object if we want to persist the value object to database? Here we mix the domain model with the persistence.

In domain model, we care about object's behavior, persistence is irrelevant. For example, an order is an entity because we have a use case that get an order by an order id. But order row, it is not an entity because we don't have a use case to get order row without reference to other object. We need to have an order id, to get an order row. Although we can argue that in the order row table, each record still has an primery key( orderId, productId), but that key does not make the order row object an entity. Because it does not make sense to get the an order row without an order. Oder row is parasite of order. Contrary to this, customer is an entity, event Order (an entity object reference customer). Customer does not depend on the existence of an order.

Aggregates are groups of objects that work and live together. We group them along natural operational lines, and one entity serves as the aggregate root. The aggregate root serves as the entry point and the hub of operations for all objects in the aggregate. An aggregate can have many objects, or it can just be a single entity, but the aggregate root is always an entity since the aggregate root must be able to stand on its own, and only entities can stand on their own.

Nov 9, 2008

Persistence Ignorance and ORM

The purpose Of Persistence Ignorance is to keep your domain model decoupled from your persistence layer. Nilsson establishes the following characteristics as things you should not have to do in persistence ignorance

Inherit from a certain base class (besides the object)

A common pattern in ORM solutions is to force consumers to inherit from a provider-specific base class. The reason for this is dependent on the provider, but typically the base class has some sort of attribute or method required for persistence. This is not a significant problem if you’re designing a system from the ground up, but if you already have a domain model and you’re trying to add persistence, this can be a pain because .NET supports only single inheritance.

Instantiate only via a provided factory

Domain Driven theory supports the use of factories when building domain models. We don’t want to have to use a provider-specific factory implementation to create our persistent classes. This couples our model to the ORM instead of keeping it independent, and is usually required by ORM solutions for object tracking and notifications.

Use specially provided data types, such as for collections

This is another pretty typical situation that you’ll see in ORM tools in order for them to provide functionality for out-of-the- box lazy loading. This is so common in the ORM solution world that it doesn’t bother me too much, because you can usually design around this functionality to keep your model independent. However, I can understand the desire to have this as a feature of your ORM.

Implement a specific interface

Similar to base class inheritance, this is another situation in which the ORM engine needs a specific implementation in the persistent classes to do its job. This is obviously a better design, to have to implement an interface instead of having to use up your only class inheritance option in .NET, but you are still tightly coupling your domain model to the ORM, making it less portable.

Provide specific constructors

This is common in ORM solutions so the engine can create instances of your domain model type or reconstitute a particular value. My personal opinion is that having to implement a default constructor doesn’t really violate any major design law. However (and I have yet to see an example this), anything beyond the default constructor implementation would be a significant irritation.

Provide mandatory specific fields:

Providing specific types on fields (for example, a GUID for an ID) is sometimes mandatory in ORM frameworks. This is often part of an interface or a base class implementation, and is required in many cases for handling associations and relationships.

Avoid certain constructs and forced usage of certain constructs

This criterion can consist of a forced access modifier on a field or method or can be the metadata used for mapping. A good example of this is using get and set functions as you might in Java versus a property in C#. Additionally, as you will see later, this can also be the use of .NET attributes in your model. Attributes, extraneous methods, base classes, and so forth are a big concern of mine when developing a domain model because I don’t like having to change my well-thought- out access modifiers or pollute my model with some garbage in order for the persistence engine to work.

Another Notes of DDD

Entity

Real word entity is an independent, seperate, or self-contained existence. It's identity is what gives it uniqueness and differentiates it from other thing else. This is typically a set of characteristics or traits that defines what it is.

Database entity is a table, it's identity is key.

Software identity is representation of a real world identity. But it is not a business object. It is not an extension of database entity, although they have some relevance. It is a modeling effort. According to Evans, the entity is an object that is defined by a "thread of identity that runs though time and often across distinct representations"

  • It run though times

    This means after close the application, and start a new application, an object(entity) can still be reconstructed.

  • It run across distinct represenations

    This means the same object can be consturcted in different machine, or different software

If we find the need to identity an object which runs through the time and across distinct represenation, we need to define it as an entity.

But what exactly is an identity for software entity? In real life, how can people identify me? In real life, I am entity. Although I have an social security number, people do not use it to call identify me. They identify me by name. May be somebody has the same name as me, but they can still identity me, because I still have other fact which is different, for example, my job, my height, color or what ever.

How what is an idenitity in domain model?

  1. Not every object in your domain model is an entity, and therefore our framework must have the capability to evaluate the identity of multiple different objects. This is typically done through comparison operations and by overriding equals, and it is necessary to promote a healthy existence.
  2. Ensure that our entity objects have stability throughout their life cycle. This is largely controlled by the ORM tool; however, it is important to keep stability in mind when using transactions and developing your model.
  3. Focus on identity by building each entity with some mechanism for defining uniqueness.

Value Objects

Evans says, "When you care only about the ttributes of an element of the model, classify it as a value object." We can think of value object as an object that cannot exist on its own, an object that has no identity by itself. For all intents and purposes, value objects are the parasites of your model because there is no reason or their existence except to describe and associate themselves with our entities. Most of the time, we shouldn’t assign or track their identity for value objects or you will likely impair system performance. These objects are used to describe aspects of the system and so they should, in most cases, be treated as immutable.

Aggregates

According to Merriam-Webster Online, an aggregate is “formed by the collection of units or particles into a body, mass, or amount.” Aggregates, in terms of the domain model, are just that: a logical grouping of entities and value objects into a collection. The reason for aggregation in your model is that complex relationships can lead to data inconsistencies in your application and database.

This concept is simple: the more moving parts in your model, the more likely you are to end up with problems. A case in point is the cleanup of orphaned data and objects. Say, for example, that you have an account record in your database. If you delete the account, you can use a cascading delete to ensure that you don’t have any orphaned data hanging out in other related tables. In the object world, we should forget about the database concept like primary kye, foreign key, cascading update/reference. We need to create aggregate to prevent memory leaking or data store corruption. Our Automobile entity, is the perfect example of an aggregate. The automobile has value objects such as Seats and Tires, and can also have other entity objects such as the Owner object. By this account, the Automobile object becomes the source of the aggregate and for all intents the owner of the group. You may be asking yourself how this helps to enforce referential integrity in your model. The answer actually lies in the structure of your domain model and the objects you expose to consumers. By controlling what objects a consumer can create and by exposing the aggregate, you can ensure integrity in your model. The most common way to enforce this technique is to use the factory pattern discussed later in this chapter and demonstrated in detail in Chapter 8. However, a solid understanding of accessibility modifiers and a well-laid-out hierarchy will also be critical to ensure integrity.

Services

Not everything in our model can be classified as an entity or a value object. Typically in our domain model, a service will be developed as an action or an activity, which doesn’t make sense to build into our entities or value objects.

Some concepts from the domain aren’t natural to model as objects. Forcing the required domain functionality to be the responsibility of an Entity or Value either distorts the definition of a model-based object or adds meaningless artificial objects. - Eric Evans

Continuing with the automobile example, suppose the automobile informs you when it is time to change oil. This service requires the evaluation of a series of domain objects and thresholds to determine that it is time for an oil change. Although the service is expressed by using Automobile entity (technically an aggregate), it wouldn’t make sense to encapsulate it as that object. This service interface needs to be outside the entity and value to keep it reusable.

Service does not only reside in domain layer, it can also reside in other layer such as application, infrastructure. Service is a natual object concept, its purpose is to build functions in as much reusability as possible, and encapsulate outside the implementation of our value and entity objects.

Domain Model

At its worst, business logic can be very complex. Rules and logic describe many different cases and slants of behavior, and it’s this complexity that objects were designed to work with. A Domain Model creates a web of interconnected objects, where each object represents some meaningful individual, whether as large as a corporation or as small as a single line on an order form. —Martin Fowler

The domain model is much more than just an object model because its creation is rooted in the collaboration among the experts in the organization. Specifically, the domain model is the conceptual layer that can be used to represent the process as a whole and is fundamentally a mechanism that can bring the people in the software life cycle closer together. Similar to UML acting as a common vocabulary, a completed domain model can also be a catalyst for enhanced cross-process and cross-functional communication.

As an example, take Company X, comprising a handful of new developers, a few senior developers, some quality control people, a couple of business analysts, and a project manager (in other words, a rather typical development team). Suppose that the developer and business analysts have a hard time getting anything done because the developers don’t really understand the nuances of banking and likewise the business analysts can’t explain things effectively to the technical personnel. To overcome these communication problems, Company X has implemented a Software Development Life Cycle (SDLC) process, involving reams of paper defining specific problems and development needs for the current system. The quality control (QC) people resent the developers because the developers have never adequately explained the situation from an impact standpoint, and the project manager is frustrated because the communication issues are reducing the time he is able to spend on the golf course.

Now, give this team a robust domain model that conceptualizes the realm of interactions in the software, and many of these communication issues disappear. The UML (or any common modeling language) used to diagram the domain is a common way for everyone to communicate. The domain model itself can be used to explain complex interactions from a functional and a technical perspective.

When you are working on modeling a business domain, don’t get hung up on formalized UML in meetings with the domain experts. The UML should not become an obstacle in development. Instead, it should help people communicate by using a common lexicon. The easiest way to build a good domain model is with paper and pencil or a whiteboard. We can use rudimentary notation that everyone can understand, demonstrating the relationships and behavior within the model. After the initial meetings, we take the whiteboard drawing and use a formal modeling tool and add any formal notation that we may have glossed over in the meeting.

Nov 6, 2008

Notes for Domain Driven Design Quickly

What is domain driven design?

The best way to do it is to make software a reflection of the domain. Software needs to incorporate the core concepts and elements of the domain, and to precisely realize the relations between them. Sofeware has to model the domain.

Somebody without knowledge of banking should be able to learn a lot just buy reading the code in a domain model. This is essential. Software which does not have its roots planted deep into the the domain will not react well to change over time.

We need to create an abstraction of the domain. It is a domain model. It is not a particular diagram, it is the idea that the diagram is intended to convey. It is not just the knowledge in a domain expert's head, It is a rigorously organized and selective abstraction of that knowledge. It can be in the form a diagram , carefully written code or just english sentence.

A specific domain could be more than a human can handle at one time. We need to orgainze information, to systematize, to divid it up in smaller pieces, to group those pieces into logical modules, and take one at a time and deal with it.

A model is the essence of the software, but need to create ways to express it, to communicate it with others. We need to cummunicate the model. There are different ways to do that. One is graphical: diagrams, use cases, drawings, pictures, etc. Another is writing. We write down our vision about the domain. Another is language. We can and we should create a language to communicate specific issues about the domain. The right way to design software is domain driven design. It combines design and development practice, and shows how design and development can work together to create a better solution. Good design will accelerate the development, while feed back coming from the development process will enhance the design.

You and the domain experts need to exchanging knowledge. You start asking questions, and they respond. While do do that, they dig essential concepts out of the domain. Those concepts may come out unpolished and disorganized, but nonetheless they are essential for understanding the domain. You need to learn as much as possible about the domain from the experts. And by putting the right questions, and processing the information in the right way, you and the experts will start to sketch a view of the domain, a domain model. This view is neither complete nor correct, but it is the start you need. Try to figure out the essential concepts of the domain. This is an important part of the design. Usually there are long discussions between software architects or developers and the domain experts. The software specialists want to extract knowledge from the domain experts, and they also have to transform it into a useful form. At some point, they might want to create an early prototype to see how it works so far. While doing that they may find some issues with their model, or their approach, and may want to change the model. The communication is not only one way, from the domain experts to the software architect and further to the developers. There is also feedback, which helps create a better model, and a clearer and more correct understanding of the domain. Domain experts know their area of expertise well, but they organize and use their knowledge in a specific way, which is not always the best to be implemented into a software system. The analytical mind of the software designer helps unearth some of the key concepts of the domain during discussions with domain experts, and also help construct a structure for future discussions as we will see in the next chapter. We, the software specialists (software architects and developers) and the domain experts, are creating the model of the domain together, and the model is the place where those two areas of expertise meet. This might seem like a very time consuming process, and it is, but this is how it should be, because in the end the software’s purpose is to solve business problems in a real life domain, so it has to blend perfectly with the domain.

Model Driven Design

After we create a great model, we need to implement the model in code, propertyly transfer it into code. Any domain can be expressed with many models, and any model can be expressed in various ways in code. For each particular problem there can be more than one solution. Which one do we choose? Having one analytically correct model does not mean the model can be directly expressed in code. Or maybe its implementation will break some software design principles, which is not advisable. It is important to choose a model which can be easily and accurately put into code. The basic question here is: how do we approach the transition from model to code?

The disconnection between model and code design

It happens that software analysts work with business domain experts for months, discover the fundamental elements of the domain, emphasize the relationshipbs between them, and create a correct model, which accurately captures the domain. Then the model is passed on to the software developers. The developers might look at the model and discover that some of the concepts or relationships found in it cannot be properly expressed in code. So they use the model as the original source of inspiration, but they create their own design which borrows some of the ideas from the model, and adds some of their own. The development process continues further, and more classes are added to the code, expanding the divide between the original model and the final implementation. The good end result is not assured. Good developers might pull together a product which works, but will it stand the trials of time? Will it be easily extendable? Will it be easily maintainable?

Any domain can be expressed with many models, and any model can be expressed in various ways in code. For each particular problem there can be more than one solution. Which one do we choose? Having one analytically correct model does not mean the model can be directly expressed in code. Or maybe its implementation will break some software design principles, which is not advisable. It is important to choose a model which can be easily and accurately put into code. The basic question here is: how do we approach the transition from model to code?

One of the recommended design techniques is the so called analysis model, which is seen as separate from code design and is usually done by different people. The analysis model is the result of business domain analysis, resulting in a model which has no consideration for the software used for implementation. Such a model is used to understand the domain. A certain level of knowledge is built, and the model resulting may be analytically correct. Software is not taken into account at this stage because it is considered to be a confusing factor. This model reaches the developers which are supposed to do the design. Since the model was not built with design principles in mind, it probably won’t serve that purpose well. The developers will have to adapt it, or to create a separate design. And there is no longer a mapping between the model and the code. The result is that analysis models are soon abandoned after coding starts.

One of the main issues with this approach is that analysts cannot foresee some of the defects in their model, and all the intricacies of the domain. The analysts may have gone into too much detail with some of the components of the model, and have not detailed enough others. Very important details are discovered during the design and implementation process. A model that is truthful to the domain could turn out to have serious problems with object persistence, or unacceptable performance behavior. Developers will be forced to make some decisions on their own, and will make design changes in order to solve a real problem which was not considered when the model was created. They create a design that slips away from the model, making it less relevant.

If the analysts work independently, they will eventually create a model. When this model is passed to the designers, some of the analysts’ knowledge about the domain and the model is lost. While the model might be expressed in diagrams and writing, chances are the designers won’t grasp the entire meaning of the model, or the relationships between some objects, or their behavior. There are details in a model which are not easily expressed in a diagram, and may not be fully presented even in writing. The developers will have a hard time figuring them out. In some cases they will make some assumptions about the intended behavior, and it is possible for them to make the wrong ones, resulting in incorrect functioning of the program.

Analysts have their own closed meetings where many things are discussed about the domain, and there is a lot of knowledge sharing. They create a model which is supposed to contain all that information in a condensed form, and the developers have to assimilate all of it by reading the documents given to them. It would be much more productive if the developers could join the analyst meetings and have thus attain a clear and complete view of the domain and the model before they start designing the code.

Connect model and code design

A better approach is to closely relate domain modeling and design. The model should be constructed with an eye open to the software and design considerations. Developers should be included in the modeling process. The main idea is to choose a model which can be appropriately expressed in software, so that the design process is straightforward and based on the model. Tightly relating the code to an underlying model gives the code meaning and makes the model relevant.

Getting the developers involved provides feedback. It makes sure that the model can be implemented in software. If something is wrong, it is identified at an early stage, and the problem can be easily corrected.

Those who write the code should know the model very well, and should feel responsible for its integrity. They should realize that a change to the code implies a change to the model; otherwise they will refactor the code to the point where it no longer expresses the original model. If the analyst is separated from the implementation process, he will soon lose his concern about the limitations introduced by development. The result is a model which is not practical.

Any technical person contributing to the model must spend some time touching the code, whatever primary role he or she plays on the project. Anyone responsible for changing code must learn to express a model through the code. Every developer must be involved in some level of discussion about the model and have contact with domain experts. Those who contribute in different ways must consciously engage those who touch the code in a dynamic exchange of model ideas through the Ubiquitous Language.

If the design, or some central part of it, does not map to the domain model, that model is of little value, and the correctness of the software is suspect. At the same time, complex mappings between models and design functions are difficult to understand and, in practice, impossible to maintain as the design changes. A deadly divide opens between analysis and design so that insight gained in each of those activities does not feed into the other.

Design a portion of the software system to reflect the domain model in a very literal way, so that mapping is obvious. Revisit the model and modify it to be implemented more naturally software, even as you seek to make it reflect deeper insight in the domain. Demand a single model that serves both purpose well, in addition to supporting a fluent Ubiquitous Language.

Draw from the model the terminology used in the design and the basic assignment of responsibilities. The code becomes an expression of the model, so a change to the code may be a change to the model. Its effect must ripple through the rest of the project’s activities accordingly.

To tightly tie the implementation to a model usually requires software development tools and languages that support a modeling paradigm, such as object-oriented programming.

The building blocks of a model driven design

When we create a software application, a large part of the application is not directly related to the domain, but it is part of the infrastructure or serves the software itself. It is possible and ok for the domain part of an application to be quite small compared to the rest, since a typical application contains a lot of code related to database access, file or network access, user interfaces, etc.

In an object-oriented program, UI, database, and other support code often gets written directly into the business objects. Additional business logic is embedded in the behavior of UI widgets and database scripts. This some times happens because it is the easiest way to make things work quickly.

However, when domain-related code is mixed with the other layers, it becomes extremely difficult to see and think about. Superficial changes to the UI can actually change business logic. To change a business rule may require meticulous tracing of UI code, database code, or other program elements. Implementing coherent, model-driven objects becomes impractical. Automated testing is awkward. With all the technologies and logic involved in each activity, a program must be kept very simple or it becomes impossible to understand.

Therefore, partition a complex program into LAYERS. Develop a design within each LAYER that is cohesive and that depends only on the layers below. Follow standard architectural patterns to provide loose coupling to the layers above. Concentrate all the code related to the domain model in one layer and isolate it from the user interface, application, and infrastructure code. The domain objects, free of the responsibility of displaying themselves, storing themselves, managing application tasks, and so forth, can be focused on expressing the domain model. This allows a model to evolve to be rich enough and clear enough to capture essential business knowledge and put it to work.

  • User Interface (Presentation Layer)

    Responsible for presenting information to the user and interpreting user commands.

  • Application Layer

    This is a thin layer which coordinates the application activity. It does not contain business logic. It does not hold the state of the business objects, but it can hold the state of an application task progress.

  • Domain Layer

    This layer contains information about the domain. This is the heart of the business software. The state of business objects is held here. Persistence of the business objects and possibly their state is delegated to the infrastructure layer.

  • Infrastructure Layer

    This layer acts as a supporting library for all the other layers. It provides communication between layers, implements persistence for business objects, contains supporting libraries for the user interface layer, etc.

It is important to divide an application in separate layers, and establish rules of interactions between the layers. If the code is not clearly separated into layers, it will soon become so entangled that it becomes very difficult to manage changes. One simple change in one section of the code may have unexpected and undesirable results in other sections. The domain layer should be focused on core domain issues. It should not be involved in infrastructure activities. The UI should neither be tightly connected to the business logic, nor to the tasks which normally belong to the infrastructure layer. An application layer is necessary in many cases. There has to be a manager over the business logic which supervises and coordinates the overall activity of the application.

Entity

There is a category of objects which seem to have an identity, which remains the same throughout the states of the software. For these objects it is not the attributes which matter, but a thread of continuity and identity, which spans the life of a system and can extend beyond it. Such objects are called Entities

Therefore, implementing entities in software means creating identity. For a person it can be a combination of attributes: name, date of birth, place of birth, name of parents, current address. The Social Security number is also used in US to create identity. For a bank account the account number seems to be enough for its identity. Usually the identity is either an attribute of the object, a combination of attributes, an attribute specially created to preserve and express identity, or even a behavior. It is important for two objects with different identities to be to be easily distinguished by the system, and two objects with the same identity to be considered the same by the system. If that condition is not met, then the entire system can become corrupted.

Value Objects

We may be tempted to make all objects entities. Entities can be tracked. But tracking and creating identity comes with a cost. We need to make sure that each instance has its unique identity, and tracking identity is not very simple

If we don't need to keep track of an object, then it is value objects.

A value object can be immutable or mutable. But it is highly recommended that value objects be immutable. They are created with a constructor, and never modified during their life time.When you want a different value for the object, you simply create another one. This has important consequences for the design. Being immutable, and having no identity, Value Objects can be shared. That can be imperative for some designs. Immutable objects are sharable with important performance implications. They also manifest integrity, i.e. data integrity. Imagine what it would mean to share an object which is not immutable. An air travel booking system could create objects for each flight. One of the attributes could be the flight code. One client books a flight for a certain destination. Another client wants to book the same flight. The system chooses to reuse the object which holds the flight code, because it is about the same flight. In the meantime, the client changes his mind, and chooses to take a different flight. The system changes the flight code because this is not immutable. The result is that the flight code of the first client changes too.

One golden rule is: if Value Objects are shareable, they should be immutable. Value Objects should be kept thin and simple. When a Value Object is needed by another party, it can be simply passed by value, or a copy of it can be created and given. Making a copy of a Value Object is simple, and usually without any consequences. If there is no identity, you can make as many copies as you wish, and destroy all of them when necessary.

Services

A Service should not replace the operation which normally belongs on domain objects. We should not create a Service for every operation needed. But when such an operation stands out as an important concept in the domain, a Service should be created for it. There are three characteristics of a Service:

  1. The operation performed by the Service refers to a domain concept which does not naturally belong to an Entity or Value Object.
  2. The operation performed refers to other objects in the domain.
  3. The operation is stateless.

When a significant process or transformation in the domain is not a natural responsibility of an Entity or Value Object, add an operation to the model as a standalone interface declared as a Service. Define the interface in terms of the language of the model and make sure the operation name is part of the Ubiquitous Language. Make the Service stateless.

While using Services, is important to keep the domain layer isolated. It is easy to get confused between services which belong to the domain layer, and those belonging to the infrastructure. There can also be services in the application layer which adds a supplementary level of complexity. Those services are even more difficult to separate from their counterparts residing in the domain layer. While working on the model and during the design phase, we need to make sure that the domain level remains isolated from the other levels.

Both application and domain Services are usually built on top of domain Entities and Values providing required functionality directly related to those objects. Deciding the layer a Service belongs to is difficult. If the operation performed conceptually belongs to the application layer, then the Service should be placed there. If the operation is about domain objects, and is strictly related to the domain, serving a domain need, then it should belong to the domain layer.