Code readability is really important part of programming. The readable and cleaner code is easily manageable and customizable. The programmers don’t take it seriously but it’s important. Actually, there is always an ongoing debate, but returning often, and returning early will make your code much cleaner looking and readable.
public function saveUser($data = [], $sendEmail) { // Checking data is exiest or not if ($data) { $isSaved = $this->UserModel->save($data); // Checking if the data is successfully stored or not. if ($isSaved) { // If stored then doing some other work // send the email to the user if ($sendEmail) { // send the email } } else { // Otherwise return false return false; } } else { // Otherwise return false return false; } }
If you look over the above code snippet, then you can see there is some nested if-else. And code quickly becomes unreadable and complex. You have to have a deep look to understand this sort of code.
public function saveUser($data = [], $sendEmail) { if(!$data) { // If data not exiest then return. return false; } $isSaved = $this->UserModel->save($data); if (!$isSaved) { // If data not saved then return. return false; } if (!$sendEmail) { // send the email } // If everything good, then return true. return true; }
Now see this code snippet, this code is much easier to read and very cleaner look. Both snippets are doing same work but the second one is much more readable and clearer than first one. And this can be easily manageable & customizable. so that avoid too much complexity to the code, instead of returning often and early.