Why two Models should not talk to each othetr - wpf

Well , In MVVM pattern it is good practice that two models should not know or talk with each other. That means you should not create a object of one model in other and then register for event or performing similar things.
But why, what is wrong if two models know each other. I am writing the code and what will happen if both my models know each other.

If you are going to circumvent MVVM in any way you want to have a good reason (otherwise you might as well just write it as traditional code-behind and save some typing) :)
There are several benefits of using MVVM, which are mainly to do with very loose coupling, unit testing and reuse.
The basic principal of loose coupling goes something like this:
A View knows how to display data of a certain shape, but has no idea where the data comes from.
A ViewModel provides a certain shape of data and settings, that views can use, but has no idea who is displaying it.
A Model knows how to hold generic data, but no idea who is consuming it
A Controller (missing from most MVVM explanations) decides what data to fetch, what data to display and where to display it. This is where the decision making belongs.
If you require your ViewModels to know about each other, then you are most likely missing a Controller object that manages your 2 ViewModels and associated Models/Views.
If you can provide more information about why your models are currently linked, I may be able to suggest an alternative.

It's often perfectly appropriate for view models to interoperate with each other. Parent/child relationships in the view involve the parent view model holding a collection of child view models, after all. There are any number of circumstances in which, for instance, the availability of commands in the parent view depend on the state of its children. It's sometimes appropriate to delegate this to a separate controller class, but it's also often not worth the effort to do this.
It really depends on the overall complexity of your application. Sometimes that kind of effort is essential; sometimes it's just gold-plating.

Related

Are current MVVM view model practices a violation of the Single Responsibility Principle?

