I have a property that is loaded lazily, any time after the ctor is called.

It is possible that the binary that my property relies on is invalid. If invalid I might have to throw an exception.

Should I

  1. Make the property a method, and be done with it.
  2. Leave things as is.
  3. Leave the property as-is, but add a method to validate the object, which will invoke the lazy parse, that might throw an exception.

I would stick to throwing an unchecked exception.

The reason is it is not up to calling objects to validate your object. Furthermore, pulling the loading logic to a separate method means calling code must know to call method A before method B, and potentially method A can/should only be called once. This is a sequencing anti-pattern.

In this case, I prefer lazy loading which if done correctly ensures A. that loading is done only once, B. calling code does not need to know that methods in your class should be called in a specific order, potentially breaking if they do not.


public object getObject() {
  if (this.data == null) {
  return this.data

private void loadObject() {
  // Expensive loading logic...

Edit: I would like to clarify that getters/accessors should, generally, not throw anything. However, in this case, we are not dealing with a simple getter. I like to think of this not as "get some simple variable stored on the object" but "go get me some beer from the fridge, and if there are none left, throw a NullPointerException." After all if you are getting a value from some binary file or whatever, are you going to set it too? Probably not. So maybe another question is "should this be called a 'getter' to begin with?" which is a separate question.

| improve this answer | |
  • From your casing I infer you're using Java. Does this advice apply to C# as well? I'm porting this code from Java and see many API approaches I would have done differently. – goodguys_activate Mar 10 '14 at 21:00
  • My advice is language-agnostic, and my code is generic "object-oriented in a C-like syntax." The API is different between the two languages, but the same OO concepts can be expressed in either. – user22815 Mar 10 '14 at 21:03

It depends on how much the user of the class knows about the file:

  • If they do not know it exists or its format, then having the property is sufficient as the users do not have any idea how to deal with the exception.
  • If the user of the class knows that this file exists, can specify the path, or can create this file, then having a method with clear exception throwing semantics would be better.
  • If you can get both types of users, then a property and method might have to be done.
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.