Welcome back, everyone! It feels good to be motivated and share my knowledge in the C# corner community. Thank you, everyone, for your valuable comments, and I will share my knowledge continuously by writing articles and blogs hereafter. So here in this article, we will explore creating a NULL object for solving a problem by identifying the NULL check code smell. Basically, there are some ways by which the NULL code smell can be ignored; likewise, let’s take an overview of implementing the NULL object. And of course we can also take a look at the code after removing the code smell. What we will do is just we need to check the indicator (Checking for NULL)
we can also take a small dive into the following properties.
They are:
-
Identifying the NULL Check Code Smell
-
When to ignore the NULL Check Code Smell
-
Creating a NULL Object for rectifying the problem and implementation of the created NULL Object.
-
And finally, the overview of the code structure after removing the code smell
Prerequisites
-
Angular CLI
-
Visual Studio Code
Step 1
First, let’s create a new Angular application by using the following command
ng new CheckCodeSmell
Open the code in Visual Studio code. This code is a sample code designed for an E-commerce-site application.
Here we have used a function which will determine the discount to be applied for the order. If the user is checking in as a customer the object will be NULL. By looking at this method the NULL check seems the reasonable way to implement the necessary functionality.
Now let’s again get back to another method from the same class.
Let’s take a look -- we can see the same thing going on. We must know if the user is checking out as a guest or not so that we can see the the problem. The NULL checks are littered around the code. We can assume that the logic is common and we need to check if the customer is null for the order or not.
So what we can do is fix this by applying NULL object. The NULL objects are a kind of special class that will replace a null Value in our code so that the code will get simplified.
Let’s create a NULLCustomer class in component.ts file and we can see this is our NULL Object . We can see it has two functions.
By following from the previous step we need to create NULLCustomer and use it instead of setting the customer to NULL and we can do the NULL check once.
Let’s keep on to the next step. We have to fix the getDiscount and processOrder methods because the NULL objects will implement the methods.
In fact, we can see that getDiscount has become so simple and we may consider dropping it altogether. This is the power of the NULL object that is used to solve the NULL Check Code smell from my point of view. That’s it -- I hope this article will be useful for you and please do comment below if you have any queries and thanks for reading.