Business Logic placement in WPF application - c#

This might be a long list of questions but please bear with me. I started building LOB applications with WPF, PRISM, CODE FIRST and SQL CE, and after my first application (or attempt) I have many questions, so to begin with:
Where should business logic go, in the model or in a BLL layer just above the domain layer ?
Should view models receive references to repositories or should repositories be used only by the domain model objects ?
To put the second question in another way, what sort of objects should be given to view models ?
I use the same view model in display (in a data grid for example) and for editing in a form but that causes a lot of trouble, is there a better way to do this without code duplication ?
The biggest problem I have faced was that I always organized my view models in hierarchical relationships without allowing the children in the hierarchy to obtain references to their parents, and since the views bound to those children and invoked methods that caused the addition of objects to the repositories I couldn't find a way to notify the parents of the changes to the those repos. so the bound views could be updated, I have seen some people solve this using events but I don't like this solution and I would like to know if there is a better way to do it ?
Can anyone point to an example of building real life LOB applications using the technologies mentioned above, at least not examples that use VB .NET or WCF (I want local databases).

I'm developing a LOB app right now, with WPF, Entity Framework Code First and SQL CE 4.0 with a local database. I'm not using PRISM, but I'm using MEF as IoC with my own implementation.
So far, I recommend that you use the benefits of Code-First approach and implement as much business logic in your domain classes as possible. Also implement INPC in them. If you don't you'll end up having all your properties duplicated in your ViewModels, which is nonsense. There is no rule that says that the model should be dumb (although some people tend to think so), but a dumb model just makes the ViewModels more tedious to work with.
No clear recommendation here without knowing more of your project, but common sense: try to stick to best practices unless they start coming in your way. "Perfect" is often the enemy of "good".
Let the ViewModel get whatever they need (single model objects, collections, etc.) to serve your views. Often the simpler solution is easier to maintain in the long term.
I don't quite understand what you mean with this... I use my ViewModels several times if possible, but think that a ViewModel's function is to serve a View, if you are having trouble trying to get one VM to work for several Views, it's probable that you need to divide it into two different VM. Just gather all the common properties and methods in a base class and inherit from it as you need.
There are some loose-coupled ways for the VMs to communicate with each other. I'm using MVVM Light Messenger class for such things, but I understand that PRISM provides a similar functionality. It's not a sin to reference the parent from the child if you don't abuse it. I have a ViewModelBase<T> and the child have a reference for their parent pointing to the base class and specifying the T type, a good balance between hard and loose reference so far.
If someone points you to such an example, let me know! Actually, working with a local database should be simpler. In my case I'm using a singleton context (which a lot of people seem to loathe) but since this is a local app, with a single user and no threading complications a singleton context makes my life much easier. I'm still waiting to find a real good reason not to do so with this conditions.
PS: some people will probably downvote your question because... it is not ONE question, and it opens room for a lot of debate. If it gets closed, try the chat.
Hope this helps you, regards!

Related

Is grouping View Model properties into different categories a good practice?

I'm working on a WPF project using the MVVM pattern and I was wondering if I can improve the internal structure of my ViewModel by abstracting its exposed properties into separate classes.
It's common practice for VMs to contain lots of properties laying around in the same class: Some are used to retrieved user inputs, some are used to expose commands, others to expose the models, and probably some other properties for the view model's own business logic. Not to mention that these properties often have set and get bodies that adds some bulk to the package. This can quickly become messy inside a VM class and finding one's way there can become challenging.
As a way to solve this issue, I am exploring with my team the idea of grouping properties inside my VM into different categories. As a first approach, I chose to group them this way:
ViewData, UserInputs and Commands, each one represented by its own class. Then I referenced them as properties inside my VM class.
My intention is that these classes will only act as placeholders to free up the bloat in my VM and keep it clean and focused only on interaction logic for handling user events.
It's a simple refactoring, but I get the following pros:
Cleaner and readable VM.
Easier binding from the XAML because you know what the entry point is/should be.
Let me elaborate on the latter one: If I want to bind a text box to a property of my VM, I know the binding expression should start with Userinput.MyVMProperty. If I need to show a value from my VM, I know my binding's entry point is going to be ViewData.MyOtherVMProperty. Binding intellisense will also become better because when you know your entry point, the
suggestion list would be smaller and more focused. This also works the other way around: when reading through your XAML controls, any binding that starts with UserInput necessarily means it's a a control that should send data back to the VM.
The only cons I can find is that this will require creating extra classes for each VM, but I believe it's a fair price to pay for the benefits you get.
Take note that the grouping I suggested may not be the best, but I don't mind any other grouping as long as it solves the problem with bulky VMs.
So, has any one ever tried a similar pattern? Do you think this is a good idea/practice? What other good practices I can use to improve my VMs?
Bonus question: One developer in my team who seemed to agree with this idea, suggested to go the extra mile and consider the grouped classes as VM dependencies and that they need to be injected inside the VM. What do you think about this?
So for every ViewModel you need to create own inner classes for every group. You cannot use Interfaces because ViewModels have different properties and commands
Then did you considered that every "groupclass" must to "know" about other groups for ViewModel will work properly.
In my opinion Class should be solid logical structure with minimal outside dependency.
Based on the pros you trying to achieve I can suggest another approach without changing structure of the ViewModel classes
Readability can be achieved partly by #regions.
Or use Partial class for separating different groups in the different files,
while keeping them inside one logical structure
Intellisense can be improved by naming conveniences - using prefix based on group property belong to. For example UserInputMyName, ViewDataFullName or CommandDelete

