Data Beans can simplify calls to functions with lots of parameters.
Often a method or constructor starts out with simple aims but evolves into a monster. For example, consider a library method to render an HTML text input field. At first cut of the code the render method takes one parameter, just the name of the field.
public static void render(String fieldName)
{
:
}
Soon, a customization of the method is required with an extra style parameter and a readOnly flag. To maintain backward compatibility with existing callers of the library, another method is added and then the old method calls that. Another method is added to allow an ID field:
public static void render(String fieldName)
{
render(fieldName,null,null,false);
}
public static void render(String fieldName,
String style,
boolean readOnly)
{
render(fieldName,null,style,readonly);
}
public static void render(String fieldName,
String id,
String style,
boolean readOnly)
{
:
}
:
And so on. Pretty soon the class has ten different render methods that do mostly the same thing. Worse, many of the parameters can have default values so most of the code only exists to avoid compilation problems when method signatures differ. The class is getting out of hand.
There is a better way. After more parameters are found, the developer could write a data bean InputFieldRenderData for all the possible parameters of the render method.
Since the data bean is only used for direct access to parameters, and these parameters are unlikely to change, an old C-style structure is appropriate to save time (ie. with public values and no methods). Take a look at the full implementation in the following example.
// a new structure used only for communicating data:
public class InputFieldRenderData
{
public String fieldName;
public String id;
public String style;
public boolean readOnly = false;
:
}
// and then the updated render method:
public static void render(InputFieldRenderData renderData)
{
if (renderData.id != null && renderData.id.trim().length() > 0)
{
:
}
:
}
By using this neat trick, even if the attributes of InputFieldRenderData change, the calling code needs to change less often.
Tip: This data bean rule is not just for use by code that is expected to grow in the number of parameters. It can also be used in this specific situation to neaten up constructors or methods with more than ten parameters.
Please read the following [basic.struct] rule for tips on when to use this kind of structure.