Child pages
  • Builders
Skip to end of metadata
Go to start of metadata

Builders allow users to construct objects and object hierarchies in a more convenient way. Instead of a manual instantiation of each and every object in the hierarchy and setting its properties one-by-one, with a dedicated builder the same data structure can be created in a more concise and intuitive way.

As an example, let's assume we're building a house.

A house needs an address, which itself consists of several items, a bunch of rooms in it, each of which needs a couple of properties, and so on.

Instead of the cumbersome way, builders give you a syntaxtic shortcut to take:

Looking at the code you can quickly grasp the structure of the created object graph, since the structure of the code itself mirrors the dependencies among created objects. Builders are nested into one another and they can hold properties. Both the property values and mutual nesting of builders is then transformed into the object hierarchy built behind the scenes.

MPS brings a few of handy builders directly to your door as part of some of the languages - JavaBeans, XML, XMLSchema or XMLQuery being the most prominent users.

Building Builders

To build your own builder, you first need to invoke New -> Now you define builders for each object type that participates in the hierarchy. These builders hold their own properties and children, out of which they build the requested data structure. To stick to our earlier "House building" example, check out the sample below:

We defined a builder for the Room class as well as for the Address class and also a root builder for the House class. Root builders, unlike plain builders, can be used directly in user code after the new keyword. Notice also that we have two builders for the Room class. The first definition allows properties to be nested inside the room block, while the second allows the two properties to come directly as parameters to the room method call. Both approaches can certainly be combined in a single builder.

The House, Room and Address classes in our case are ordinary classes with methods and properties. The methods as well as setters for the properties manipulated in builders must be visible to the builders. The "package" visibility will do in typical cases. To give you an example, see below the House class definition from our example.

  • No labels