Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a parameter, or create a new method?

Let's say I have a long established repository like this:

interface IDonutRepository
{
    public IEnumerable<Donut> GetDonuts();
}

It's been around for ages, and the GetDonuts method does what it says. Then one day I need to add a new screen that shows all the donuts in the database, and it turns out that the method has a hidden feature - it filters out all donuts where stale = true. But on my new screen, I want to show all of them, even the stale ones! What is the best approach here?

Assuming that this method is used all over the place, and the default behaviour needs to stay the same, is it best to add a new method called GetAllDonuts that doesn't do the filtering, or should I just add a onlyFresh parameter onto the GetDonuts method?

I'm guessing its just down to judgement, but I'm wondering if there are any more informed answers out there?

like image 697
GoatInTheMachine Avatar asked Mar 23 '11 17:03

GoatInTheMachine


People also ask

How to create method in java with parameter?

Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

What are parameters in methods java?

Note: Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.

What is argument and parameter in java?

The term parameter refers to any declaration within the parentheses following the method/function name in a method/function declaration or definition; the term argument refers to any expression within the parentheses of a method/function call.


1 Answers

I would overload the method creating a new overload that takes the showStale parameter and then modify the old method to use the new overload passing false for the parameter value.

The interface would look like:

interface IDonutRepository
{
    public IEnumerable<Donut> GetDonuts();
    public IEnumerable<Donut> GetDonuts(bool showStale);
}

Or if you're using .NET 4.0, you can use an optional parameter:

interface IDonutRepository
{
    public IEnumerable<Donut> GetDonuts(bool showStale = false);
}
like image 151
Justin Niessner Avatar answered Oct 05 '22 19:10

Justin Niessner