I like readability.
So, I came up with an extension mothod a few minutes ago for the (x =! null) type syntax, called IsNotNull. Inversly, I also created a IsNull extension method, thus
if(x == null) becomes if(x.IsNull())
and
if(x != null) becomes if(x.IsNotNull())
However, I'm worried I might be abusing extension methods. Do you think that this is bad use of Extenion methods?
As extension methods are in reality static methods of another class, they work even if the reference is null . This can be utilized to write utility methods for various cases.
Adding extension methods to any type is a great way to improve productivity and simplify code.
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
The extension method will get a null parameter. Yes, an exception will be thrown if the method tries to access the object without first testing if it is null. A guy here wrote “IsNull” and “IsNotNull” extension methods that check is the reference passed null or not.
I don't find that incredibly useful, but this:
someString.IsNullOrBlank() // Tests if it is empty after Trimming, too
someString.SafeTrim() // Avoiding Exception if someString is null
because those methods actually save you from having to do multiple checks. but replacing a single check with a method call seems useless to me.
It doesn't seem any more readable and could confuse people reading the code, wondering if there's any logic they're unaware of in those methods.
I have used a PerformIfNotNull(Func method) (as well as an overload that takes an action) which I can pass a quick lambda expression to replace the whole if block, but if you're not doing anything other than checking for null it seems like it's not providing anything useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With