Avoid boolean parameters in method parameters

*Updated* 12/07/2010: Response from Uncle Bob added at the end


Uncle Bob has a coding rule: Avoid boolean parameters in method parameters

He preaches that up and down the street, and I couldn't agree more with that!

The reason:

  • We all know that 1 method should do only 1 thing (Single Responsibility Principle  for methods and classes)
  • If your method has a boolean parameter it is highly possible that your method is doing 2 things

 

See the following code examples

        private string GetAuctionStatus(long auctionID, bool includeClientDetails)
        {

if (includeClientDetails)
{

-- snip snip snip -

Bad Figure: A method with a boolean parameter --> Create 2 methods!

 

So that should look like

        private string GetAuctionStatus(long auctionID)
        {

-- snip snip snip -

        private string GetAuctionStatusWithDetails(long auctionID)
        {

-- snip snip snip -

Good Figure: 2 methods that do different things

This is how Uncle Bob would like to see it

 

But…
What about the below Uncle Bob?

 

With C# Named Parameters we can call the method like this

   logHelper.Debug(GetAuctionStatus(auction.Key, includeClientDetails:true));

 

@UncleBob: Are you happy with that?

 

I am quite happy.
I still suggest to create 2 different methods, when the 1 method does 2 different things.
If its just passing parameters to lower methods, lets use the named parameters



image1%5B1%5D[2]
Only 1 problem: Others on the team can still call the method like this

    logHelper.Debug(GetAuctionStatus(auction.Key, true));


Update:

Response from Uncle Bob on Twitter:

. @peitor Named parameters good. Boolean arguments to functions bad. Boolean arguments to constructors mostly bad.
http://twitter.com/unclebobmartin/statuses/17329673268

  • Named parameters good
  • Boolean arguments to functions bad
  • Boolean arguments to constructors mostly bad

Latest Posts

Popular Posts