-
-
Notifications
You must be signed in to change notification settings - Fork 85
Description
Hello brick/math
team,
First, thank you for developing and maintaining this excellent and very useful library.
I've been using brick/math
and noticed that when working with potentially null
values, I consistently need to perform a separate null
check before calling factory methods like BigDecimal::of()
, BigInteger::of()
, etc., to prevent exceptions.
For example:
$value = get_value_that_might_be_null();
$bigDecimal = null;
if ($value !== null) {
$bigDecimal = BigDecimal::of($value);
}
// Now work with $bigDecimal, which might have remained null
Proposal
Would it be possible to add an alternative factory method or a new helper method that handles this scenario more fluently? For instance, a method like BigDecimal::ofNullable($value)
or BigDecimal::tryFrom($value)
that would simply return null
if $value
is null
, and otherwise behave like the current of()
method.
Example usage of the proposed method:
// With the proposed method
$value = get_value_that_might_be_null();
$bigDecimal = BigDecimal::ofNullable($value); // If $value is null, $bigDecimal will also be null
// Or, as another option:
// $bigDecimal = BigDecimal::tryFrom($value);
I understand that the current design philosophy might be for factory methods to always return a valid instance or throw an exception. However, I believe offering an option for more streamlined null
handling could be beneficial for many users, especially when dealing with data from external sources (like databases or APIs) which can naturally contain null
values.
If this idea is approved, I would be happy to contribute to its implementation by submitting a pull request.
Thank you very much for your time and consideration.