DEV Community

JohnDivam
JohnDivam

Posted on

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!