Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default values to all wrong or null parameters of method?

At the moment I have this code (and I don't like it):

private RenderedImage getChartImage (GanttChartModel model, String title,
                                     Integer width, Integer height,
                                     String xAxisLabel, String yAxisLabel,
                                     Boolean showLegend) {
    if (title == null) {
        title = "";
    }
    if (xAxisLabel == null) {
        xAxisLabel = "";
    }
    if (yAxisLabel == null) {
        yAxisLabel = "";
    }
    if (showLegend == null) {
        showLegend = true;
    }
    if (width == null) {
        width = DEFAULT_WIDTH;
    }
    if (height == null) {
        height = DEFAULT_HEIGHT;
    }
    ...
}

How can I improve it?

I have some thoughts about introducing an object which will contain all these parameters as fields and then, maybe, it'll be possible to apply builder pattern. But still don't have clear vision how to implement that and I'm not sure that it's worth to be done. Any other ideas?

like image 384
Roman Avatar asked Apr 30 '10 13:04

Roman


1 Answers

So many parameters to a method is definitely a code smell. I would say a Chart object is waiting to be born. Here is a basic outline:

 private RenderImage getChartImage(Chart chart) { 
     //etc.
 }
 private static class Chart {
      private GanttChartModel model;
      private String title = "";
      //etc, initializing each field with its default value.
      private static class Builder {
           private Chart chart;
           public Builder(GanttChartModel model) {
                chart = new Chart();
                chart.model = model;
           }
           public setTitle(String title) {
                if (title != null) {
                    chart.title = title;
                }
           }
      }
  }

Other options include using primitives on the methods instead of objects to indicate that null isn't allowed, although that doesn't necessarily make it better. Another option is a bunch of overloaded methods, but given the types of parameters here, that doesn't really work because I get the idea that you want to make any of the parameters optional rather than having the first ones required and subsequent ones optional.

like image 147
Yishai Avatar answered Oct 12 '22 23:10

Yishai