Applying the Application Layer in Domain-Driven Design

Peter Veentjer published his second post on Domain-Driven Design in which he questions the need for a Service Layer. First, the Service Layer is what Eric Evans calls the Application Layer. Let’s see what Eric has to say about this particular layer in his excellent book Domain-Driven Design.

Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.

According to Peter the Application Layer is still very useful for security, transactions, decoupling and as a facility to store application logic. I’m not sure about the security and transactions in the service layer since it leads to the problem of not isolating the domain. The all seeing eye Frans Bouma responded with:

How can the Application Layer coordinate tasks and delegate work if it doesn’t contain business rules?

Interesting question!

Let’s concentrate on DDD and the patterns that play a role in this discussion: Application Layer, Domain Layer, Infrastructure Layer, Application Service, Domain Service, and Infrastructure Service. With these patterns in mind I tend to agree with Eric that it is straightforward to identity Infrastructure Services, but significantly harder to distinguish Application from Domain services. What I find a big help in separating the apples from the oranges is thinking in terms of application workflow. All logic concerning the application workflow typically end up being Application Services factored into the Application Layer, whereas concepts from the domain that don’t seem to fit as model objects end up forming one or more Domain Services. Otherwise you’ll be definitely messing up a real model object which, in my opinion, has been done in Peter’s example. Human Resource Management fires people, since they are the ones that know the details about the “firing policy”, that is, assuming I am the domain expert in this case. To capture this important domain concept I would introduce the HrmService, Domain Service in the Domain Layer. This way the Application Layer does not contain any domain/business related logic and focuses on the application logic only.

Now let’s see what Jimmy Nilsson has to say about the Application Layer in his more down to earth book Applying Domain-Driven Design and Patterns.

The Application Layer isn’t mandatory; it is only there if it really adds value. Since my Domain Layer is so much richer than before, it’s often not interesting with the Application Layer.

Right on the spot! So, the question remains: when do we need an Application Layer and Application Services? Imagine we need to build an application on top of our Domain Model using the HrmService, Domain Service to accept an employee-firing request from this big SAP system. It requires the HrmService to determine whether it’s possible to fire the given employee by interacting with the necessary Employee, EmployeeFile, ContractFile and FirePolicy objects. We also need to communicate the advice by sending e-mails, letters and other communications for which we use the Infrastructure Layer. We now have captured a small part of the application workflow which fits nicely inside the Application Layer. Now part of the Application Layer’s responsibility is to digest the employee-firing request and send a message to the HrmService, Domain Service for fulfillment. It then decides to send notifications to the Infrastructure Service.

It’s important to note that the domain layer isn’t being distracted from representing the important concepts of the business, a healthy heart I'd say!

