Mastering Enums: Enhance Your Programming Skills with Enums
Written on
Chapter 1 Understanding Enums
As a novice coder, I often encountered enums, which initially seemed quite challenging to grasp. This article will explore how enums can enhance our coding practices, particularly in PHP, although the concepts apply broadly across various programming languages.
What Are Enums?
Enums, short for enumerations, enable developers to create a custom type with a defined set of values. They are prevalent in numerous programming languages. In PHP, an enum functions as a class, and each potential value is an instance of that class. Consequently, enum cases are legitimate objects that can be manipulated like any other object.
While this article focuses on PHP for examples and practical illustrations, it's crucial to note that in languages like C, C++, and C#, enums are typically treated as named integers. Thus, interacting with enums in those languages is akin to working with integers. In contrast, PHP treats enums as distinct types rather than mere integer constants.
Using Enums
Let's examine a straightforward example from PHP's documentation:
In this basic example, you'll perform the following steps:
- Transform user input into an enum value.
- Within the function, convert the enum back to a string.
- Utilize the string in your query.
Why Utilize Enums?
How can enums reduce workload? One might think we could simply compare user input against known valid values manually. However, the key point is that using enums doesn't necessarily lessen the effort but enhances the accuracy of our code. This becomes evident when considering invalid input scenarios.
For instance, if you attempt to execute the following:
query($fields, $filter, SortOrder:Dec);
An error will occur since 'Dec' is not a valid option. Likewise, using a string does not prevent this error:
query($fields, $filter, "Dec");
To circumvent this issue, the recommended approach is as follows:
// Attempt to parse user input.
// If invalid, tryFrom will return null, defaulting to Asc.
$order = SortOrder::tryFrom($input) ?? SortOrder::Asc;
query($fields, $filter, $order);
Conclusion
In this article, you learned how to effectively leverage enums and their significance for creating robust code. My inspiration for writing this piece came from exploring discussions on StackOverflow, particularly the question: "What are some uses of Enums?"
Chapter 2 Practical Applications of Enums
In this video, "Master TypeScript Enum Basics: Essential Tips for Beginners," viewers will gain foundational knowledge about enums in TypeScript and their practical applications.
The video titled "ENUMS in Every Programming Language (All You Need to Know)" provides a comprehensive overview of how enums function across various programming languages.