Archive for the ‘Patterns’ Category

YAGNI–Whose Definition of Simple?

I have read a lot about YAGNI lately, especially regarding TDD. The thing that keeps bugging me is the definition of “simple.” Who defines simple? For instance, wouldn’t static methods be simpler than building objects? You could then write more functionally. Or is that not simpler to you? If you follow command-query separation, wouldn’t building everything as either pure functions or commands be simplest? JB and I have found this set of patterns immensely easy to create and test of late, especially in comparison to the ever-increasing-in-complexity procedural/OO code in place before.

So I guess my question is this: Is it really so bad to start with some basic patterns that will let you refactor more easily? I think the desire to make things as simple as possible–especially when you know you will need it–can be a waste of time and a good way of getting bad code into your source.

I know I will hear it from the Agile community that I just don’t get it, but I think I do. I really like starting simple and keeping things in nice, bite-sized testable chunks. And yes, I’m still learning. However, without a consistent and meaningful definition of “simple,” we’re likely to end up with a follow-up movement of making things complex for the sake of extensibility again.

So what do you think: is CQS too complex a starting point, or is it a nice, “simple,” and testable approach for YAGNI?

CQS – A Literary Perspective

If you have been following the DDD and DDDD waves, you’re sure to have come across the CQS pattern. When I first heard of this, I immediately liked it but thought it was surely a pattern for very, very large systems. Most systems probably don’t need CQS, but this morning over breakfast, a discussion with my wife on child learning patterns made me rethink this.

We have a friend whose children have grown at very different rates of reading comprehension and writing skill. The interesting part is that the rates are nearly opposite from one another. The one with excellent reading comprehension does not excel at writing while the other is and excellent writer but has trouble reading. I found this somewhat strange. After all, logically, I would think that the one who reads should be able to write better. But that’s not the case. No one can do everything best. The same is true of databases.

This is such a true statement that in the Collective Intelligence session at the Houston ALT.NET Open Spaces, four distinct database tiers were promoted for proper separation of concerns to allow each tier to most effectively perform its task. Is this necessary for every application? Probably not, but as we move toward a more virtualized server world, the cost is really swinging in the favor of using multiple databases for reading and writing concerns. This may break the YAGNI principle, but I think we may often find that simplest may really be the best, simplest, smallest part that can fit the bill. (I’m sure that last statement will really ruffle feathers, but that’s where I am atm.)

Acase().for(patternType.FluentInterfaces).create()

When I was first exposed to the idea of fluent interfaces my response was… big flipping deal.

It wasn’t until I actively started using fluent interfaces in my code did I begin to see their power and elegance.

What is a fluent interface? Here is the obligatory link to wikipedia ;)

In simple terms, its returning a type instead of void in order to achieve method chaining.

The end goal of the method chaining is to provide a more readable interface and code.

First, does it break the Law of Demeter?

Law of Demeter doesn’t equal the number of periods. I am of the opinion fluent interfaces do not violate the Law of Demeter.

What is LoD? Another link to wiki and here is a link to a stack overflow on this very subject! :)

To me, Law of Demeter is about restricting communication between objects.

A common violation of LoD (imho) is the exposure of a list property on an object. I believe this serves as a good example of LoD as well as being an example on how to make a fluent interface. :)

A Person object has a name and a list of friends.

   1:      public class Person
   2:      {
   3:          public string Name { get; set; }
   4:          public List<Person> Friends { get; set; }
   5:   
   6:          public Person()
   7:          {
   8:              Friends = new List<Person>();
   9:          }
  10:      }

I could then add friends by…

 
   1:  var roger = new Person{ Name="Roger" };
   2:  roger.Friends.Add(new Person { Name = "Eddie" });
   3:  roger.Friends.Add(new Person { Name = "Freddie" });
   4:  roger.Friends.Add(new Person { Name = "Gordie" });

Now this is pretty typical, so what’s the problem?

Well my code knows WAY too much about Person. I know it has a list of friends and if they change that list to say a dictionary, I am hosed.

Not only that, but poor Person class… people can add friends to his collection without him every knowing. What if some additional logic needs to be done when adding a friend?

What if the person wants to record the birth date of every friend so they can send out birthday cards? Person is SOL.