With current practices (at least with WPF and Silverlight) we see views bound via command bindings in the view model or we at least see view events handled in view models. This appears to be a violation of SRP because the view model doesn't just model the view state, but responds to the view (user). Others have asked how to build view models without violating SRP or asked whether their implementations do so (this last is the controller in MVC, but roughly analogous).
So are current practices a violation of SRP? Or is "view model" really a collection of things that don't violate SRP? To frame this a bit, it seems we need to know what is the single responsibility or if there are multiple responsibilities in the concept, are the individual responsibilities split out, conforming to SRP. I'm not sure.
Wikipedia's definition of view model says
[T]he ViewModel is a “Model of the View” meaning it is an abstraction of the View that also serves in data binding between the View and the Model
This seems good enough for SRP, but then the entry later says (my emphasis added)
[The ViewModel] acts as a data binder/converter that changes Model information into View information and passes commands from the View into the Model
In a Prism blog post about the view model's role, the author says (again, my emphasis)
What it boils down is that the view model is a composite of the following:
an abstraction of the view
commands
value converters
view state
I'm sure I've missed many definitions out there, but they seem to fall into these categories:
Single "vague" responsibility of modeling view state (so what do we
mean by state)
Multiple responsibilities (view state, user interaction (i.e.
commands))
A composite of single specific responsibilities (abstraction,
state, interaction, conversion), thus having a single
responsibility: "managing all that stuff".
If you're curious, I "care" about this because (2) feels right, but seems counter to the prevailing implementations.
Single Responsibility as Martin defines it:
"THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE."
A ViewModel, as far as MVVM is concerned is really just a specialized implementation of a Presentation Model.
So while it could be argued that a Presentation Model should only represent the state of the UI, and that a Presenter/Controller should always broker the commands between the UI and the Presentation Model. If one follows this idea, with SRP dividing on State and Commands, then adding a command should not affect the class that represents state. Therefore MVVM would break SRP.
However...
I think this is grasping at straws. MVVM is a fairly specialized implementation used basically in WPF/Silverlight (and now browser clients).
Patterns are designed to make designs simpler where the alternative would be more cumbersome or less maintainable. Since MVVM is designed to take advantage of the extremely rich data binding capabilities of the presentation technologies, then it is a worthwhile trade off.
No! MVVM does not violate SRP, (the programmer does, lol!)
There is no reason that using the MVVM pattern needs to ignore the SRP. MVVM does not mean that there is only one Model Class, one View-Model Class, and one View Class. Certainly, if you only had one View Class, you could only ever show one simple screen.
Those classes that are in the View tier, should be responsible for one thing; doing, deciding, or containing. A View can consist of several sub-views who's jobs are to do certain pieces of the users interractions. Consider a basic form, it has a display grid, items in the grid can be edited, and there is a "Save" button.
The main View would be a container for two other views; the datagrid (a user control, or something) and a command control. The datagrid then is responsible for choosing the right childview to render data in; in essense it's a container that databinds. The View to edit items is a child view of the datagrid, which is in-turn a child of the main View. Lastly the command control is a set of buttons (in this case a single one) who's single responsibility is to raise signals that commands have been issued by the user.
In this way the Edit View (used by the DataGrid) is agnostic about what uses it, and has one responsibility; Same with the command control. Likewise the DataGrid doesn't care about who uses it, only that it can contain the Edit View (child). Nice SRP there.
ViewModels to match the Views (and children) are also responsible for one thing. The Edit View Model is a container to which the Edit View Binds; it simply contains the data fields that can be displayed/edited. It doesn't care about anything but signalling when one of its properties change. The Command Button View Model is a class that does things. It's commands are bound to the buttons, and it will do work based on what the user clicks on. It will have to have access to other parts of the ViewModel(s) to do it's work.
The main page View Model is there to contain the other child views. It's sole responsibility is as an initializer, making all the required ViewModel instances, and passing constructor parameters to other ViewModel instances (say, the Command Button View Model so it knows where to get data for it's work)
It's natural to cram a whole bunch of functionality into a single ViewModel that a large View would bind to. But it doesn't have to be that way, and SRP can be maintained in MVVM.
The main goal of MVVM is to allow for testable design, the Model layer can be tested independantly, all classes in the Model can easily follow SRP. The ViewModel can be tested without the need of a view; it gets trickier to think SRP in the ViewModel, but it is certainly doable; just remember to break out your classes so they only have one concern. The View is bound to parter ViewModels, with any luck, your testing of the ViewModel makes snapping the View(s) on super easy. Remember you can have each View-let adhere to SRP to be part of a larger conglomerate View (container).
TL;DR?
To answer your question directly, the View is a collection of classes that does not break the SRP. Thus, when the ViewModel is abstracted from the View(s) (View-First), they are also a collection of classes that adhere to good SRP.
I consider many of the current practices around MVVM violate SPR (at least). This is yet another situation where simply adding controllers back to MVVM would solve all the problems cleanly. I call it MVCVM :)
The pattern we are using successfully on all recent projects is to register controllers only, in modules, and initialise them at startup. The controllers are very light/slim and the only thing that needs to hang around for the life of the app listening for, or sending, messages. In their initialise methods they then register anything they need to own (views and viewmodels etc). This lightweight logic-only-in-memory pattern makes for slimmer apps too (e.g. better for WP7).
The problem with just using VMs, as you have found, is that eventually you hit cases where they need to know about views, or commands, or other stuff no self-respecting ViewModel should be involved with!
The basic rules we follow are:
Controllers make decisions based on events
Controllers fetch data and place it in appropriate View Model properties
Controllers set ICommand properties of View Models to intercept events
Controllers make views appear (if not implied elsewhere)
View Models are "dumb". The hold data for binding and nothing else
Views know they display a certain shape of data, but have no idea where it comes from
The last two points are the ones you should never break or separation of concerns goes out the window.
Simply adding controllers back into the MVVM mix seems to solve all the problems we have found. MVVM is a good thing, but why did they not include controllers? (but this is of course just my opinion) :)
What it boils down is that the view model is a composite of the following:
an abstraction of the view
commands
value converters
view state
I don't see why you've separated the first two items. Commands are part of the view.
As for the rest - you're right. In some cases. I've built applications where the tasks of value conversion and maintaining view state were sufficiently complex that it didn't make sense for a single view model class to do it all, and I broke them out into separate classes that interoperate with the VMs.
So?

Should ViewModels ever be reused by different Views? If so, when?

From what I have read, it seems to be considered a best practice in MVVM for each View to have its own corresponding ViewModel, which makes sense, since the ViewModel is supposed to be the model of the View. Generally, reuse of ViewModels by different Views seems to be discouraged. Is this always the case? If not, what are the general guidelines for determining whether or not a ViewModel should be reused in this manner?
One situation I can think of where it might be satisfactory to reuse a ViewModel with a different View is when two Views make use of the exact same data from the Model and the Views themselves just represent the data differently. If the Views can handle representing the same data in different ways themselves, one ViewModel might be able to serve each View effectively.
The reason we have rules is so that you think before breaking them.
That is: there's nothing wrong with using the same ViewModel for two similar views. You do need to be very careful that your two views don't diverge, leaving you with a viewmodel that's attempting to do two different things.
This is why the recommendation is to have one viewmodel per view. Even though this might lead to duplication, it'll make maintaining the views easier in the long run.
As for the duplication, there's nothing wrong with viewmodel classes that have a shared base class.

