Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>OK, I now this has been technically answered a million times but I have to say this because this is an un-ending discussion with Java programmers.</p> <p>Sorry but I disagree will almost all of above. The reason we have to be testing for null in Java is because must Java programmers don’t know how to handle memory. </p> <p>I say this because I have a long experience programming in C++ and we don’t do this. In other words, you don’t need to. And note that, in Java, if you hit a dangling pointer you get a normal exception; in C++ this exception normally is not caught and terminates the program.</p> <p>Don’t want to do this? Then follow some simple rules ala C/C++.</p> <p>Don’t instantiate things so easily, <em>think</em> that every "new" can get you in lots of trouble and FOLLOW these simple rules.</p> <p>A class shall access memory in only 3 ways -></p> <ol> <li><p>It can "HAVE" class members, and they will follow these rules:</p> <ol> <li>ALL "HAS" members are created "new" in the constructor.</li> <li>You will close /de allocate in destructor or equivalent close() function in Java for that same class and in NO other.</li> </ol></li> </ol> <p>This means that you need to have in mind (just like Java does) who is the owner or parent of each resource and respect that ownership. An object is only deleted by the class who created it. Also -></p> <ol start="2"> <li><p>Some members will be "USED" but not own or "HAVE". This are "OWN" in another class and passed as arguments to the constructor. Since these are owned by another class, we will NEVER delete or close this, only the parent can.</p></li> <li><p>A method in a class can also instantiate local objects for internal use which will NEVER pass out side of the class, or they should have been normal "has" objects.</p></li> </ol> <p>Finally for all this to work, you need to have a disciplined design with classes in hierarchy form and making no cycles.</p> <p>Under this design, AND following the above rules, there is no way that a child class in a hierarchy design will ever access a pointer which was destroyed, because that means that a parent was destroyed before a child, which the hierarchical acyclic design will not allow it.</p> <p>Finally, also remember when starting your system you should build from top to bottom of the hierarchy and destroy bottom to top. You will never have a null pointer anywhere, or someone is violating the rules.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload