Search code examples
functionparametersprocedure

Best practice for interface design


I am wondering which version is the best one to implement. The parameters are states that have 2 possible values. This is an abstract example of the actual problem. I am programming in a language that is procedural (without classes) and does not have typed variable. I just read an article stating that version 1 is bad for readability and the caller. Personally I don't like version 2 either. Maybe there is a better option?

Version 1:

doSth(par1, par2)

  • Not redundant +

  • Single Method for a task +

  • More complex implementation -

  • Wrong parameters can be passed easily -

Version 2:

doSthWithPar1Is1AndPar2Is1() 
doSthWithPar1Is1AndPar2Is2() 
doSthWithPar1Is2AndPar2Is1() 
doSthWithPar1Is2AndPar2Is2()
  • Redundant -

  • Too many methods (especially with more parameters) -

  • Long Method Names -

  • Simple implementation +

  • No parameters that could be passed wrong +


Solution

  • Given that you already have considered V1 feasible tells me, that the different argument value combinations have something in common with regards to how the values are to be processed.

    In V2 you simply have to type and read more, which I'd say is the single most frequent reason for introducing errors/incorrectness and lose track of your requirements.

    In V2 you have to repeat what is common in the individual implementations and if you make a mistake, the overall logic will be inconsistent at best. And if you want to fix it, you probably have to fix it in several places.

    But, you can optimize code safety based on V1: choose a more "verbose" name for the procedure, like

    doSomethingVerySpecificWithPar1OfTypeXAppliedToPar2OfTypeY(par1, par2)
    

    (I am exaggerating a bit...) so you see immediately what you have originally intended.

    You could even take the best out of V2 and introduce the individual functions, which simply redirect to the common function of V1 (so you avoid the redundancy). The gain in clarity almost always outweighs the slight loss of efficiency.

    doSthWithPar1Is1AndPar2Is1()
    {
        doSomethingVerySpecificWithPar1OfTypeXAppliedToPar2OfTypeY(1, 1);
    }
    

    Always remember David Wheeler: "All problems in computer science can be solved by another level of indirection".

    Btw: I don't consider long method names a problem but rather a benefit (up to a certain length of course).