DEV Community

JohnDivam
JohnDivam

Posted on

1

Encapsulate conditionals. Clean code.

Encapsulating conditionals is a crucial aspect of writing clean and maintainable PHP code. It involves structuring your code in a way that reduces complexity, improves readability, and makes it easier to extend and modify. Here are some principles and techniques for encapsulating conditionals in PHP code:

#BAD
if($article->state == 'published'){
 // ...
}

#GOOD
if($article->isPublished()){
  // ...
}

# in Article Model 
const PUBLISHED = 'published';
public function isPublished(){
   return $this->state == self::PUBLISHED;
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
respect17 profile image
Kudzai Murimi

Thanks!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay