Deeply nested code can become a maintenance problem.

This rule can apply to loops, where four or more loops are nested beneath each other.  It can also relate to if() statements where many conditions require testing.  In these situations, consider moving code out to helper methods or encapsulate just the boolean logic in helper methods.

The following code runs correctly, but nests deeply in hundreds of lines to perform its task.  Apart from the method being confusing to the reader, any further changes will be difficult.  (much of the content was removed to illustrate this example).

private void validateForumCategory(Category category) throws InvalidDataException
{
    :
    if ((category != null) && (category.getForums().size() > 0))
    {
        :
        for (Iterator fi = category.getForums().iterator(); fi.hasNext();)
        {
            Forum forum = (Forum)i.next();
            if (forum != null && forum.getTopics().size() > 0)
            {
                for (Iterator ti = forum.getTopics().iterator(); ti.hasNext();)
                {
                    Topic topic = (Topic)ti.next();
                    for (Iterator pi = topic.getPosts().iterator(); pi.hasNext();)
                    {
                        Post post = (Post)pi.next();
                        if (!post.isValid())
                        {
                            :
                        }
                    }
                }
            }
        }
    }
}

The method might be better defined by splitting self-contained portions into convenient chunks:

private void validateForumCategory(Category category) throws InvalidDataException
{
    :
    if ((category != null) && (category.getForums().size() > 0))
    {
        category.validateContents();
    }
}
blog comments powered by Disqus