Sunday, August 28, 2011

DEV302 Lesser Known Design Patterns

Bevan Arps
Apologies that this post is fairly nonsensical. I've put my raw NZ TechEd 2011 notes up here for my reference. I'd like to think that I'll refine them over time, but that probably won't be the case.

Null object pattern

Ceremony of checking if something is null before using it.

if(_logger != null) { _logger.Debug(""); }

Create a stand in that performs no operations.

* Simplifies the code
* Localise default behaviour 
* Allows API improvements IDisposable Activity ****

* Reliance on interface
* Who creates the null object?
* Parameter evaluation cost - was the string.format called to create a parameter?


Method Objects

Alternative to adding additional methods to interface.

Open for extension, closed for modification
Adding a new capability to the system should not require major alterations to the existing system.

* New function - new object
* Localizes code for a new function
* Extension

* Increases the number of classes
* Likelihood of change - another layer of abstraction high overhead if it is unlikely to change or be extended.

Object Emancipation

Respecting Object Autonomy

var person = Person.FindByName("Stephen");
person.Name = "Richard";

Objects are more than just buckets of information.
Give your objects responsibility for managing their State.


* Read/only properties
* Mutator methods - all changes are made via methods
* Validation

* Applicability - domain modelling
* Reusability - Method will always do the right thing
* ORMs and other tools - Tools expect objects to be done in a certain way. Expectations of setters on properties.

Why not put the validation in the property? May make more sense if the property can be changed in isolation.


Complex Domain Factories

Typical system can only capture valid data.

"Domain object that require a process to create" Wrap the process up as a Domain object.

* Natural Validation Point
* Reduced Complexity
* Increased Flexibility
* Error Tolerance - Could be saved in invalid state before progressing.

* Process Complexity
* Process Duration
Useful pattern if either of these is high.

State Pattern

Complex Domain Behaviour

Partially change the type of the object by swapping out behaviour based on state.

* Switching removed
* Grouped behaviour

* # Classes
* Encapsulation - nested classes
* Complexity of behaviour - not so useful is behaviour doesn't change much. Good for radical change