Link to home
Start Free TrialLog in
Avatar of Axter
AxterFlag for United States of America

asked on

Why doesn't Java take default parameter values?

Why doesn't Java take default parameter values?

I don't understand why they would leave this out of the language.

I know you can accomplish the same thing by overloading and calling the main function with default values, but this seems like extra work, which could have been easily avoided if the language supported default values.

I just want to know what would have motivated the language designers to exclude this feature, which is found in many modern languages.
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Because it doesn't...

What you can do is:

public void function( String a, String b )
{
    // Do stuff!
}

public void function( String a )
{
    function( a, "default b" ) ;
}

public void function( )
{
    function( "default a", "default b" ) ;
}
They decided it was uneccesary, confusing, or superfluous...

C doesn't have them does it?  Or C++?

I know Delphi has...  but that's all I can think of..

I may be wrong...
@Tim,
>> I know you can accomplish the same thing by overloading and calling the main function with default values
;°)
>> Or C++?
C++ has them ... as far as I can remember
Avatar of Axter

ASKER

>>TimYates,
That's not really an answer, and in my question, I already stated that I now you can accomplish the sameting by function overloading.

FYI:
**** I am not looking for opinions.  I'm asking this in the hope that someone here knows factually the answer, and can supply a link or reference a book to support the answer. *****

Thank you
>> **** I am not looking for opinions.  I'm asking this in the hope that someone here knows factually the answer, and can supply a link or reference a book to support the answer. *****

Can I ask why?

Thank you
>> I know you can accomplish the same thing by overloading and calling the main function with default values
Then what's the problem.
If you call it

    function();   // cf. the Tim's example

you even don't (have to) know if it is "done" via overloading or via default parameters
Avatar of Axter

ASKER

>>C doesn't have them does it?  Or C++?

C++ has ALWAYS had it.

Compilers complying to the C99 standard has it.
>>  @Tim,

Yeah, saw that the second after I hit "Submit" :-/
>> C++ has ALWAYS had it.

Fair enough...

C++ has multiple inheritance too...

doesn't mean Java does...or should...

They always felt like a bit of a hacky shortcut to me when I used to use Delphi...
Avatar of Axter

ASKER

>>Then what's the problem.

The problem is the extra useless typing I have to perform, and the extra code I need to support this.
I like my code small and compact.
If I have a function with seven arguments, and I want the last six to be default values, I have to create six extra functions.
I think this is a total waste of time and code space for something that could have easily been done with a common language method of default parameter values.
>> If I have a function with seven arguments, and I want the last six to be default values, I have to create six extra functions.
True

>> I think this is a total waste of time and code space for something that could have easily been done
>> with a common language method of default parameter values.
True again...
But apparently the java guys had other reasons not to do it
Avatar of Axter

ASKER

>>C++ has multiple inheritance too...
>>doesn't mean Java does...or should...

I can understand the reason for removing Multipel inheritance (although I may not totally agree with it).

However, I see no down side to default parameter values, and  I see plenty of upside.
Avatar of Axter

ASKER

>>But apparently the java guys had other reasons not to do it

Again, not an answer.
I can speculate on my own.   I'm looking for a factual answer.
>> If I have a function with seven arguments, and I want the last six to be default values, I have to create six extra functions.

Write your function to take a class...

class MyParameters
{
    String param1 = "a" ;
    String param2 = "b" ;
    String param3 = "c" ;
    String param4 = "d" ;
}

public void myFunction( MyParameters params )
{
    // do stuff
}

then call it with:

MyParamters params = new MyParameters() ;
params.param2 = "fish" ;
myFunction( params ) ;
Avatar of Axter

ASKER

No offence, but the “because it is” answer does not provide me any useful information.

It’s like asking why is the sky blue, and someone answering because it is.

And the “because they decided it that way” is along the same lines of “because it is”
>> However, I see no down side to default parameter values, and  I see plenty of upside.

The only upside is that is makes you type less code...
Avatar of Axter

ASKER

>>Write your function to take a class...

That makes the code more ambiguous, and also makes the code larger then what it has to be.

