String literals vs consts overuse?

Posted 3 years ago by dmitry.g.ivanov

Hi there!

A lot of developers (including me) - are using consts for almost each primitive (int, string) in the code. When it comes to integers (so called "magic numbers") - it perfectly makes sense, but I have some doubts according strings. I understand that consts are more IDE-friendly, they are protecting me from typos, it's easy to find, to change... But how often actually do we need to find, or change them? How often do we create const with the name which exactly match it's value? Does it makes sense?

For example:

class User extends Authenticatable
    // ...
    const ROLE_ADMIN = 'admin';
    const ROLE_MODERATOR = 'moderator';
    const ROLE_USER = 'user';
    // ...
class AdminsController extends Controller
    public function __construct()
        $this->middleware('role:' . User::ROLE_ADMIN);
        // vs

Without consts code can be more simple, clear and readable. Do we need that strict practice? I've searched through Laravel code - and it has only 19 declared class consts. Taylor is mostly using string literals in Laravel.

I understand that this is the question of preference, and probably there is no just one correct answer - all depends of situation. But can we at least say that using string literals instead of consts overuse is NOT a bad practice? Are there any "best practices"? It would be very interesting to hear @JeffreyWay here, if possible.

Thanks and have a great day!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.