MVVM, UWP & Template 10 - Independency of model from view technology - mvvm

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.

Related

Is there penalty in using too many EnvironmentObject?

I'm writing a keyboard extension which resources are more limited. I am trying to pick a code structure and need some help. The project will have multiple classes or struct to encapsulate a fair amount of data, with functions to manipulate them. There will be one or two variables in each class to define the state which UI will need to be updated accordingly.
Two design choices
Make each class as EnvironmentObject and publish the variables the UI needs to observe. This would mean I need to set ~10 classes as EnvironmentObject.
Consolidate the state variables to one class which is set as EnvironmentObject. It is less clean but I will only need to set 1 class as EnvironmentObject.
My question is: Is there any penalty in picking 1?
Everybody's application will be slightly different in terms of setup.
However, the ObservableObject protocol means that each object – whether declared as an environment object or a state object – has a single objectWillChange() method which fires whenever any observable attribute changes. The #Published property wrapper automatically handles that for us.
But that message only tells the SwiftUI rendering system that something in the object has changed; the rendering system then has to work out whether any of the changed object's new properties require the UI to be redrawn.
If you have a single environment object with a huge amount of published properties, it is possible that might result in a performance hit. If you split that single object into multiple environment objects, and each view only opts into the environment object it needs to watch in order to redraw itself, you might see some performance improvements, because some views' dependencies would not have changed and so SwiftUI would be able to, in essence, skip over them.
But having multiple objects can have downsides. As a developer, it can be harder to maintain. You would also need to ensure that each environment object was truly independent of all the others (otherwise you'd get cascading updates which would negate any performance improvements, and possibly make things worse). It can sometimes be easier as a developer, too – if you get the separation of functionality right, it can help keep your code organised and maintainable. Getting that sweet spot can be really tricky, though.
So there's a balance to be struck. If performance is turning out to be an issue, Instruments ought to be able to help in terms of deciding where your individual pain points are and how to start addressing them.
But generally, I'd start from the code structure that makes it easier to write and debug for you. It's easier to optimise well-structured code than it is to maintain highly optimised but hard-to-read code!
(Disclaimer: I'm not a deep expert in SwiftUI and Combine internals – the above is gained from my practical application experience, as well as facing similar questions in the world of ReactJS and Redux in the JavaScript world, where single large state objects face similar scale issues)

MVC in Cocoa Touch

I'm having troubles understanding if I'm properly implementing the MVC pattern in an iPhone app. In my app I have views, view controllers and models. The view controllers manage the interfaces, navigate to other view controllers, set variables to other view controllers and models, and communicate with the models. But this way, am I correctly following the MVC pattern? Don't I miss a model controller?
Another question: I have a User Model that I need to have access to in almost every models and some controllers. Would it be correct to define it as a variable in the appDelegate? I'm all the time reading that this is a bad practice, but I don't see why in this case.
Global objects
All non trivial code has bugs, and they are harder to track if you use dumb global objects. By "dumb" I mean generic objects from the API that lack a single point of access in case you need to log, validate, key-value observe, and notify, changes. You can wrap the global object in a class to route everything through your own accessors.
Some say using globals at all gets you into a bad habit. Others say it depends on the size of your code because it is a trade between development speed and complexity.
The appdelegate is a Singleton, so this discussion is related: What is so bad about singletons? and Singletons: good design or a crutch?.
MVC
Apple talks about it in Cocoa Core Competencies and Cocoa Fundamentals Guide.
One can merge the MVC roles played by
an object, making an object, for
example, fulfill both the controller
and view roles—in which case, it would
be called a view controller. In the
same way, you can also have
model-controller objects. For some
applications, combining roles like
this is an acceptable design.
Is your design complex enough to need a model controller? Whatever your decission is, suffering the consequences will teach you a lot. :)
A design pattern in which the model (any data in your program), the view (what the user sees), and the controller (a layer that handles all interaction between the view and model) are separated in such a manner that modifying either the view or model component of your program has no effect on one another.
The purpose:
The purpose is that later on you may need to change your programs view, and by programming things in this matter you will not have to modify your programs model. Say for instance Apple comes out with an iPad for which the view is programmed somewhat differently than on the iPhone, but you would like to
Now I received some messages after making the video above, some thanking me for making the concept of MVC sound so simple, and others telling me that I had confused them, and wondering how I could understand any of this stuff.
Well, don’t fret.. I’ve seen arguments all over the place as to what components should be classified in the model, the view, or the controller, and I’ve even seen accomplished "guru authors" mess things up when explaining what goes where, just keep in mind that the key idea here is that you can modify one of these key areas without completely wrecking another key area of your program, and leave the rants to the wannabe coders who like to argue about what exactly what fits what acronym, and MVC is often their target.

Entity Framework, application layers and separation of concerns

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.

How to architect an asp.net mvc application?

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.

What is CSLA Framework and Its use?

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)