patternjavaMinor
Can I always use variable-length argument lists instead of arrays in argument types whenever is a choice?
Viewed 0 times
typescanarraysargumentlengthalwayswheneverinsteadchoicelists
Problem
I changed the
so it receives variable-length argument list instead of array:
Now I can write both:
and
But of course,
So are there any disadvantages in declaring argument type as a variable-length argument list, not array, whenever is a choice?
withColumns() method in this class:public static class Options {
public String table;
public String[] columns;
public Options withTable(String table) {
this.table = table;
return this;
}
public Options withColumns(String[] columns) {
this.columns = columns;
return this;
}
}so it receives variable-length argument list instead of array:
public Options withColumns(String... columns) {
this.columns = columns;
return this;
}Now I can write both:
new Options().withColumns(SubjectContract.TITLE, SubjectContract.PHOTO);and
new Options().withColumns(new String[] { SubjectContract.TITLE, SubjectContract.PHOTO });But of course,
withColumns(SubjectContract.TITLE, SubjectContract.PHOTO) is more readable.So are there any disadvantages in declaring argument type as a variable-length argument list, not array, whenever is a choice?
Solution
so basically it is your choice :
with optional params you cannot enforce user to input the value, so user can leave giving any input and complier will not complain.
with list of string , you need to give at least one value , value can be null.
so it all depends upon your use case.In this case table will always have columns so passing a array of column will make sense.
with optional params you cannot enforce user to input the value, so user can leave giving any input and complier will not complain.
new Options().withColumns();with list of string , you need to give at least one value , value can be null.
new Options().withColumns(null);so it all depends upon your use case.In this case table will always have columns so passing a array of column will make sense.
Code Snippets
new Options().withColumns();new Options().withColumns(null);Context
StackExchange Code Review Q#59790, answer score: 4
Revisions (0)
No revisions yet.