As for Law of Demeter, my code is using the Person object to communicate through to the List<Person>. I am exposing my code to changes in Person.

Let’s change Person to eliminate this problem.

   1:      public class Person2
   2:      {
   3:          public string Name { get; set; }
   4:          private readonly List<Person2> _friends;
   5:   
   6:          public Person2()
   7:          {
   8:              _friends = new List<Person2>();
   9:          }
  10:   
  11:          public void AddFriend(Person2 friend)
  12:          {
  13:              _friends.Add(friend);
  14:          }
  15:      }

Now the only way to add a friend is through Person. Yippie!

 

   1:  var roger2 = new Person2 {Name = "Roger"};
   2:  roger2.AddFriend(new Person2 { Name = "Eddie" });
   3:  roger2.AddFriend(new Person2 { Name = "Freddie" });
   4:  roger2.AddFriend(new Person2 { Name = "Gordie" });

 

If I wanted to make this a fluent interface all I would need to do is instead of returning void, return the Person class.

   1:      public class Person3
   2:      {
   3:          public string Name { get; set; }
   4:          private readonly List<Person3> _friends;
   5:   
   6:          public Person3()
   7:          {
   8:              _friends = new List<Person3>();
   9:          }
  10:   
  11:          public Person3 AddFriend(Person3 friend)
  12:          {
  13:              _friends.Add(friend);
  14:              return this;
  15:          }
  16:      }

Now I can do the same logic like…

   1:  var roger3 = new Person3 { Name = "Roger" }
   2:                              .AddFriend(new Person3 { Name = "Eddie" })
   3:                              .AddFriend(new Person3 { Name = "Freddie" })
   4:                              .AddFriend(new Person3 { Name = "Gordie" });

That is pretty cool, but fluent interfaces really shine with the builder pattern.

This time around I want to force construction of a person through a builder and have the builder use a fluent interface. Notice my Person’s constructor and fields are private. I embed the builder class within the Person class so the builder has access to the constructor and fields. In this manner only my builder class has access to constructing a person. My builder can now act as an anti-corruption layer for Person.

   1:      public class Person4
   2:      {
   3:          private string _name;
   4:          private List<Person4> _friends;
   5:   
   6:          private Person4()
   7:          {
   8:              _friends = new List<Person4>();
   9:          }
  10:   
  11:          public Person4 AddFriend(Person4 friend)
  12:          {
  13:              _friends.Add(friend);
  14:              return this;
  15:          }
  16:   
  17:          public static PersonBuilder createAPerson()
  18:          {
  19:              return new PersonBuilder();
  20:          }
  21:   
  22:          public class PersonBuilder
  23:          {
  24:              private Person4 _person;
  25:              public PersonBuilder()
  26:              {
  27:                  _person = new Person4();
  28:              }
  29:   
  30:              public PersonBuilder named(string name)
  31:              {
  32:                  _person._name = name;
  33:                  return this;
  34:              }
  35:   
  36:              public PersonBuilder withFriend(Person4 friend)
  37:              {
  38:                  _person.AddFriend(friend);
  39:                  return this;
  40:              }
  41:   
  42:              public PersonBuilder withaFriendNamed(string name)
  43:              {
  44:                  var friend = createAPerson().named(name).finish();
  45:                  _person.AddFriend(friend);
  46:                  return this;
  47:              }
  48:   
  49:              public Person4 finish()
  50:              {
  51:                  return _person;
  52:              }
  53:          }
  54:      }

Now to create Roger and his friends I do..

 
   1:  var roger4 = Person4.createAPerson()
   2:                      .named("Roger")
   3:                      .withaFriendNamed("Eddie")
   4:                      .withaFriendNamed("Freddie")
   5:                      .withaFriendNamed("Gordie")
   6:                      .finish();       

It’s a simple example but maybe it sparked some ideas on how to use fluent interfaces to chain methods and make your code more approachable to people without Computer Science degrees. :D

JB

Correctly Naming Patterns

JB and I were discussing some of the patterns we were using on our current project today while working on merging some of our disparate (but completely related) code. I had created several classes named XyzBuilder with the intention of actually following the Builder pattern. My final classes are really just Strategies, but I never changed the name (though I’ve meant to do so).