Not at all a good subsitute for default parameter values.
>> Not at all a good subsitute for default parameter values.

In your opinion.
Consider this:

public class A
{
    public void someMethod( int i, double d = 1.0d )
    {
        System.out.println( "A: " + i + ", " + d ) ;
    }

    public void someMethod( int i )
    {
        System.out.println( "B: " + i + ", " + d ) ;
    }
}

public class B extends A
{
    public void someMethod( int i )
    {
        super.someMethod( i ) ;
        System.out.println( "B: " + i + ", " + d ) ;
    }
}

Then, if I do:

B obj = new B() ;
b.someMethod( 4 ) ;

What gets printed out?

Tim
Avatar of Axter

ASKER

>>The only upside is that is makes you type less code...

1.  Less code
2.  Code easier to maintain
3.  Less storage space required for code
4.  Code is easier to read
5.  Less functions
6.  Less ambiguity
7.  Code transport faster because less code


Just look at the help document for the JOptionPane common dialog functions like showMessageDialog.
I have to scan up and down the page several times just to find what I'm looking for.  Just look at the following link, and check the Method Summary.
http://java.sun.com/j2se/1.3/docs/api/javax/swing/JOptionPane.html

Several pages, that could have been condense down to one page if they had default values.
I'd disagree with:

2.  Code easier to maintain
4.  Code is easier to read
6.  Less ambiguity

(see my example)
Avatar of Axter

ASKER

>> Not at all a good subsitute for default parameter values.
>>In your opinion.

It must be the opinion of the Swing designers, since they also didn't use that method.  See link I posted.


>>Then, if I do:
>>B obj = new B() ;
>>b.someMethod( 4 ) ;
>>What gets printed out?

No offence, but if you have to ask that question, then you don't know too much about default parameter values, and how they work.

The answer is, that your posted code would not compile.
IMHO, If you don't know enough about default parameter values, I don't think you really are in the position to make a judgement call.

Avatar of Axter

ASKER

>>I'd disagree with:
>>2.  Code easier to maintain
>>4.  Code is easier to read
>>6.  Less ambiguity
>>(see my example)

Your example shows you're not in a good position to disagree, since you don't understand how default values work.
> Your example shows you're not in a good position to disagree, since you don't understand how default values work.

That's because I'm a java developer...

We don't have default values.
Avatar of Axter

ASKER

>>That's because I'm a java developer...
>>We don't have default values.

I completely understand that.

I'm mainly a C++ developer, and if someone asked me why C++ doesn't have a garbage collector, I would TRY to tell them why it doesn't have it.
However, since I'm not an expert on garbage collector, and I have little experience with using code that uses this feature, I would not try to give pros and cons for garbage collector.

My question is really targeted to Java experts that are also experts in other languages like C++ or C, and do understand default values.
Avatar of Webstorm
Webstorm

Hi Axter,

>> I know you can accomplish the same thing by overloading and calling the main function with default values
As you know how to do, you can create a program to compile your java program before passing it to javac.

public void method(int b,int a = 0, String s="");
{...}

-->

public void method(int b,int a, String s);
{...}
public void method(int b, String s);
{method(b,0,s);}
public void method(int b,int a);
{method(b,a,"");}
public void method(int b);
{method(b,0,"");}


or you call also replace the method calls to avoid this amount of new methods ( 2^N instead of 1 methods where N=number of default parameters ).

related link:
http://forum.java.sun.com/thread.jspa?threadID=563847&tstart=15
I don't know why Java doesn't have this feature. Maybe it may confuse when you are searching for a method with 1 parameter, and only found method with more parameters...

