473,396 Members | 1,608 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,396 software developers and data experts.

How do I check for a Null pointer in a composite reference ?


I want a simple method or function to check if at least one of the
field in a composite object is null (nothing).

For instance, if Field5 is null I would like that a function such
as

AtLeastOneReferenceNull(Class1.Field3.Property4.Fi eld5.something)

would return TRUE

where

Function AtLeastOneReferenceNull ( o as object) as boolean
' how ???
end function

or similar.

How can I do that (clearly without a slow try/catch) ?

-P

Apr 10 '07 #1
9 1507
On Apr 10, 8:58 am, "pamela fluente" <pamelaflue...@libero.itwrote:
I want a simple method or function to check if at least one of the
field in a composite object is null (nothing).

For instance, if Field5 is null I would like that a function such
as

AtLeastOneReferenceNull(Class1.Field3.Property4.Fi eld5.something)

would return TRUE
You can't do that. By the time the method is called, the expression
will have been evaluated. You need:

if (Class1 == null ||
Class1.Field3 == null ||
Class1.Field3.Property4 == null ||
Class1.Field3.Property4.Field5 == null ||
Class1.Field3.Property4.Field5.something == null)
{
...
}

Do you often use expressions with that many levels of indirection
though? In the rare cases where I have several layers of indirection
like that, it's usually an error for any of the "early" levels to be
null anyway.

Jon

Apr 10 '07 #2
No easy way, without checking Class1 == null || Class1.Field3 == null
|| {etc}

Note that try/catch is not as slow as people often think... the
debugger might be fooling you here; but it isn't an elegant solution.

Another option (far from perfect, and only suitable for properties)
might be something using the component model... i.e.
SomeFunc(class1, "Field3.Property4.Field5")
with
bool SomeFunc(object component, string path) {
if(component==null) return true;
foreach(string section in path.Split('.')) {
component = TypeDescriptor.GetProperties(component)
[section].GetValue(component);
if(component == null) return true;
}
return false;
}

Direct reflection might work for fields, but I can't bring myself to
ever recommend coding against fields directly ;-p

Just a thought...

Marc

Apr 10 '07 #3
Just to clarify; "SomeFunc" as described would be noticeably slower
than either other option (try-catch / pyramid testing).
Apr 10 '07 #4
Thanks you Jon , Thanks Marc,

I will be working on your insightful suggestions.

Actually I have often several levels of indirection in complex
programs and I would like
the possibility to check the whole thing is a simple easy way instead
of using all those ugly IF/andalso/orelse .

I was suspecting that perhaps using reflection something could be
done.
But actually reflections seems to work just on actual instances...

-P
Apr 10 '07 #5
On 10 Apr, 10:17, "Marc Gravell" <marc.grav...@gmail.comwrote:
Just to clarify; "SomeFunc" as described would be noticeably slower
than either other option (try-catch / pyramid testing).
Are you sure about that? I would feel that the slowest is Try/catch.

In my experience Try/catch is the most terrible slodownthing to
use :-)

I never use it unless there is an actual error to catch ...

I use often reflection (when restoring object with nonserialized
fields) and does not seem to be so bad.
-P

Apr 10 '07 #6
On Apr 10, 10:19 am, "pamela fluente" <pamelaflue...@libero.itwrote:
Just to clarify; "SomeFunc" as described would be noticeably slower
than either other option (try-catch / pyramid testing).

Are you sure about that? I would feel that the slowest is Try/catch.

In my experience Try/catch is the most terrible slodownthing to
use :-)
In the debugger, or in a "normal" environment?
I never use it unless there is an actual error to catch ...

I use often reflection (when restoring object with nonserialized
fields) and does not seem to be so bad.
Reflection is fairly slow. I wouldn't like to guess which would be
faster, although it will clearly depend on what proportion of the time
an exception is thrown. If you're particularly interested in the
performance of this part of the code, it would be worth benchmarking/
profiling.

Neither is particularly clean - reflection would require the
expression to be duplicated in some form (eg putting it in a string
literal) and catching an exception in this case just really isn't
nice. I would prefer to "design it away" in some form or other, so
that you have more control/understanding over when it's reasonable for
any particular part of the expression to be null.

Jon