Is there a common DDD pattern to deal with under-loading of domain objects?

Sometimes when working on applications, especially when trying to follow proper OOD and DDD patterns, we end up with domain classes such as Customer. Then we have some repository that will load this object, and everything is nice and clean.
Then the application grows in complexity, and we start optimizing for performance. We often find ourselves in situations, where we do not really need to load, say, a list of full Customer objects, but maybe just IDs and names, or a small subset of properties (for example to display in a grid)
Solutions that I have often seen include:
Under-loading domain objects, so basically we would still use Customer class, but we would use separate repository method to load those, and that repository method would load from database only required fields, and populate corresponding properties in objects. Remaining Customer fields would just remain at their default values. This is simple solution, but can lead to many errors if developer (or existing code) expects certain properties to be loaded.
Purpose-classing where we create classes such as CustomerIdName, CustomerInfo, CustomerHeader that contain only properties we need. This approach could create a large number of classes, but with careful subclassing is workable. It seems like it takes away from ubiquitous domain language concept though.
So is there some generally agreed convention to handle those in DDD world? I tried to google this, but were not able to find anything authoritative.
Or maybe it is just a well-known limitation of classic DDD approach and CQRS or other approaches would be better in those scenarios?
I think second approach is the way to go.
We are doing that way in our projects but only for read only DTO classes. As long as you are not using them for insert/update that is just fine I guess.
There is also that answer you maybe interested in:
It's a well-known limitation of DDD and CQRS is a very good approach to solve it.
CQRS on the read side is basically solution #2 with all necessary precautions to avoid confusing Read Models with modifiable domain Entities : no Repositories for them, readonly classes, etc.
Have you looked into Entity Framework? They have multiple levels of entity lazy loading: MSDN Post
I don't understand why under loading can be a problem. You know which fields are invalid so can block access/lazy load them

Business Layer Facade vs Mingled Business Components

I'm currently designing the foundation for a large application. We are going with the traditional 3 tier system using EF in the data layer, plain jane c# classes in the business layer and MVC / WCF for the ui layer. We have prototyped enough of the application to realize that this will work for us, however due to the complexity of the business requirements it will be common for some of the business components interact with one another.
Consider the following two business components:
RetailManager - Deal with everything related to retail in the system
CartManager - Deals with everything related to the shopping cart experience
The two interact, for instance, during the checkout process when an item is purchased. The inventory for the purchased item needs to be reduced.
Here is my thought process so far:
Let business components reference each other and ensure cyclical references never happen (CartManager references RetailManager, but never the other way). "Checkout" would be a method on the CartManager class, and it would call a method on the RetailManager to adjust inventory. While this will work, I'm not sure how well it will scale, and what the maintenance cost will be over time. It doesn't feel 100% "right" to me.
Create a Facade between the business components and the UI tier. In this example, the Facade would have the checkout method and a reference to both managers. I like this approach more than the first, however I know that not all of my business objects will need a Facade, and I don't want to create a ton of Facade classes just to have empty pass through methods.
I'm leaning towards 2, with the caveat that I will only create facade classes where needed. The UI tier will have access to both the Facade and the business layer components and will have to know when to use which (the only part I don't like about this solution).
I've done a lot of research but haven't been able to come to come up with a solution that feels completely right.
Any thoughts on using the facade pattern in this way, or other ideas to solve the problem are welcome.
Thanks in advance.
That's a typical problem for using manager/service classes. they always tend to get bloated. When you come to that point it's probably better to start using commands instead.
The great thing since you are using an IoC is that you doesn't have to refactor all the code directly, but can do it when there is time. Simply start writing commands for all new features while keeping the old architecture for everything else.
Here is a intro to commands: http://blog.gauffin.org/2012/10/writing-decoupled-and-scalable-applications-2/
And an intro to my own framework: http://blog.gauffin.org/2012/10/introducing-griffin-decoupled/
I would tend to go with facade implementation.
I would first ask myself, whose responsibility is it to make sure that inventory is reduced when a checkout happens? I don't think it is responsibility of CartManager to reduce the inventory. I would have a third class (in your case facade) that makes sure that whenever an item is checked out by CartManager, corresponding item is reduced from inventory.
Another option I would consider is event based implementation. CartManager would raise a ItemCheckedOut event whenever an item is checked out. RetailManager would subscribe to this event and would reduce the inventory whenever an event is raised. If you are new to event driven design, follow this question on quora - http://www.quora.com/What-are-some-good-resources-on-event-driven-software-design
I personally like the pattern of CQRS, it fits naturally with other architerural patterns
such as Event Sourcing and suited to complex domains.

