SubSonic - How can i create my business logic layer - subsonic

Im new to subsonic and generally this was of programming, i usually develop from a rad perspective so using the visual studio dataset designer, but i wanted to start looking at developing n teir approach.
Ive never used a business logic layer, (naughy) normally my code behind takes care of validation so to speak aswell as general page level validation.
How can i generate my business logic, do i create a partial class of one of my classes and then add the business logic into this? and how would this look? just so i have an idea.
Any exmaples or advice would be greatly appreciated.
Thanks
Dan

The big gotchya with SubSonic is that it generates classes from database tables, there is a 1-to-1 correspondence between the two. That makes the classes SubSonic generates quite unsuitable for use as business objects, because it would tie your business layer very directly to your database structure. This is a bad thing (in nearly all scenarios that come to my mind, anyway).
SubSonic is a query tool and little more. It most certainly is not an ORM.
With that in mind, I believe the correct way to create a Business Logic Layer is to write your own business classes, and write Repository classes to manage loading and storing the data. But use SubSonic only internally to the Repository classes to handle the actual persisting of your data to the database.
If you use the SubSonic generated classes throughout your project you will find you are most likely doing it wrong, and the first significant change to your DB schema will illustrate that nicely (or .. not nicely).
In fact, I would recommend quickly moving into learning a real ORM like NHibernate or Entity Framework. They bring you much farther down the Happy Path, whereas SubSonic still requires one to do much of the Data Layer implementation themselves.

Related

DDD + node.js: Where should domain logic go

I am trying to institute DDD into a node.js application using es6. I am using mongoose for my data access layer. I noticed that mongoose has a ".methods" property tied to the model schema. In terms of adding business logic to an entity, would this be an ideal place to add business logic or should I consider creating another object that holds the business logic that mirrors the model schema object and just copy the data from one to the other? If I were using sequalize, what would be the preferred approach here?
I don't think there is really a definitive answer to this, but I'll give you some opinions.
A number of DDD related concepts and instruments are built around features exposed by OOP languages (in-particular: interfaces & IOC). In the JavaScript world, things tend to be a little different, particularly when leveraging the module system. That said, it's not impossible, but compromises might need to be made.
One of the more important points in DDD is that your models are "plain". They are completely ignorant of any persistence mechanisms, etc, they are simply just data and logic. By defining your models using Mongoose, you pretty much lose that; your business logic is being attached to a Mongoose schema object. But perhaps that is where you can compromise, it very much depends on how puristic you wish to be about it. Now, you can do mapping, as you suggested. If you do decide to go ahead with that idea, something like AutoMapper could help. I've been involved in a project that used ES7 decorators from cerialize for a terser approach (we weren't using schemas, however).

What is common practise for designing an initial class diagram for a project?

