DEV Community

Cover image for Our way: Let the code breath
Robson Tenório
Robson Tenório

Posted on • Updated on

Our way: Let the code breath

👉 Go to Summary

There is no wrong or right way, there is our way.

-- Someone

.
.
.

Separate contexts

WTF!?

$post = Helper::sanitize($post);
$post = Helper::validation($post);
$post->notify($user);
$comments = Helper::crazy('hello');
$comments->gosh();
Enter fullscreen mode Exit fullscreen mode

Nice!

$post = Helper::sanitize($post);
$post = Helper::validation($post);
$post->notify($user);

$comments = Helper::crazy('hello');
$comments->gosh();
Enter fullscreen mode Exit fullscreen mode

.
.
.

Please, line breaks!

WTF!?

$hello = 'Mary';
if(...) {

}
foreach(...) {

}
if(...) {

}
$go = 'Paul';

Enter fullscreen mode Exit fullscreen mode

Nice!

$hello = 'Mary'; 
// <---here
if (...) {

}
// <---here
foreach(...) {

}
// <---here
if(...) {

}
// <---here
$go = 'Paul';
Enter fullscreen mode Exit fullscreen mode

.
.
.

Cleaner IF

WTF!?

if (User::where('name', 'Joe')->first() && 
   Product::where('name', 'xbox')->count() == 0) {
   throw new Exception("I'm sorry Joe. We don't have Xbox");
}

Enter fullscreen mode Exit fullscreen mode

Nice!

$isJoe = User::where('name', 'Joe')->first();
$hasXbox = Product::where('name', 'xbox')->count() == 0;

if ($isJoe && ! $hasXbox) {
   throw new Exception("I'm sorry Joe. We don't have Xbox");
}
Enter fullscreen mode Exit fullscreen mode

.
.
.

Early return

WTF!?

// You can buy a toy ONLY:
//  - If you have money 
//  - If it is weekend
//  - If it is NOT snowing

if($haveMoney) {
   if(! $isWeekend) {
       throw new Exception("It is not weekend!")
   } else {
      if($isSnowing) {
          throw new Exception("It is snowing!")
      } else {
          return 'Yes! I can buy!';
      }
   }
} else {
   throw new Exception("I don't have money!")
}

// Oh my... who did this!?
Enter fullscreen mode Exit fullscreen mode

Nice!

// No need to read rules, I can read the code.

if (! $haveMoney) {
   throw new Exception("I don't have money!")   
}

if (! $isWeekend) {
    throw new Exception("It is not weekend!")
}

if ($isSnowing) {
    throw new Exception("It is snowing!")
} 

return 'Yes! I can buy!';
Enter fullscreen mode Exit fullscreen mode

Top comments (0)