This hasn’t lead to confusion, however, as (a) the “builder” is in fact “building” an object for me so the name is still meaningful and (b) most of my team members aren’t that familiar with using patterns on a daily basis (or they at least say they don’t). I’ve a thought, though, that objects with pattern-ish names should be renamed to either non-pattern names or the name of the pattern they use.

Should the name match the pattern or does it really matter?

LINQ to SQL and Entity Framework as Internal Object Databases

I’ve now used and/or tried LINQ to SQL, Entity Framework, and Fluent NHibernate and can now say I understand the differences as expressed in the ADO.NET Entity Framework Vote of No Confidence. Yet I still appreciate what the former two products from Microsoft offer. Well, I like LINQ to SQL anyway. After spending four hours today trying to create a simple example with Entity Framework and getting nowhere with many-to-many mappings despite several blogs’ assistance, I finally gave up. I think the problem with LINQ to SQL and Entity Framework is not in their usefulness but in the approach Microsoft has tried to take in marketing them as object-relational mapping technologies.

An object-relational mapping technology generally takes an object and maps it to a database, not the other way around. At least, I think that’s how it started. The abundance of MVC frameworks using the Active Record pattern seems to have changed that recently with generators creating models from database tables, though many of these actually create the tables in the database from the object definition, as well. Nevertheless, I’d disagree with Microsoft that LINQ to SQL and Entity Framework qualify as ORM technologies, though they do perform that role, as well.

LINQ to SQL and Entity Framework provide a language-integrated object database against which to create applications. This is huge! Let that sink in a bit. Now, I find nothing wrong with that approach. In fact, it’s quite nice! The trouble is that developers think, “Wow, I’ve got all these great objects ready to use!” Not so fast. You have entities that represent rows in tables, not business objects. Yes, LINQ to SQL and Entity Framework provide means of modifying those classes to mimic more class-like behavior (and that can indeed be a great benefit do easing domain model or active record development) but really should not be used for anything other than database records.

This greatly simplifies any data mapping you have to do between your domain objects and your database, and you can write everything in your OO language of choice. If you want something more automatic, you might try an object-to-object mapper (e.g. NBear–though I haven’t tried it myself and can’t imagine that object-to-object mapping would be that difficult).

As a final analysis, in case you care, I really like LINQ to SQL’s defaults. It’s super simple to get started and use, though it’s only for SQL Server. Entity Framework… I am just not a fan. If I can stay away, I will. Maybe someone will show me how to configure it so that it works for me, but so far it’s a FAIL. Also, keep tabs on DbLinq. It’s an open source tool that attempts to mimic LINQ to SQL for SQL Server and a number of other database technologies and should work on Mono. Of course, NHibernate is great for those who would rather connect to a real database, and I found Fluent NHibernate to be a great tool. I love its fluent interface for mapping to the database and its AutoMapping functionality. However, making everything virtual annoyed me and really makes me question how so many can prefer it for persistence ignorance when it so obviously requires that detail. (I get it’s a small sacrifice, but I wouldn’t code that way normally, so I am quite reminded that I’m connecting to a database through NHibernate.)

Domain Model, Data Mapper, Repository, Unit of Work Patterns and Lazy Load, oh my!

Our efforts to create a library for building enterprise-level LOB has led us to the Domain Model, Data Mapper, Repository, Unit of Work and Lazy Load patterns, just like everybody else. I just got my copy of Nilsson’s Applying Domain-Driven Design and Patterns and enjoy it very much. I believe Rob Conery commented on the pattern of patterns approach that defines Domain-Driven Design. That statement, while a bit incomplete, appears to hold true.

Aside from well-documented pitfalls, domain-driven design appears quite fresh and appealing, at least to me. Nevertheless, I ran into several hurdles while trying to implement the Unit of Work and Repository patterns. In particular, where do I add the Data Mapper? I’ve puzzled over this the last few days without any good answers.

This evening as we were walking out the door, JB and I decided we’d finally look into Expressions and building our own IQueryable implementation so that we could lazy load our mapped domain models. Lo and behold, I think this answers my other questions, as well, as building the query expression also allows us to map to the data provider, no matter what that may be, including Entity Framework or LINQ to SQL Expression trees.

