Is domain driven design an anti-SQL pattern?Do stored procedures violate three-tier separation?Are Domain Objects in Domain Driven Design only supposed to be write-only?Breaking the “ubiquitous language” by having an IoC Container in Domain Model?Domain driven design and WCF services architectureShould I use the repository in the Domain Object or push the Domain Object back to the Service Layer?In DDD, is validation application logic, or domain logic?How to structure a Domain Driven Design in an Onion Architecture?Domain Driven Design in Net - Project StructureDomain validation accessible by the presentation layerDomain Driven Design in an Onion ArchitectureDDD accessing reference values in Domain layer without repositories

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

How to move the player while also allowing forces to affect it

Re-submission of rejected manuscript without informing co-authors

Can I find out the caloric content of bread by dehydrating it?

What to wear for invited talk in Canada

Are objects structures and/or vice versa?

Is domain driven design an anti-SQL pattern?

Filling an area between two curves

Does bootstrapped regression allow for inference?

Information to fellow intern about hiring?

What causes the sudden spool-up sound from an F-16 when enabling afterburner?

Why is the design of haulage companies so “special”?

Is "plugging out" electronic devices an American expression?

COUNT(*) or MAX(id) - which is faster?

Is this food a bread or a loaf?

What do the Banks children have against barley water?

Denied boarding due to overcrowding, Sparpreis ticket. What are my rights?

Is there any use for defining additional entity types in a SOQL FROM clause?

What is the command to reset a PC without deleting any files

Ideas for 3rd eye abilities

I see my dog run

What are the advantages and disadvantages of running one shots compared to campaigns?

Pristine Bit Checking

Are cabin dividers used to "hide" the flex of the airplane?



Is domain driven design an anti-SQL pattern?


Do stored procedures violate three-tier separation?Are Domain Objects in Domain Driven Design only supposed to be write-only?Breaking the “ubiquitous language” by having an IoC Container in Domain Model?Domain driven design and WCF services architectureShould I use the repository in the Domain Object or push the Domain Object back to the Service Layer?In DDD, is validation application logic, or domain logic?How to structure a Domain Driven Design in an Onion Architecture?Domain Driven Design in Net - Project StructureDomain validation accessible by the presentation layerDomain Driven Design in an Onion ArchitectureDDD accessing reference values in Domain layer without repositories






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








22















I am diving in the domain driven design (DDD) and while I go more deeply in it there are some things that I don't get. As I understand it, a main point is to split the Domain Logic (Business Logic) from the Infrastructure (DB, File System, etc.).



What I am wondering is, what happens when I have very complex queries like a Material Resource Calculation Query? In that kind of query you work with heavy set operations, the kind of thing that SQL was designed for. Doing those calculations inside the Domain Layer and working with a lot of sets in it is like throwing away the SQL technology.



Doing these calculations in the infrastructure can't happen too, because the DDD pattern allows for changes in the infrastructure without changing the Domain Layer and knowing that MongoDB doesn't have the same capabilities of e.g. SQL Server, that can't happen.



Is that a pitfall of the DDD pattern?










share|improve this question









New contributor




Leonardo Mangano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 14





    While SQL is designed to handle relational set algebra, it is not a fun day when you realize that half of your business logic is buried in a handful of SQL functions that are hard to refactor and even harder to test. So, moving this to the domain layer where it can play with its friends sounds appealing to me. Is this throwing away a good chunk of the SQL technology? Sure, but SQL is a lot easier to manage when you're only using SELECT/JOIN.

    – Jared Goguen
    16 hours ago







  • 14





    @JaredGoguen but this can be because your not an SQL expert and not because of the technology

    – Leonardo Mangano
    16 hours ago











  • Related: softwareengineering.stackexchange.com/q/170808/20756

    – Blrfl
    16 hours ago











  • I'm not sure what you mean by "can't happen" in the last part or why allowed changes in the infrastructure is a barrier, if that's what you are saying.

    – JimmyJames
    15 hours ago






  • 1





    @JimmyJames what I tried to say is that if the DDD is well implemented it allows to change layers with the minimum effort, like switching from SQL Server to MongoDB. But, if have complex queries in the SQL, it's possible that I won't be able to switch to MongoDB because their technical differences. I think I said a obvious thing.

    – Leonardo Mangano
    15 hours ago


















22















I am diving in the domain driven design (DDD) and while I go more deeply in it there are some things that I don't get. As I understand it, a main point is to split the Domain Logic (Business Logic) from the Infrastructure (DB, File System, etc.).



What I am wondering is, what happens when I have very complex queries like a Material Resource Calculation Query? In that kind of query you work with heavy set operations, the kind of thing that SQL was designed for. Doing those calculations inside the Domain Layer and working with a lot of sets in it is like throwing away the SQL technology.



Doing these calculations in the infrastructure can't happen too, because the DDD pattern allows for changes in the infrastructure without changing the Domain Layer and knowing that MongoDB doesn't have the same capabilities of e.g. SQL Server, that can't happen.



Is that a pitfall of the DDD pattern?










share|improve this question









New contributor




Leonardo Mangano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 14





    While SQL is designed to handle relational set algebra, it is not a fun day when you realize that half of your business logic is buried in a handful of SQL functions that are hard to refactor and even harder to test. So, moving this to the domain layer where it can play with its friends sounds appealing to me. Is this throwing away a good chunk of the SQL technology? Sure, but SQL is a lot easier to manage when you're only using SELECT/JOIN.

    – Jared Goguen
    16 hours ago







  • 14





    @JaredGoguen but this can be because your not an SQL expert and not because of the technology

    – Leonardo Mangano
    16 hours ago











  • Related: softwareengineering.stackexchange.com/q/170808/20756

    – Blrfl
    16 hours ago











  • I'm not sure what you mean by "can't happen" in the last part or why allowed changes in the infrastructure is a barrier, if that's what you are saying.

    – JimmyJames
    15 hours ago






  • 1





    @JimmyJames what I tried to say is that if the DDD is well implemented it allows to change layers with the minimum effort, like switching from SQL Server to MongoDB. But, if have complex queries in the SQL, it's possible that I won't be able to switch to MongoDB because their technical differences. I think I said a obvious thing.

    – Leonardo Mangano
    15 hours ago














22












22








22


5






I am diving in the domain driven design (DDD) and while I go more deeply in it there are some things that I don't get. As I understand it, a main point is to split the Domain Logic (Business Logic) from the Infrastructure (DB, File System, etc.).



What I am wondering is, what happens when I have very complex queries like a Material Resource Calculation Query? In that kind of query you work with heavy set operations, the kind of thing that SQL was designed for. Doing those calculations inside the Domain Layer and working with a lot of sets in it is like throwing away the SQL technology.



Doing these calculations in the infrastructure can't happen too, because the DDD pattern allows for changes in the infrastructure without changing the Domain Layer and knowing that MongoDB doesn't have the same capabilities of e.g. SQL Server, that can't happen.



Is that a pitfall of the DDD pattern?










share|improve this question









New contributor




Leonardo Mangano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












I am diving in the domain driven design (DDD) and while I go more deeply in it there are some things that I don't get. As I understand it, a main point is to split the Domain Logic (Business Logic) from the Infrastructure (DB, File System, etc.).



What I am wondering is, what happens when I have very complex queries like a Material Resource Calculation Query? In that kind of query you work with heavy set operations, the kind of thing that SQL was designed for. Doing those calculations inside the Domain Layer and working with a lot of sets in it is like throwing away the SQL technology.



Doing these calculations in the infrastructure can't happen too, because the DDD pattern allows for changes in the infrastructure without changing the Domain Layer and knowing that MongoDB doesn't have the same capabilities of e.g. SQL Server, that can't happen.



Is that a pitfall of the DDD pattern?







domain-driven-design database-design sql database-development






share|improve this question









New contributor




Leonardo Mangano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Leonardo Mangano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 14 hours ago









Freiheit

648615




648615






New contributor




Leonardo Mangano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 16 hours ago









Leonardo ManganoLeonardo Mangano

11416




11416




New contributor




