Refactor throwing not null exception if using a method that has a dependency on a certain contructor

Posted by N00b on Stack Overflow See other posts from Stack Overflow or by N00b
Published on 2010-04-07T15:07:26Z Indexed on 2010/04/07 15:13 UTC
Read the original article Hit count: 278

Filed under:
|
|

In the method below the second constructor accepts a ForumThread object which the IncrementViewCount() method uses. There is a dependency between the method and that particular constructor.

Without extracting into a new private method the null check in IncrementViewCount() and LockForumThread() (plus other methods not shown) is there some simpler re-factoring I can do or the implementation of a better design practice for this method to guard against the use of the wrong constructor with these dependent methods?

Thank you for any suggestions in advance.

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);
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about constructors