How Can I Avoid Using Exceptions for Flow Control?

后端 未结 11 1253
天涯浪人
天涯浪人 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:11

    Looking for an object that does not exist seems like an exceptional case to me. Coupled with a method that allows a caller to determine if an object exists, I think it would be ok to throw the exception when it doesn't.

    public bool exists( String key ) { ... }
    

    Caller could do:

    if (exists(key)) {
       CustomObject modified = get(key,DateTime.Today.AddDays(-1));
       if (modified != null) { ... }
    }
    
    or
    
    try {
        CustomObject modified = get(key,DateTime.Today.AddDays(-1));
    }
    catch (NotFoundException) { ... }
    

提交回复
热议问题