Re: Style: order of fields, params and methods
On Aug 15, 6:50 am, Karsten Wutzke <kwut...@web.de> wrote:
Hello!
When programming I keep switching the order of declared fields, method
params (especially for constructors) and sometimes methods themselves
in the class.
-> Is there a specific order recommended? <-
For constructors:
Mostly I keep ordering them in "most mandatory order first". I put
those in the param list first, probably coming off some PHP coding
where you can omit passing optional method params at the end:
function do_something($param1, $param2, $param3, $param4 = null,
$param5 = "black")
{
...
}
=> Calling do_something(1, "dfgdf", 0); is perfectly valid.
Is it better to keep "mandatory order first", use "order by topic",
e.g. group somewhat related params whether mandatory or optional. Or
another?
Karsten
I find that if I think I might want to re-order, add, or remove
parameters from a constructor or function that has a large number of
parameters already, I choose to use the Parameter Object, and have it
usually fulfill the Builder pattern as well.
class SomethingParams {
private String param;
private String blah;
public SomethingParams setParam(String value) {
param = value;
return this;
}
public SomethingParams setBlah(String blah) {
this.blah = blah;
return this;
}
}
doSomething(new SomethingParams().setBlah("My blah is better than your
blah").setParam(null));
You should also add a validation check (either as a method on
SomethingParams, or in doSomething) that throws an
IllegalArgumentException or some such, if the manditory arguments
aren't correctly set.
Also, at this point, you might consider whether or not doSomething
actually belongs in SomethingParams, and if SomethingParams can be
made to be more self contained.
Or, if you would pass this Param object into a constructor, use the
Factory pattern instead, and have a SomethingBuilder.newSomething(),
which calls the appropriate constructor for the client, based on the
other configuration they've done.