473,750 Members | 2,190 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 NotNullExceptio n("An uninitialised NotNull
was accessed.");
}
return value;
}
}
public NotNull(T v)
{
if (v==null)
{
throw new NotNullExceptio n("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 AddToMyCollecti on(NotNull<Widg etw)
{
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:

AddToMyCollecti on(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 2144
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 NotNullExceptio n("An uninitialised NotNull
was accessed.");
}
return value;
}
}
public NotNull(T v)
{
if (v==null)
{
throw new NotNullExceptio n("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 AddToMyCollecti on(NotNull<Widg etw)
{
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:

AddToMyCollecti on(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
ArgumentNullExc eption.

Apr 19 '07 #2
On 19 Apr, 20:09, Andy <a...@med-associates.comw rote:
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
ArgumentNullExc eption.
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 ArgumentNullExc eption("arg1");
}
if (arg2==null)
{
throw new ArgumentNullExc eption("arg2");
}
if (arg3==null)
{
throw new ArgumentNullExc eption("arg3");
}

-OR-

if (arg1==null || arg2==null || arg3==null)
{
throw new ArgumentNullExc eption("Somethi ng 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 NullReferenceEx ception, 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
9134
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 www.geog.cam.ac.uk/~mvl22 www.lucas-smith.co.uk Senior Computing Technician (Web Technician) Department of Geography, University of Cambridge (01223 3)33390
1
1661
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
6175
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 of 2 Bits. In a SQL Server database every column has a NULL-bit telling about this column it is NULL or NOT. That means that a varchar-empty NULLABLE column takes no space at all since the Nullable column defines it as NULL.
18
6677
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 hard drive file system. Over time, the more often use call new/delete or alloc/free, there will be gaps and fragments in the heap. This can lead to inefficient use of available memory, as well as cache-hit inefficiencies.
39
23821
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 *pFile; char *cFileName; cFileName=argv; pFile = fopen(cFileName,"a+"); cFileName has a valid filename ('apm.dbg'), and I have full write
64
3935
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")? - AFAIK C allows "null pointers" to be represented differently then "all bits 0". Is this correct? - AFAIK I can't `#define NULL 0x10000' since `void* p=0;' should work just like `void* p=NULL'. Is this correct?
4
1716
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 appreciated. Henry =====================
9
5135
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 UserControl (or Panel, etc). If that particular control is being edited, it IS possible to assign handlers and get events. However, when the control is used on the main form, assigning a handler to the particular control does nothing--the...
3
12304
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) length string, an empty Field, or no value at all - so exactly what is Null? The purpose of this Topic is hopefully to explain what a Null Value is, discuss some peculiarities about Nulls, show how we can detect them, and finally, how to convert...
0
9575
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9394
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9338
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8260
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4712
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4885
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3322
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.