you can ask sun (http://java.sun.com) to add this feature in a future release of their JDK.
Avatar of Axter

ASKER

Webstorm,

>>As you know how to do, you can create a program to compile your java program before passing it to javac.

I am considering doing that, but I'm still really looking for an answer to my main question.  Which is why was it left out of the language in the first place.

>>or you call also replace the method calls to avoid this amount of new methods ( 2^N instead of 1 methods
>>where N=number of default parameters ).

I don't understand.  What do you mean?

>>related link:
The link kind of reiterates what I've stated.
It would be nice if they added it to the language, but I'm not sure if they could safely add it now.
Personally, I find having default parameters more ambiguous. In a language with default parameters, it can get confusing as to whether a set of parameters is all that can be passed to a function, or if it can have more. In Java, well, that's your function call, take it or leave it.

Further, if you do have multiple default parameters in a function call, you often need to pass the default value anyway. E.g. (if you'll pardon some PHP)

function myFunc ( $x = 1, $y = 2, $z =3 ) {
//Do something
}

//Call passing $a and $b as $x and $z parameters
myFunc( $a, 2 , $b );

I have to do this kind of call all the time in VB.

To refer to your example about the JOptionPane, if I wanted to call showConfirmDialog with a parent, message and icon, and Java had default values, I'd have to pass the other 3 parameters anyway.

Default values can be useful, quicker, and yeah, reduce code. But being explicit is ultimately more useful, and not having defaults makes me personally think more about what I'm using to call with. And I suspect that this is why defaults were left out (being explicit, not to help me! ).

It would appear others have wondered about the same thing, though: http://c2.com/cgi/wiki?EmulateKeywordAndDefaultParameters
>>>>or you call also replace the method calls to avoid this amount of new methods ( 2^N instead of 1 method where N=number of default parameters ).
>>I don't understand.  What do you mean?

i mean: if you replace a method declaration containing N default parameters, you will get 2^N methods.
to avoid it, you can replace method calls instead of method declaration :

meth(int a=0,int b=0)
{...}

meth()
meth(5);
meth(5,1);

-->
meth(int a,int b)
{...}

meth(0,0)
meth(5,0);
meth(5,1);

but this replacement is more difficult to be done automatically (searching which classes call this method, ...).
Avatar of Axter

ASKER

>>But being explicit is ultimately more useful
Not when it increases your code size, so that you basically have to filter out all the extera code in order to find what you're looking for.
Example

int ShowMessage(string MainMsg, string Title = "Info", int MessageType = FooWarning, int MessageButtons = IDOK)
{
      //Do message
}

The above is much easier to understand, easier to maintain, and easier to find what you're looking for then the following:

int ShowMessage(string MainMsg, string Title, int MessageType, int MessageButtons)
{
      //Do message
}

int ShowMessage(string MainMsg, string Title, int MessageType)
{
  return ShowMessage(MainMsg, Title, MessageType, IDOK);
}

int ShowMessage(string MainMsg, string Title)
{
  return ShowMessage(MainMsg, Title, FooWarning, IDOK);
}

int ShowMessage(string MainMsg)
{
  return ShowMessage(MainMsg, "Info", FooWarning, IDOK);
}

continue.....
Unfortunately, this is a difference that exists between C++ and Java.  Java just doesn't allow default parameters.  Why?  Well, one of my co-workers would say, "Because Java was written to annoy C++ developers."  The truth of it lies in the tradeoff between compact code and resolving ambiguities.  Compact code leaves lots of room for ambiguity, and if you've ever seen any "hard-core" C, you'd know what I'm talking about.  Take, for example, the super-quick-and-dirty string copy in C:

while(*dest++ = *src++);

The Java language was built to get rid of these sort of "tricky" things.  That's why it's a compile-time error, rather than a warning, when you attempt to use an uninitialized variable.  Default values also fall into the same category - they leave room for ambiguity.  The Java language designers saw the extra verbosity having more benefits than the potential for super-compact code.  Java is what you might call a "padded-cell language" (http://jargon.net/jargonfile/p/paddedcell.html) in some respects.
Avatar of Axter

ASKER

I don't see how anyone could think that using the Java overloaded method, is easier to understand or easier to code.

To find my default parameters using the Java method, I have to search through several functions.

Using the very simple default value method, the information is right in the function declaration.
It's very clear, very easy to understand what you get, and very easy to maintain.
The overloaded method is very ambiguous in comparison.
If I just look at ShowMessage(string MainMsg), I don't know what I'm getting.  I don't know what it's going to use for a default title, or messagetype or button types.
To figure that out, I have to hunt through the code, and find the other functions.


>>Further, if you do have multiple default parameters in a function call, you often need to pass the default value
>>anyway. E.g. (if you'll pardon some PHP)

That would be the case in improper design, and not a problem with default value.
Moreover, you would still face that problem with function overloading method.
So that really doesn't address default value usage.

In a properly designed function that uses default values, you placed the most commonly used variable argument first, and arguments that have common values, are placed at the end.
So if you had a function that most callers would need to modify the ICON parameter, you wuold place that as one of the first arguments.
Avatar of Axter

ASKER

guitaristx,

As my example shows, the overloading method is more ambiguous then just using a clear and easy to read plus understand default value method.

I'm sorry, but I can't see how anyone with experience using default value method, could believe that overloading method is easier to read, understand, or maintain.

And I can't see how the Java designers whould have believe that either.

I'm sure there has to be some real valid and logical explanation why it's excluded from the language.
ASKER CERTIFIED SOLUTION
Avatar of Rick_Townsend
Rick_Townsend

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Java doesn't do it for the simple reason that it's a bad idea. Just because somethng can be done, does not make it something that should.

The reason for this is that human beings are not happy when ambiguities can arise (which point has been made umptenn times in this thread already). Whilst you, the programme may feel an affinity of authorship with your code and its method architecture, another programmer would not be so easily able to grasp your set - up, costing him a lot of time, and  / or the possibility of introducing bugs due to misunderstandings. The people who designed Java were aware of this.

However, as Tim says (and by the way IMHO his comments in no way justify the venom they attracted, since he is one of this TA's major scientists), but he outlined how you can go about implementing what you want, java-style. So now that you know that Java thinks ambiguity is bad and that's why it was left out, you can implement Tim and others reasoning to get your code.

Personally, I'd probably have written simplistic call which took a single int param, and indexed into a switch block similar to Tim's which decided how many of your parameters would be actually called - like a call to proxy method if you like. Or even if you don't like. :0)
Avatar of Axter

ASKER

>>One of my standards is to use NULL for a value that you want to use a default for, where the called method
>>immeadiately validates incoming parameters and assigns defaults for NULL values.

That's not a bad idea.

>>J2SE 1.5.0 (or just 5.0 or whatever it's called now - sheesh, get consistent!) includes some features to allow
>>variable numbers of arguments (look for "varargs" for more details.)  The arguments you supply end up in an
>>array, which you presumably parse through to identify how many they supplied.  In this way you avoid the need
>>to overload functions with 1, 2, 3, ... parameters.

That would be a good workaround, although IMHO, default values would still be clear from the user's point of view, since this method still would not give you information as to what would be the default values.
Avatar of Axter

ASKER

>>Java doesn't do it for the simple reason that it's a bad idea. Just because somethng can be done, does not make
>>it something that should.

I completely disagree.

>>The reason for this is that human beings are not happy when ambiguities can arise
I agree, but I would say using overloaded functions to simulate default values is much more ambiguous.

>>The people who designed Java were aware of this.
IMHO, that's an assumption, that has no concrete data to support it.

>>So now that you know that Java thinks ambiguity is bad and that's why it was left out

Another assumption.

Sorry, but as I've stated, I'm not looking for assumptions.  I can make my own assumptions.
I'm looking for concrete information, that can be validated via link(s) or reference to a hardcopy.
Avatar of Axter

ASKER

Please DO NOT post any more OPINIONS as to why default values are not included in Java.
Please DO NOT post any more OPINIONS as to why default values are not included in Java.
Please DO NOT post any more OPINIONS as to why default values are not included in Java.
Please DO NOT post any more OPINIONS as to why default values are not included in Java.
Please DO NOT post any more OPINIONS as to why default values are not included in Java.
Please DO NOT post any more OPINIONS as to why default values are not included in Java.
Please DO NOT post any more OPINIONS as to why default values are not included in Java.
Please DO NOT post any more OPINIONS as to why default values are not included in Java.
Please DO NOT post any more OPINIONS as to why default values are not included in Java.

I'm not interested in any opinions to that effect.

I'm looking for concrete data that can be reference to a reputable web site or book.

I don’t mine opinions on workarounds like Rick_Townsend  posted, but I’m NOT interested in opinions as to why it’s not included in the language.
I’m interested in facts!
>> I'm not interested in any opinions to that effect.

You are, however, incredibly rude.
I'm unsubscribing. No-one here needs a joker like you to go off on one like this. Are you drunk or something?

It's one thing for an expert to take issue with another expert for plagiarism, incorrectness, defamation or cajoling, but it's another for someone to come on with a question and then make a stink about not liking the answers, comments and opinions as you have done. It seems to me that your attitude of not wanting to hear "opinions" is about as inflexible as your adhesion to the notion that default parameters are unquestionably great. Rubbish.

If you think you know better, then either you didn't need to ask the question in the first place (thus wasting everyone's time), or you should go ask Sun about it all - they probably just plain **forgot all about** default params, and would love to hear your rants. Ho . ho ho . Goodbye, nie aufwiedersehen and goodbye once more.
Avatar of Axter

ASKER

>>You are, however, incredibly rude.

Well, I'm sorry, but I don't know how else I could have gotten the message across.
There are times when I post a question, in which I’m interested in an opinion, and I usually explicitly state so.
However, in this question I’ve stated over and over again, that I did not want an opinion.

If I’m rude, then please explain to me how I should have I got my message across that would not have offended you or anyone else.

I understand that some of you may have strong opinions on this, but I just don’t want it posted on my question.
Avatar of Axter

ASKER

>>I'm unsubscribing.

Thank you krakatoa.
I would prefer that you do unsubscribe rather then you continue to post more unwanted information in my question.

Thank you very much
Avatar of Axter

ASKER

Since I'm not interested in a debate, I'm closing this question.

Thank you Rick_Townsend,
Although I didn't get the answer to my question, I still awarded you the points because you're the only one who provided any information that I could actually use.

Avatar of Axter

ASKER

TimYates  and krakatoa,
In the future, if you're not interested in respecting my request on my questions, please refrain from attempting to assist me.
You don’t have to waste your time trying to help me, and I don’t have to waste my time trying to get my message across to you.

Thank  you
Avatar of Axter

ASKER

>>If you do not want the help and knowledge of the experts, why you post a question?

I did not post here to get an opinion.  I post my question in the hope that an expert new the answer and had a reference to back it up.

I am one of the top C++ experts in the C++ topic area.
If a questioner ask me details of the C++ language, and wants a reference to the standard, I have no problems providing that information.
I realize Java has no ANSI standard, and that's why I would have accepted a link or a book for factual information.


>>Rudeness is not appreciated and won't be tolerated.

I don't think you really completely read all my comments.
I repeatedly ask that experts not post opinions.
My VERY FIRST comment clearly stated “I am not looking for opinions”
I even added asterisk around it
**** I am not looking for opinions.  I'm asking this in the hope that someone here knows factually the answer, and can supply a link or reference a book to support the answer. *****

Is that not clear?  If not, what exactly did I need to say to make my wishes more understandable?
Why do you think is OK for an expert to disregard the questioners wishes”?

I didn’t post my question to get an opinion.  I posted it to get facts.
Avatar of Axter

ASKER

Venabili,
I also see that you failed to make any comments about krakatoa's last remarks, in which he results in name calling, and ask me if I was drunk.

I did not call anyone names here, and I don't think is comment was warranted.

Please completely read this thread before you jump to conclusions
I don't want to step into a flame-war here, but I came upon some additional info that might benefit the solution (for anyone that searches it out.)  There is some discussion in the JCP forums about how to create custom JavaDoc tags and what info to include in them.

http://forum.java.sun.com/thread.jspa?forumID=41&threadID=206633

The thread was in relation to a JSR, but the point is that you could put the default values in the JavaDoc description of each parameter.  (This assumes you're using proper javadoc'ing styles.)  That way the info would be at your fingertips, espescially if your IDE pops up JavaDoc tooltips or descriptions (eg: Eclipse does this.)

The other point made in that thread was that you could introduce a new doc tag like @optional that would replace the @param tag.  Optional parameters would be documented differently, or in a separate section of the class' page.  Of course, j2SE 1.5.0 changed that somewhat, and I expect to see some comments on how to properly document vararg parameters.

I've got a great book on the history of programming languages at home.  The authors backup all their points with full references.  I'll see if it expands on this question.


Anyways, thanks for the points.  I think some of the rudeness (on _all_ sides, btw, not just the Author) stemmed from frustration that the experts couldn't properly word or back-up their reponses (the first one started with "Because it doesn't"; no one likes a 'just because' answer.)  Comment 5 did clearly state that he wanted information or a link to back it any opinions; although I agree that the Author shouldn't simply discount an opinion just because it isn't fully fleshed out...
Avatar of Axter

ASKER

Venabili,

For most questions, the more information you get, the better.
However, when you get an overwhelming amount of information that you don’t want, that reduces the chances of you actually getting a good answer.

For example, if I ask a question about dogs, and 5 experts each post 5 answers about cats, that’s going to leave me with 25 comments about cats.
The expert who really knows the answer about dogs might open my question, and see 25 comments, and assume that one of those comments must have answered the question about dogs.
He’ll more then likely will ignore the question, and move on to a question that has very little responds to it.
I guess I should refresh a question before clicking Submit.  I see some nasty stuff must be going on.  Anyone mind if I Unsubscribe?
Axter,

Let's calm down.
I tried to explain you that in Java things are a little different than in the old languages (I usually find an answer in a thread from an archive from 1999 for an example... and I know what it says but never can find the link again). It happens that often that in one moment we all get used to it :) Not to mention that in a lot of questions here links actually appear days later - when someone finally founds the strange link they had read this from...

However - you could just skip the answers that you do not like...and not becoming rude  Besides  - the answers were on the theme so it is not the cat/dog situation :) There are no offtopic comments, not before you started to complain that you does not want opinions.

As I said - the experts did their best here. You do not like it. Ok. But this does not give you the right to become rude. Get the point?

Let's call this issue solved.

Venabili
>> Anyone mind if I Unsubscribe?

Yes, I do.

I think you should stick around. ;)
I mean until objects gets here, because I think he can clear this up, and he often visits dead questions.
Avatar of Axter

ASKER

>>I've got a great book on the history of programming languages at home.  The authors backup all their points
>>with full references.  I'll see if it expands on this question.

I would appriciate it.

I was thinking of another workaround in which I would pass in an array of objects that are mapped to names.
But the down side is that this method wouldn't find argument errors at compile time, and instead would be found at runtime.

I'm trying to think of a way to make it a compile time error.
Avatar of Axter

ASKER

Venabili,

Now it seems that the only expert who could have given me the answer I was looking for, has now unsubscribed.

This kind of validates my original point.

I'm posting a new question, and in the question I'm going to specifically state I don't want opinions.

If I continue to get harassment in my new question,  I would hope that you take care of it immediately.

Thank you
Avatar of Axter

ASKER

Venabili,
>> But this does not give you the right to become rude. Get the point?

Please point out exactly where you think I was rude?

If I ask a vendor for a hotdog, and I ask "PLEASE do-not to include a bun", is that rude?

IMHO, my comments where well mannered.

I now consider this issue closed.
Was thinking this over last night, and it occurred to me that it would be difficult to set default values for object parameters.

e.g.: How do you specify a default value for a Person object?

They could have let you specify a constructor call as the default, I suppose, and then only generated that object if the parameter was left blank?  Maybe check out how the NICE ( http://nice.sourceforge.net/ ) programming language set up their optional parameters.
Avatar of Axter

ASKER

>>e.g.: How do you specify a default value for a Person object?

Example:
void Somefunction(int xyz, Person = new Person());

Or
void Somefunction(int xyz, Person = NULL);

The ladder would be along the lines you suggested for a workaround.
Avatar of Axter

ASKER

I'm probably just going to end up creating an addon that will automatically convert default parameter functions into multiple functions automatically.
I can't see it being that difficult to code, which is one of the reasons why I can't see why the compiler can do that itself.