Can the VM of MVVM be reused?

I just need a simple clarification:
I have an example application with a Model of a ball, and two views (lets say one shows the ball and lets you resize if with the mouse, change it's colour with a click, the second has a control with two child controls (size textbox and colour picker)).
Does MVVM say I must have two VM here, one for each specific View, or am I allowed to reuse the VM without breaking the pattern?
As a follow up question, if I am required to have two VM's is it legitimate, according to the pattern to have one as a derived type of the other, or both as derived types of a base class, or composite classes based on common parts? Basically fulfilling the need for two types but improving reuse?
My example is contrived, I've tried to make the point that both Views affect the same two properties of the model. Max size, available colours, etc are the same between both views.
Thanks
Use the same coding practices in MVVM that you use anywhere else. In particular, stay DRY. So if you can use the same view model, then do so. I would say reuse of a view model is extremely rare though. If you later have to refactor into two separate view models but can derive from a common base class to reuse common parts, etc. then do so.
Yes, VM is very specific to a view and likelihood of re-using is very slim.
In fact I would go further, if you can re-use a VM then I would say it is most probably duplication of the view.
The only exception I can think of is the child view in a nested hierarchical object model structure.
It is entirely appropriate to share ViewModels in this situation. A ViewModel is the glue that allows a View to create a representation of a Model. If you have two Views that represent the same aspects of the Model, it is logical to use the same ViewModel.
If you find over time that the Views are different representations of the Model, then you need to revisit the design.
Although not directly answering your question, check out this insightful post from Josh Smith regarding the re-use of ViewModels and the "friction" caused from sharing: http://groups.google.com/group/wpf-disciples/msg/c29b3935ec9d3c4e
He is basically proposing an improvement to MVVM (calling it MMVVVM; phew!) - the extra MV is for ModelView. As the others have mentioned, the ViewModel is specific to a View and re-using that is not very likely. But rather, create a wrapper around the Model (the ModelView), which can be re-used with any ViewModel.
We had a case some time ago where we needed a view duplicated in several places, but the underlying types of the views and viewmodels were different. In that case, we created a generic viewmodel and passed in the underlying types as parameters when constructing the viewmodels and were able to avoid code duplication that way. As the others say, this situation is rare so most times you'll be creating new viewmodels (although all viewmodels will probably inherit from a common base class for e.g. property notification.)
We also tend to create POCOs from our database entities so that our database context isn't changed until we really want to apply changes (i.e. the MMVVVM(!) pattern that Chris described)

Whats so bad about binding your View to Property of a Model and NOT ViewModel?

I often hear a Model must be wrapped by a ViewModel that the View is not coupled to the Model/not aware of it.
With MVC it is common to bind the View to the Model... nobody complains so what ?
I am frightened of creating all that wrappers and doing nearly only duplicating property stuff.
In some cases you don't need to, just as you don't need properties in many cases but can get away with public fields.
But your model should mirror the domain structure and logic, while a view model mirrors the UI structure and logic. At least, as far as I understood it. Those two are not necessarily the same and each one can change independently from the other.
You should always apply a pattern to your individual problem, and modify it in areas where it does not apply. Just because the pattern implies the usage of a view-model, doesn't mean you necessarily need a view-model in every scenario. In the case that your model exposes all of the needed properties and no further abstraction is needed, maybe a view-model is unnecessary.
However, in many cases the view-model will eventually be of great use and far easier to maintain than adding extra properties to the model. Consider this carefully before binding directly to the model.
The ViewModel is used to only pass the data that you really need to a view.
When you use the model, instead of the viewmodel it is possible that you use data that came directly from the database.
When using the model the wrong way, it is possible to edit data in the database that you don't want to edit.
It is safer to use a ViewModel.
One point which didn't seem to come up (directly) yet is that ViewModel can easily support data that should never even be in the model such as the text typed in the search text box or selected list items in case these values are needed in commands or further data bindings and passing them as parameters every time seems like too much trouble.
But as stated already, if you are confident that all the data you need is already available in the Model, go ahead and do away with the ViewModel.
One common scenario where ViewModels come in very handy is when Enum values should be displayed. In my eyes, a ViewModel is the perfect place to convert Enum values to user-friendly representations. You could even introduce a localization step in your ViewModel.
Furthermore, ViewModels can simplify some other scenarios. However, as you said, they can also duplicate a lot of code. That said, you could create a ViewModel with a Model property which allows to bind directly to the properties of the Model class. Now if you later realize that you need some conversion step, you can still add that property to the ViewModel and bind to that property.
But I think in most cases it makes sense to use a ViewModel from the beginning because it might be hard to introduce it in a later development stage.
There is no problem binding directly to a Model from your View where possible.
What you will find though is very quickly you run into a situation where you need to model things your view needs that aren't in your Model.
Given you never want to corrupt your Model with View concerns, you are left with no choice but to create a ViewModel.
It depends on may indicators: e.g. if your model is provided by EF there's no point in exposing it to your View - why the heck the View would need all model's method/properties and tons of stuff (not mentioning data security) But if your model is really simple and you feel, that you're not going to expand/change it much by and VM, there's nothing on the way to use it just like that :)
You might as well ask, "What's wrong with putting all the functionality of my program into one giant class?" On the one hand, there's nothing wrong; it can be made to work. On the other hand, everything is wrong: if your program is one big ball of wire, you have to straighten all of it out in order to change any of it.
Look at a Windows Forms programmer written by a beginner. You'll find all of the business logic in the buttons' Click event handlers. What's wrong with that? Don't you want that logic to be executed when the user clicks the button?
This is essentially what you're proposing doing within the world of WPF. Will it work? Sure. For trivial projects, it may even work well. You're accumulating technical debt, though, and when the time comes, you'll have to pay it off by refactoring your code into something manageable.

