开发者

Alternative to if(x >= 200 && x <= 299)?

In PHP (or any similar language), is there a better alternative t开发者_开发问答o:

if(x >= 200 && x <= 299){
   return 'ok';
}

My goal is to validate if a number is in the range of the 2xx code (for HTTP requests). I don't like the double-if clause because I must define the end of the range, and for some reason it's not practical when doing various automated validations.


In PHP (or any similar language), is there a better alternative to...

No there isn't, in my opinion.

Your code:

if (x >= 200 && x <= 299) {
    return 'ok';
}

is very readable and clearly defines what is being checked.


If you want a statement that you'll be sure to forget what you meant by it three months from now:

if(2 == (int)floor(x / 100)) ...

If nothing else, for readability's sake, wrap it in a function that describes it:

function isHttpSuccess(status) {
    return 2 == (int)floor(x / 100);
}


If you have a function, you can use the return 'trick':

function getStatus(x) {
    if(x < 200) return 'status 1xx';
    if(x < 300) return 'status 2xx'; // will only get executed if x >= 200 as well
                                     // otherwise already returned '1xx'
    ...
}


Wow this thread is over 10 years old! Adding another answer is probably just beating a dead horse (awful expression) but here goes...

The original question was about PHP but the code example provided looks like JavaScript. Here are some ideas for both languages (although the most upvoted answer is likely the best—just because we can do something doesn't mean we should)

In JavaScript, strings are objects that provide quick access to characters by index, so this could work:

if (x.toString()[0] === '2') {
    return 'ok';
}

If, instead of x we passed-in Response.status or similar, the concerns raised about legibility become somewhat moot:

if (Response.status.toString()[0] === '2') {
    return 'ok';
}

In PHP

if (substr($x, 0, 1) === '2') {
    return 'ok';
}

or

if (substr((string)$response->getStatusCode(), 0, 1) === '2') {
    return 'ok';
}

To take it further (maybe too far?) we can write a function to resolve status code "groupings"

const getStatusCodeGroup = (code) => {
  const groups = {
    '1': 'Informational responses (100–199)',
    '2': 'Successful responses (200–299)',
    '3': 'Redirection messages (300–399)',
    '4': 'Client error responses (400–499)',
    '5': 'Server error responses (500–599)'
  }
  return groups[code.toString()[0]] ?? 'Throw IRL';
}


return in_array($code, range(200, 300));


When you repeat a task over and over, and want to reuse code, you should write a new function. These examples assume you want to use the >= and <= operators, although oftentimes I would use >= and < to include the min val and exclude the max val.

A PHP abstraction:

function between( $val, $min, $max )
{
  return $val >= $min && $val <= $max;
}

A JavaScript abstraction:

if ( !Number.prototype.between )
{
  Number.prototype.between = function(min,max){
    return this >= min && this <= max;
  };
}

For your issue of HTTP ranges, I'd use the bottom-inclusive form as:

if ( between( $val, 200, 300 ) )...

Of course it could make sense to change the order of the parameters so that the declaration is:

between( 200, $val, 300 );

But really it's up to you.

A further abstracted example:

function between( $val, $min, $max, $mode = null )
{
  switch ( $mode )
  {
    case INCLUSIVE:
      return $val >= $min && $val <= $max;
    case EXCLUSIVE:
      return $val > $min && $val < $max;
    case TOP_INCLUSIVE:
      return $val > $min && $val <= $max;
    case BOTTOM_INCLUSIVE:
    default:
      return $val >= $min && $val < $max;
  }
}


You can write your own function to make it easier:

function inRange(val,lower,upper) {
    return val >= lower && val <= upper;
}

Then call it like this:

if(inRange(x,200,299)) {
    //execute code
} else {
   //other code
}


There's no built-in shorthand for this in most languages. But there's nothing wrong with writing a clear utility function of your own, like:

function inRange( $val, $low, $high )
{
    return ($val >= $low) && ($val <= $high);
}

which you'd then use as:

if (inRange(x, 200, 299))
{
   return "ok";
}

It's pretty easy or a future maintainer of your code to get the gist of what you're doing here -- arguably even more so than with the original 'double-if'.


In JavaScript:

if ([199,299,x].sort().indexOf(x) == 1)


For your purpose you don't need the equality operator, all responses are integers.

if(x>199 && x<300)

is as simple as life gets.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