Sergey Shishkin

on agile software development

Making the Builders Discoverable

Suppose you have several fluent builders (or factories) that reside in different assemblies. How do you make your builders really discoverable?

If you organize builder classes and namespaces according to the assemblies, you will have a hard time to add the namespace usings and finally find the builders in the intellisense suggestion list among all the available types. However, if you put all the builders in a special dedicated namespace (e.g. MyAppName.Create) you can come up with the following code, which looks very interesting:

Customer newCustomer = Create.NewCustomer.

    WithId(23).

    WithFirstName("Bob").

    WithLastName("Smith");

Note that I have overloaded the implicit cast operator here to convert the builder to the built instance. That’s why I have to explicitly declare the type of the variable instead of just using "var" keyword.

The "WithId" method is static and it returns the instance of the builder. There is a second similar method – "WithNewId" (not shown in the code), which is responsible to generate a new identity for the instance being built. The "WithFirstName" and the "WithLastName" methods are not static.

As a bonus you instantly get all the builders in the same "Create" namespace right after referencing an appropriate assembly.

Advertisements

Written by Sergey Shishkin

06.06.2008 at 16:44

Posted in Uncategorized

%d bloggers like this: