MyException - 我的异常网
当前位置:我的异常网» 编程 » Item 二: Consider a builder when faced with many

Item 二: Consider a builder when faced with many constructor parameters

www.MyException.Cn  网友分享于:2013-02-16  浏览:0次
Item 2: Consider a builder when faced with many constructor parameters

1.    Static factories and constructors share a limitation: they do not scale well to large numbers of optional parameters.


2.    Telescoping constructor pattern provides a constructor with only the required parameters, another with a single optional parameter, a third with two optional parameters, and so on, culminating in a constructor with all the optional parameters. When you want to create an instance, you use the constructor with the shortest parameter list containing all the parameters you want to set. Typically this constructor invocation will require many parameters that you don’t want to set, but you’re forced to pass a value for them anyway. So it is hard to write client code when there are many parameters, and harder still to read it.


3.    A second alternative when you are faced with many constructor parameters is the JavaBeans pattern, in which you call a parameterless constructor to create the object and then call setter methods to set each required parameter and each optional parameter of interest. However a JavaBean may be in an inconsistent state partway through its construction. Also the JavaBeans pattern precludes the possibility of making a class immutable, and requires added effort on the part of the programmer to ensure thread safety.


4.    Instead of making the desired object directly, the client can call a constructor (or static factory) with all of the required parameters and gets a builder object. Then the client calls setter-like methods on the builder object to set each optional parameter of interest. Finally, the client calls a parameterless build method to generate the object, which is immutable. The builder can be a static member class of the class it builds. The builder’s setter methods return the builder itself so that invocations can be chained.


5.    Like a constructor, a builder can impose invariants on its parameters. The build method can check these invariants. It is critical that they be checked after copying the parameters from the builder to the object, and that they be checked on the object fields rather than the builder fields (in case the parameters are mutable, the object can have defensive copy of the parameters). If any invariants are violated, the build method should throw an IllegalStateException. The exception’s detail method should indicate which invariant is violated


6.    Another way to impose invariants involving multiple parameters is to have setter methods take entire groups of parameters on which some invariant must hold. If the invariant isn’t satisfied, the setter method throws an IllegalArgumentException. This has the advantage of detecting the invariant failure as soon as the invalid parameters are passed, instead of waiting for build to be invoked.


7.    A minor advantage of builders over constructors is that builders can have multiple var-args parameters.(Actually var-args are same as array, so it’s not important.)


8.    A builder whose parameters have been set makes a fine Abstract Factory. (why?) In other words, a client can pass such a builder to a method to enable the method to create one or more objects for the client. To enable this usage, you need a type to represent the builder. A single generic type suffices for all builders, no matter what type of object they’re building:

// A builder for objects of type T
public interface Builder<T> {
public T build();


9.    Methods that take a Builder instance would typically constrain the builder’s type parameter using a bounded wildcard type. For example, here is a method that builds a tree using a client-provided Builder instance to build each node:

Tree buildTree(Builder<? extends Node> nodeBuilder) { ... }

10.    The traditional Abstract Factory implementation in Java has been the Class object, with the newInstance method playing the part of the build method. The newInstance method always attempts to invoke the class’s parameterless constructor, which may not even exist. You don’t get a compile-time error if the class has no accessible parameterless constructor. Instead, the client code must cope with InstantiationException or IllegalAccessException at runtime, which is ugly and inconvenient. Also, the newInstance method propagates any exceptions thrown by the parameterless constructor, even though newInstance lacks the corresponding throws clauses. In other words, Class.newInstance breaks compile-time exception checking.

11.    In order to create an object, you must first create its builder. While the cost of creating the builder is unlikely to be noticeable in practice, it could be a problem in some performance critical situations.


12.    The Builder pattern is more verbose than the telescoping constructor pattern, so it should be used only if there are enough parameters, say, four or more.


13.    In summary, the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters, especially if most of those parameters are optional. Client code is much easier to read and write with builders than with the traditional telescoping constructor pattern, and builders are much safer than JavaBeans.


软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有