Does this function have explicit return values on all control paths?

后端 未结 3 991
[愿得一人]
[愿得一人] 2020-12-08 18:18

I have a Heaviside step function centered on unity for any data type, which I\'ve encoded using:

template 
int h1(const T& t){
   if (t         


        
3条回答
  •  暖寄归人
    2020-12-08 19:02

    As noted, some special numbers can be both < and >=, so your reviewer is simply right.

    The question is: what made you want to code it like this in the first place? Why do you even consider making life so hard for yourself and others (the people that need to maintain your code)? Just the fact that you are smart enough to deduce that < and >= should cover all cases doesn't mean that you have to make the code more complex than necessary. What goes for physics goes for code too: make things as simple as possible, but not simpler (I believe Einstein said this).

    Think about it. What are you trying to achieve? Must be something like this: 'Return 0 if the input is less than 1, return 1 otherwise.' What you've done is add intelligence by saying ... oh but that means that I return 1 if t is greater or equal 1. This sort of needless 'x implies y' is requiring extra think work on behalf of the maintainer. If you think that is a good thing, I would advise to do a couple of years of code maintenance yourself.

    If it were my review, I'd make another remark. If you use an 'if' statement, then you can basically do anything you want in all branches. But in this case, you do not do 'anything'. All you want to do is return 0 or 1 depending on whether t<1 or not. In those cases, I think the '?:' statement is much better and more readable than the if statement. Thus:

    return t<1 ? 0 : 1;

    I know the ?: operator is forbidden in some companies, and I find that a horrible thing to do. ?: usually matches much better with specifications, and it can make code so much easier to read (if used with care) ...

提交回复
热议问题