logo
podcast Podcast
get help Get Unstuck

When would you use an enum?

A very useful addition to PHP

Joel Clermont
Joel Clermont
2024-11-26

I like establishing general rules for how I structure and write code. It guides me as I go about my work, keeps my code consistent, and also saves me from making a bunch of tiny decisions over and over.

One example of a programming rule I've established is when something should become an enum instead of just a literal value in my code.

There are two big reasons that would make me refactor a literal value into an enum:

First, I'd prefer an enum when there are a bunch of related options. Having all the possible values bundled together in an enum makes it easy to see what the other options are.

Even better, PHP watches my back by enforcing exhaustive pattern matching in a match statement, so I don't accidentally forget to handle a possible value in my code.

Second, I'd reach for an enum when the value drives business logic. A classic examples of this is the name of a role or a permission. Other examples might be the status of an order, or the type of product.

These string values definitely impact how the code works. By using an enum, it's easy to find usages throughout my code, and makes refactoring a breeze.

As a bonus, with the enum you avoid weird typos that you might have in an arbitrary string literal.

Here to help,

Joel

P.S. Collect all the tips and keep them for ready reference in our latest volume.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.