* Null reference


 Null reference is every programmer's nightmare.


Null reference happens when an object is referenced without being initialized. Every programmer knows how to solve this error. They also know how to check and prevent this. But most of the times this error creeps in unexpected. In most cases this error is pretty hard to debug and fix.

As a concept null means empty - nothing - vacuum. Funny thing is programming languages allow you to pass null around. How can I transfer nothing to you. In real life passing nothing is meaningless. But there is a reason for this in programming. Each program has a logic which dictates when a value is assigned to an object. At the beginning it will be empty. After some event it will have certain value. After some other event it will have some other value and then it will be out of scope and die. 

Developer will specifically set null to a variable to indicate there is no meaningful value available at the time. Another aspect is about allocating memory. A computer has limited memory and it has to be allocated judiciously. When you declare a variable of reference type it only has a pointer to the memory. Actual memory is not allocated till it is instantiated. When you access the reference run time does not find anything and tells you, you are trying to access something which does not exist.

Why do developers end up with this error. Most of the time they do not think all the possible scenarios. Sometime scenario changes, and value can be null but not handled. In many cases writing unit tests which cover the code, prevents this error. For writing unit tests developer need to think all the possible scenario for the method. This itself is a big step in preventing the issue.

Comments

Popular posts from this blog

ChatGPT for cavemen

Greedy computing with API

Event driven architecture for micro services