The subtle art of refactoring 1

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;


    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](https://unsplash.com/@maxcodes?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/c%23?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)Photo by [Max Nelson](https://unsplash.com/@maxcodes?utmsource=unsplash&utmmedium=referral&utmcontent=creditCopyText) 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.


We wrote an extension method like this

    public static bool IsNotNull(this object obj){

    return obj != null;

If you are using C# > 7.0 you can write the same code like this

    public static bool IsNull(this object obj){
        return obj is null;

So whenever we do an api call or retrieve something from the database, all we need to do is

    var students = _studentRepository.GetAllStudents();


    //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.


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.



Full Stack Developer

Read More