Implementing IQueryable also allows us to catch each object as it is pulled through the iterator and tag it for change tracking. Now many reading this post will probably be thinking that this sounds like a lot of work—and I’m sure it is—and that these benefits were supposed to be delivered through Entity Framework, LINQ to SQL, etc. Well, you are right, but due to the lack of interfaces and current limitations, these may not always be the best options.

I’ve just started learning this myself, so I can only point you to the how, not the how hard. Check out the LINQ: Building an IQueryable Provider Series. As I progress, you can be I’ll be commenting on the ease or difficulty of building a custom IQueryable provider. Several others appear to have gone this route, so it can’t be a completely worthless pursuit (see SubSonic and IQToolkit).

Anyone else taken the plunge? What were your experiences?

Composite WPF Patterns

Microsoft’sComposite Application Guidance for WPF (Composite WPF) gives WPF a lightweight yet effective application block with which to build exciting applications. However, the biggest struggle is deciding on a pattern for applying the library. The Model-View-ViewModel (MVVM), mentioned across the web as the perfect pattern for implementing MVC with WPF, was for some reason not specifically mentioned in the Composite WPF documentation. Nevertheless, the MVVM pattern is many times used and alluded to under the name PresentationModel and is arguably the best approach in most cases.

Dan Crevier posted a series of excellent articles defining the pattern and giving examples of the implementation of MVVM in WPF. These were written several years ago, before development of the Composite WPF block, but they are simple to understand and can give added understanding to the objects included in Composite WPF. For example, his post on encapsulating commands is very similar to the DelegateCommand object provided with CompositeWPF, though the latter uses lambdas to define Execute and CanExecute methods, whereas the former uses a base class and inheritance to define the methods. Using Dan’s example, the equivalent DelegateCommand, contained within the DelegateCommand’s definition, would look something like this:

public DelegateCommand<object> MyCommand { get; private set; }

public Window1()
{
    InitializeComponent();
    MyCommand = new DelegateCommand<object>(
        p => {
                 string text = p as string;
                 // Do something with text
             },
        p => !string.IsNullOrEmpty(p as string));
}

Dan’s definitions of the Model, which he calls DataModel, View and ViewModel match very closely with Composite WPF’s PresentationModel pattern. In this case, the DataModel is a representative object that is fit for display within the View. Using the entities generated for Linq to SQL, you might add properties to the partial classes create the necessary properties to which to bind. These classes should also implement INotifyPropertyChanged so that other DataModels can respond to changes from another, related View and update their data accordingly.

The View should use bindings for everything. The beauty of WPF is truly in its DataBinding functionality. The observer pattern is built right into the Binding, so that whenever one view changes, other views are notified by their bindings to their DataModels. Even the actions to be performed on a user interaction with the UI can be removed to the ViewModel, DataModel, or in the case of Composite WPF, a controller, Shell, or App level, as appropriate. This leaves the View looking very passive, indeed, which greatly helps when unit testing.

The ViewModel is the actual PresentationModel. It hosts the DataModel, as well as the View’s commands. ViewModel should be the object used to bind to the View’s DataContext and should implement INotifyPropertyChanged if any of the properties could change. The QuickStarts and RIStockTrader examples provide excellent samples of the PresentationModel, though be warned that the examples often use different patterns, if for no other reason than to show other pattern implementations.

That covers the MVVM pattern. However, there’s one more aspect that needs to be covered: composite regions. Composite WPF provides regions for managing the display of different modules in the Shell, but what if you need to display multiple modules or views within a “summary” view that is already on the Shell? In this case, you can use a Controller to manage the child use cases. The UIComposition QuickStart shows a terrific example of creating a controller in a ViewModel for the purposes of managing child use cases. This removes the dependencies and depth of a View that includes a tab control containing a large number of child use cases. (The UIComposition QuickStart uses a Supervising Controller pattern instead of the PresentationModel/MVVM pattern, so you’ll have to adjust it accordingly, but it works beautifully.)

The MVVM pattern is a great solution for WPF applications by allowing WPF’s DataBinding and Commanding to remove much of the logic formerly found in the View layer out to a unit testable ViewModel. The architecture stays clean and also fairly shallow in that an additional Presenter class is unnecessary (as opposed to the Supervising Controller pattern.)

Additional Resources:
John Grossman – Tales from the Smart Client
Pete Weissbrod – Model-View-ViewModel Pattern for WPF: Yet Another Approach