开发者

Java Associative Array as Options for Method

I am re-learning Java after having an affair with PHP for some years, and I have a question about 开发者_开发知识库a convention used in PHP, and how I would accomplish a similar goal in Java...

PHP

function getReport( $options = array() ) {

}

in the above function you would be passing in an optional associative array of options that may look like this

Array(
    from => "20110325",
    to   => "20110413",
    subject_id => "2432",
    ...etc...
);

And if there is no argument passed, it processes fine with no options.

Below is my attempt to form the same function in java, being as it is Strongly typed (which is quite refreshing in some instances) I am having trouble building in the same flexibility. I've considered using a Dictionary but not sure how "best practice" that would be.

public TimeReport getTimeReport(Date from, Date to, int subjectId, int toDoItemId, int filterProjectId, int filterCompanyId) {

}

To call this with one/two/none options it gets pretty ugly with the arguments being...

getTimeReport(null,null,null,234,null,null);


Can you call the getTimeReport with another object used to represent the parameters needed to invoke the getTimeReport function?

Looks like your used to passing strings to functions when you may want to be passing an object.


This kind of flexibility is not built-in to Java, and the language is not very well suited to it in my opinion. You could check each input argument; if null, set it to a default value.

To be more general/didactic, it looks like you are trying to have a Factory of some sort (what class does the method getTimeReport() belong to?). Do you instead want to have the constructor of TimeReport handle these options? Or make different TimeReport constructors for different circumstances?


Usually you would introduce a class representing the configuration parameters for the report generation, like TimeReportSpecification or something.

You can then have static factory methods that give you instances of a TimeReportSpecification, like withToDoItem, so you get:

getTimeReport(TimeReportSpecification.withToDoItem(234));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