{ $fee = $this->calculate($data); if ($period === ‘monthly’) { $fee = $fee / 12; } } Redundant comment: for what? Commented comment: what does this do here? Todo: What was the original intention? // Calculates the fee public function calculateFee( $data, $period ) { // $data = $this->clean($data); $fee = $this->calculate($data); /** @todo: refactor this */ if ($period === ‘monthly’) { $fee = $fee / 12; } }
= $this->calculate($data); if ($period === ‘monthly’) { $fee = $fee / 12; } } public function calculateFee( $data, $periodicity ) { $fee = $this->calculate($data); if ($periodicity === ‘monthly’) { $fee = $fee / 12; } } Before After $period not longer means “period” here. Perhaps long time ago it meant that, but now clearly refers to another concept. This gap carries a cognitive load we don’t need.
be concealed by the more complex one. if ($someCondition) { // Lots // and // lots // of // lines // .. } else { // one line } if (!$someCondition) { // one line } else { // Lots // and // lots // of // lines // .. }
(!$data) { throw new Exception(‘Bad data’); } $fee = $this->calculate($data); if ($period === ‘monthly’) { $fee = $fee / 12; } } Return or fail early and reduce the complexity of the function. public function calculateFee($data, $period) { if ($data) { $fee = $this->calculate($data); if ($period === ‘monthly’) { $fee = $fee / 12; } } else { throw new Exception(‘Bad data’); } }
new CommissionDoesNotExistException( sprintf(self::MISSING_CUPS, $reactivationDTO->cups()) ); } $commission = $this->commissionRepository->lastByCups($reactivationDTO->cups()); if (!$commission) { throw new CommissionDoesNotExistException( sprintf(self::MISSING_CUPS, $reactivationDTO->cups()) ); } Before After Also to note: what about throw exception from inside repository call? $commission = $this->commissionRepository->lastByCups($reactivationDTO->cups()); After all
do Something } function userCanModifyProduct() { return $user->hasModifyPrivilege() && $user- >isAuthorized() && $product->isAvailable(); } Extract complex conditional to make them self-explanatory if ($user->hasModifyPrivilege() && $user->isAuthorized() && $product- >isAvailable()) { // do Something }
$this->doThis() } else { $this->doAnotherThings() } Moving the legs of conditionals to their own methods makes easy to understand the main flow of the code, hiding concrete details. if ($someCondition) { // Lots // and // lots // of // lines // .. } else { // Lots // and // lots // of // lines // … }