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 ****

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

Command

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.

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

Considerations
* 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";
person.Save;

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

person.Rename("Richard");

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

Considerations
* 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.

Proposal

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.

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

Considerations
* 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.

Effects
* Switching removed
* Grouped behaviour

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