views:

105

answers:

2

What is the best "rule of thumb" to determine when to use method overloads and when to use a separate "request" class? for example:

MakePancakes(int size)
MakePancakes(int size, bool addBlueBerries)
MakePancakes(int size, bool addBlueBerries, ...)

As opposed to:

MakePancakes(PancakeOptions options)

Is it best to stick to one way or the other, or using either when "necessary"? Is there some point as to when or where one should be used over the other?

How do you decide which to use, and why?

+1  A: 

I wouldn't need many overloads myself before I created a request type or enum (array of enum seems like a pretty simple request object). Maybe 3-4? Some framework methods have 9-10 overloads and I find that to be a bit annoying but this is more of a style question I think.

Jeremy
+2  A: 

The real advantage of using MakePancakes(PancakeOptions options) is that you can change the number of attributes of PacakeOptions without having to change the method implementation. It can be helpful when the number of parameters can change or are optional. It does make sense to represent configuration/properties/options this way.

But I don't think it is a replacement for overloading methods.

Some rule of thumb:

  • if a method has more than 5 arguments, then it is probably doing more than 1 thing. I would review the method and try to split it in more specific functions.

  • All attributes of a method are required (i.e. cannot be null)

Handerson