Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compiler warning on (ambiguous) method resolution with named parameters

One question regarding whether the following code should yield a compiler warning or not (it doesn't). It declares two methods of the same name/return type, one has an additional named/optional parameter with default value.

NOTE: technically the resolution isn't ambiguous, because the rules clearly state that the first method will get called. See here, Overload resolution, third bullet point. This behavior is also intuitive to me, no question.

public void Foo(int arg) { ... }

public void Foo(int arg, bool bar = true) { ...} 

Foo(42); // shouldn't this give a compiler warning?

I think a compiler warning would be kind of intuitive here. Though the code technically is clean (whether it is a sound design is a different question:)).

like image 453
FireSnake Avatar asked Apr 17 '10 09:04

FireSnake


2 Answers

I disagree that it needs a warning, actually. The main issue is, that code is potentially legitimate, and if that's the case you would have to explicitly disable the warning.

What I mean is, in general when you get a warning, you will be able to change your code to get rid of the warning (and presumably make the code better at the same time). But in this case, it may be that you did it like that intentionally and would not be able to change your code to get rid of the warning.

For example, the "unreachable code" warning is something you can just delete the unreachable code to get rid of the warning. Or the "could not find reference" warning - this is usually a signal that you're going to get "undefined type" errors, but if not then you can simply delete the reference. Or maybe "A previous catch clause already catches all exceptions" warning: in this case, you need to change your code so that either the new clause comes before the catch-all, or remove the catch altogether.

But the point is that in every case when you get a warning, you should change your code, and making the change will always result in "better" code. However, in the case of this question, the call is not ambiguous (as far as the compiler is concerned) and I don't think you can argue that it's always a mistake to write code like that, so therefore there shouldn't be a warning.

If the compiler issued a warning about every case where you do something that's probably not the best idea, then we'd be inundated with warnings!

like image 183
Dean Harding Avatar answered Sep 30 '22 09:09

Dean Harding


Warnings are to notify programmers of potentially dumb mistakes. This is an area that could generate a dumb mistake, so yes, it should generate a warning. Are you trying to form a petition?

like image 44
nick Avatar answered Sep 30 '22 09:09

nick