References in D

Regan Heath regan at netmail.co.nz
Fri Oct 5 05:31:05 PDT 2012


On Fri, 05 Oct 2012 05:19:13 +0100, Alex Burton  
<alexibureplacewithzero at gmail.com> wrote:

> On Saturday, 15 September 2012 at 17:51:39 UTC, Jonathan M Davis wrote:
>> On Saturday, September 15, 2012 19:35:44 Alex Rønne Petersen wrote:
>>> Out of curiosity: Why? How often does your code actually accept null as
>>> a valid state of a class reference?
>>
>> I have no idea. I know that it's a non-negligible amount of the time,  
>> though
>> it's certainly true that they normally have values. But null is how you
>> indicate that a reference has no value. The same goes for arrays and  
>> pointers.
>> Sometimes it's useful to have null and sometimes it's useful to know  
>> that a
>> value can't be null. I confess though that I find it very surprising  
>> how much
>> some people push for non-nullable references, since I've never really  
>> found
>> null to be a problem. Sure, once in a while, you get a null  
>> pointer/reference
>> and something blows up, but that's very rare in my experience, so I  
>> can't help
>> but think that people who hit issues with null pointers on a regular  
>> basis are
>> doing something wrong.
>>
>> - Jonathan M Davis
>
> In my experience this sort of attutide is not workable in projects with  
> more than one developer.

Almost all my work is on projects with multiple developers in C/C++ and  
making extensive use of null.

> It all works OK if everyone knows the 'rules' about when to check for  
> null and when not to.

As every good C/C++ developer does.  The rule is simple, always check for  
nulls on input passed to "public" functions/methods.  What you do with  
internal protected and private functions and methods is up to you (I use  
assert).

> Telling team members that find bugs caused by your null references that  
> they are doing it wrong and next time should check for null is a poor  
> substitute for having the language define the rules.

Having language defined rules is a nice added /bonus/ it doesn't let you  
off the hook when it comes to being "null safe" in your code.

> A defensive attitude of checking for null everywhere like I have seen in  
> many C++ projects makes the code ugly.

That's a matter of opinion.  I like to see null checks at the top of a  
function or method, it makes it far more likely to be safe and it means I  
can ignore the possibility of null from then on - making the code much  
cleaner.

R

-- 
Using Opera's revolutionary email client: http://www.opera.com/mail/


More information about the Digitalmars-d mailing list