I am currently taking a course that gives an introduction to project planning. It is mostly about how to draw UML diagrams (blegh), but also has a few other topics.
One part in particular keeps bugging me. In the course they describe a method for going from a set of requirements to an initial class diagram, but everything about the method gives me this feeling that it is most definitely not the way to go. Let me first give an example before proceeding.
Let's consider a system that manages a greenhouse company. The company has multiple greenhouses, and every employee is assigned to his/her own greenhouse. A greenhouse has a location and a type of plant being grown in there. An employee has a name and phone number.
Here's what according to the course's method the class diagram would look like:
To me this looks like a database layout adapted for code. When I go about designing a program, I try to identify major abstractions. Like all the code that interacts with the database or the code that is responsible for the GUI are all different parts of the system. That would be what I consider to be an initial class diagram.
I simply can not imagine that this is a common way to start designing the architecture of a project. The classes look ugly, since if you take a slightly larger example the classes will be flooded with responsibilities. To me they look like data objects that have functionality to them they shouldn't have. It does not give me a clue on how to continue from here and get a general architecture going. Everything about it seems obsolete.
All I want to know if there's someone out there that can tell me if this is a common way to get a first class diagram on paper for reasons I am overlooking.
I would say it's reasonable to start with a logical model that's free of implementation constraints. That logical model is not necessarily concerned with physical implementation details (e.g. whether or not to use a database, what type of database, OS / UI choice, etc.) and thus represents just "real" business domain objects and processes. The similarity to a potential database implementation shouldn't be surprising for the simple example.
By understanding your business domain (through the logical model you've started to construct), you will be better placed to subsequently identify, for example, which architectural patterns are appropriate, what screens you need to build, and database elements to design. Possibly, there will be another part of the course that will aid you in this stage.
In practice, you will often know that you're intending to implement, say, a web-based application using MVC with a back-end database, and may look to model the implementation classes in parallel with your business items. For your course to use a method that emphasises the distinction between logical and physical stages doesn't sound unreasonable.
When I go about designing a program, I try to identify major
abstractions
Same principle in UML as well. You represent abstractions and their relationships and due to existing Visual Tools you can do a presentation of a system to stakeholders or even generate automatically stubs from your design.

Can't help but see Domain entities as wasteful. Why?

I've got a question on my mind that has been stirring for months as I've read about DDD, patterns and many other topics of application architecture. I'm going to frame this in terms of an MVC web application but the question is, I'm sure, much broader. and it is this:  Does the adherence to domain entities  create rigidity and inefficiency in an application? 
The DDD approach makes complete sense for managing the business logic of an application and as a way of working with stakeholders. But to me it falls apart in the context of a multi-tiered application. Namely there are very few scenarios when a view needs all the data of an entity or when even two repositories have it all. In and of itself that's not bad but it means I make multiple queries returning a bunch of properties I don't need to get a few that I do. And once that is done the extraneous information either gets passed to the view or there is the overhead of discarding, merging and mapping data to a DTO or view model. I have need to generate a lot of reports and the problem seems magnified there. Each requires a unique slicing or aggregating of information that SQL can do well but repositories can't as they're expected to return full entities. It seems wasteful, honestly, and I don't want to pound a database and generate unneeded network traffic on a matter of principle. From questions like this Should the repository layer return data-transfer-objects (DTO)? it seems I'm not the only one to struggle with this question. So what's the answer to the limitations it seems to impose? 
Thanks from a new and confounded DDD-er.  
What's the real problem here? Processing business rules and querying for data are 2 very different concerns. That realization leads us to CQRS - Command-Query Responsibility Segregation. What's that? You just don't use the same model for both tasks: Domain Model is about behavior, performing business processes, handling command. And there is a separate Reporting Model used for display. In general, it can contain a table per view. These tables contains only relevant information so you can get rid of DTO, AutoMapper, etc.
How these two models synchronize? It can be done in many ways:
Reporting model can be built just on top of database views
Database replication
Domain model can issue events containing information about each change and they can be handled by denormalizers updating proper tables in Reporting Model
as I've read about DDD, patterns and many other topics of application architecture
Domain driven design is not about patterns and architecture but about designing your code according to business domain. Instead of thinking about repositories and layers, think about problem you are trying to solve. Simplest way to "start rehabilitation" would be to rename ProductRepository to just Products.
Does the adherence to domain entities create rigidity and inefficiency in an application?
Inefficiency comes from bad modeling. [citation needed]
The DDD approach makes complete sense for managing the business logic of an application and as a way of working with stakeholders. But to me it falls apart in the context of a multi-tiered application.
Tiers aren't layers
Namely there are very few scenarios when a view needs all the data of an entity or when even two repositories have it all. In and of itself that's not bad but it means I make multiple queries returning a bunch of properties I don't need to get a few that I do.
Query that data as you wish. Do not try to box your problems into some "ready-made solutions". Instead - learn from them and apply only what's necessary to solve them.
Each requires a unique slicing or aggregating of information that SQL can do well but repositories can't as they're expected to return full entities.
http://ayende.com/blog/3955/repository-is-the-new-singleton
So what's the answer to the limitations it seems to impose?
"seems"
Btw, internet is full of things like this (I mean that sample app).
To understand what DDD is, read blue book slowly and carefully. Twice.
If you think that fully fledged DDD is too much effort for your scenario then maybe you need to take a step down and look at something closer to Active Record.
I use DDD but in my scenario I have to support multiple front-ends; a couple web sites and a WinForms app, as well as a set of services that allow interaction with other automated processes. In this case, the extra complexity is worth it. I use DTO's to transfer a representation of my data to the various presentation layers. The CPU overhead in mapping domain entities to DTO's is small - a rounding error when compared to net work calls and database calls. There is also the overhead in managing this complexity. I have mitigated this to some extent by using AutoMapper. My Repositories return fully populated domain objects. My service layer will map to/from DTO's. Here we can flatten out the domain objects, combine domain objects, etc. to produce a more tabulated representation of the data.
Dino Esposito wrote an MSDN Magazine article on this subject here - you may find this interesting.
So, I guess to answer your "Why" question - as usual, it depends on your context. DDD maybe too much effort. In which case do something simpler.
Each requires a unique slicing or aggregating of information that SQL can do well but repositories can't as they're expected to return full entities.
Add methods to your repository to return ONLY what you want e.g. IOrderRepository.GetByCustomer
It's completely OK in DDD.
You may also use Query object pattern or Specification to make your repositories more generic; only remember not to use anything which is ORM-specific in interfaces of the repositories(e.g. ICriteria of NHibernate)

MDD: How dynamic is MDD at runtime?

Over the years, I've investigated a lot of ways to use code generators and MDD. I've always felt that something is lacking: Patching and changes to the model at runtime.
Patching: If you have a code generator, all your classes should look the same. Now you have a single exception. All code generators so far would require that I modify the template or the template engine to make this work.
Wouldn't it be better if I could apply patches to the result of the code generation step to fix the exceptions?
Well, it depends on how you build your model. If fact, it depends on what code generator you are using, its approach, and what it lets you do.
Creating an exception to a rule (model) is more or less against the nature of MDD, unless the applied modeling approach allows you to add exceptions as modeling entities.
I think ABSE is the only modeling approach that accepts "custom code" as a first-class entity, just like a text or an integer. If you create a template that contains a "CustomCode" parameter, you can later add your exception code only when necessary, without breaking your model rules. This can be used to add or replace code. You just need to specify it in your template.
AtomWeaver is a free implementation of the ABSE modeling methodology.
MDD doesn't work because it is based on a view of the domain and not the entire domain. I mean that usually MDD take an XMI in entry coming from an UML diagram. The problem is that this diagram is only a view of the domain and therefore you have many alternative and the real world is a mot more complex specially at deployment stage.
The only company which has provided me real value in my project was Omondo with EclipseUML. EclipseUML doesn't try to do MDD but create UML at diagram level live synchronized with code. Deployment is made using stereotypes which are added in the java annotation in the code. I can therefore model and if I add deployment stereotypes then my application can be deployed immediately/ If I manually change my code, then my model is refactored and all my views updated. If I want to add a documentation then I just add notes in the metamodel. These notes are live available when I click on each element. No more printed documentation needed because live navigation, dynamic views creations etc...
My EclipseUML model is always up to date, and I can deploy it immediately because Java annotations are lived synchronized between the model, the metamodel, the diagrams and the code. Really cool :-) :-)