Apr 10 '07 #7
Pretty much, yes; but it depends on how your code is structured. If
this isn't in a tight loop, then use which ever approach you like: you
will most likely never see an issue, so don't do premature
optimisation. But for certain the pyramid testing (see Jon's example)
is going to be the fastest.

Jon talks about quantified cost of exceptions here:
http://www.yoda.arachsys.com/csharp/exceptions.html
(with follow-up: http://www.yoda.arachsys.com/csharp/exceptions2.html)

This at least gives you some figures. As for reflection; following are
timings (ms) taken from 250k get/set pairs against a simple class
(actually it implements INotifyPropertyChanged for my purposes, but
there are no subscribers) with a checksum to ensure no compiler
optimisations; this shows the absolute cost of reflection (don't trust
the 0; obviously this is too tight a scale for just DateTime, but I'm
not going to bother changing it). For comparison, I have also included
some stats for my own "property-bag" implementation, which stores data
in a dictionary rather than fields and provides custom
PropertyDescriptor (via ICustomTypeDescriptor)... this improves
PropertyDescriptor (component-model) access, but at the cost of
levelling direct access... PropertyInfo (reflection) access is still
very slow though, but the aim here was to improve UI-binding access;
job done I believe ;-p

Simple class [250000]
Direct read 0
Direct write 40.0576
PropDesc read 5618.0784
PropDesc write 6669.5904
PropInfo read 4546.5376
PropInfo write 5688.1792

PropertyBag class [250000]
Direct read 260.3744
Direct write 400.576
PropDesc read 290.4176
PropDesc write 420.6048
PropInfo read 5457.848
PropInfo write 6899.9216

Marc
Apr 10 '07 #8

Thank you.
>
Jon talks about quantified cost of exceptions here:http://www.yoda.arachsys.com/csharp/exceptions.html
(with follow-up:http://www.yoda.arachsys.com/csharp/exceptions2.html)
Hmm interesting reading.
>From my point of view should, however, be usually not so important
whether the try/catch takes a lot or little time, because personally I
would never use
to test anything. The times I use it is because there is a real
possible error you want to catch and then the execution
time is the last concern.

It is true that I found some very *rare* tasks for which I could not
find a substitute for try catch (for instance
determining if a port is being used by a program when opening a
socket), but hopefully it is used outside of tight loops.

These occurrences seems to me more a result of not having the
functionality directly within the language instead of a real
necessity.
Like for instance some people used a try/catch instead of isnumeric()
to determine if a field is a number....

-P

Apr 10 '07 #9
PS
"pamela fluente" <pa***********@libero.itwrote in message
news:11**********************@o5g2000hsb.googlegro ups.com...
>
I want a simple method or function to check if at least one of the
field in a composite object is null (nothing).

For instance, if Field5 is null I would like that a function such
as

AtLeastOneReferenceNull(Class1.Field3.Property4.Fi eld5.something)

would return TRUE

where

Function AtLeastOneReferenceNull ( o as object) as boolean
' how ???
end function

or similar.

How can I do that (clearly without a slow try/catch) ?

-P
You might consider some design changes. If you pass primitives to a method
then the method is much easier to test as it involves less setup. Also if
you find yourself having to make a lot of null testing then you can
encapsulate the behavior of what to do with a null reference into a Null
Object.

PS
Apr 10 '07 #10

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

Similar topics

102
by: junky_fellow | last post by:
Can 0x0 be a valid virtual address in the address space of an application ? If it is valid, then the location pointed by a NULL pointer is also valid and application should not receive "SIGSEGV"...
11
by: zhong | last post by:
Error Message: Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention...
35
by: fcvcnet | last post by:
Hi, This is c code , but the question is same to c++ £¨new/delete£©. char* p = malloc(10); strcpy(p, "hello"); printf("%s\n", p); free(p); // free just add p to the free list of memory, and...
27
by: David W | last post by:
I'm almost tearing my hair out. A colleague claimed that a null reference can exist, like this: void f( int& p ) { printf( "%d\n", p ); } int main (int argc, char *argv) {
9
by: pamela fluente | last post by:
I want a simple method or function to check if at least one of the field in a composite object is null (nothing). For instance, if Field5 is null I would like that a function such as ...
30
by: Jess | last post by:
Hello, I tried a program as follows: include<iostream> using namespace std; class A{ public:
76
by: valentin tihomirov | last post by:
As explained in "Using pointers vs. references" http://groups.google.ee/group/borland.public.delphi.objectpascal/browse_thread/thread/683c30f161fc1e9c/ab294c7b02e8faca#ab294c7b02e8faca , the...
14
by: Mark | last post by:
Hi, I would like to check if my object has been deleted or not, but my program keeps crashing. Here's the simplified code (in infinite loop) delete tetromino; //if(tetromino==NULL)...
2
by: NotGuru | last post by:
I was writing some C extensions for Python and use PyTupleType_Check extensively. I found that all the PySomeType_Check macros directly delegate the job to PyObject_TypeCheck(op, &PyType_Type). The...
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: 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
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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
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...
0
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...

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.