Home > Software engineering >  Is it more "correct" to disable a function with a special value or a second parameter?
Is it more "correct" to disable a function with a special value or a second parameter?

Time:04-06

Say I have some function that I may or may not want to execute during a particular run of the code, and this function also takes some argument that is passed in as a parameter at runtime. Is there some guidance as to whether a second variable to enable/disable the execution of the function is warranted, or is a "special value" of the argument just as good? I like the idea of reducing the number of parameters but I can understand how the former might be more readable.

For example, consider a 'Delay' function (which we may or may not want to run and) which accepts 1 floating point argument for the length of the delay. We can then check first that the argument-parameter is positive, and if it is not, we can not bother calling the function at all. Is this bad code?

I generally write in C/C if that matters.

CodePudding user response:

check first that the argument-parameter is positive, and if it is not, we can not bother calling the function at all

This seems like a poor design, if we call the function, but some extra logic is there to decide, whether we should actually call it, based on current state.

However, if you want a single argument, which defines the delay value, but also could mean that there is no delay at all, you could use std::optional. Still, it seems like a bad idea, to mix extra logic into this quite straightforward delay function. I'd focus on calling the delay function only when it's really needed.

CodePudding user response:

Given a predicate p the first option is to conditionally call the function:

if(p) Delay(42);

This makes the calling code a bit more verbose, but you don't have the overhead of the function call. If the code uses lots conditions along those lines, it may obscure what is going on. Error handling or if code is ported with lots of conditionally enabled code via macros comes to mind.

The 2nd option is to have a special value indicating that Delay() shouldn't do anything:

float t = 42;
if(!p) {
  t = 0;
}
...
Delay(t);

This means the disabling the feature is now both in the caller and in callee which I would consider a negative. On the other hand, if the special case is an implementation detail of Delay(), say, you figure out a function call overhead is delta then you might have logic along these lines:

if(arg <= delta) return;

Now you are merely making use of that particular implementation detail.

  • Related