Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to pass arguments in constructor

I have a class that create rows in table layout. The row creation depend upon data and metadata. As metadata is same for each row like show/hide visibility properties etc. so I have created metadata property as a static and initialize once using initWidget of RowWidget.

just example:

class RowWidget extends FlexTable{

  public static void initWidget(Form form,
    HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
    GridMode gridMode,
    boolean isApplied,
    boolean isChildExist,
    boolean isChildAttachment)
    { 
      // ...
    }
}

Then I called below constructor for each record data.

public RowWidget(DataRawType dataRawType, Data data, Data parentData) {
 // ...
}

As I thought this is not right approach. because as pattern when anyone see this class then understand it will create one row. I don't want to call initially initWidget. I want to pass each required parameter in constructor only like

public RowWidget(DataRawType dataRawType,
  Data data,
  Data parentData,
  Form form,
  HashMap<Long, ContractorPermissionEnum> formModePermissionMap,
  GridMode gridMode,
  boolean isApplied,
  boolean isChildExist,
  boolean isChildAttachment) {
  // ...
}

But due to this, constructor have no of arguments. and I think it's also bad pattern to have 5+ parameter in constructor.

Is Anyone suggest me:

  • How to construct class which have same property required in another instance?

Note:I know this is possible through static only but don't want to use static.

  • What is best way to construct class with having some default fix property for all instances?

Note: I don't want to create another class to achieve it. or any getter/setter method.

Thanks In advance.

like image 968
bNd Avatar asked May 28 '13 06:05

bNd


1 Answers

I would suggest builder pattern. You would need one extra class to create RowWidget objects. So the call would look like that:

RowWidget widget = new RowWidget.Builder().withData(data).withParentData(parentData).withDataRawType(dataRawType).build();

Here is neat explanation of the pattern:https://stackoverflow.com/a/1953567/991164

like image 65
Jarosław Jaryszew Avatar answered Nov 10 '22 19:11

Jarosław Jaryszew