I have read little bit about architecture and also patterns in order to follow the best practices. So this is the architecture we have and I wanted to know what you think of it and any proposed changes or improvements -
Presentation Layer - Contains all the views,controllers and any helper classes that the view requires also it containes the reference to Model Layer and Business Layer.
Business Layer - Contains all the business logic and validation and security helper classes that are being used by it. It contains a reference to DataAccess Layer and Model Layer.
Data Access Layer - Contains the actual queries being made on the entity classes(CRUD) operations on the entity classes. It contains reference to Model Layer.
Model Layer - Contains the entity framework model,DTOs,Enums.Does not really have a reference to any of the above layers.
What are your thoughts on the above architecture ? The problem is that I am getting confused by reading about like say the repository pattern, domain driven design and other design patterns. The architecture we have although not that strict still is relatively alright and it works well and I think and does not really muddle things but I maybe wrong. I would appreciate any help or suggestions here. I am really looking for some real big issues that I have missed ... Thanks!
It slightly depends on the underlying reasons as to why you want a particular architecture, but assuming a standard MVC application with a small amount of separation of concerns to allow for interoperability and testability then the structure you have outlined is exactly right.
If you go for this then you should enforce it strongly with no exceptions. Saying the Model layer "Does not really have a reference to any of the above" is a bit vague - it should not reference any of the higher levels.
Other aspects such as a repository pattern would be introduced as the way in which the data layer is implemented - it does not dictate the layers themselves.
Related
My understading of MVVM is that View is responsible for user presentation logic, view-model for interaction logic and specific data transformation from UI independent model classes and model itself representing business domain from data point of view.
Key point is that model classes should be UI indenpendent.
Here comes UWP dev model and Template 10 BindableBase from which model classes are supposed to be derived from. It's quite handy but it ties the model to the specific UI implementation, namely UWP + Template 10.
I've got a data access layer spitting out domain object I want to feed directly as model to the UI. The domain is quite complicated. What I don't wan't to do is to reimplement data domain objects in the UI nor I wan't to pollute it with UI specific functions.
Any thoughts on this?
thank you
With all due respect, I think you might be thinking about this wrong.
The goal of MVVM is to separate your logic exactly like you describe. The intent of this separation is to simplify your code. Does this make view-models testable and separate concerns? Yes. But, I argue those are secondary goals to simplicity – which keeps your code manageable and maintainable.
Here’s another way to say it.
MVVM is a terrific approach for XAML applications. But, if MVVM did not make your view-models testable or separate concerns, MVVM is still a terrific approach for XAML applications because it simplifies code so much – smaller, simpler, and isolated.
Worth every penny.
You might argue that MVVM creates another layer of code that developers must understand before they can reason and contribute to the base. I would agree. But I would NOT conclude that MVVM is therefore impracticable. That added layer is trivial compared to the otherwise coupling of logic.
Now to your question.
Your data layer object, probably a data transfer object, is remarkably like your UI object, probably a model. Your developer instincts compel you to unite similar things through polymorphism, code generation, or interfaces to avoid added opportunity for bugs, complexity, and tests.
Consider this.
Objects created in your data layer are created for your data layer. Likewise, objects created in your UI layer are created for your UI layer. Similarity in structure is a byproduct of similarity in domain. Of course, they are similar: their intents, however, are not. Why would you merge them?
You already see the problem.
The only differences you have are, perhaps, a data layer constructor taking in some type of data reader and populating properties. That is perfect for the data layer but inappropriate for the UI layer. Your UI layer might have messaging events or a custom method to handle interaction. That is perfect for the UI layer but inappropriate for the data layer.
So, where’s the similarity?
I think developers, including myself, tend to see similar things as potentially identical. Your data-relevant features do not belong in your UI nor the other way. Instead what you need to do is to see the similarity but recognize that they are drastically different objects and don’t deserve to be made the same.
We’re lazy.
Duplicate code isn’t about tests and bugs. Not really. It’s about how we, as developers, are so obsessed with “Work smarter not harder” that we tend to look down on “working hard”. If an object is built for one layer it should be in that layer, and not shared by another. I strongly feel this way.
The right solution
The easiest solution is to let your DTO serialize on the data layer from DataLayer.Object and then deserialize it on the UI layer as UILayer.Model. This is the easiest and simplest approach and adequately allows you to coerce the data and the object API for the use by its unique layer.
This means there are two nearly identical objects: one on the data layer and one on the UI layer. But it does NOT mean there are two identical objects. They are not identical because they have functionality unique to each of the tiers, each of the layers.
What if there is no functionality?
It makes sense to wonder if this applies to objects and models that have no added functionality. I believe strongly that objects and models in any layer without added functionality are simply waiting for that functionality to be added. Should you assume there is none and build to that assumption, you force the future you or forthcoming maintenance developers to never add layer-specific functionality.
Does that matter?
I think it does. Why? Because layer-specific functionality in an object or model allows me to add sophistication (not complexity) to my architecture and implementation within the context of the data object or model, and not in an external construct like a manager, helper, or utility. There is no question that Type.DoSomething is easier than Helper.DoSomethingForType(Type).
I actually have three
Just so you know, here’s how I do it: in my projects, you and I probably have similar data layers/services. But, my UI layer actually has TWO models – not one. (Let’s pretend Users is the data type.) My UI layer has json.User and Models.User. The json.User is a bare bones structure, deserialized from my service, and matches the service object exactly. But my UI rarely needs the Service API surface/structure.
Service(DataLayer.User) > | net | > UI(json.User > Models.User)
So, then json.User is used to create Model.User, whose structure meets my UI layer’s needs exactly - including methods, events, and messaging constructs. I am free to change my Models.User as I add features to my UI, too - including merging data from other/new data services. Also, Model.User can implement INotifyPropertyChanged where the data layer objects and the json objects never would (or need to).
Consider this
If you keep your models separate and you keep one codebase from improperly influencing another, then any change in your database or change in your data service/layer does not REQUIRE a change in your UI layer, even if you change the API surface. Only json.User changes or tweaks to your deserialization hints in your UI layer are impacted. To me, this only makes sense.
But what about testing and bugs?
Tests rarely test structures. Data structures are the simplest thing you can add to a solution and rarely contribute to complexity. You can reason over a structure in about a second. You can reason over a method in about a minute. Structures have very little cost. They also have very little construction cost. If you copy/paste the initial structure from your data layer to your UI layer – that’s what we all do. But that is NOT duplicating code. It is just building similar objects appropriately decoupled.
That’s what I think.
I'm using the Entity Framework 4.1 and ASP.Net MVC 3 for my application. MVC provides the presentation layer, an intermediate library provides the business logic and the Entity Framework sort of acts as the data layer I guess?
I could separate the Entity Framework code into a set of repository classes, or an appropriate variation thereof, whatever constitutes a worthwhile data layer, but I'm having trouble resolving a design problem I have.
If the multi-layered approach exists to help me keep concerns separated, then it stands to reason that my choice of data persistence should also not be a concern of the presentation layer. The problem is that by using the Entity Framework, I'm basically tightly coupling my application to the notion that entity changes are tracked and persisted automatically.
As such, let's say in a hypothetical world I found a reason not to use the Entity Framework and wanted to swap it out. A well-designed solution should allow me to do this at the appropriate layer and not have dependent layers affected, but because all code is being written with the knowledge that the data layer tracks object changes, I would only be able to swap out the Entity Framework for something that works in a similar fashion, for example nHibernate.
How do I get to use the Entity Framework but not need to write my code in a way that assumes that entity changes are being tracked by the data layer?
UPDATE for those still wondering about this issue in their own scenarios:
Ayende Rahien wrote a great article shooting down this whole argument:
http://ayende.com/blog/4567/the-false-myth-of-encapsulating-data-access-in-the-dal
If you want to continue this way you should give up programming job and go to study philosophy. Entity framework is abstraction of persistence and there is a rule of Leaky abstraction which says that any non-trivial abstraction is to some degree leaky.
Agile methodologies come with really interesting phenomenon: Do not prepare for hypothetical situations. The most of the time it is just Gold plating. Each change has its cost. Changing persistence layer later in the project is costly but it is also very rare. From customer perspective there is no reason to pay part of these costs in the most of projects where this change is not needed. If we discus customer perspective more deeply we can say that he should not pay for that at all because choosing bad API which has to be replaced later on is failure of developers / architects. Refactor your code regularly but only to the point which is needed for adding new features which customer wants otherwise you can hardly be competitive on the market. This of course has some exceptions:
Customer wants (or architecture demands it for any reason and customer agrees with it) such abstraction. In such case you must count with it and define architecture open for such changes.
It is hobby or open source project where you can do what you want because it is not constrained by some resources
Now to your problem. If you want such high level abstraction you should not expose entities to your controller. Expose DTOs from the business layer (or even from repositories) and add fields like IsNew, IsModified, IsDeleted to those DTOs. Now your UI is completely separated from the persistence but your architecture is much more complex and there is probably no reason for such complexity - it is over architected. Another way can be simply turning off tracking (add AsNoTracking() to each query) and proxy creation on your entities (context.Configuration.ProxyCreationEnabled) - lazy loading will not work as well. That's like throwing away most of features persistence frameworks offer to you.
There are also other points of view. I recommend you reading Ayende's recent posts about repository and his comments to Sharp architecture.
Short answer? You don't. You could turn off EF's tracking and then not worry about it, but that's about it.
If you're going to write your presentation layer with the expectation that changes are being tracked and persisted automatically, then whatever you replace EF with has to do that. You can't swap it out for something that doesn't track and persist changes automatically and just expect things to keep working. That'd be like taking a system that relies on a TCP/IP connection for duplex communication, swapping it to a HTTP connection (which by the nature of HTTP isn't really duplex) and expect things to work the same way. It doesn't.
If you want to be able to swap out your persistence layer for something else and not have to change anything else, then you need to wrap EF (or whatever) in your own custom code to provide the functionality you want. Then you have to provide implementations for anything not provided by whatever you swap to.
This is doable, but it's going to be an awful lot of work for a problem that very rarely actually happens. It's also going to add extra complexity to the project. Ladislav is bang on: it's not worth abstracting this far.
You should implement the repository pattern and plain POCOS if you are concerned about potentially swapping out EF.
There is a great project on Codeplex that goes over Domain Driven design including documentation. Take a look at that.
http://microsoftnlayerapp.codeplex.com/
Please after reading Microsoft n-layer project, read ayenede's weblog.
Mr.ayende posted series posts about advantage and disadvantage Microsoft n-layer project.
I have recently learned of the Repository and Unit of Work Design Patterns and thought that I would implement them in a new EF4 MVC3 project, since abstraction is generally good.
As I add them to the project, I am wondering if the juice is worth the proverbial squeeze, given the following:
It is EXTREMELY unlikely that the underlying data access mechanism will change from EF4.
This level of abstraction will require more overhead/confusion to the project and to other developers on the team.
The only real benefit I see to using the Repository pattern is for unit testing the application. Abstracting away the data store doesn't seem useful since I know the datastore won't change, and further, that EF4 already provides a pretty good abstraction (I just call .AddObject() and it looks like I am modifying an in-memory collection and I just call .SaveChanges() which already provides the unit of work pattern).
Should I even bother implementing this abstraction? I feel like there must be some massive benefit that I am missing, but it just doesn't feel like I need to go down this route. I am willing to be convinced otherwise; can someone make a case? Thanks.
I recommend you reading this answer and all linked questions. The repository is very popular pattern and it really makes your application nice and clean. It make you feel that your architecture is correct but some assumptions about repository pattern with EF are not correct. In my opinion (described in those answers):
It will make some more complex EF related task much harder to achieve or your repository and UoW implementation will need to have public interface very similar to EF's
It will not make your code better unit testable because all interactions with repository must still be covered by integration tests. Not only my experience proved that mocking EF code by replacing linq-to-entities with linq-to-objects does not test your code.
yes yes yes : ) - first of all - the repository pattern helps to inject your dependencies for unit testing. Secondly, it gives a very clear view of exactly what data access methods are available to get something rather than people misc. coding against the EF layer directly. Download the POCO templates though for EF4 so your classes don't carry the EF properties around with them if you happen to use them as models and/or don't want any EF dependency libraries references in your mvc app assuming your repository work is in a separate project (which I recommend). If you are using all viewmodels then its not as much of a concern, but its nice working with a "Customer" object without extra methods on them. Its cleaner in my opinion.
My question is a design issue and it has been driving crazy over the last couple of days. I am new to cocoa touch development.
I have an application that has a UINavigarion controller and a 3 views. I need to keep communicate with a WCF service and store the data on the app side.
How do I create my Model (MVC) in a way that makes the data available to all controllers?
What I started doing is a singleton that handles all the storage and web calls but I read thru the threads that it is a bad idea. I also considered putting the code in the appDelegate but people say that is a bad idea too.
Conceptually how would u design your model and communicate with the controllers?
Any help is much appreciated.
You will get different advice because opinions differ on the best method to use. As you noted, for handling a data model, there are two major design patterns: Dependency Injection and Singleton.
Dependency Injection relies on passing the data model object from view controller to view controller as needed. Marcus Zarra (author of Core Data: Apple's API for Persisting Data on Mac OS X which I recommend) wrote a good article explaining Dependency Injection. Most of the Apple documentation recommends that you use the Dependency Injection design.
I like the Singleton pattern but it is very, very, very dangerous for a novice to use. The Singleton pattern is so easy to do wrong that most graybeards have given up on it and simply advise novices to never use it.
The Singleton pattern has the advantage of increasing modularity and flexibility of the app. However, it requires that you have a firm idea of what the data model will do before you start coding both the Data Model and the UI. It requires more work up front to get correct and it is not as forgiving as Dependency Injection. You have to use singletons with greater discipline.
For a simple app with three hierarchal views, Dependency Injection is the simplest and cleanest design to implement. You won't need the flexibility of a singleton and a singleton will just add unneeded complexity. The Navigation-based template with Core Data provided by Xcode will give you 50% of the app to start. Just add the second and third tier views and you're done.
What is CSLA Framework and Its use ?
My Opinions From My Experience w/ a 1.7M LOC code base:
CSLA is intended for a distributed application/database environment. This is why the basic business object is and does everything, for example it's own data persistence. An object (and everything remotely associated w/ its state) is intended to be serialized, sent to a different application and/or data server and work.
If the above is not a problem you need to solve, CSLA is overkill, big time. Our development team regrets having committed to CSLA.
Juggling all the CSLA balls in a complex Windowed UI is tough. We have multi-tabbed screens (which may in turn open sub-screens) that, unless you follow the "left to right, top to bottom" flow of data entry, and click save often, ends up putting and/or fetching incomplete data to/from the database; or dropping data altogether that you just entered. Yes, our original coders are at fault, but so is CSLA... It just seems that there are so many moving parts to enable, control, and coordinate CSLA features. It's like having to deal with all the dials & switches of a fighter jet when all you really need is something more like a Cessna 152.
You will write lots of custom code to enable the CSLA features. For example CSLA will never be confused with object relational mapper (ORM) tools like Hibernate and Entity Framework. Our SAVE() methods are non trivial, so are the trivial ones.
Encouraging the use of code generators compounds problems. We used CodeSMith to generate classes from data tables. So we end up with code that has a 1-1 correspondence of table to c# class. So you must write all the code to handle dataStore to your "real" objects.
Data store/ and fetch is very inefficient w/ CSLA. Because of the Behemoth, monolithic BusinessObject-does-all-and-knows-all centric paradigm, objects end up doing a one-object-at-a-time data fetch and instantiate. Collections of composite objects significantly compound the problem. A single "get this object" always results in a cascade of separate data fetches (one or more for each individual object) to instantiate the entire inheritance & composite relationship chains. Its known as the "N+1 query problem." Oh, and fetching data ALWAYS results in a new object being created, even if we're only updating an existing one. No wonder our more complex screens are FUBAR.
It allows you to architect your application with solid object oriented principals and a good seperation of concerns.
Yes and no. Mostly no.
The BusinessObject handles it's own data storing. That is anti separation of concerns.
"It allows you..." well, yeah - so does a blank text editor screen, but does not force or encourage you like the MVC.NET framework does, for example. IMHO, CLSA provides absolutely zero benefit for ensuring that the code you develop with it follows "solid OO principles". In fact coders w/ weak OO skills (the majority, in my experience) will really stand out when using CSLA! Woe betide the maintenance programmer.
CSLA is the poster child for the solid object oriented principle favor composition over inheritance. CLSA code is untestable. Because an inherited framework BusinessObject is, does, and needs everything, all at once and every time, it's not likely that you will be able to get much test coverage. You can't get at the pieces because everything is tightly coupled.The framework is not amenable to dependency injection. It is an iron curtain of code.
Your code will be difficult to debug. Call stacks get very deep and as you get near the center of the sun so to speak, everything turns into reflection - "what *&^# methods just got called???" And you simply get lost. period.
EDIT 7 Mar 2016
What more insight can I add after the original post? Two things, perhaps:
First, It feels like CSLA has some promise. If we knew how to juggle all those moving parts together. But CSLA is so enigmatic that even things we have done right are corrupted over time. IMHO without a very strong team-wide CSLA wherewithal, any implementation is doomed. Without a vibrant "open source" of technical references, training, and community it's hopeless. In almost a decade our CSLA code, in my final analysis, is just compounding technical debt.
Second, here is a recent comment I made, below:
Our complexity often does not seem to fit in the CSLA infrastructure
so we write outside of the framework. This and cheap labor results in
rampant SRP violations and has me hitting brick walls managing dynamic
rule application, for example. Then, CSLA parent/child infrastructure
propagates composite object validation but we don't always want c/p
relationships, so we write more validation and store code. So today
our CSLA implementation is inconsistent & confusing. Refactoring to
more-better CSLA will have profound domino effects. So after that
initial injection CSLA is essentially abandoned.
end Edit
CSLA is business object framework that allows you to easily create business objects on top of a data layer. It allows you to architect your application with solid object oriented principals and a good seperation of concerns.
I would highly recommend you read the CSLA book by Rocky Lhotka called Expert C# 2008 Business Objects. That will not only teach you about the framework but also teach good software architecture principals.
You can grab the book here on Amazon
I suggest reading the What is CSLA? page, and browse through the CSLA .NET FAQ site.
For the latest published information check out the Using CSLA 4 ebook series.
In reply to #radarbob https://stackoverflow.com/a/10922373/261363, hope I won't regret this and start a flame war.
Our team has been developing a couple of LOB applications with CSLA. From my experience on writing green field apps with CSLA and maintaining existing code here are my replies to your points.
The BO is not suppose to do it's own data persistence, you will have a Factory that will handle all data persistance, for example using a ORM to map to Models that are later on saved.
Sorry to hear that, I make sure I study the framework documentation and write at least one toy application before committing to a existing code database. Furthermore you can even download and browse the CSLA code.
You have BO -> Portal -> Factories that should not be very complicated the existing CSLA examples go a long way on explaining what is happening on each level.
CLSA should never be confused with a ORM
As you should, business object are rarely mapped to one table and thus require a bit of work when saving. In the case they are mapped to one table to you use something like AutoMapper to map your BO to your POCO in 1 line.
Look into CSLA Commands, also is nothing stopping you from keeping your BO as small or big as you want as long as you keep in mind that they are not the same as the POCO's that you will persist.
In a project we worked on we where able to easily test BO to ensure that the business logic was correct. Because of the nice separation of concerns we tested our Factories in isolation to make sure that business objects will be persisted accordingly.
At one point I was able to easily persist part of my BO's in MongoDB so the application was running on a hybrid database MSSQL and MongoDB without having to even change one line of code in my business objects, all I had to do was to update the factories to use Mongo instead of the current ORM.
Hope this addresses all your points in a fair manner,
Regards
CSLA: Component-based Scalable Logical Architecture
A paragraph in a nutshell that described CSLA to me from the website was this:
CSLA .NET enables you to create an object-oriented business layer that abstracts and encapsulates your business logic and data. The framework ensures your business objects work seamlessly with all .NET interface technologies, including WinRT XAML, WPF, ASP.NET MVC, ASP.NET Web Forms, WCF, asmx services, Windows Phone 7, Silverlight, Windows Workflow and Windows Forms.
Why you might use it:
Business rule management. Once you learn the business rule system, it provides a way to enforce business logic in a tidy package. If you have an object with child objects that need to report Validation to the parent most level, there is a way to handle that. (see http://www.lhotka.net/weblog/CSLA4BusinessRulesSubsystem.aspx for more information on the rule system)
You have business objects that you need to support N-level undo? A CSLA BusinessBase has a baked in property management system (like dependency properties) for functionality like N-Level Undo (it is actually completely implemented.) (This also ties into the business rule management. You can fire validation when a primary property changes, or you can change a property based on the value of another property.)
Data portal management. This one was an interesting concept. If I need to execute data operations locally, CSLA is configured for this out of the box. I can also stand up a WCF service that references my business object libraries, and use a few lines of configuration to make a WCF endpoint to manage data operations. The WCF service is a part of the CSLA framework. It was neat to see this in action. Other scenarios? Sure! Your business object library doesn't need to change, the DataPortal class determines if it needs to execute remotely or locally, according to your configuration.
CSLA does force you to use a few mechanisms that may not feel natural at first. I think that is somewhat true of any pattern you choose to implement. However, when it comes to the challenges of implementing Service Oriented Architecture, CSLA offers a lot. Yes, you are going to have an architect level developer authoring some of your libraries. However, if you're building an enterprise class application, shouldn't you be doing that already?
CSLA, when architected correctly, is testable. We use the repository pattern to replace out the actual dal with a mock layer and test both by specification (using NUnit/SpecFlow) and in a unit fashion when appropriate.
As far as support, including Rocky himself, there is a community of contributors that ensure things like CSLA.Net for Xamarin become a reality. There are consultancies that know CSLA and use it on a regular basis depending on the scope of work (and no, not just the consultancy for which I work.)
All things considered, CSLA may not be for you. Like others have indicated, read the site and the books (especially Expert C# 2008 Business Objects.) Ask questions, as the CSLA community tends to give quality advice.
CSLA is described in detail here. The new book is a great starting point. As a great compliment to the book I would recommend checking out our CSLA 3.8 templates. Rocky recommends using a Code Generator, and we have the leading set of templates, that will get you up and running in no time.
Thanks
-Blake Niemyjski (Author of the CodeSmith CSLA Templates)