Originally posted in Medium
Every developer would have come through the below scenario frequently while writing business logic. The examples here are written is from C, but it applies to any language that you use.
Let’s imagine you query something from the database and you need to find the studentId of the first one or maybe filter the student using a name
var students = _studentRepository.GetAllStudents();
var studentId = students.FirstOrDefault().StudentId;
or
var studentName = students.Select(student=> student.Name.Equals(“John”,StringComparison.OrdinalIgnoreCase);
Do you notice any issue in the above code? No? Even I was not aware that there is a PosibleNullReference
here
**FirstOrDefault* returns the default value of a type if no item matches the predicate. For reference types that is null. That is the reason for this exception.*
Photo by Max Nelson on Unsplash
How do we resolve this?
Instead of directly finding the name using FirstOrDefault(), you can change it like this and the NullReference warning is gone.
Pro Tips for readable code
Imagine you find something from the database or get something from an API, you need to check if its Null / NotNull / Empty / EmptyOrNotNull etc..
We were doing this earlier but most often we forget to check this before proceeding with the business logic and the ton of if(something!=null)
loops get piled up.
Resolution
We wrote an extension method like this
public static bool IsNotNull(this object obj){
return obj != null;
}
So whenever we do an api call or retrieve something from the database, all we need to do is
var students = _studentRepository.GetAllStudents();
if(students.IsNotNull()){
//do something
}
It is more readable as well as it will be unforgettable in the future since our minds will automatically remember the small things that are readable.
The power of the extension method is it should be generic and not tied to one particular project or area. Write it in a common area so that it is shareable across projects and benefits you.
Conclusion
Write more extension methods for handling small business logic like checking for empty/null/
trimming the string etc. It makes the code base more readable and maintainable.
Thanks for reading. Stay tuned for more blogs.
Top comments (1)
Don't use
obj != null
- this approach might yield unexpected results when obj is an instance of a class that overloaded the==
and!=
operator.Check out my post here on how to properly test for null / not null:
The perfect non-null test
Zohar Peled ・ Nov 13 ・ 2 min read