How Can I Avoid Using Exceptions for Flow Control?

后端 未结 11 1250
天涯浪人
天涯浪人 2020-12-20 14:51

I have been assigned a project to develop a set of classes that act as an interface to a storage system. A requirement is that the class support a get method with the follo

11条回答
  •  星月不相逢
    2020-12-20 15:24

    With the given requirement you cannot do this.

    If you designed the contract, then add a condition and make the caller invoke

    exists(key): bool
    

    The service implementation look like this:

    if (exists(key)) {
        CustomObject o = get(key, ifModifiedSince);
        if (o == null) { 
          setResponseCode(302);
        } else {
          setResponseCode(200);
          push(o);
       }
    
    } else {
          setResponseCode(400);
    }
    

    The client remains unchanged and never notice you've validated upfront.

    If you didn't design the contract Probably there's a good reason for that or probably it's only the designer (or architect) fault. But since you cannot change it, then you don't have to worry either.

    Then you should adhere to the specifications and proceed like this:

     CustomObject o = get(key, ifModifiedSince);
    
     if (o != null) {
         setResponseCode(200);
         push(o);
      } else {
         setResponseCode(404); // either not found or not modified.
      }
    

    Ok, you're not sending 302 in this case, but probably that is the way it was designed.

    I mean, for security reasons, the server should not return more information than that [ the probe is get( key, date ) only return either null or object ]

    So don't worry about it. Talk with your manager and let him know this decision. Comment the code with this decision too. And if you have the architect in hand confirm the rationale behind this strange restriction.

    Chances are they you didn't see this coming and they can modify the contract after your suggestion.

    Sometimes while wanting to proceed right we may proceed wrong and compromise the security of our app.

    Communicate with your team.

提交回复
热议问题