How Can I Avoid Using Exceptions for Flow Control?

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

    You could follow the .Net library pattern of and have a public static readonly field in the custom object called CustomObject.Empty that is of type CustomObject (like string.Empty and Guid.Empty). You could return this if the object is not modified (the function consumer will need to compare against it).
    Edit: I only just spotted that you're working in Java, but the principle still applies

    This gives you the option of the following

    • Return null if the key doesn't exist.

    • Return CustomObject.Empty if the key exists but the object has not been modified.

    The drawback is that the consumer would need to know the difference between a null return value and a CustomObject.Empty return value.

    Perhaps the property would be more aptly called CustomObject.NotModified as Empty is really intended for Value types as they cannot be null. Also NotModified would convey the meaning of the field more easily to the consumer.

提交回复
热议问题