Reduce input of functions to improve readability

Reduce input of functions to improve readability
Photo by Victor Barrios / Unsplash

One of the elements we evaluate when reading a function call are the parameters given to it. To understand what's happening inside (not how, just what) it's necessary to see the relevant data as part of the function call.

Counterintuitiv, this sometimes means to increase the amount of parameters or splitting a function into a few atomic functions. Lets look at this example:

$this->userMustBeAbleToAccessProject($user, $project);

This doesn't give any indication of what's validated. Sometimes that can be remedied by adapting the name. But depending on the level of the encapsulation it might not.

It could be split into multiple functions like this:

$this->userMustBeManager($user->role);
$this->userMustHavePermissionToReadProjects($user->permissions);
$this->userMustHaveExplicitAccessToProject(
  $user->explicitlyAccessibleProjects,
  $project,
)

Or simply adding parameters and therefore reducing the input. This way it's not all properties of the user any more but only the explicit ones.

$this->userMustBeAbleToAccessProject(
  $user->role,
  $user->permissions,
  $user->explicitlyAccessibleProjects,
  $project,
)

Here's another example:

$this->updateUser(
  $user, 
  $command,
);
$this->updateUser(
  $user, 
  $command->firstName,
  $command->lastName,
  $command->emailAddress,
  $command->password,
  $command->address,
);

The second gives a clear indication of what's updated.

As an additional benefit, building test data for the second use case is also easier as you only need to configure the data that is actually needed and not 5 other parameters the command might additionally have.