DEV Community

Cover image for How to write clean code.
Moataz khaled
Moataz khaled

Posted on

How to write clean code.

Good code

At some time we write if statement like:

public function create($type) {

    if ($type == 1) {
        return "A";
    } elseif ($type == 2) {
        return "B";
    } elseif ($type == 3) {
        return "C";
    }
}
Enter fullscreen mode Exit fullscreen mode

this code is good and worked but not clean code.

clean code

we can convert this code to be like:

priviate $array = [1 => 'A', 2 => 'B', 3 => 'C']; 

public function create($type) {


    return key_exists($type, $this->array)? $this->array[$type]:false; 
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
lito profile image
Lito

More clean:

protected static TYPES = [1 => 'A', 2 => 'B', 3 => 'C'];

public function create(int $type): ?string
{
    return static::TYPES[$type] ?? null;
}
Enter fullscreen mode Exit fullscreen mode