Most of the systems I work with allow a end user to create or modify a data object. Inevitably you see a "Create" method and an "Edit" method. One depressing thing is that these often have a very large amount of duplicated code. Here is simple strategy pattern to alleviate this. Done in C#.
Create(MyObjectType myObject) {
Modify(new CreateStrategy(), myObject);
}
Edit(MyObjectType myObject) {
Modify(new EditStrategy(), myObject);
}
private Modify(IModStrategy strategy, MyObjectType myObject) {
...
strategy.DoSomeStuff();
...
}
// inner classes
private interface IModStrategy {
SomeThing DoSomeStuff();
}
private class CreateStrategy : IModStrategy {
SomeThing DoSomeStuff() { ... }
}
private class EditStrategy: IModStrategy {
SomeThing DoSomeStuff() { ... }
}
This is a simple, well understoof patterns which clearly calls out the differences between an edit and a create as well as preventing duplication between the two. Duplication between edit and create is a very easy place to generate subtle errors.
No comments:
Post a Comment