How would you refactor this boolean parameter?

I’ve got this piece of code and I’d like to get rid of the boolean parameter. How would you do it? I have some ideas, but I’m looking for some alternate perspectives.

Posted June 25th, 2009 12:18 PM
Read more posts about C#, Programming.

View Comments
Link

  • I might use an enumeration if I were trying to make it very explicit.

    public static PostCollection ListComments(int parentId, int pageNum, int pageSize)
    {
    return PostRepository.List(parentId, pageNum, pageSize, PostCollectionIncludeOptions.IncludeDeleted);

    }

    public enum PostCollectionIncludeOptions {
    IncludeDeleted,
    ExcludeDeleted
    }
  • Didn't you say you want to actually REMOVE the parameter (not just comment it). So I assume we can change the PostRepository...

    In this case I would change the PostRepository.List method to always include deleted items and write an extension method that filters (excludes) deleted posts.

    This way you should be able to write something like this:

    return PostRepository.List(parentId, pageNum, pageSize).ExcludeDeleted();

    or if you want deleted items you just don't use the filter.
  • Matt
    firstly the above code could be improved directly by making the value const.

    Obviously you wish to avoid having a naked true for readability so you have a few options:

    public static PostCollection ListComments(int parentId, int pageNum, int pageSize) {
    return PostRepository.List(parentId, pageNum, pageSize, true /* includeDeleted */);
    }

    I tend to dislike this because /**/ doesn't nest which can be very painful.
    The safer way does increase the space consumed at call site, especially on the last parameter

    public static PostCollection ListComments(int parentId, int pageNum, int pageSize) {
    return PostRepository.List(
    parentId, pageNum, pageSize,
    true -- includeDeleted
    );
    }

    If you use the parameter in more than one place adding named constants for it can help but is dependent on there being some reasonable place to have the named constants.

    I am assuming you don't have access to PostRepository to modify it to include an overload with the default or to add ListActive() and ListAll() or some such?

    Since named optional parameters are coming to a c# compiler near you in 2010 I wouldn't suggest doing much with this at all until then though.





  • Manu Temmerman-Uyttenbroeck
    Since the method call doesn't have a lot of parameters, I would use the following:

    public static PostCollection ListComments(int parentId, int pageNum, int pageSize) {
    return PostRepository.List(parentId, pageNum, pageSize, true /* includeDeleted */);
    }

    ps: Maybe someone already mentioned it to you, but in chrome your choose-subscription dropdown looks completely black :)
blog comments powered by Disqus