Leonardo Mangano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Leonardo Mangano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Leonardo Mangano is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 14





    While SQL is designed to handle relational set algebra, it is not a fun day when you realize that half of your business logic is buried in a handful of SQL functions that are hard to refactor and even harder to test. So, moving this to the domain layer where it can play with its friends sounds appealing to me. Is this throwing away a good chunk of the SQL technology? Sure, but SQL is a lot easier to manage when you're only using SELECT/JOIN.

    – Jared Goguen
    16 hours ago







  • 14





    @JaredGoguen but this can be because your not an SQL expert and not because of the technology

    – Leonardo Mangano
    16 hours ago











  • Related: softwareengineering.stackexchange.com/q/170808/20756

    – Blrfl
    16 hours ago











  • I'm not sure what you mean by "can't happen" in the last part or why allowed changes in the infrastructure is a barrier, if that's what you are saying.

    – JimmyJames
    15 hours ago






  • 1





    @JimmyJames what I tried to say is that if the DDD is well implemented it allows to change layers with the minimum effort, like switching from SQL Server to MongoDB. But, if have complex queries in the SQL, it's possible that I won't be able to switch to MongoDB because their technical differences. I think I said a obvious thing.

    – Leonardo Mangano
    15 hours ago













  • 14





    While SQL is designed to handle relational set algebra, it is not a fun day when you realize that half of your business logic is buried in a handful of SQL functions that are hard to refactor and even harder to test. So, moving this to the domain layer where it can play with its friends sounds appealing to me. Is this throwing away a good chunk of the SQL technology? Sure, but SQL is a lot easier to manage when you're only using SELECT/JOIN.

    – Jared Goguen
    16 hours ago







  • 14





    @JaredGoguen but this can be because your not an SQL expert and not because of the technology

    – Leonardo Mangano
    16 hours ago











  • Related: softwareengineering.stackexchange.com/q/170808/20756

    – Blrfl
    16 hours ago











  • I'm not sure what you mean by "can't happen" in the last part or why allowed changes in the infrastructure is a barrier, if that's what you are saying.

    – JimmyJames
    15 hours ago






  • 1





    @JimmyJames what I tried to say is that if the DDD is well implemented it allows to change layers with the minimum effort, like switching from SQL Server to MongoDB. But, if have complex queries in the SQL, it's possible that I won't be able to switch to MongoDB because their technical differences. I think I said a obvious thing.

    – Leonardo Mangano
    15 hours ago








14




14





While SQL is designed to handle relational set algebra, it is not a fun day when you realize that half of your business logic is buried in a handful of SQL functions that are hard to refactor and even harder to test. So, moving this to the domain layer where it can play with its friends sounds appealing to me. Is this throwing away a good chunk of the SQL technology? Sure, but SQL is a lot easier to manage when you're only using SELECT/JOIN.

– Jared Goguen
16 hours ago






While SQL is designed to handle relational set algebra, it is not a fun day when you realize that half of your business logic is buried in a handful of SQL functions that are hard to refactor and even harder to test. So, moving this to the domain layer where it can play with its friends sounds appealing to me. Is this throwing away a good chunk of the SQL technology? Sure, but SQL is a lot easier to manage when you're only using SELECT/JOIN.

– Jared Goguen
16 hours ago





14




14





@JaredGoguen but this can be because your not an SQL expert and not because of the technology

– Leonardo Mangano
16 hours ago





@JaredGoguen but this can be because your not an SQL expert and not because of the technology

– Leonardo Mangano
16 hours ago













Related: softwareengineering.stackexchange.com/q/170808/20756

– Blrfl
16 hours ago





Related: softwareengineering.stackexchange.com/q/170808/20756

– Blrfl
16 hours ago













I'm not sure what you mean by "can't happen" in the last part or why allowed changes in the infrastructure is a barrier, if that's what you are saying.

– JimmyJames
15 hours ago





I'm not sure what you mean by "can't happen" in the last part or why allowed changes in the infrastructure is a barrier, if that's what you are saying.

– JimmyJames
15 hours ago




1




1





@JimmyJames what I tried to say is that if the DDD is well implemented it allows to change layers with the minimum effort, like switching from SQL Server to MongoDB. But, if have complex queries in the SQL, it's possible that I won't be able to switch to MongoDB because their technical differences. I think I said a obvious thing.

– Leonardo Mangano
15 hours ago






@JimmyJames what I tried to say is that if the DDD is well implemented it allows to change layers with the minimum effort, like switching from SQL Server to MongoDB. But, if have complex queries in the SQL, it's possible that I won't be able to switch to MongoDB because their technical differences. I think I said a obvious thing.

– Leonardo Mangano
15 hours ago











6 Answers
6






active

oldest

votes


















22














These days, you are likely to see reads (queries) handled differently than writes (commands). In a system with a complicated query, the query itself is unlikely to pass through the domain model (which is primarily responsible for maintaining the consistency of writes).



You are absolutely right that we should render unto SQL that which is SQL. So we'll design a data model optimized around the reads, and a query of that data model will usually take a code path that doesn't not include the domain model (with the possible exception of some input validation -- ensuring that parameters in the query are reasonable).






share|improve this answer


















  • 6





    +1 Good answer, but you should give this concept its proper name, Command-Query Segregation.

    – Mike
    15 hours ago






  • 2





    @Mike Having completely different models for reading and writing is more like CQRS rather than CQS.

    – Andy
    14 hours ago






  • 2





    The "read model" is not the domain model (or part of it)? I am not an expert on CQRS, but I always thought the command model is quite different from the classic domain model, but not the read model. So maybe you can give an example for this?

    – Doc Brown
    12 hours ago



















13














If you've ever been on a project where the organization paying to host the application decides that the database layer licenses are too expensive, you'll appreciate the ease of which you can migrate your database/data storage. All things considered, while this does happen, it doesn't happen often.



You can get the best of both worlds so to speak. If you consider performing the complex functions in the database an optimization, then you can use an interface to inject an alternate implementation of the calculation. The problem is that you have to maintain logic in multiple locations.



Deviating from an architectural pattern



