Wednesday, March 13, 2013

More OO Around That Island of Functional

In my last post I showed how C# seamlesly supports having little functional islands inside an otherwise OO code base. I did that using a simple object model, in which one of the objects was implemented in a functional manner. The other objects, though, were just data containers, really.In that post I made the off hand remark that these could be better encapsulated. In this post I'll address this, and also show that the "other" objects could easily have more behavior as well. All-in-all this brings the example closer to the original intention: To show how the overall design can be OO, but the insides of individual classes can be functional.

The classes involved were CourseTemplate, Course, Registrant and CoursePlan. The example is to create a course plan, where registrants are placed in in courses bsed on which course they wish to take.

Slightly Better Encapsulation

To get to a more object oriented design the first step is to move away from simple auto properties with public getters and public setters to a least have private setters. Using CourseTemplate as an example this simply means moving to this:


Adding Basic Domain Operations

Nest step is to start adding basic domain operations that make the objects have just a little bit of actual behavior and some more encapsulation. To illustrate lets add a method for wishing courses to the Registrant class, and lets also add an override of equals that makes more sense from a domain perspective:


Adding other Behaviors

We're getting the hang of this. Let's add the same type of basic domain methods along with a few other (made up) methods to the Course class:


By adding Register, IsFull and IsEmpty some responsibility is being moved from the CoursePlan version in the last post to the Course - which makes much more sense. By adding Start and AwardDiplomas I point toward the fact that these classes can have more behavior if we need it.

The Functional Island is Still Functional

Despite these changes the CoursePlan doesn't change all that much. The places the implementation has changed is where the new methods on Course are used. The implementation is still just as functional:



Conclusion

The functional islands I talked about in the last post can easily exist in a truly object oriented code base.