Get in touch

Every class and method must resolve only one problem / function.

Sometimes we don’t want to write too many lines of code… And trying to write code more faster because customer don’t want to pay for pretty code… But… However we can fall into the trap, when we add some functionality to our code. And good practice for that is Single responsibility. It is mean that any function or method of our object must do only one thing. If it is a condition – we must write the function or method that calculate and returns result of the condition. If it is output message – we must write function for getting message and so on… I know… It is hard to start doing that… But you must start trying…

 

Bad practice:

public function getFullNameAttribute()
{
    if (auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified()) {
        return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' $this->last_name;
    } else {
        return $this->first_name[0] . '. ' . $this->last_name;
    }
}

 

Good practice

 

public function getFullNameAttribute()
{
    return $this->isVerifiedClient() ? $this->getFullNameLong() : $this->getFullNameShort();
}

public function isVerfiedClient()
{
    return auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified();
}

public function getFullNameLong()
{
    return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name;
}

public function getFullNameShort()
{
    return $this->first_name[0] . '. ' . $this->last_name;
}

If you don’t try – you don’t get a result