In a previous blog, we talked about the anti-pattern of partially filled objects. Another horrendous anti-pattern is defining a method that tries to be multi-purpose. This brings me to my next set of rules.


1. DO NOT Define a Method that does more than one well-defined task.

1a. Do not define a function that does completely opposite tasks in the same method

1b. Do not pass a boolean or any other parameter into a method that flags the method to behave completely differently than it was intended.

Let me give an example. Let's take the following method


void LoadProject (bool save)
{
// load the project into the project class
if (save == false)
GetProjectFromDatabase();

if (save == true)
{
SaveTheProject(_currentProject)
}

}

The fact that this project is doing two completely different tasks breaks the main rule #1. Since the method is accepting a boolean that changes the intended behavior of the method, this part of the definition breaks rule 1a and 1b.

You may think I'm making this up, but I just came across this in code, and I've even seen it before in some older standard libraries.

Correct Behavior

How should this method be refactored to defeat this scary anti-pattern? If we just think about rule #1, we can quickly come up with a solution. Simply divide the method into two well defined tasks and name them appropriately

void LoadProject()
{
GetProjectFromTheDatabase();
}

void SaveProject()
{
SaveTheProject(_currentProject);
}

Now it is very clear to other programmers looking at your code what each method is doing. Rule #1 is based on the basic CS concept of high cohesion