Archive for June, 2015



Polymorphic Equality

The default generation of Equality members provided by Resharper let you choose three different implementations when overriding the "Equals" method in a class (Alt+Insert -> Equality Members):

The default choice is "Exactly the same type as 'this'" which IS NOT polymorphic. I mean, subtypes of that class will be considered not equal regardless of the values:

equalityGeneration
  1. public override bool Equals(object obj){
  2. if (ReferenceEquals(null, obj)){
  3. return false;
  4. }
  5. if (ReferenceEquals(this, obj)){
  6. return true;
  7. }
  8. if (obj.GetType() != this.GetType()){
  9. return false;
  10. }
  11. return Equals((Base) obj);
  12. }

On line 8 it compares the types which in the case of subtypes will be different thus returning false.
I didn't pay attention to this detail today and for some reason assumed that the comparison was going to work for subtypes. Lesson learned: always pay attention to generated code!

This is the generated code to consider subtypes equal:

  1. public override bool Equals(object obj){
  2. if (ReferenceEquals(null, obj)){
  3. return false;
  4. }
  5. if (ReferenceEquals(this, obj)){
  6. return true;
  7. }
  8. var other = obj as Base;
  9. return other != null && Equals(other);
  10. }

And this is yet another implementation that works:

  1. public override bool Equals(object obj){
  2. if (ReferenceEquals(null, obj)){
  3. return false;
  4. }
  5. if (ReferenceEquals(this, obj)){
  6. return true;
  7. }
  8. if (!(obj is Base){
  9. return false;
  10. }
  11. return Equals(other);
  12. }

The other lesson learned is that overriding the Equals method in the child class when the base class already overrides it, increases the complexity too much. The code is hard to follow and surprising. It increases the coupling between the child class and the parent.
Avoid overriding the equality members in class hierarchies if you can.

What is a ViewModel?

A ViewModel is one of the three parts that comprises the MVVM (Model View View-Model). This pattern is a variation of the Presentation Model (M. Fowler). In the Presentation Model, as opposed to Passive View, the "controller" doesn't hold any reference to the view - and it isn't called "controller" but "Presentation Model". The View is the one which references the Presentation Model. The Presentation Model communicates changes to the View through events and data-binding. The View handles GUI events (user interaction) and may invoke methods on the Presentation Model.

In 2005, John Gossman from Microsoft introduced the MVVM pattern which has been evolving since then. In this post Josh Smith explains the pattern as it's commonly used today with an example. According to this post, a ViewModel is an object which wraps a model (CustomerViewModel contains a Customer model inside). However the another ViewModel is the MainWindowsViewModel, an abstract representation of the MainWindow. So there you go, the same term is used for two different things. So what is a ViewModel?

In this other example by Jeremy Likness, there is a class called Contact which he says is a Model, a domain model. I bet that to some people Contact is rather a ViewModel - specially given its implementation of INotifyPropertyChanged.  This is getting more and more confusing!

In our team, a ViewModel is the class handling all the logic related to the GUI. It acts as an Application Service, the entry point to the hexagon. I believe that in his book, Vaughn Vernon discourages the reader from using this kind of "controller" as an application service. But we haven't encounter any good reason not to use it as such. In fact, I find the definition of application service quite contradictory in that book. We never expose domain models directly to the GUI. We may wrap domain models into other objects which in turn are bounded to the GUI (data-binding) and implement interfaces like INotifyPropertyChanged. Although more often than not, our domain models are not even there. These objects are definitely a kind of "view" of the model, I was tempted to call them "ModelView". I understand they may be called ViewModels, it's reasonable. In some articles thew ViewModel is more model-ish than view-ish. Nonetheless to avoid the dilemma of calling these objects ViewModels, we decided not to add the suffix *ViewModel to them. We simply keep them under the *.ViewModel namespace but they are just objects - a Vehicle, a Customer...
What we definitely know is that they are not domain models. They are anemic models to support a particular view of the application. They should not hold references to other services. The application service (what we call ViewModel) holds the references to these data bounded objects in order to get the information from the user.

It's important is to remember the Presentation Model. It does not make calls to the view, it should not have references to any view component. If the GUI logic requires to pop up a confirmation dialog, the Presentation Model (ViewModel) should not make a direct call to some kind of "Dialog", it should rather trigger an event that the View can listen to show up the dialog.

What do you think? I appreciate your comments and thoughts 😉

 

 

 

 

Heuristics, bad smells and principles in the design of our Windows 8 app, which shares the core domain with a rich JavaScript client application. In Par I, we exposed some of the difficulties we were facing when modeling. How we are working today:

  • Our repositories work with aggregates (entities). This is, rich domain models rather than plain anemic models. The repository performs database queries and then pass in the raw results to the aggregate's constructor or to some adapter to build up the model.  Thus the repository returns models to the service layer and receives models.
  • Currently an object is a DTO only if it's used to send and receive data through the network (via HTTP requests).
  • Bad smell: the fact that only certain fields of a DTO are used in some part of the application and the other fields are used in another place. That means we are trying to reuse concepts that are different. The solution is to split the object in two. Principle: a data object have to be consistent, all its fields must be in use.
  • The objects we bind to the GUI are not called DTOs anymore. But we are not happy calling them ViewModels either, because we still want to make the distinction between a data object bound to the GUI, and a kind of "Controller" that manages GUI logic and depends on collaborators like application services. So we are avoiding prefixes and suffixes for those objects and using their namespaces to distinguish them. For example if "Vehicle" happens to have the same properties in the model, the communications layer and the GUI, there will be three objects:
    • ProjectName.Model.Vehicle
    • ProjectName.Dto.Vehicle
    • ProjectName.ViewModel.Vehicle
  • The transformations between DTO and Model are performed by an adapter as described in Part I. But we do not create the three objects from the very beginning when there is just one object with one field or two. We may use the same object all over the place until it grows and starts acquiring some logic.
  • We usually talk about "bindable objects" to refer to those data objects bound to the GUI. Sometimes the tranformation between domain model and bindable object is performed by some ViewModel/Controller. Sometimes we delegate the task in an adapter, within the ViewModel namespace.
  • Transfer the minimum amount of data for each operation, no more. A single service may work with many different DTOs because each operation requires different data setsFor instance, the OfferService (an application service) has public methods to create and update offers. The OfferDto used to contain all the data required for both operations:
         public void Create(OfferDto offer);
         public void Update(OfferDto offer);
    However only a subset of the data is required for each operation. Now we prefer to exchange a minimal amount of data:
         public void Create(NewOffer offer);
         public void UpdatePrice(OfferId offerId, decimal price);
    public void Update(UpdatedOffer offer);

    This approach help us realize those objects are used just to transfer data, nothing more.

  • Keep data structures simple in the client/GUI side: if all I need of some entities are their identities, I don't need whole objects in that view, I can just hold a list of strings. Once the strings enter the hexagon, they'll be turned into domain models.
  • Keep the outer interface of the hexagon simple so as to make it simple to interact with: it's OK to receive primitives as arguments in our application services or actions.

 

Today has been a special day. Not because it's my 34th Birthday which I never really celebrate (although I do appreciate all the greetings and warm words from all my friends and family!) but because I've had the pleasure to spend the day working with Carlos Peix for the first time. Carlos is a well-known software craftsman from Argentina. It's his first time in Spain and we are lucky that he chose us to spend two days working with us as part of his journey. It's an exchange, something a journeyman does to learn and share. Among other things we have been mob programming today, refactoring code aiming to come up with a proper domain model. We have been identifying anemic models and data transfer objects trying to turn some of them into domain models. Trying hard to make up a good object oriented design. Things I like from Carlos' suggestions today:

  • Enumerate a list of all the classes we plan to refactor (or classes that are going to be affected) so as to be able to estimate how much time we are going to invest in this task and thus make a better decision on where to stop refactoring.
  • Rather than refactoring every object in depth, apply little changes to all the objects visiting all of them to build a mental map of dependencies and structure. For instance, we decided we wanted to hide setters and create constructors to inject the attributes. Although a single class suffered from other smells, we performed only that change to it and moved to the others until all of them changed. To me it's like exploring the tree breadth-first.
  • Sequence diagrams help understand the complexity of the design. It's funny that this should happen exactly at the same time I am reading Sandy Metz's book on OOP. Carlos hasn't read the book but he recommends the same technique than Sandy Metz. The sequence diagram was an "aha" moment to my colleague Miguel.
  • We commented on the different strategies to expose an object to different bounded contexts, using interfaces and using wrappers. We didn't have much time to dig into it.
  • Repositories retrieve aggregates when possible, that is rich domain models rather than anemic models.

Looking forward to more synergy tomorrow, it's been an exciting day.

And you fellow journeyman, remember that we are open minded and value your visit to our office. If you want to work with us for a few days drop us a line, we look forward to it!