473,385 Members | 1,712 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Preventing null propagation

Back in C++, I had a type that looked something like this (entering
from memory so this might not quite compile):

template <class T>
class NotNull
{
private:
T* value;
public:
NotNull(T* ptr)
:value(ptr)
{
if (ptr==0)
{
// Throw an exception here.
}
}
T& operator*()
{
return *value;
}
// ...
private:
// Private constructor prevents default initialisation:
NotNull() {}
};

There's a bit more to it that I've omitted there, but essentially it
behaves like a pointer except that it throws an exception if you try
to initialise it to null. This is really handy to use as a parameter
type. A method that takes these as parameters doesn't need to have a
bunch of null argument tests because it knows that it's simply not
possible for these to be null. (Sadly C++ references can end up null
through careless code, which is why this class is used rather than
references.) I've been trying to create some kind of analogue in C#,
because otherwise it seems necessary to test for null arguments in
virtually every method, since every single class reference could be
null.

For a start, I can't use a class for this because the reference to it
itself could be null. I've been looking at using a struct, and this
partially works. I can do this:

struct NotNull<T>
{
public T Value
{
get
{
if (value==null)
{
throw new NotNullException("An uninitialised NotNull
was accessed.");
}
return value;
}
}
public NotNull(T v)
{
if (v==null)
{
throw new NotNullException("A NotNull was initialised to
null.");
}
value = v;
}
private T value;
};

This looks like it will more-or-less work, but I don't like the fact
that the default constructor allows a null NotNull to exist in the
first place, and necessitates the null test in the get accessor. A
method that takes one of these as a parameter cannot be entirely
robust to bad usage unless it does the null argument testing that this
was supposed to avoid. E.g.:

void AddToMyCollection(NotNull<Widgetw)
{
AllocateSlot();
PutWidgetInSlot(w.Value);
}

Since the backup null test happens only when w.Value is accessed, an
exception could be thrown after the call to AllocateSlot() and
presumably leaves the collection in an invalid state. It's not
*likely*, because it would require the caller to do something like:

AddToMyCollection(NotNull());

....but I feel a bit uneasy that it's not as water-tight as the C++
solution was. Any suggestions? Is there a better way to do this?

Apr 19 '07 #1
2 2126
On Apr 19, 1:28 pm, Weeble <clockworksa...@gmail.comwrote:
Back in C++, I had a type that looked something like this (entering
from memory so this might not quite compile):

template <class T>
class NotNull
{
private:
T* value;
public:
NotNull(T* ptr)
:value(ptr)
{
if (ptr==0)
{
// Throw an exception here.
}
}
T& operator*()
{
return *value;
}
// ...
private:
// Private constructor prevents default initialisation:
NotNull() {}

};

There's a bit more to it that I've omitted there, but essentially it
behaves like a pointer except that it throws an exception if you try
to initialise it to null. This is really handy to use as a parameter
type. A method that takes these as parameters doesn't need to have a
bunch of null argument tests because it knows that it's simply not
possible for these to be null. (Sadly C++ references can end up null
through careless code, which is why this class is used rather than
references.) I've been trying to create some kind of analogue in C#,
because otherwise it seems necessary to test for null arguments in
virtually every method, since every single class reference could be
null.

For a start, I can't use a class for this because the reference to it
itself could be null. I've been looking at using a struct, and this
partially works. I can do this:

struct NotNull<T>
{
public T Value
{
get
{
if (value==null)
{
throw new NotNullException("An uninitialised NotNull
was accessed.");
}
return value;
}
}
public NotNull(T v)
{
if (v==null)
{
throw new NotNullException("A NotNull was initialised to
null.");
}
value = v;
}
private T value;

};

This looks like it will more-or-less work, but I don't like the fact
that the default constructor allows a null NotNull to exist in the
first place, and necessitates the null test in the get accessor. A
method that takes one of these as a parameter cannot be entirely
robust to bad usage unless it does the null argument testing that this
was supposed to avoid. E.g.:

void AddToMyCollection(NotNull<Widgetw)
{
AllocateSlot();
PutWidgetInSlot(w.Value);

}

Since the backup null test happens only when w.Value is accessed, an
exception could be thrown after the call to AllocateSlot() and
presumably leaves the collection in an invalid state. It's not
*likely*, because it would require the caller to do something like:

AddToMyCollection(NotNull());

...but I feel a bit uneasy that it's not as water-tight as the C++
solution was. Any suggestions? Is there a better way to do this?
Don't apply what you know about C++ to C#. Syntactically they are
similar, but they are different languages. Generics != C++
templates.

It looks like you're trying to do some fancy check to make sure null
is not added to your collection. Instead, simply code your method to
ensure the parameter is null, and if it is, throw an
ArgumentNullException.

Apr 19 '07 #2
On 19 Apr, 20:09, Andy <a...@med-associates.comwrote:
Don't apply what you know about C++ to C#. Syntactically they are
similar, but they are different languages. Generics != C++
templates.
That's pretty clear to me. I tried to use them for numeric tasks and
found out that there's no way to use arithmetic operators on them. I
guess they really are only much use for collections.
It looks like you're trying to do some fancy check to make sure null
is not added to your collection. Instead, simply code your method to
ensure the parameter is null, and if it is, throw an
ArgumentNullException.
Thanks, but what I'm saying is that with this approach I could easily
have to start every public method with:

if (arg1==null)
{
throw new ArgumentNullException("arg1");
}
if (arg2==null)
{
throw new ArgumentNullException("arg2");
}
if (arg3==null)
{
throw new ArgumentNullException("arg3");
}

-OR-

if (arg1==null || arg2==null || arg3==null)
{
throw new ArgumentNullException("Something was null! Um, not sure
what. Sorry.");
}

I was hoping there was a solution (like in C++) where I can make sure
these arguments can't be null even before the method is entered.
Microsoft's guidelines say never to throw NullReferenceException, but
they don't seem to provide any good way of ensuring this other than
mountains of null-checking code. :(

Apr 23 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Martin Lucas-Smith | last post by:
Can anyone provide any suggestions/URLs for best-practice approaches to preventing SQL injection? There seems to be little on the web that I can find on this. Martin Lucas-Smith ...
1
by: cliff | last post by:
My asp pages will not update rigth away on my Win2k3 server with IIS 6. I have found disabling lazy content propagation but it has not worked? Has anyone else had this problem?
3
by: A.M. de Jong | last post by:
Reading a lot about Nulls right now I still can't find a Technical reason to use it or not. For what I've understand is this: In an Ingres database a Null column has a standard extra storage...
18
by: Tron Thomas | last post by:
Given the following information about memory management in C++: ----- The c-runtime dynamic memory manager (and most other commercial memory managers) has issues with fragmentation similar to a...
39
by: ferrad | last post by:
I am trying to open a file for appending. ie. if the file exists, open it for appending, if not, create it. I am getting back a NULL pointer, and do not know why. Here is my code: FILE...
64
by: yossi.kreinin | last post by:
Hi! There is a system where 0x0 is a valid address, but 0xffffffff isn't. How can null pointers be treated by a compiler (besides the typical "solution" of still using 0x0 for "null")? -...
4
by: Henry Stockbridge | last post by:
Hi, I am attempting to build a full name of a doctor using combo box values, but all of the additional characters (commas, spaces, periods) are returned. Any help you can lend would be...
9
by: Rob | last post by:
When a custom control is used within a form, that control does not get events directly. I've run into this a couple times with both mouse and keyboard events. Ex: A custom control inherits from...
3
ADezii
by: ADezii | last post by:
Null as it relates to database development is one of life's little mysteries and a topic of total confusion for novices who venture out into the database world. A Null Value is not zero (0), a zero...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.