Tutorial :Factor out a null check for a variable only set by one constructor



Question:

In the class below, only the second constructor takes a ForumThread object. Otherwise, it is set to null.
IncrementViewCount(), LockForumThread(), and other methods depend on _ft being non-null.

Without extracting the null check into a new private method, is there some simpler re-factoring I can do or a better design to guard against the use of the wrong constructor with those dependent methods?

private readonly IThread _forumLogic;  private readonly ForumThread _ft;    public ThreadLogic(IThread forumLogic)      : this(forumLogic, null)  {  }    public ThreadLogic(IThread forumLogic, ForumThread ft)  {      _forumLogic = forumLogic;      _ft = ft;  }    public void Create(ForumThread ft)  {      _forumLogic.SaveThread(ft);  }    public void IncrementViewCount()  {      if (_ft == null)          throw new NoNullAllowedException("_ft ForumThread is null; this must be set in the constructor");        lock (_ft)      {          _ft.ViewCount = _ft.ViewCount + 1;          _forumLogic.SaveThread(_ft);      }  }    public void LockForumThread()  {      if (_ft == null)          throw new NoNullAllowedException("_ft ForumThread is null; this must be set in the constructor");        _ft.ThreadLocked = true;      _forumLogic.SaveThread(_ft);  }  


Solution:1

If you implement a property for the ForumThread then you could throw the exception from the get if it is null. This may create a method in the underlying IL but its not a new private method in your class (plus - whats wrong with having a new method?)


Solution:2

Why don't sub-class ThreadLogic and provide additional constructor and dependent methods only in the sub-class? Alternatively, if you already have some hierarchy, you can use delegation and decorator pattern to add new features. In both cases you can check null in single place: constructor


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »