DEV Community

Cover image for Result<T, E> type in PHP
Harutyun Mardirossian
Harutyun Mardirossian

Posted on

Result<T, E> type in PHP

I've always been a huge fan of both Rust and GoLang. Their approaches to programming, particularly in error handling, have resonated with me throughout my career. After dedicating over four years to GoLang development, I recently transitioned to a project where I'm refactoring legacy PHP code into a newer, more robust version. This shift has been both exciting and challenging, especially when it comes to adapting to PHP's traditional error-handling mechanisms.

Having grown accustomed to Go's "errors as values" concept, switching back to languages that rely on the conventional try-catch paradigm has been a significant adjustment. The idea of expecting the unexpected through exceptions feels counterintuitive. In GoLang, errors are treated as explicit return values that functions can produce, requiring developers to handle them directly. This explicitness promotes clarity and encourages thorough error checking at every function call.

In contrast, exception-based error handling can sometimes lead to overlooked edge cases. It's possible to call a function that throws an exception and only discover the oversight in production when the application crashes a scenario every developer aims to avoid.

To address this challenge, I decided to introduce a Rust-inspired Result type in my PHP controller methods. Rust's approach to error handling, much like Go's, emphasizes returning results that explicitly indicate success or failure. By implementing a Result type in PHP, I aimed to bring this level of explicitness and safety to my current project.

php

For instance, in the user registration endpoint, I wrapped Laravel’s validator to return a Result containing either a valid value or an error. This modification allows me to explicitly handle validation failures, enabling the application to return a 422 Unprocessable Entity status code when appropriate. Not only does this make the error handling more transparent, but it also improves the API's reliability by ensuring that all potential errors are accounted for and managed properly.

Here are some key benefits I've observed from this approach:

  • Enhanced Readability: By handling errors explicitly, the code becomes more readable and maintainable. Developers can see at a glance where errors might occur and how they're managed.
  • Improved Reliability: Explicit error handling reduces the risk of uncaught exceptions causing unexpected crashes in production environments.
  • Consistency Across Languages: Adopting a Result type in PHP brings the language's error-handling closer to that of Rust and GoLang, which can be beneficial for teams working across multiple languages.

To provide a clearer picture of this methodology, I've prepared three code examples to highlight the contrasts and similarities between the languages and showcase how adopting certain patterns can lead to more robust and maintainable code.

Golang

go

Rust

rust

I'm curious to hear your thoughts on this approach. Do you think incorporating concepts from one language into another is beneficial in the long run?

Feel free to share your experiences or ask any questions.

Top comments (2)

Collapse
 
c0d3rh3art profile image
c0d3rh3art

Thanks for the post, I was literally thinking about this Idea after touching golang and was interested in your exploration of this idea. Pros of this approach - explicit handling of all possible errors, this makes programmers think of it at least for a bit and something about it. Though good programmers should do it anyway. The cons - code bloat. Imagine there might be 5 or even more possible errors, and a chain of method calls - this would produce pretty long switch/match expressions in multiple places. This is not bad per se, just a tradeoff. With exceptions you could hide under the carpet all cases that you do not foresee or don't bother to care and simply handle all other cases with general catch{Throwable}. Another point is that there could be an exception thrown in your switch/match if you would try to do something more sophisticated than checking length and call some custom logic. I think php relies on exceptions heavily and passed point of no return, to me using this approach in php is something similar to using raise / recover in go. Not impossible but somewhat strange. Thanks again for the post!

Collapse
 
crusty0gphr profile image
Harutyun Mardirossian

Thanks for the thoughtful comment! I totally agree that exceptions still have their place, and in some cases, they’re inevitable. My focus here is more on minimizing the need for exceptions by handling errors explicitly wherever possible. For cases where exceptions might still be thrown, I’m considering wrapping those exceptions — catching them and returning an error instead. This way, we keep the flow simple and predictable, which is a key part of my approach.

Regarding the potential for switch/match bloat, I’m aiming to follow Go’s philosophy to achieve simplicity. In Go, any error halts the flow, and I’m applying that same principle in PHP. Rather than matching every possible error, I’m sticking to essential cases only, stopping the program flow if Result->error !== null. This keeps the code manageable and avoids unnecessary branching, allowing the program to respond only when errors arise without clutter.

Thanks again for sharing your insights!