When you find yourself at odds with implementing a pattern purely, or deviating in some area, then you have a decision to make. A pattern is simply a templated way to do things to help organize your project. At this point take time to evaluate:



  • Is this the right pattern? (many times it is, but sometimes it's just a bad fit)

  • Should I deviate in this one way?

  • Just how far have I deviated so far?

You'll find that some architectural patterns are a good fit for 80-90% of your application, but not so much for the remaining bits. The occasional deviation from the prescribed pattern is useful for performance or logistical reasons.



However, if you find that your cumulative deviations amount to a good deal more than 20% of your application architecture, it's probably just a bad fit.



If you choose to keep going with the architecture, then do yourself a favor and document where and why you deviated from the prescribed way of doing things. When you get a new enthusiastic member on your team, you can point them to that documentation which includes the performance measurements, and justifications. That will reduce the likelihood of repeat requests to fix the "problem". That documentation will also help disincentivize rampant deviations.






share|improve this answer























  • I would avoid the use of phrases like "is this the right pattern" in answers. It's hard enough to get people to be specific when they write their questions, and by your own admission "sometimes it's a bad fit," which suggests that no, it's not the right pattern.

    – Robert Harvey
    14 hours ago


















5














The set manipulation logic that SQL is good at can be integrated with DDD no problem.



Say for example I need to know some aggregate value, total count of product by type. Easy to run in sql, but slow if I load every product into memory and add them all up.



I simply introduce a new Domain object,



ProductInventory

ProductType
TotalCount
DateTimeTaken



and a method on my repository



ProductRepository

List<ProductInventory> TakeInventory(DateTime asOfDate) ...



Sure, maybe I am now relying on my DB having certain abilities. But I still technically have the separation and as long as the logic is simple, I can argue that it is not 'business logic'






share|improve this answer























  • Well, so far I recall. Repositories are supposed to get Query as parameters too. repository.find(query);. I have read the same but with Specs. That opens a door to leave Query` as an abstraction and QueryImpl or the specific-query implementation to the infrastructure layer.

    – Laiv
    15 hours ago







  • 1





    oh god, I know some people do that but I think it's awful. You can view this kind of thing as a step down that road. But I think it can be taken with caution.

    – Ewan
    15 hours ago











  • I know some people do that some people are Pivotal and its framework. SpringFramework has a lot of this:-). Anyways, As @VoiceOfUnreason has suggested, the key around DDD is keeping the consistency of the writings. I'm unsure about forcing the design with domain models whom only purpose is querying or parametrizing queries. That could be approached out of the domain with data structures (pocos, pojos, dtos, row mappers, whatever).

    – Laiv
    14 hours ago











  • obviously we need some sort of inquisition to help those people back to sanity. But I'm sticking to my guns. The partial exposure of the datalayer is acceptable when it objectively makes for a better application, where what is or isn't a "Domain Object" is subjective

    – Ewan
    14 hours ago











  • @Ewan what kind of object will be ProductInventory, Entity? Value Object? or just a class

    – Leonardo Mangano
    14 hours ago


















5















As I understand it, a main point is to split the Domain Logic (Business Logic) from the Infrastructure (DB, File System, etc.).




This is the foundation of the misunderstanding: the purpose of DDD isn't to separate things along a hard line like "this is in the SQL server, so must not be BL", the purpose of DDD is to separate domains and create barriers between them that allow the internals of a domain to be completely separate from the internals of another domain, and to define shared externals between them.



Don't think of "being in SQL" as the BL/DL barrier—that's not what it is. Instead, think of "this is the end of the internal domain" as the barrier.



Each domain should have external-facing API's that allow it to work with all the other domains: in the case of the data storage layer, it should have read/write (CRUD) actions for the data-objects it stores. This means SQL itself isn't really the barrier, the VIEW and PROCEDURE components are. You should never read directly from the table: that is the implementation detail DDD tells us that, as an external consumer, we should not worry about.



Consider your example:




What I am wondering is, what happens when I have very complex queries like a Material Resource Calculation Query? In that kind of query you work with heavy set operations, the kind of thing that SQL was designed for.




This is exactly what should be in SQL then, and it's not a violation of DDD. It's what we made DDD for. With that calculation in SQL, that becomes part of the BL/DL. What you would do is use a separate view / stored procedure / what-have-you, and keep the business logic separated from the data-layer, as that is your external API. In fact, your data-layer should be another DDD Domain Layer, where your data-layer has it's own abstractions to work with the other domain layers.




Doing these calculations in the infrastructure can't happen too, because the DDD pattern allows for changes in the infrastructure without changing the Domain Layer and knowing that MongoDB doesn't have the same capabilities of e.g. SQL Server, that can't happen.




That's another misunderstanding: it says implementation details internally can change without changing other domain layers. It doesn't say you can just replace a whole infrastructure piece.



Again, keep in mind, DDD is about hiding internals with well-defined external API's. Where those API's sit is a totally different question, and DDD doesn't define that. It simply defines that these API's exist, and should never change.



DDD isn't setup to allow you to ad-hoc replace MSSQL with MongoDB—those are two totally different infrastructure components.



Instead, let's use an analogy for what DDD defines: gas vs. electric cars. Both of the vehicles have two completely different methods for creating propulsion, but they have the same API's: an on/off, a throttle/brake, and wheels to propel the vehicle. DDD says that we should be able to replace the engine (gas or electric) in our car. It doesn't say we can replace the car with a motorcycle, and that's effectively what MSSQL → MongoDB is.






share|improve this answer

























  • Thanks for the explanation. For me is a very hard topic, everyone have a different point of view. The only thing I don't agree is the comparison between MSSQL(car) and MongoDB (motorcycle), for me the right comparison is that these are two different engines for the same car, but it's just a opinion.

    – Leonardo Mangano
    14 hours ago






  • 2





    @LeonardoMangano Ah, but they're not. MSSQL is a relational database, MongoDB is a document database. Yes, "database" describes both, but that's about as far as it goes. The read/write techniques are completely different. Instead of MongoDB, you could use Postgre or MySQL as an alternative, and that would be a valid comparison.

    – Der Kommissar
    14 hours ago











  • "You should never read directly from the table..." Madness.

    – jpmc26
    4 hours ago


















1














As usual, this is one of those things that depends on a number of factors. It's true that there's a lot that you can do with SQL. There are also challenges with using it and some practical limitations of relational databases.



As Jared Goguen notes in the comments, SQL can be very difficult to test and verify. The main factors that lead to this are that it can't (in general) be decomposed into components. In practice, a complex query must be considered in toto. Another complicating factor is that be behavior and correctness of SQL is highly dependent on the structure and content of your data. This means that testing all the possible scenarios (or even determining what they are) is often infeasible or impossible. Refactoring of SQL and modification of database structure is likewise problematic.



The other big factor that has lead to moving away from SQL is relational databases tend to only scale vertically. For example, when you build complex calculations in SQL to run in SQL Server, they are going to execute on the database. That means all of that work is using resources on the database. The more that you do in SQL, the more resources your database will need both in terms of memory and CPU. It's often less efficient to do these things on other systems but there's no practical limit to the number of additional machines you can add to such a solution. This approach is less expensive and more fault-tolerant than building a monster database server.



These issues may or may not apply to the problem at hand. If you are able to solve your problem with available database resources, maybe SQL is fine for your problem-space. You need to consider growth, however. It might be fine today but a few years down the road, the cost of adding additional resources may become a problem.






share|improve this answer






























    0














    Sequel became popular when memory were expensive, because relational data model provided possibility to normalise your data and effectively store it in the file system.



    Now memory is relatively cheap, so we can skip normalisation and store in in the format we use it or even duplicate a lot of same data for sake of speed.



    Consider database as simple IO device, which responsibility to store data in the file system - yes I know it is difficult to imagine it, because we wrote plenty of applications with important business logic written into SQL queries - but just try to imagine that SQL Server is just another printer.



    Would you embedded PDF generator into printer driver or added a trigger which will print log page for every sales order printed out of our printer?



    I assume the answer will be no, because we don't want that our application are coupled to the specific device type (not even talking about efficiency of such idea)



    In 70's- 90's SQL database were efficient, now? - Not sure, in some scenarios asynchronous data query will returns required data faster than multiple joins in SQL query.



    SQL wasn't designed for complicated queries, it were designed for storing data in efficient way and then provide interface/language to query stored data.



    I would say building your application around relational data model with complicated queries is abuse of database engine. Of course database engine providers are happy when you tightly coupling your business to their product - they will be more than happy to provide more features which make this bound stronger.






    share|improve this answer























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "131"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: false,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );






      Leonardo Mangano is a new contributor. Be nice, and check out our Code of Conduct.









      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f389981%2fis-domain-driven-design-an-anti-sql-pattern%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown




















      StackExchange.ready(function ()
      $("#show-editor-button input, #show-editor-button button").click(function ()
      var showEditor = function()
      $("#show-editor-button").hide();
      $("#post-form").removeClass("dno");
      StackExchange.editor.finallyInit();
      ;

      var useFancy = $(this).data('confirm-use-fancy');
      if(useFancy == 'True')
      var popupTitle = $(this).data('confirm-fancy-title');
      var popupBody = $(this).data('confirm-fancy-body');
      var popupAccept = $(this).data('confirm-fancy-accept-button');

      $(this).loadPopup(
      url: '/post/self-answer-popup',
      loaded: function(popup)
      var pTitle = $(popup).find('h2');
      var pBody = $(popup).find('.popup-body');
      var pSubmit = $(popup).find('.popup-submit');

      pTitle.text(popupTitle);
      pBody.html(popupBody);
      pSubmit.val(popupAccept).click(showEditor);

      )
      else
      var confirmText = $(this).data('confirm-text');
      if (confirmText ? confirm(confirmText) : true)
      showEditor();


      );
      );






      6 Answers
      6






      active

      oldest

      votes








      6 Answers
      6






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      22














      These days, you are likely to see reads (queries) handled differently than writes (commands). In a system with a complicated query, the query itself is unlikely to pass through the domain model (which is primarily responsible for maintaining the consistency of writes).



      You are absolutely right that we should render unto SQL that which is SQL. So we'll design a data model optimized around the reads, and a query of that data model will usually take a code path that doesn't not include the domain model (with the possible exception of some input validation -- ensuring that parameters in the query are reasonable).






      share|improve this answer


















      • 6





        +1 Good answer, but you should give this concept its proper name, Command-Query Segregation.

        – Mike
        15 hours ago






      • 2





        @Mike Having completely different models for reading and writing is more like CQRS rather than CQS.

        – Andy
        14 hours ago






      • 2





        The "read model" is not the domain model (or part of it)? I am not an expert on CQRS, but I always thought the command model is quite different from the classic domain model, but not the read model. So maybe you can give an example for this?

        – Doc Brown
        12 hours ago
















      22














      These days, you are likely to see reads (queries) handled differently than writes (commands). In a system with a complicated query, the query itself is unlikely to pass through the domain model (which is primarily responsible for maintaining the consistency of writes).



      You are absolutely right that we should render unto SQL that which is SQL. So we'll design a data model optimized around the reads, and a query of that data model will usually take a code path that doesn't not include the domain model (with the possible exception of some input validation -- ensuring that parameters in the query are reasonable).






      share|improve this answer


















      • 6





        +1 Good answer, but you should give this concept its proper name, Command-Query Segregation.

        – Mike
        15 hours ago






      • 2





        @Mike Having completely different models for reading and writing is more like CQRS rather than CQS.

        – Andy
        14 hours ago






      • 2





        The "read model" is not the domain model (or part of it)? I am not an expert on CQRS, but I always thought the command model is quite different from the classic domain model, but not the read model. So maybe you can give an example for this?

        – Doc Brown
        12 hours ago














      22












      22








      22







      These days, you are likely to see reads (queries) handled differently than writes (commands). In a system with a complicated query, the query itself is unlikely to pass through the domain model (which is primarily responsible for maintaining the consistency of writes).



      You are absolutely right that we should render unto SQL that which is SQL. So we'll design a data model optimized around the reads, and a query of that data model will usually take a code path that doesn't not include the domain model (with the possible exception of some input validation -- ensuring that parameters in the query are reasonable).






      share|improve this answer













      These days, you are likely to see reads (queries) handled differently than writes (commands). In a system with a complicated query, the query itself is unlikely to pass through the domain model (which is primarily responsible for maintaining the consistency of writes).



      You are absolutely right that we should render unto SQL that which is SQL. So we'll design a data model optimized around the reads, and a query of that data model will usually take a code path that doesn't not include the domain model (with the possible exception of some input validation -- ensuring that parameters in the query are reasonable).







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered 16 hours ago









      VoiceOfUnreasonVoiceOfUnreason

      18k12051




      18k12051







      • 6





        +1 Good answer, but you should give this concept its proper name, Command-Query Segregation.

        – Mike
        15 hours ago






      • 2





        @Mike Having completely different models for reading and writing is more like CQRS rather than CQS.

        – Andy
        14 hours ago






      • 2





        The "read model" is not the domain model (or part of it)? I am not an expert on CQRS, but I always thought the command model is quite different from the classic domain model, but not the read model. So maybe you can give an example for this?

        – Doc Brown
        12 hours ago













      • 6





        +1 Good answer, but you should give this concept its proper name, Command-Query Segregation.

        – Mike
        15 hours ago






      • 2





        @Mike Having completely different models for reading and writing is more like CQRS rather than CQS.

        – Andy
        14 hours ago






      • 2





        The "read model" is not the domain model (or part of it)? I am not an expert on CQRS, but I always thought the command model is quite different from the classic domain model, but not the read model. So maybe you can give an example for this?

        – Doc Brown
        12 hours ago








      6




      6





      +1 Good answer, but you should give this concept its proper name, Command-Query Segregation.

      – Mike
      15 hours ago





      +1 Good answer, but you should give this concept its proper name, Command-Query Segregation.

      – Mike
      15 hours ago




      2




      2





      @Mike Having completely different models for reading and writing is more like CQRS rather than CQS.

      – Andy
      14 hours ago





      @Mike Having completely different models for reading and writing is more like CQRS rather than CQS.

      – Andy
      14 hours ago




      2




      2





      The "read model" is not the domain model (or part of it)? I am not an expert on CQRS, but I always thought the command model is quite different from the classic domain model, but not the read model. So maybe you can give an example for this?

      – Doc Brown
      12 hours ago






      The "read model" is not the domain model (or part of it)? I am not an expert on CQRS, but I always thought the command model is quite different from the classic domain model, but not the read model. So maybe you can give an example for this?

      – Doc Brown
      12 hours ago














      13














      If you've ever been on a project where the organization paying to host the application decides that the database layer licenses are too expensive, you'll appreciate the ease of which you can migrate your database/data storage. All things considered, while this does happen, it doesn't happen often.



      You can get the best of both worlds so to speak. If you consider performing the complex functions in the database an optimization, then you can use an interface to inject an alternate implementation of the calculation. The problem is that you have to maintain logic in multiple locations.



      Deviating from an architectural pattern



      When you find yourself at odds with implementing a pattern purely, or deviating in some area, then you have a decision to make. A pattern is simply a templated way to do things to help organize your project. At this point take time to evaluate:



      • Is this the right pattern? (many times it is, but sometimes it's just a bad fit)

      • Should I deviate in this one way?

      • Just how far have I deviated so far?

      You'll find that some architectural patterns are a good fit for 80-90% of your application, but not so much for the remaining bits. The occasional deviation from the prescribed pattern is useful for performance or logistical reasons.



      However, if you find that your cumulative deviations amount to a good deal more than 20% of your application architecture, it's probably just a bad fit.



      If you choose to keep going with the architecture, then do yourself a favor and document where and why you deviated from the prescribed way of doing things. When you get a new enthusiastic member on your team, you can point them to that documentation which includes the performance measurements, and justifications. That will reduce the likelihood of repeat requests to fix the "problem". That documentation will also help disincentivize rampant deviations.






      share|improve this answer























      • I would avoid the use of phrases like "is this the right pattern" in answers. It's hard enough to get people to be specific when they write their questions, and by your own admission "sometimes it's a bad fit," which suggests that no, it's not the right pattern.

        – Robert Harvey
        14 hours ago















      13














      If you've ever been on a project where the organization paying to host the application decides that the database layer licenses are too expensive, you'll appreciate the ease of which you can migrate your database/data storage. All things considered, while this does happen, it doesn't happen often.



      You can get the best of both worlds so to speak. If you consider performing the complex functions in the database an optimization, then you can use an interface to inject an alternate implementation of the calculation. The problem is that you have to maintain logic in multiple locations.



      Deviating from an architectural pattern



      When you find yourself at odds with implementing a pattern purely, or deviating in some area, then you have a decision to make. A pattern is simply a templated way to do things to help organize your project. At this point take time to evaluate:



      • Is this the right pattern? (many times it is, but sometimes it's just a bad fit)

      • Should I deviate in this one way?

      • Just how far have I deviated so far?

      You'll find that some architectural patterns are a good fit for 80-90% of your application, but not so much for the remaining bits. The occasional deviation from the prescribed pattern is useful for performance or logistical reasons.



      However, if you find that your cumulative deviations amount to a good deal more than 20% of your application architecture, it's probably just a bad fit.



      If you choose to keep going with the architecture, then do yourself a favor and document where and why you deviated from the prescribed way of doing things. When you get a new enthusiastic member on your team, you can point them to that documentation which includes the performance measurements, and justifications. That will reduce the likelihood of repeat requests to fix the "problem". That documentation will also help disincentivize rampant deviations.






      share|improve this answer























      • I would avoid the use of phrases like "is this the right pattern" in answers. It's hard enough to get people to be specific when they write their questions, and by your own admission "sometimes it's a bad fit," which suggests that no, it's not the right pattern.

        – Robert Harvey
        14 hours ago













      13












      13








      13







      If you've ever been on a project where the organization paying to host the application decides that the database layer licenses are too expensive, you'll appreciate the ease of which you can migrate your database/data storage. All things considered, while this does happen, it doesn't happen often.



      You can get the best of both worlds so to speak. If you consider performing the complex functions in the database an optimization, then you can use an interface to inject an alternate implementation of the calculation. The problem is that you have to maintain logic in multiple locations.



      Deviating from an architectural pattern



      When you find yourself at odds with implementing a pattern purely, or deviating in some area, then you have a decision to make. A pattern is simply a templated way to do things to help organize your project. At this point take time to evaluate:



      • Is this the right pattern? (many times it is, but sometimes it's just a bad fit)

      • Should I deviate in this one way?

      • Just how far have I deviated so far?

      You'll find that some architectural patterns are a good fit for 80-90% of your application, but not so much for the remaining bits. The occasional deviation from the prescribed pattern is useful for performance or logistical reasons.



      However, if you find that your cumulative deviations amount to a good deal more than 20% of your application architecture, it's probably just a bad fit.



      If you choose to keep going with the architecture, then do yourself a favor and document where and why you deviated from the prescribed way of doing things. When you get a new enthusiastic member on your team, you can point them to that documentation which includes the performance measurements, and justifications. That will reduce the likelihood of repeat requests to fix the "problem". That documentation will also help disincentivize rampant deviations.






      share|improve this answer













      If you've ever been on a project where the organization paying to host the application decides that the database layer licenses are too expensive, you'll appreciate the ease of which you can migrate your database/data storage. All things considered, while this does happen, it doesn't happen often.



      You can get the best of both worlds so to speak. If you consider performing the complex functions in the database an optimization, then you can use an interface to inject an alternate implementation of the calculation. The problem is that you have to maintain logic in multiple locations.



      Deviating from an architectural pattern



      When you find yourself at odds with implementing a pattern purely, or deviating in some area, then you have a decision to make. A pattern is simply a templated way to do things to help organize your project. At this point take time to evaluate:



      • Is this the right pattern? (many times it is, but sometimes it's just a bad fit)

      • Should I deviate in this one way?

      • Just how far have I deviated so far?

      You'll find that some architectural patterns are a good fit for 80-90% of your application, but not so much for the remaining bits. The occasional deviation from the prescribed pattern is useful for performance or logistical reasons.



      However, if you find that your cumulative deviations amount to a good deal more than 20% of your application architecture, it's probably just a bad fit.



      If you choose to keep going with the architecture, then do yourself a favor and document where and why you deviated from the prescribed way of doing things. When you get a new enthusiastic member on your team, you can point them to that documentation which includes the performance measurements, and justifications. That will reduce the likelihood of repeat requests to fix the "problem". That documentation will also help disincentivize rampant deviations.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered 15 hours ago









      Berin LoritschBerin Loritsch

      34.1k564136




      34.1k564136












      • I would avoid the use of phrases like "is this the right pattern" in answers. It's hard enough to get people to be specific when they write their questions, and by your own admission "sometimes it's a bad fit," which suggests that no, it's not the right pattern.

        – Robert Harvey
        14 hours ago

















      • I would avoid the use of phrases like "is this the right pattern" in answers. It's hard enough to get people to be specific when they write their questions, and by your own admission "sometimes it's a bad fit," which suggests that no, it's not the right pattern.

        – Robert Harvey
        14 hours ago
















      I would avoid the use of phrases like "is this the right pattern" in answers. It's hard enough to get people to be specific when they write their questions, and by your own admission "sometimes it's a bad fit," which suggests that no, it's not the right pattern.

      – Robert Harvey
      14 hours ago





      I would avoid the use of phrases like "is this the right pattern" in answers. It's hard enough to get people to be specific when they write their questions, and by your own admission "sometimes it's a bad fit," which suggests that no, it's not the right pattern.

      – Robert Harvey
      14 hours ago











      5














      The set manipulation logic that SQL is good at can be integrated with DDD no problem.



      Say for example I need to know some aggregate value, total count of product by type. Easy to run in sql, but slow if I load every product into memory and add them all up.



      I simply introduce a new Domain object,



      ProductInventory

      ProductType
      TotalCount
      DateTimeTaken



      and a method on my repository



      ProductRepository

      List<ProductInventory> TakeInventory(DateTime asOfDate) ...



      Sure, maybe I am now relying on my DB having certain abilities. But I still technically have the separation and as long as the logic is simple, I can argue that it is not 'business logic'






      share|improve this answer























      • Well, so far I recall. Repositories are supposed to get Query as parameters too. repository.find(query);. I have read the same but with Specs. That opens a door to leave Query` as an abstraction and QueryImpl or the specific-query implementation to the infrastructure layer.

        – Laiv
        15 hours ago







      • 1





        oh god, I know some people do that but I think it's awful. You can view this kind of thing as a step down that road. But I think it can be taken with caution.

        – Ewan
        15 hours ago











      • I know some people do that some people are Pivotal and its framework. SpringFramework has a lot of this:-). Anyways, As @VoiceOfUnreason has suggested, the key around DDD is keeping the consistency of the writings. I'm unsure about forcing the design with domain models whom only purpose is querying or parametrizing queries. That could be approached out of the domain with data structures (pocos, pojos, dtos, row mappers, whatever).

        – Laiv
        14 hours ago











      • obviously we need some sort of inquisition to help those people back to sanity. But I'm sticking to my guns. The partial exposure of the datalayer is acceptable when it objectively makes for a better application, where what is or isn't a "Domain Object" is subjective

        – Ewan
        14 hours ago











      • @Ewan what kind of object will be ProductInventory, Entity? Value Object? or just a class

        – Leonardo Mangano
        14 hours ago















      5














      The set manipulation logic that SQL is good at can be integrated with DDD no problem.



      Say for example I need to know some aggregate value, total count of product by type. Easy to run in sql, but slow if I load every product into memory and add them all up.



      I simply introduce a new Domain object,



      ProductInventory

      ProductType
      TotalCount
      DateTimeTaken



      and a method on my repository



      ProductRepository

      List<ProductInventory> TakeInventory(DateTime asOfDate) ...



      Sure, maybe I am now relying on my DB having certain abilities. But I still technically have the separation and as long as the logic is simple, I can argue that it is not 'business logic'






      share|improve this answer























      • Well, so far I recall. Repositories are supposed to get Query as parameters too. repository.find(query);. I have read the same but with Specs. That opens a door to leave Query` as an abstraction and QueryImpl or the specific-query implementation to the infrastructure layer.

        – Laiv
        15 hours ago







      • 1





        oh god, I know some people do that but I think it's awful. You can view this kind of thing as a step down that road. But I think it can be taken with caution.

        – Ewan
        15 hours ago











      • I know some people do that some people are Pivotal and its framework. SpringFramework has a lot of this:-). Anyways, As @VoiceOfUnreason has suggested, the key around DDD is keeping the consistency of the writings. I'm unsure about forcing the design with domain models whom only purpose is querying or parametrizing queries. That could be approached out of the domain with data structures (pocos, pojos, dtos, row mappers, whatever).

        – Laiv
        14 hours ago











      • obviously we need some sort of inquisition to help those people back to sanity. But I'm sticking to my guns. The partial exposure of the datalayer is acceptable when it objectively makes for a better application, where what is or isn't a "Domain Object" is subjective

        – Ewan
        14 hours ago











      • @Ewan what kind of object will be ProductInventory, Entity? Value Object? or just a class

        – Leonardo Mangano
        14 hours ago













      5












      5








      5







      The set manipulation logic that SQL is good at can be integrated with DDD no problem.



      Say for example I need to know some aggregate value, total count of product by type. Easy to run in sql, but slow if I load every product into memory and add them all up.



      I simply introduce a new Domain object,



      ProductInventory

      ProductType
      TotalCount
      DateTimeTaken



      and a method on my repository



      ProductRepository

      List<ProductInventory> TakeInventory(DateTime asOfDate) ...



      Sure, maybe I am now relying on my DB having certain abilities. But I still technically have the separation and as long as the logic is simple, I can argue that it is not 'business logic'






      share|improve this answer













      The set manipulation logic that SQL is good at can be integrated with DDD no problem.



      Say for example I need to know some aggregate value, total count of product by type. Easy to run in sql, but slow if I load every product into memory and add them all up.



      I simply introduce a new Domain object,



      ProductInventory

      ProductType
      TotalCount
      DateTimeTaken



      and a method on my repository



      ProductRepository

      List<ProductInventory> TakeInventory(DateTime asOfDate) ...



      Sure, maybe I am now relying on my DB having certain abilities. But I still technically have the separation and as long as the logic is simple, I can argue that it is not 'business logic'







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered 15 hours ago









      EwanEwan

      43.5k33697




      43.5k33697












      • Well, so far I recall. Repositories are supposed to get Query as parameters too. repository.find(query);. I have read the same but with Specs. That opens a door to leave Query` as an abstraction and QueryImpl or the specific-query implementation to the infrastructure layer.

        – Laiv
        15 hours ago







      • 1





        oh god, I know some people do that but I think it's awful. You can view this kind of thing as a step down that road. But I think it can be taken with caution.

        – Ewan
        15 hours ago











      • I know some people do that some people are Pivotal and its framework. SpringFramework has a lot of this:-). Anyways, As @VoiceOfUnreason has suggested, the key around DDD is keeping the consistency of the writings. I'm unsure about forcing the design with domain models whom only purpose is querying or parametrizing queries. That could be approached out of the domain with data structures (pocos, pojos, dtos, row mappers, whatever).

        – Laiv
        14 hours ago











      • obviously we need some sort of inquisition to help those people back to sanity. But I'm sticking to my guns. The partial exposure of the datalayer is acceptable when it objectively makes for a better application, where what is or isn't a "Domain Object" is subjective

        – Ewan
        14 hours ago











      • @Ewan what kind of object will be ProductInventory, Entity? Value Object? or just a class

        – Leonardo Mangano
        14 hours ago

















      • Well, so far I recall. Repositories are supposed to get Query as parameters too. repository.find(query);. I have read the same but with Specs. That opens a door to leave Query` as an abstraction and QueryImpl or the specific-query implementation to the infrastructure layer.

        – Laiv
        15 hours ago







      • 1





        oh god, I know some people do that but I think it's awful. You can view this kind of thing as a step down that road. But I think it can be taken with caution.

        – Ewan
        15 hours ago











      • I know some people do that some people are Pivotal and its framework. SpringFramework has a lot of this:-). Anyways, As @VoiceOfUnreason has suggested, the key around DDD is keeping the consistency of the writings. I'm unsure about forcing the design with domain models whom only purpose is querying or parametrizing queries. That could be approached out of the domain with data structures (pocos, pojos, dtos, row mappers, whatever).

        – Laiv
        14 hours ago











      • obviously we need some sort of inquisition to help those people back to sanity. But I'm sticking to my guns. The partial exposure of the datalayer is acceptable when it objectively makes for a better application, where what is or isn't a "Domain Object" is subjective

        – Ewan
        14 hours ago











      • @Ewan what kind of object will be ProductInventory, Entity? Value Object? or just a class

        – Leonardo Mangano
        14 hours ago
















      Well, so far I recall. Repositories are supposed to get Query as parameters too. repository.find(query);. I have read the same but with Specs. That opens a door to leave Query` as an abstraction and QueryImpl or the specific-query implementation to the infrastructure layer.

      – Laiv
      15 hours ago






      Well, so far I recall. Repositories are supposed to get Query as parameters too. repository.find(query);. I have read the same but with Specs. That opens a door to leave Query` as an abstraction and QueryImpl or the specific-query implementation to the infrastructure layer.

      – Laiv
      15 hours ago





      1




      1





      oh god, I know some people do that but I think it's awful. You can view this kind of thing as a step down that road. But I think it can be taken with caution.

      – Ewan
      15 hours ago





      oh god, I know some people do that but I think it's awful. You can view this kind of thing as a step down that road. But I think it can be taken with caution.

      – Ewan
      15 hours ago













      I know some people do that some people are Pivotal and its framework. SpringFramework has a lot of this:-). Anyways, As @VoiceOfUnreason has suggested, the key around DDD is keeping the consistency of the writings. I'm unsure about forcing the design with domain models whom only purpose is querying or parametrizing queries. That could be approached out of the domain with data structures (pocos, pojos, dtos, row mappers, whatever).

      – Laiv
      14 hours ago





      I know some people do that some people are Pivotal and its framework. SpringFramework has a lot of this:-). Anyways, As @VoiceOfUnreason has suggested, the key around DDD is keeping the consistency of the writings. I'm unsure about forcing the design with domain models whom only purpose is querying or parametrizing queries. That could be approached out of the domain with data structures (pocos, pojos, dtos, row mappers, whatever).

      – Laiv
      14 hours ago













      obviously we need some sort of inquisition to help those people back to sanity. But I'm sticking to my guns. The partial exposure of the datalayer is acceptable when it objectively makes for a better application, where what is or isn't a "Domain Object" is subjective

      – Ewan
      14 hours ago





      obviously we need some sort of inquisition to help those people back to sanity. But I'm sticking to my guns. The partial exposure of the datalayer is acceptable when it objectively makes for a better application, where what is or isn't a "Domain Object" is subjective

      – Ewan
      14 hours ago













      @Ewan what kind of object will be ProductInventory, Entity? Value Object? or just a class

      – Leonardo Mangano
      14 hours ago





      @Ewan what kind of object will be ProductInventory, Entity? Value Object? or just a class

      – Leonardo Mangano
      14 hours ago











      5















      As I understand it, a main point is to split the Domain Logic (Business Logic) from the Infrastructure (DB, File System, etc.).




      This is the foundation of the misunderstanding: the purpose of DDD isn't to separate things along a hard line like "this is in the SQL server, so must not be BL", the purpose of DDD is to separate domains and create barriers between them that allow the internals of a domain to be completely separate from the internals of another domain, and to define shared externals between them.



      Don't think of "being in SQL" as the BL/DL barrier—that's not what it is. Instead, think of "this is the end of the internal domain" as the barrier.



      Each domain should have external-facing API's that allow it to work with all the other domains: in the case of the data storage layer, it should have read/write (CRUD) actions for the data-objects it stores. This means SQL itself isn't really the barrier, the VIEW and PROCEDURE components are. You should never read directly from the table: that is the implementation detail DDD tells us that, as an external consumer, we should not worry about.



      Consider your example:




      What I am wondering is, what happens when I have very complex queries like a Material Resource Calculation Query? In that kind of query you work with heavy set operations, the kind of thing that SQL was designed for.




      This is exactly what should be in SQL then, and it's not a violation of DDD. It's what we made DDD for. With that calculation in SQL, that becomes part of the BL/DL. What you would do is use a separate view / stored procedure / what-have-you, and keep the business logic separated from the data-layer, as that is your external API. In fact, your data-layer should be another DDD Domain Layer, where your data-layer has it's own abstractions to work with the other domain layers.




      Doing these calculations in the infrastructure can't happen too, because the DDD pattern allows for changes in the infrastructure without changing the Domain Layer and knowing that MongoDB doesn't have the same capabilities of e.g. SQL Server, that can't happen.




      That's another misunderstanding: it says implementation details internally can change without changing other domain layers. It doesn't say you can just replace a whole infrastructure piece.



      Again, keep in mind, DDD is about hiding internals with well-defined external API's. Where those API's sit is a totally different question, and DDD doesn't define that. It simply defines that these API's exist, and should never change.



      DDD isn't setup to allow you to ad-hoc replace MSSQL with MongoDB—those are two totally different infrastructure components.



      Instead, let's use an analogy for what DDD defines: gas vs. electric cars. Both of the vehicles have two completely different methods for creating propulsion, but they have the same API's: an on/off, a throttle/brake, and wheels to propel the vehicle. DDD says that we should be able to replace the engine (gas or electric) in our car. It doesn't say we can replace the car with a motorcycle, and that's effectively what MSSQL → MongoDB is.






      share|improve this answer

























      • Thanks for the explanation. For me is a very hard topic, everyone have a different point of view. The only thing I don't agree is the comparison between MSSQL(car) and MongoDB (motorcycle), for me the right comparison is that these are two different engines for the same car, but it's just a opinion.

        – Leonardo Mangano
        14 hours ago






      • 2





        @LeonardoMangano Ah, but they're not. MSSQL is a relational database, MongoDB is a document database. Yes, "database" describes both, but that's about as far as it goes. The read/write techniques are completely different. Instead of MongoDB, you could use Postgre or MySQL as an alternative, and that would be a valid comparison.

        – Der Kommissar
        14 hours ago











      • "You should never read directly from the table..." Madness.

        – jpmc26
        4 hours ago















      5















      As I understand it, a main point is to split the Domain Logic (Business Logic) from the Infrastructure (DB, File System, etc.).




      This is the foundation of the misunderstanding: the purpose of DDD isn't to separate things along a hard line like "this is in the SQL server, so must not be BL", the purpose of DDD is to separate domains and create barriers between them that allow the internals of a domain to be completely separate from the internals of another domain, and to define shared externals between them.



      Don't think of "being in SQL" as the BL/DL barrier—that's not what it is. Instead, think of "this is the end of the internal domain" as the barrier.



      Each domain should have external-facing API's that allow it to work with all the other domains: in the case of the data storage layer, it should have read/write (CRUD) actions for the data-objects it stores. This means SQL itself isn't really the barrier, the VIEW and PROCEDURE components are. You should never read directly from the table: that is the implementation detail DDD tells us that, as an external consumer, we should not worry about.



      Consider your example:




      What I am wondering is, what happens when I have very complex queries like a Material Resource Calculation Query? In that kind of query you work with heavy set operations, the kind of thing that SQL was designed for.




      This is exactly what should be in SQL then, and it's not a violation of DDD. It's what we made DDD for. With that calculation in SQL, that becomes part of the BL/DL. What you would do is use a separate view / stored procedure / what-have-you, and keep the business logic separated from the data-layer, as that is your external API. In fact, your data-layer should be another DDD Domain Layer, where your data-layer has it's own abstractions to work with the other domain layers.




      Doing these calculations in the infrastructure can't happen too, because the DDD pattern allows for changes in the infrastructure without changing the Domain Layer and knowing that MongoDB doesn't have the same capabilities of e.g. SQL Server, that can't happen.




      That's another misunderstanding: it says implementation details internally can change without changing other domain layers. It doesn't say you can just replace a whole infrastructure piece.



      Again, keep in mind, DDD is about hiding internals with well-defined external API's. Where those API's sit is a totally different question, and DDD doesn't define that. It simply defines that these API's exist, and should never change.



      DDD isn't setup to allow you to ad-hoc replace MSSQL with MongoDB—those are two totally different infrastructure components.



      Instead, let's use an analogy for what DDD defines: gas vs. electric cars. Both of the vehicles have two completely different methods for creating propulsion, but they have the same API's: an on/off, a throttle/brake, and wheels to propel the vehicle. DDD says that we should be able to replace the engine (gas or electric) in our car. It doesn't say we can replace the car with a motorcycle, and that's effectively what MSSQL → MongoDB is.






      share|improve this answer

























      • Thanks for the explanation. For me is a very hard topic, everyone have a different point of view. The only thing I don't agree is the comparison between MSSQL(car) and MongoDB (motorcycle), for me the right comparison is that these are two different engines for the same car, but it's just a opinion.

        – Leonardo Mangano
        14 hours ago






      • 2





        @LeonardoMangano Ah, but they're not. MSSQL is a relational database, MongoDB is a document database. Yes, "database" describes both, but that's about as far as it goes. The read/write techniques are completely different. Instead of MongoDB, you could use Postgre or MySQL as an alternative, and that would be a valid comparison.

        – Der Kommissar
        14 hours ago











      • "You should never read directly from the table..." Madness.

        – jpmc26
        4 hours ago













      5












      5








      5








      As I understand it, a main point is to split the Domain Logic (Business Logic) from the Infrastructure (DB, File System, etc.).




      This is the foundation of the misunderstanding: the purpose of DDD isn't to separate things along a hard line like "this is in the SQL server, so must not be BL", the purpose of DDD is to separate domains and create barriers between them that allow the internals of a domain to be completely separate from the internals of another domain, and to define shared externals between them.



      Don't think of "being in SQL" as the BL/DL barrier—that's not what it is. Instead, think of "this is the end of the internal domain" as the barrier.



      Each domain should have external-facing API's that allow it to work with all the other domains: in the case of the data storage layer, it should have read/write (CRUD) actions for the data-objects it stores. This means SQL itself isn't really the barrier, the VIEW and PROCEDURE components are. You should never read directly from the table: that is the implementation detail DDD tells us that, as an external consumer, we should not worry about.



      Consider your example:




      What I am wondering is, what happens when I have very complex queries like a Material Resource Calculation Query? In that kind of query you work with heavy set operations, the kind of thing that SQL was designed for.




      This is exactly what should be in SQL then, and it's not a violation of DDD. It's what we made DDD for. With that calculation in SQL, that becomes part of the BL/DL. What you would do is use a separate view / stored procedure / what-have-you, and keep the business logic separated from the data-layer, as that is your external API. In fact, your data-layer should be another DDD Domain Layer, where your data-layer has it's own abstractions to work with the other domain layers.




      Doing these calculations in the infrastructure can't happen too, because the DDD pattern allows for changes in the infrastructure without changing the Domain Layer and knowing that MongoDB doesn't have the same capabilities of e.g. SQL Server, that can't happen.




      That's another misunderstanding: it says implementation details internally can change without changing other domain layers. It doesn't say you can just replace a whole infrastructure piece.



      Again, keep in mind, DDD is about hiding internals with well-defined external API's. Where those API's sit is a totally different question, and DDD doesn't define that. It simply defines that these API's exist, and should never change.



      DDD isn't setup to allow you to ad-hoc replace MSSQL with MongoDB—those are two totally different infrastructure components.



      Instead, let's use an analogy for what DDD defines: gas vs. electric cars. Both of the vehicles have two completely different methods for creating propulsion, but they have the same API's: an on/off, a throttle/brake, and wheels to propel the vehicle. DDD says that we should be able to replace the engine (gas or electric) in our car. It doesn't say we can replace the car with a motorcycle, and that's effectively what MSSQL → MongoDB is.






      share|improve this answer
















      As I understand it, a main point is to split the Domain Logic (Business Logic) from the Infrastructure (DB, File System, etc.).




      This is the foundation of the misunderstanding: the purpose of DDD isn't to separate things along a hard line like "this is in the SQL server, so must not be BL", the purpose of DDD is to separate domains and create barriers between them that allow the internals of a domain to be completely separate from the internals of another domain, and to define shared externals between them.



      Don't think of "being in SQL" as the BL/DL barrier—that's not what it is. Instead, think of "this is the end of the internal domain" as the barrier.



      Each domain should have external-facing API's that allow it to work with all the other domains: in the case of the data storage layer, it should have read/write (CRUD) actions for the data-objects it stores. This means SQL itself isn't really the barrier, the VIEW and PROCEDURE components are. You should never read directly from the table: that is the implementation detail DDD tells us that, as an external consumer, we should not worry about.



      Consider your example:




      What I am wondering is, what happens when I have very complex queries like a Material Resource Calculation Query? In that kind of query you work with heavy set operations, the kind of thing that SQL was designed for.




      This is exactly what should be in SQL then, and it's not a violation of DDD. It's what we made DDD for. With that calculation in SQL, that becomes part of the BL/DL. What you would do is use a separate view / stored procedure / what-have-you, and keep the business logic separated from the data-layer, as that is your external API. In fact, your data-layer should be another DDD Domain Layer, where your data-layer has it's own abstractions to work with the other domain layers.




      Doing these calculations in the infrastructure can't happen too, because the DDD pattern allows for changes in the infrastructure without changing the Domain Layer and knowing that MongoDB doesn't have the same capabilities of e.g. SQL Server, that can't happen.




      That's another misunderstanding: it says implementation details internally can change without changing other domain layers. It doesn't say you can just replace a whole infrastructure piece.



      Again, keep in mind, DDD is about hiding internals with well-defined external API's. Where those API's sit is a totally different question, and DDD doesn't define that. It simply defines that these API's exist, and should never change.



      DDD isn't setup to allow you to ad-hoc replace MSSQL with MongoDB—those are two totally different infrastructure components.



      Instead, let's use an analogy for what DDD defines: gas vs. electric cars. Both of the vehicles have two completely different methods for creating propulsion, but they have the same API's: an on/off, a throttle/brake, and wheels to propel the vehicle. DDD says that we should be able to replace the engine (gas or electric) in our car. It doesn't say we can replace the car with a motorcycle, and that's effectively what MSSQL → MongoDB is.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 14 hours ago

























      answered 14 hours ago









      Der KommissarDer Kommissar

      19610




      19610












      • Thanks for the explanation. For me is a very hard topic, everyone have a different point of view. The only thing I don't agree is the comparison between MSSQL(car) and MongoDB (motorcycle), for me the right comparison is that these are two different engines for the same car, but it's just a opinion.

        – Leonardo Mangano
        14 hours ago






      • 2





        @LeonardoMangano Ah, but they're not. MSSQL is a relational database, MongoDB is a document database. Yes, "database" describes both, but that's about as far as it goes. The read/write techniques are completely different. Instead of MongoDB, you could use Postgre or MySQL as an alternative, and that would be a valid comparison.

        – Der Kommissar
        14 hours ago











      • "You should never read directly from the table..." Madness.

        – jpmc26
        4 hours ago

















      • Thanks for the explanation. For me is a very hard topic, everyone have a different point of view. The only thing I don't agree is the comparison between MSSQL(car) and MongoDB (motorcycle), for me the right comparison is that these are two different engines for the same car, but it's just a opinion.

        – Leonardo Mangano
        14 hours ago






      • 2





        @LeonardoMangano Ah, but they're not. MSSQL is a relational database, MongoDB is a document database. Yes, "database" describes both, but that's about as far as it goes. The read/write techniques are completely different. Instead of MongoDB, you could use Postgre or MySQL as an alternative, and that would be a valid comparison.

        – Der Kommissar
        14 hours ago











      • "You should never read directly from the table..." Madness.

        – jpmc26
        4 hours ago
















      Thanks for the explanation. For me is a very hard topic, everyone have a different point of view. The only thing I don't agree is the comparison between MSSQL(car) and MongoDB (motorcycle), for me the right comparison is that these are two different engines for the same car, but it's just a opinion.

      – Leonardo Mangano
      14 hours ago





      Thanks for the explanation. For me is a very hard topic, everyone have a different point of view. The only thing I don't agree is the comparison between MSSQL(car) and MongoDB (motorcycle), for me the right comparison is that these are two different engines for the same car, but it's just a opinion.

      – Leonardo Mangano
      14 hours ago




      2




      2





      @LeonardoMangano Ah, but they're not. MSSQL is a relational database, MongoDB is a document database. Yes, "database" describes both, but that's about as far as it goes. The read/write techniques are completely different. Instead of MongoDB, you could use Postgre or MySQL as an alternative, and that would be a valid comparison.

      – Der Kommissar
      14 hours ago





      @LeonardoMangano Ah, but they're not. MSSQL is a relational database, MongoDB is a document database. Yes, "database" describes both, but that's about as far as it goes. The read/write techniques are completely different. Instead of MongoDB, you could use Postgre or MySQL as an alternative, and that would be a valid comparison.

      – Der Kommissar
      14 hours ago













      "You should never read directly from the table..." Madness.

      – jpmc26
      4 hours ago





      "You should never read directly from the table..." Madness.

      – jpmc26
      4 hours ago











      1














      As usual, this is one of those things that depends on a number of factors. It's true that there's a lot that you can do with SQL. There are also challenges with using it and some practical limitations of relational databases.



      As Jared Goguen notes in the comments, SQL can be very difficult to test and verify. The main factors that lead to this are that it can't (in general) be decomposed into components. In practice, a complex query must be considered in toto. Another complicating factor is that be behavior and correctness of SQL is highly dependent on the structure and content of your data. This means that testing all the possible scenarios (or even determining what they are) is often infeasible or impossible. Refactoring of SQL and modification of database structure is likewise problematic.



      The other big factor that has lead to moving away from SQL is relational databases tend to only scale vertically. For example, when you build complex calculations in SQL to run in SQL Server, they are going to execute on the database. That means all of that work is using resources on the database. The more that you do in SQL, the more resources your database will need both in terms of memory and CPU. It's often less efficient to do these things on other systems but there's no practical limit to the number of additional machines you can add to such a solution. This approach is less expensive and more fault-tolerant than building a monster database server.



      These issues may or may not apply to the problem at hand. If you are able to solve your problem with available database resources, maybe SQL is fine for your problem-space. You need to consider growth, however. It might be fine today but a few years down the road, the cost of adding additional resources may become a problem.






      share|improve this answer



























        1














        As usual, this is one of those things that depends on a number of factors. It's true that there's a lot that you can do with SQL. There are also challenges with using it and some practical limitations of relational databases.



        As Jared Goguen notes in the comments, SQL can be very difficult to test and verify. The main factors that lead to this are that it can't (in general) be decomposed into components. In practice, a complex query must be considered in toto. Another complicating factor is that be behavior and correctness of SQL is highly dependent on the structure and content of your data. This means that testing all the possible scenarios (or even determining what they are) is often infeasible or impossible. Refactoring of SQL and modification of database structure is likewise problematic.



        The other big factor that has lead to moving away from SQL is relational databases tend to only scale vertically. For example, when you build complex calculations in SQL to run in SQL Server, they are going to execute on the database. That means all of that work is using resources on the database. The more that you do in SQL, the more resources your database will need both in terms of memory and CPU. It's often less efficient to do these things on other systems but there's no practical limit to the number of additional machines you can add to such a solution. This approach is less expensive and more fault-tolerant than building a monster database server.



        These issues may or may not apply to the problem at hand. If you are able to solve your problem with available database resources, maybe SQL is fine for your problem-space. You need to consider growth, however. It might be fine today but a few years down the road, the cost of adding additional resources may become a problem.






        share|improve this answer

























          1












          1








          1







          As usual, this is one of those things that depends on a number of factors. It's true that there's a lot that you can do with SQL. There are also challenges with using it and some practical limitations of relational databases.



          As Jared Goguen notes in the comments, SQL can be very difficult to test and verify. The main factors that lead to this are that it can't (in general) be decomposed into components. In practice, a complex query must be considered in toto. Another complicating factor is that be behavior and correctness of SQL is highly dependent on the structure and content of your data. This means that testing all the possible scenarios (or even determining what they are) is often infeasible or impossible. Refactoring of SQL and modification of database structure is likewise problematic.



          The other big factor that has lead to moving away from SQL is relational databases tend to only scale vertically. For example, when you build complex calculations in SQL to run in SQL Server, they are going to execute on the database. That means all of that work is using resources on the database. The more that you do in SQL, the more resources your database will need both in terms of memory and CPU. It's often less efficient to do these things on other systems but there's no practical limit to the number of additional machines you can add to such a solution. This approach is less expensive and more fault-tolerant than building a monster database server.



          These issues may or may not apply to the problem at hand. If you are able to solve your problem with available database resources, maybe SQL is fine for your problem-space. You need to consider growth, however. It might be fine today but a few years down the road, the cost of adding additional resources may become a problem.






          share|improve this answer













          As usual, this is one of those things that depends on a number of factors. It's true that there's a lot that you can do with SQL. There are also challenges with using it and some practical limitations of relational databases.



          As Jared Goguen notes in the comments, SQL can be very difficult to test and verify. The main factors that lead to this are that it can't (in general) be decomposed into components. In practice, a complex query must be considered in toto. Another complicating factor is that be behavior and correctness of SQL is highly dependent on the structure and content of your data. This means that testing all the possible scenarios (or even determining what they are) is often infeasible or impossible. Refactoring of SQL and modification of database structure is likewise problematic.



          The other big factor that has lead to moving away from SQL is relational databases tend to only scale vertically. For example, when you build complex calculations in SQL to run in SQL Server, they are going to execute on the database. That means all of that work is using resources on the database. The more that you do in SQL, the more resources your database will need both in terms of memory and CPU. It's often less efficient to do these things on other systems but there's no practical limit to the number of additional machines you can add to such a solution. This approach is less expensive and more fault-tolerant than building a monster database server.



          These issues may or may not apply to the problem at hand. If you are able to solve your problem with available database resources, maybe SQL is fine for your problem-space. You need to consider growth, however. It might be fine today but a few years down the road, the cost of adding additional resources may become a problem.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 15 hours ago









          JimmyJamesJimmyJames

          13.6k12553




          13.6k12553





















              0














              Sequel became popular when memory were expensive, because relational data model provided possibility to normalise your data and effectively store it in the file system.



              Now memory is relatively cheap, so we can skip normalisation and store in in the format we use it or even duplicate a lot of same data for sake of speed.



              Consider database as simple IO device, which responsibility to store data in the file system - yes I know it is difficult to imagine it, because we wrote plenty of applications with important business logic written into SQL queries - but just try to imagine that SQL Server is just another printer.



              Would you embedded PDF generator into printer driver or added a trigger which will print log page for every sales order printed out of our printer?



              I assume the answer will be no, because we don't want that our application are coupled to the specific device type (not even talking about efficiency of such idea)



              In 70's- 90's SQL database were efficient, now? - Not sure, in some scenarios asynchronous data query will returns required data faster than multiple joins in SQL query.



              SQL wasn't designed for complicated queries, it were designed for storing data in efficient way and then provide interface/language to query stored data.



              I would say building your application around relational data model with complicated queries is abuse of database engine. Of course database engine providers are happy when you tightly coupling your business to their product - they will be more than happy to provide more features which make this bound stronger.






              share|improve this answer



























                0














                Sequel became popular when memory were expensive, because relational data model provided possibility to normalise your data and effectively store it in the file system.



                Now memory is relatively cheap, so we can skip normalisation and store in in the format we use it or even duplicate a lot of same data for sake of speed.



                Consider database as simple IO device, which responsibility to store data in the file system - yes I know it is difficult to imagine it, because we wrote plenty of applications with important business logic written into SQL queries - but just try to imagine that SQL Server is just another printer.



                Would you embedded PDF generator into printer driver or added a trigger which will print log page for every sales order printed out of our printer?



                I assume the answer will be no, because we don't want that our application are coupled to the specific device type (not even talking about efficiency of such idea)



                In 70's- 90's SQL database were efficient, now? - Not sure, in some scenarios asynchronous data query will returns required data faster than multiple joins in SQL query.



                SQL wasn't designed for complicated queries, it were designed for storing data in efficient way and then provide interface/language to query stored data.



                I would say building your application around relational data model with complicated queries is abuse of database engine. Of course database engine providers are happy when you tightly coupling your business to their product - they will be more than happy to provide more features which make this bound stronger.






                share|improve this answer

























                  0












                  0








                  0







                  Sequel became popular when memory were expensive, because relational data model provided possibility to normalise your data and effectively store it in the file system.



                  Now memory is relatively cheap, so we can skip normalisation and store in in the format we use it or even duplicate a lot of same data for sake of speed.



                  Consider database as simple IO device, which responsibility to store data in the file system - yes I know it is difficult to imagine it, because we wrote plenty of applications with important business logic written into SQL queries - but just try to imagine that SQL Server is just another printer.



                  Would you embedded PDF generator into printer driver or added a trigger which will print log page for every sales order printed out of our printer?



                  I assume the answer will be no, because we don't want that our application are coupled to the specific device type (not even talking about efficiency of such idea)



                  In 70's- 90's SQL database were efficient, now? - Not sure, in some scenarios asynchronous data query will returns required data faster than multiple joins in SQL query.



                  SQL wasn't designed for complicated queries, it were designed for storing data in efficient way and then provide interface/language to query stored data.



                  I would say building your application around relational data model with complicated queries is abuse of database engine. Of course database engine providers are happy when you tightly coupling your business to their product - they will be more than happy to provide more features which make this bound stronger.






                  share|improve this answer













                  Sequel became popular when memory were expensive, because relational data model provided possibility to normalise your data and effectively store it in the file system.



                  Now memory is relatively cheap, so we can skip normalisation and store in in the format we use it or even duplicate a lot of same data for sake of speed.



                  Consider database as simple IO device, which responsibility to store data in the file system - yes I know it is difficult to imagine it, because we wrote plenty of applications with important business logic written into SQL queries - but just try to imagine that SQL Server is just another printer.



                  Would you embedded PDF generator into printer driver or added a trigger which will print log page for every sales order printed out of our printer?



                  I assume the answer will be no, because we don't want that our application are coupled to the specific device type (not even talking about efficiency of such idea)



                  In 70's- 90's SQL database were efficient, now? - Not sure, in some scenarios asynchronous data query will returns required data faster than multiple joins in SQL query.



                  SQL wasn't designed for complicated queries, it were designed for storing data in efficient way and then provide interface/language to query stored data.



                  I would say building your application around relational data model with complicated queries is abuse of database engine. Of course database engine providers are happy when you tightly coupling your business to their product - they will be more than happy to provide more features which make this bound stronger.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 26 mins ago









                  FabioFabio

                  1,7731020




                  1,7731020




















                      Leonardo Mangano is a new contributor. Be nice, and check out our Code of Conduct.









                      draft saved

                      draft discarded


















                      Leonardo Mangano is a new contributor. Be nice, and check out our Code of Conduct.












                      Leonardo Mangano is a new contributor. Be nice, and check out our Code of Conduct.











                      Leonardo Mangano is a new contributor. Be nice, and check out our Code of Conduct.














                      Thanks for contributing an answer to Software Engineering Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsoftwareengineering.stackexchange.com%2fquestions%2f389981%2fis-domain-driven-design-an-anti-sql-pattern%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown











                      Popular posts from this blog

                      Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                      Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                      199年 目錄 大件事 到箇年出世嗰人 到箇年死嗰人 節慶、風俗習慣 導覽選單