DEV Community

loading...
Cover image for How to write clean code.

How to write clean code.

Moataz khaled
・1 min read

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

Discussion (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