The model in MVVM: business object or something else?

I'm trying to get to grips with MVVM and so I've read a bunch of articles - most focus on the View -> ViewModel relationship and there's general agreement about what's what. The ViewModel -> Model relationship and what constitutes the Model gets less focus and there's disagreement. I'm confused and would like some help. For example, this article describes the Model as a business object whereas this article describes a class which manages business objects. Are either of these right or is it something else?
I think you are on the right track. The "model" is vague in a lot of cases because it is different things to other people, and rightly so.
For me, my business objects that come back from my WCF service I consider my model. Because of this my projects don't have that pretty file structure with the holy trinity of namespaces: *.Models, *.ViewModels, and *.Views. I personally consider objects coming back from business logic or anything of that nature the "model".
Some people tend to lump both the business objects and the business logic together and call that the "Model", but I find that a little confusing because I picture a Model to be sort of more static than I do business logic, but it's semantics.
So when you look at examples of MVVM projects and don't see anything very clearly "Model", it's just because folks treat them differently. Unless an application is very standalone, I would actually be very suspicious of an application with an actual *.Model namespace, to be honest.
The other thing that is great here is that many times you already have an investment in these types of business objects and I think a lot of people see "MVVM" and immediately assume they need to start defining the "M", even though what they already have is perfectly fine.
The confusion between a Model and a ViewModel is pretty common, too. Essentially I know I need a ViewModel if I need a combination of data and behavior. For example, I wouldn't expect INotifyPropertyChanged to be implemented on a Model, but I would a ViewModel.
From the other answers it should be obvious that the relationship between ViewModel and Model is somewhat fuzzy. Be aware that there is nothing stopping you from having ViewModel and Model in the same class, and when your requirements in a particular area are simple enough maybe this is all that you need!
How you structure the separation between ViewModel and Model will very much depend on the needs of the project or software that requires it, how demanding your deadlines are and how much you care about having a well structured and maintainable code base.
Separating ViewModel and Model is simply a way of structuring your code. There are many different ways of structuring your code, even within this pattern! It should be no surprise then that you will hear different approaches preached by different programmers. The main thing is that the separation can help to simplify and make reusable the independent portions of code. When you have cleanly separated business data, business logic and presentation logic you can easily mix, match and reuse your views, logic and data to create new UIs. The separated and simplified code is also often easier to understand, test, debug and maintain.
Obviously not everyone will agree with this answer. I think that is part of the inherent fuzziness of the problem. In general you need to consider and trade-off the advantages versus the costs of having a separation between ViewModel and Model and know that it is not always a simple task to decide what goes in the ViewModel and what goes in the Model. It will probably help to lay down some ground rules that you or your organisation will follow and then evolve your rules as you understand which level of separation best suits your problem domain.
I think it is worth mentioning that I used to use a similar approach to MVVM when programming Windows Forms and the fact the WPF has more direct support for this (in the form of data binding and commands) has really made my day.
There are a lot of different implementations and interpretations.
In my mind, however, the value of the ViewModel comes from coordination.
The Model is representative of business data. It encapsulates scalar information, as opposed to process.
The View is obviously the presentation of the model.
The ViewModel is a coordinator. In my opinion, the job of the view model is to coordinate between the view and the model. It should NOT contain business logic, but in fact interface with business services.
For example, if you have a view that is a list of widgets, and the widgets are grabbed from a service, then I'd posit:
The Model is a List<Widget>
The View is a ListBox bound to the ViewModel property Widgets
The ViewModel exposes the Widgets property. It also has a IWidgetService reference it can call to in order to get those Widgets.
In this case, the view is coordinating with a business object so the view doesn't have to know anything about it. The model should be ignorant of view models, views, and every thing else ... they should exist independent of how they are used. The IWidgetService would get bound to the view model using some source of dependency injection container, either constructor injection with Unity or an import using MEF, etc.
Hope that makes sense ... don't overload your viewmodel. Think of it as a coordinator that understands business objects and the model, but has no knowledge of the view or how business process is performed.
The value added by the model is its decoupling from the ViewModel and the View. Think if you had to construct and maintain business logic in the ViewModel you would have lots of duplicate code.
For instance - if you had a car game with a GearBoxView (a control in the CockpitView), CarViewModel and CarModel - the advantage of abstracting what is in the CarModel from the CarViewModel is that the CarModel can be used in the WorldViewModel and any other ViewModel. The CarModel can have relationships with other Models (GearsModel, WheelModel, etc).
Your question specifically asked about using a Model as a business object or to manage business objects: my answer is it can do both - and should be responsible for both.
Heres an example
public class WorldModel //Is a business object (aka game object)
{
private List<CarModel> _cars;
public List<CarModel> Cars
{
get //Here's some management of other business objects
{
//hits NetworkIO in a multiplayer game
if(_cars == null)
{
_cars = myExternalDataSource.GetCarsInMyGame();
}
return _cars;
}
}
public Level CurrentRaceCourse { get; set; }
public CourseTime TimeElapsed { get; set; }
}
I think of the model as something that contains the smallest units of business entities. The entities in the model are used not only across the view models in my application but even across applications. So one model provides for many applications and, for those applications using MVVM, many view models.
The view model is an arbitrary collection of entities from the model that are brought together to serve whatever the view needs. If a view requires 2 of these and 1 of those, then its view model provisions them from the model. Generally, I have 1 view model per view.
So a model is like a grocery store. A view model is like a shopping cart. And a view is like a household.
Each household has unique requirements. And each household has its own shopping cart that cherry picks what the household needs from the grocery store.
My thoughts
(The "Model")
Have one model. Just data no methods (except if apt for the platform some -simple- getters/setters).
(The "View Model")
To my mind the rationale for a view model is:
(1) to provide a lower-RAM-requirement backup copy of fields so views hidden behind other views can be unloaded and reloaded (to conserve RAM until they reappear from behind views covering them). Obviously this is a general concept that may not be useful or worthwhile to your app.
(2) in apps with more complex data models, it is less work to lay out all application fields in a view model than to create one reduced model corresponding to the fields of each possible data change, and easier to maintain, and often not significantly slower performance wise.
If neither of these apply, use of a view model is inapt in my view.
If view models are apt, have a one to one relationship of view models to views.
It may be important to note/remind/point out that with a lot of UI toolkits if the exact same "String" object is referenced twice (both in the model and the view model) then the memory used by the String object itself is not double, it is only a little more (enough to store an extra reference to the String).
(The "View")
The only code in the view should be (the required) to show/hide/rearrange/populate controls for initial view load and (when user is scrolling or clicking show/hide detail buttons etc) showing/hiding parts of the view, and to pass any more significant events to the "rest" of the code. If any text formatting or drawing or similar is required, the view should call the "rest" of the code to do that dirty work.
(The "View Model" revisited)
If the (...facts of which views are showing and...) the values of view fields are to be persistent ie survive app shutdown/restart, the view model is part of the model :--: otherwise it is not.
(The "View" revisited)
The view ensures that the view model is as synch'ed with the view in terms of field changes as is appropriate, which may be very synched (on each character change in a text field) or for example only upon initial form population or when user clicks some "Go" button or requests app shutdown.
(The "Rest")
App start event: Populate the model from SQL/network/files/whatever. If view model persistent, construct views attached to view models, otherwise create initial view model(s) and create initial views attached to them.
On commit after user transaction or on app shutdown event: Send model to SQL/networkl/files/whatever.
Allow the user to ("effectively") edit the view model through the view (whether you should update the view model on the minutest change of a character in a text field or only when the user clicks some "Go" button depends on the particular app you are writing and what is easiest in the UI toolkit you are using).
On some application event: the event handlers look at the data in the view model (new data from the user), update the model as required, create/delete views and view models as required, flush the model / view models as required (to conserve RAM).
When new view must be shown: Populate each viewmodel from the model just after the viewmodel is created. Then create view attached to view model.
(Related issue: what if any data set primarily for display (not editing) should not be entirely loaded into RAM?)
For sets of objects that should not be entirely held in RAM cause of RAM use considerations, create an abstract interface to access information on the overall count of objects and also to access the objects one at a time.
The interface and its "interface consumer" may have to deal with the number of objects being unknown/estimated and/or changing depending on the API source providing the objects. This interface can be the same for the model and the view model.
(Related issue: what if any data set primarily for editing should not be entirely loaded into RAM?)
Use a custom paging system through a slightly different interface. Support modified bits for fields and deleted nits for objects - these kept in the object. Page unused data out to disk. Use encryption if necessary. When editing of set done, iterate it (loading in pages at a time - one page can be say 100 objects) and write all data or only changes in transaction or batch as appropriate.
(Conceptual significance of MVVM?)
Clean platform-agnostic way to allow and lose data changes in views without corrupting model; and to allow only validated data through to the model which remains as the "master" sanitised version of data.
Crucial to understanding the why is that flows from view model to model are conditional on data validation of user input whereas flows in the opposite direction from model to view model are not.
The separation is achieved by placing code that knows about all three (M/V/VM) into a core object responsible for handling application events including startup and shutdown at a high level. This code necessarily references individual fields as well as objects. If it didn't I don't think easy separation of the other objects can be achieved.
In response to your original question, it is a question of degree of interrelationships of validation rules on update of fields in the model.
Models are flat where they can be but with references to submodels, directly for one-to-one relationships or through arrays or other container objects for one-to-many relationships.
If the complexity of validation rules is such that merely validating a successful user form fill or incoming message against a list of field regular expressions and numeric ranges (and checking any objects against a cached or specially fetched copy of relevant reference objects and/or keys) is enough to guarantee that updates to business objects will be 'with integrity', and the rules are tested by the application as part of the event handler, then the model can just have simple getters and setters.
The application may perhaps (best) do this directly in-line in event handlers where the number of rules is so simple.
In some cases it may be better even to put these simple rules in the setters on the model but this validation overhead is then incurred on database load unless you have extra functions for setting without validate. So for simpler data models I tend to keep the validation in application event handlers to avoid writing these extra setters.
But if the rules are more complex either:
(a) a single method taking a special object that is really a composite of the usual business objects containing data for myriad field changes is written for each complex model change, and the method can succeed or fail depending on validation of the rules - facade pattern;
or
(b) a "dry run" / hypothesis / "trial" copy of the model or a subset of the model is created first, setting one property at a time, and then a validation routine run on the copy. If validation is successful, the changes are assimilated into the main model otherwise the data is discarded and an error raised.
The simple getter/setter approach is in my view preferred when analysing each individual transaction unless the vast majority of updates for your app are complex, in which case one can use the facade pattern throughout.
The other way the model ends up getting more complex than a bunch of fields with (possibly) simple getters/setters is if you start "enhancing" classes' getters/setters (with an O2R mapper tool), or adding extra aspects like calls to transaction monitoring APIs, security APIs (to check permissions, for logging etc), accounting APIs, methods that pre-fetch any related data needed for a get or set, or whatever upon get or set. See "aspect-oriented programming" for an exposition on this area.

Resources