Search code examples
c#fluent-interface

Method Chaining when no object was constructed


In my current Net Framework 4 project, I did this:

  • defined my class constructor as private
  • called static class method to obtain object of that class
  • invoked methods of that freshly constructed object, which could fail

This looks in a following manner:

MyClassName obj = MyClassName.GetObject("Name").DoJob().Close();

where

  • GetObject is a static method that returns instance of MyClassName OR NULL (I specifically want to return null on creation failure, since no other way came to mind)
  • DoJob() and Close() are instance methods, they return this and will throw a System.NullReferenceException when GetObject fails, or anything inbetween fails.

Problem is: Is it possible to design this in the way I want, without try-catch blocks? I want to have many, many one liners versus try - lineOfCode - catch. Every line will be another object doing its specific task and destroying itself / being forgotten. I don't really need to use MyClassName obj = part either.


Solution

  • Instead of returning null value, you could return a null object as part of Null Object pattern.

    In this case, this object would do nothing when DoJob and Close is called and just return itself.

    The possible problem might be need to define some kind of simple class hierarchy to implement this pattern. Which might seem like overkill when you have just one class right now.