Is it acceptable to use exceptions instead of verbose null-checks?

前端 未结 9 2421
刺人心
刺人心 2020-12-28 21:51

I recenly encountered this problem in a project: There\'s a chain of nested objects, e.g.: class A contains an instance variable of class B, which in turns has an instance v

9条回答
  •  失恋的感觉
    2020-12-28 22:12

    The problem with the "catch an exception" approach is that it seems a bit heavy-handed. The exception stack trace should show you where it failed since your method names make it quite clear where you are in the hierarchy but it is not a good way of going about it. Plus how would you recover from the exception and carry on to a good state of your code?

    If you must keep this very deep hierarchy then you could use static instances of each object which defines an "empty" state. The best example I can think of which does this is the C# string class which has a static string.Empty field. Then each call of getB(), getC() ... getZ() would return either a real value or the "empty" state, allowing you to chain the method calls.

    By making the "empty" state instances static there would only be one of each type in your system. But you would need to consider what an "empty" state looks like for each type in your hierarchy and make sure it doesn't affect any other part of your application inadvertently.

提交回复
热议问题