c# - Overloading Methods Or Not? -
what have here 2 methods (killzombie) handle cases have 1 argument (string) or more 1 argument (string[]). because same thing, made method named "killazombie" used other 2 methods. problem i'm having method "killazombie" named... kind of strangely. problem other people encounter too? best way solve , name "killazombie" method else distinguishes more "killzombie"
public void killzombie(string zombielocation){ killazombie(zombielocation); } public void killzombie(string[] zombielocations){ foreach(string zombielocation in zombielocations){ killazombie(zombielocation); } } public void killazombie(string zombielocation){ //kills zombie @ specified location }
another way can see problem being solved instead of overloading "killzombie" have 2 different methods this:
public void killzombie(string zombielocation){ //kills zombie @ specified location } public void killzombies(string[] zombielocations){ foreach(string zombielocation in zombielocations){ killzombie(zombielocation); } }
this way have 2 methods easier understand, method isn't overloaded. in mind, seems thing have overloaded methods (this means there fewer methods, less clutter) i'm not sure solution either. i'd interested in hearing best way tackle problem, thanks!
addendum:
my method takes 4 arguments, params @ end. params variable important one, putting last argument make params work seems kind of clunky. concern on putting important argument last, legitimate enough split methods killzombie , killzombies or params still right way things?
the latter of 2 choices preferable in case (given naming of function implies it's operating upon single "zombie".
however, might want params
keyword, know options are. instance, if you'd named function kill
(and if made sense in context), have:
public void kill(params string[] zombienames) { foreach(string name in zombienames) { } }
and call number of ways:
kill("zoey"); kill("francis", "zoey"); string[] survivors = { "zoey", "francis", "bill", "louis" }; kill(names);
(assuming, of course, survivors had been turned zombies!)
also, stylistically c# code uses pascal casing function names (killazombie
rather killazombie
).
edit addendum
yes, parameter ordering--while has no technical relevance--is important consideration in api design, if you're going taking "less important" parameters, you'll have without params
.
with said, i'll stand original recommendation: function named (killzombie
versus kill
), stick 2 versions sake of making name consistent parameters. suggest allowing user specify ienumerable<string>
instead of array. allow developer pass names using implements ienumerable<string>
, including string array.
Comments
Post a Comment