Should UI components ever be passed to a Business Logic assembly for binding

I've recently been handed a code base which does a few things I'm a little different to how I usually do them.
The main difference is that it seems to pass elements (say for example a drop down list control) down to the business logic layer (in this case a separate project but still in the same solution) where the binding to business data takes place.
My natural approach is always to surface the information that is required up to the UI and bind there.
I'm struggling to match the first technique to any of the standard patterns but that may be down to the actual implementation less than the idea of what it is doing.
Has anyone ever encountered this type of architecture before? If so can you explain the advantages?
The solution is an ASP.Net website. Thanks.
Thanks,
I would make the case that this is a bad architecture, since the original developer tightly coupled the business logic to the presentation layer. If you wanted to switch from webforms to, say, MVC, you'd have to refactor chunks of your business layer, which shouldn't be the case!
If it's at all possible, you should consider moving away from developing the site in this fashion. In the interim, you can at least start the decoupling process by splitting the logic up a little bit further. If, say, you have a BindDropDown(DropDownList ddl) method, split the method apart, so you have a GetDropDownData() method that returns your actual business object, and BindDropDown only sets the values of the DropDownList. That way, at least, you'll be more easily able to move away from the tight coupling of the presentation layer and business layer in the future.
Of course, if the site is already designed like that (with a clear demarcation between the presentation layer, the intermediate "presentation binding" layer, and the business layer), I could see a case being made that it's acceptable. It doesn't sound like that's the case, however.
No, you should not pass UI elements to the Domain Model to bind / Populate.
Your domain model should ideally be able to be used with Windows Forms / WPF / Silverlight / ASP.NET / MVC you name it.
Now, I kinda understand the idea that your business objects should know how to store and render themselves etc it's the OO holy grail, but in practice this doesn't work well, as there often are dependencies (database middleware, UI components etc) with those functions, that you do not want in your BO assembly, it severely limits your reusablility.
Something that you can do though that gives your users the illusion of your BO knowing how to render itself is using extension classes (in a separate assembly, to contain the dependencies) something like...
public static class AddressUIExtensions
{
public static void DisplayAddress(this Address add, AddressControl control)
{
...
}
}
Then the API user can simply do
var ctrl = new AddressControl();
address.DisplayAddress(ctrl);
but you still have physical separation.
Has anyone ever encountered this type of architecture before?
If so can you explain the advantages?
The only advantage is speed of development - in the short-term; so it's well suited to simple apps, proof-of-concepts (PoC), etc.
Implementing proper abstraction usually takes time and brings complexity. Most of the time that is what you really want, but sometimes an app might be built as a simple throw-away PoC.
In such cases it isn't so much that a room full of people sit down and debate architectures for a couple of hours and arrive at the decision that binding in the BL makes sense - it's usually a "whatever-gets-it-done-fastest" call by the developers based on speed.
Granted, that simple laziness or ignorance will probably be the reason why it's used in other cases.
Your business layer should return a model - view model that the UI layer will in turn use to populate what it needs - period. There should be nothing sent to the business layer in terms of ui components - period. Its that simple and that hard and fast of a rule.

How should my model look like?

As I am further digging into MVVM and MVVM-light I recognized, that there is no MVVM-light provided base class for models.
But from my understanding, messaging and raising notifications could also happen in a model. At least in communication between models I would find that messaging would come in very handy.
So I just decided to derive my Model from ViewModelBase, even though some of the properties (like the design time ones) will be unused.
But the more I am looking at this, the more I think I have missed something. Is it considered "bad practice" to derive my Models from ViewModelBase?
And is it ok to use Messaging for Model communication?
Derive your view-model classes from whatever you like... MVVM-light offers the VieWModelBase to provide an implementation of ICleanUp - which is good for managing the life-cycle of ViewModel objects. My own choice has been to implement all scaffolding for Property Change notifications in a base class, then derive from that for model classes. About the only strong suggestions I have regarding model classes are:
Once size doesn't fit all. How you store your data may be different from how you interact with data, and ViewModel objects should be geared towards supporting interaction, not storage, and if you need to interact with the same data (Model) in two very different ways, then design two different ViewModels to support these different interactions.
Do use attributes (a la System.ComponentModel) to annotate the models. You can get a lot of your validation work done this way - and validation feedback is the responsibility of the presentation layer (View + ViewModel), not the problem domain (i.e. the Model).
Really good ViewModel classes are also usually stateless enough that they can be recycled/reused within a single user interaction, such that large data lists can be virtualized (WPF supports virtualization) to save RAM.
Remember DRY (Do Not Repeat Yourself), KISS (Keep It Simple, Stupid!) and YAGNI (You ain't gonna need it) - are the principles you should keep in mind above any academic design principles. I've litereally wasted weeks on a WPF app implementing academically perfect MVC/MVVM patterns, only to find that they detracted form the overall understandability of the finished solution. So... keep it simple! :)
I would take a look at the EventAggregator in the Composite Application Library. The answer in this post has a good description of it. Jeremy Miller's post goes into a bit more detail.

Categories

Resources