July 28, 2007

Optional method parameters in java

Earlier this week someone was complaining java didn’t support optional method parameters. In some languages you can assign default values to parameters and if those parameters are not supplied then they will take on their default value. The syntax is usually something like SomeMethod(Param1=”foo”,Param2=2);

Whether this is actually any clearer than method overloading is debatable, personally I find it a little confusing. However, intrigued, I tried to see how close to this syntax it is possible to get in java. The following is as close as I could get, can anyone do better?:


Similar is possible in c# 3.0 with http://compsoc.pastebin.co.uk/20181 (should work with svn mono when compiled like: “gmcs -langversion:linq ./Filename.cs”)

- One comment Not publicly viewable

  1. Chris May

    You can get the same kind of effect by just having a single Map parameter to hold all the optional stuff. Define a map in your method which contains the defaults, and merge it with whatever properties are supplied using putAll

    Right now this is a bit clunky because you can’t define a map in-line (c.f. ’ options = {color=> “red”, flavour=>”chicken”, weight=>25} ’ in more dynamic languages, but this should hopefully get better in java 7; map literals being a fairly frequently wished-for feature.

    Alternatively, if you don’t like the lack of type-safety that a Map presents (if you have more than 1 class of optional parameter), then just define a Parameters object specific to that method, with default values set in the constructor. In the pathological case this means you end up with 1 (very anaemic) class for every method, but in practice this doesn’t happen, and those parameter objects often become quite useful domain classes in their own right.

    28 Jul 2007, 21:36

Add a comment

You are not allowed to comment on this entry as it has restricted commenting permissions.

July 2007

Mo Tu We Th Fr Sa Su
Jun |  Today  | Aug
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31               

Search this blog



Most recent comments

  • Hey skx, how do you do that ? I run into the fu….. problem, that curl terminate with unspec. error… by David on this entry
  • With some minor changes this will also work for updating from 11.0 to 11.1. by skx on this entry
  • You are the man!!! Great work and good documentation! It worked without any problem for me. Thanks a… by Vany on this entry
  • didn't work for me. In fact killed the system. Have to download 11.0 and burn to dvd to fix it. by maybe windows on this entry
  • Will this method work for 11 => 11.1 ? by Erik Jakobsen on this entry

Blog archive

Not signed in
Sign in

Powered by BlogBuilder