Should two overloaded methods behave in a completely different way?

as from the name. It is considered acceptable that two methods, such as foo () and foo (int), perform two unrelated operations? and why?

Edit : thanks. I see that I am not the only one who thinks that this is heresy. :)

+5
source share
14 answers

Unacceptable.

Because it will violate the user's expectations, which will lead to a communication error.

IMO it would be more understandable to use a different method name for different operations.

, , , . , , , , , .

+12

. . ++ :

operator-(void);
operator-(const Other & o);

, . .

+5

, - jQuery, , , bind click, , bind trigger , ( true bind , undefined ).

jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
    "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
    "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){

    // Handle event binding
    jQuery.fn[name] = function(fn){
        return fn ? this.bind(name, fn) : this.trigger(name);
    };
});

downvotes

+5

. "" - . , .

.

+4

, - , , / . , . , , .
, , .

+3

! , , ? , .

+2

?

, , .

, ( )

, "" .


Complete:

, , , * private.
- .
[...]

( )

,

( foo() , foo(int))

, , , , ; .
, ; , .

+2

, , .

+2

"", "" ( ).

"" " - ", "" , "" "".

"", YES. , , . , "foo" "save (theOrder)" "save (thePassenger)", , -.

+2

.

, , .

+1

: .

: - , ?

+1

!

///. , , : .

0

!

, ( , ).

There is no need to further complicate the situation by making the result of these methods unpredictable for people who use this code later.

0
source

No...

Overloads should be considered as variations of the theme. Their general functionality should be the same as that of others, and distinguish only those inputs that they accept.

Often, overloads are used to determine default parameter values ​​(in C #). eg.

// This signature allows for doing special processing
public void ProcessItem( int index, bool doSpecialProcessing );

// Most of the time special processing is not required, so call
// this method
public void ProcessItem( int index )
{
     ProcessItem( index, false );
}
0
source

All Articles