24 Comments

  • What I find important about a service layer is that it encapsulates how external parties interact with "the system". In an SOA, where a system needs to respond to messages, the message handler classes belong in the service layer. They are responsible for taking the results of the handling of a message, building one or more "response" messages, and sending them back to the requester, or possibly publishing them to many subscribers.

    If workflow is a large part of your logic, it too should be encapsulated. I'm referring to the application layer here, but I prefer to call it the workflow layer. In this layer, we'd have all the rules that the rules engine runs. If you don't use a rules engine, there is one more case that I've found the workflow layer useful for. And that is to manage long running workflows.

    In any and all cases, nothing is taken away from the domain layer.

  • I haven't been reading up on my RSS Feeds, and this seems like an interesting discussion I have to trackback to its root! :)

    Anyway, as far as I can tell, I totally agree with you here Paul.

    Udi Dahan calls it workflow layer and I have to agree I find that name (or process layer) much easier to use in discussions.

  • For an application logic itself, IF NECCESSARY, we can use an application layer to separate maybe transactions, or so called application logics.

    But, for architecture view, a service layer (really same as application layer?) like contracts of services, by which, external or local comsumers (ready for SOA) may use them. They can decouple the service implementaion from the service interfaces, which means in this kind of service interface definitions, only common data types or public shared data types should be used so that even external comsumer without any knowledge of your service implementaion can use them.

  • I know this is a late comment, but I want to say that this post helped me tremendously with figuring out how to identify when to use an Application Service. My example is this (simple I know, but useful to illustrate):

    I have a web portal that allows different types of users to log in and carry out some admin activities. If a user forgets his/her password, they can ask to have it reset. This involves the following steps...

    - Find the user account by email. (using a repository)
    - Make sure the account is eligible to have the password reset. (rule that can be checked within the account object.)
    - Generate a new password and assign it to the account. (static method on account class)
    - Change the account's status to "Pending", which will require them to change their password before being granted access. (using account object)
    - Persist changes to the account. (using repository)
    - Send an email to the user with the new password and instructions. (using an email service)

    So, you can see that the process involves domain repositories, domain entities, and an infrastructure service (for emailing). Also, I want to make sure all of these go off without a problem (so now we have a transaction scope.)

    Finally, we have multiple places in our application where this process can be carried out. It can be requested by the user, it can be initiated by an admin within the user management screens, or it can be initiated through a web service call.

    In previous days, I would have added a method to a all-encompassing "AccountManager" class that reset the password. After reading DDD and lots of posts online, I am leaning toward an "Application Service" called ResetPasswordService, which handles and coordinates these activities.

    Anyway, I would be interested in hearing comments on my thought process and to see if I am on track with this.

    Thanks!

    Kevin

  • to make Kevin Warner's example more domain driven, i think the policies to reset password should be encapsulated into the Account class resetPassword method.
    ResetPasswordService is unnecessary because we ONLY reset password of Account. we will not reset password of Door, Safe, Device, etc using the same ResetPasswordService (which was designed for account).
    anyway it's just my opinion.

  • Hi all,
    I have been following this thread with interest. Tying in to the debate on the viability of the service layer and whether or not one should have one at all and if one does wheither it should have business rules, I'd like your thoughts on the following scenario. I am currently designing a BPM/SOA application using workflow services. The workflows contain the application logic and the business rules engine, relying on domain objects for implementation which in turn communicate with repositories that encapsulate the persistence logic. I'm using DTOs to pass data between tiers. Does this design violate the tenets of DDD? Does removing the business rules from the domain layer make my domain anaemic?

  • Is repository considered as service? Domain service or application service? And is it sensible for model to *talk* to services?

  • I have seen approaches that, in the example of that employee-firing, the domain service is called from the domain entity. E.g. employee.Fire() would call the EmployeeFiringService to coordinate the firing logic across different domain entities and infrastructure layer. Is it a correct approach? Or it's preferable to rather have one-way service->domain relationship?

  • How is that relevant?

  • Very good journey and experience!

  • Как писали в 2NT.ru Парень предлагает пожить в гражданском браке , а мне может показаться на первый взгляд что гражданский брак это что-то не подразумевающее под собой серьёзных отношений . Нечто с чем просто можно расстаться просто собрав вещи и разбежаться с мотивацией "не сошлись нравами".Это так как было несерьёзно . Мне хочется стабильности и пресловутого мужского плеча , но для мужчин по-моему брак ничего символичного в себе не несёт и ответственности не налагает , он воспринимается только пачкотнёй в паспорте и буквально каждый день можно развестись.Для меня совместное размещение не может быть пробным .Я так как дама, мне нужно будет обустраивать гнёздышко и делать уют ,строить какаие-то планы чтобы тогда а в случае в случае если что не так с этим расстаться ?Я как-то заблаговременно с этим не согласна .А как-бы вы поступили на моём месте ?
    К стати меня можно найти и в поисковых системах по нику Rinata Pi7

  • Как говорилось на Seexi.net Двое мужчин: один взрослый, внешне не привлекателен, но в сексе подходит на все 100% - бывалый любовник, знает как доставить наслаждение даме, в постели с ним можно проводить сутки напролет, короче Бог!
    Второй - молодой, привлекательный, но неопытный и в сексе вообще никакой! Даже анатомически мне не подходит – своими непрезентабельными размерами!
    Они оба мне нравятся, у каждого есть свои плюсы и минусы, и обоим нравлюсь я!
    Вопрос: кого выбрать, чтоб потом не пожалеть? Может кто-нибудь уже делал прежде такой выбор – посоветуйте что-нибудь, пожалуйста!

  • Никогда не бей лежачего, ведь он может встать. Эмблема Серп и Молот. Коси и Забивай! Из рекламы шампуня:Раньше мои волосы были сухими и безжизненными,а теперь они сырые и шевелятся. Картина: “Иван Грозный делает контрольный выстрел”.

  • Never, never, never, never give up

    -----------------------------------

  • -----------------------------------------------------------
    Make sure you, are you able to PM me and inform me few additional thinks about this, I am genuinely fan of the web site.!.gets solved correctly asap."

  • -----------------------------------------------------------
    "you know, i used to be just thinking of how poor people are getting when they're attempting to industry a site, i mean, for instance, have a look at this spot, nothing but spam. seems so desperate, why not only do adverts instead of spamming all the time."

  • I prefer to take breaks throughout the day and browse by way of some blogs to determine what others are saying. This weblog appeared in my searches and I couldn't aid but clicking on it. I'm pleased I did since it had been a incredibly fulfilling study.

    --------------------------------------------------------------------
    Biological Sciences in Dental Medicine

  • ixvmiz retractable awnings rko

  • Hello! I love watching football and I loved your blog as well.

  • upghfhxfilx ee xult

  • Your writing is superior and gives food for thought. I hope that I'll have a lot more time to go via your content. Regards. I wish that you basically publish new texts and invite you to greet me.

  • I myself was an abused wife. My husband at the time would hit me and tell me if I had not made him mad it would not have happened. He broke my ribs,bruised me, locked me in closets, put me down in front of others, called me names and told me no one else would want me because I was worth nothing. He refused to let me cook, clean or do anything. Be cause he said I was not smart enough. This also happened in front of my sons. The beatings got worse so I had to leave. Now my life is better. I am going to collage and in a good relationship. My advice to you is to leave and get help repairing your self esteem. I can tell you from experience that it takes a long time but in the end it is worth it. You are worth more than letting a man beat you. If you stay it will never get any better no matter what he promises you. It is not your fault for what he is doing. I always thought it was my fault but learned through therapy it was not. He needs help for his problem. Unless he helps himself you cannot help him. I know it is painful to think of a life on your own but it gets better. The love of friends and family can help you. Good luck.

  • I'll start off saying that I have no idea what to do with my life. I had aspirations to be a video game designer when I was 11 or so, but a few years later my Dad finally proved to me that going into such a competitive, fast paced field isn't the wisest move. Other than that, I've never had an overall goal for my life.

    So now I'm almost 23, and I'm finally gritting my teeth making that big push towards getting my life going. I'm at absolute zero as far as life goes. Single, no debt, unemployed, clean record, average GPA, High School Diploma...so maybe that isn't exactly zero, but that's about where I'd place myself.

    My current plans are to join the Air Force and take advantage of the GI Bill, which covers up to 4 years of college after serving a minimum of 2 years, or 3 years for full monetary benefits. It's at this point I realized I need a heading, a goal...and fast.

    I have a considerably high IQ, I just never really applied myself to anything. I can't list much for my interests. I love the English language, reading, writing, poetry. I love philosophy and psychology, and who doesn't love technology and video games? But I don't know if I'm interested enough for a career in those fields. Basically, I wrote that out to help you help me, but please don't confine your ideas to those boundaries.

    With the military, I can get a Bachelor's Degree. I think this is the most realistic end-game goal. Maybe I could push for a higher degree in the future, but I don't have to plan that far, and who knows what the future holds?

    There's always the idea of owning my own business when all is said and done. I've never liked the idea of people making money off of my work, but everyone has a price right?

    I wanted to post this on this forum because this website is a great resource for job trends, but I don't even know what to type in the search engine, and I really want a 6 year projection. The job market is constantly changing and evolving, so where's it going?

  • Whats up,

    I need these people to help me with a scratched wooden floor and stairs. I don't have much money for this so be sure to bear this in mind when recommending feasible options.

    I'd love to hear back from you

    Thanks a lot

Comments have been disabled for this content.