How do you deal with DDD and EF4

I'm facing several problems trying to apply DDD with EF4 (in ASP MVC2 context). Your advaice would be greatly appreciated.
First of all, I started to use POCO because the dependacy on ObjectContext was not very comfortable in many situations.
Going to POCO solved some problems but the experience is not what I was used to with NHibernate.
I would like to know if it's possible to use designer and to generate not only entities but also a Value Objects (ComplexType?). If I mean Value Object is a class with one ctor without any set properties (T4 modification needed ?).
The only way I found to add behavior to anemic entities is to create partial classes that extends those generated by edmx. I'm not satisfied with this approach.
I don't know how to create several repositories with one edmx. For now I'm using a partial classes to group methods for each aggregate. Each group is a repository in fact.
The last question is about IQueryable. Should it be exposed outside the repository ? If I refer to the ble book, the repository should be a unit of execution and shouldn't expose something like IQueryable. What do you think ?
Thanks for your help.
Thomas
It's fine to use POCOs, but note that EntityObject doesn't require an ObjectContext.
Yes, Complex Types are value objects and yes, you can generate them in the designer. Select several properties of an entity, right click, and choose refactor into complex type.
I strongly recommend putting business methods in their own types, not on entities. "Anemic" types can be a problem if you must maintain them, but when they're codegened they're hardly a maintenance problem. Making business logic separate from entity types allows your business rules and your data model to evolve independently. Yes, you must use partial classes if you must mix these concerns, but I don't believe that separating your model and your rules is a bad thing.
I think that repositories should expose IQueryable, but you can make a good case that domain services should not. People often try to build their repositories into domain services, but remember that the repository exists only to abstract away persistence. Concerns like security should be in domain services, and you can make the case that having IQueryable there gives too much power to the consumer.
I think it's OK to expose IQueryable outside of the repository, only because not doing so could be unnecessarily restrictive. If you only expose data via methods like GetPeopleByBirthday and GetPeopleByLastName, what happens when somebody goes to search for a person by last name and birthday? Do you pull in all the people with the last name "Smith" and do a linear search for the birthday you want, or do you create a new method GetPeopleByBirthdayAndLastName? What about the poor hapless fellow who has to implement a QBE form?
Back when the only way to make ad hoc queries against the domain was to generate SQL, the only way to keep yourself safe was to offer just specific methods to retrieve and change data. Now that we have LINQ, though, there's no reason to keep the handcuffs on. Anybody can submit a query and you can execute it safely without concern.
Of course, you could be concerned that a user might be able to view another's data, but that's easy to mitigate because you can restrict what data you give out. For example:
public IQueryable<Content> Content
{
get { return Content.Where(c => c.UserId == this.UserId); }
}
This will make sure that the only Content rows that the user can get are those that have his UserId.
If your concern is the load on the database, you could do things like examine query expressions for table scans (accessing tables without Where clauses or with no indexed columns in the Where clause). Granted, that's non-trivial, and I wouldn't recommend it.
It's been some time since I asked that question and had a chance to do it on my own.
I don't think it's a good practice to expose IQueryable at all outside the DAL layer. It brings more problems that it solves. I'm talking about large MVC applications. First of all the refactorings is harder, many developers user IQueryable instances from the views and after struggle with the fact that when resolving IQueryable the connection was already disposed. Performance problems because all the database is often queried for a given set of resultats and so on.
I rather expose Ienumerable from my repositories and believe me, it saves me many troubles.

Resources