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

String Init best practice

Sorry if this appears twice. Our mailserver died with that virus.

I see advice on this newsgroup about initializing strings to null. I
believe it is more prudent code to initialize a string variable to
string.empty instead of null. this leads to more robust code because a
programmer may try to touch this variable without testing it leading to a
null exception. Consider:

string str = null;
[snip]
str.length + 1;// blows here

string str = string.empty
[snip]
str.length + 1;//safe

Yes I know this is wide open for debate, i'm not looking for a fight
either.
I'm simply looking to test my theory to see if it holds up hence the post.
I
think programmers should always be on the defensive. ???

--
Regards,
Alvin Bruney [ASP.NET MVP]
Got tidbits? Get it here...
http://tinyurl.com/3he3b

Nov 15 '05 #1
3 4117
In theory, I like the null initialization better b/c strings are immutable.
On the other hand, if someone happens to reference length like you show,
then an exception is thrown. Exceptions aren't cheap, so this may offset any
efficiency realized by leaving the string null and only changing it once
when you need it.

To get around this problem, I try as much as possible, to hold off
declaration until I"m going to set it to an actual value. Occassionally
this can be a pain within try catch blocks for example, but as a general
guideline , it works pretty well.

"Alvin Bruney [MVP]" <vapor at steaming post office> wrote in message
news:O4**************@TK2MSFTNGP10.phx.gbl...
Sorry if this appears twice. Our mailserver died with that virus.

I see advice on this newsgroup about initializing strings to null. I
believe it is more prudent code to initialize a string variable to
string.empty instead of null. this leads to more robust code because a
programmer may try to touch this variable without testing it leading to a
null exception. Consider:

string str = null;
[snip]
str.length + 1;// blows here

string str = string.empty
[snip]
str.length + 1;//safe

Yes I know this is wide open for debate, i'm not looking for a fight
either.
I'm simply looking to test my theory to see if it holds up hence the post. I
think programmers should always be on the defensive. ???

--
Regards,
Alvin Bruney [ASP.NET MVP]
Got tidbits? Get it here...
http://tinyurl.com/3he3b


Nov 15 '05 #2
Alvin,
I see advice on this newsgroup about initializing strings to null. I
believe it is more prudent code to initialize a string variable to
string.empty instead of null.
Personally I avoid to initialize it at all until I have something
useful to put in it if at all possible. That way the compiler will
tell me that the variable hasn't been initialized if I try to use it
too early. When it isn't possible to avoid, I usually pick null as the
initial value.

this leads to more robust code because a
programmer may try to touch this variable without testing it leading to a
null exception.


If the programmer is playing with things that haven't been properly
initialized, I'd consider it a bug. Getting an exception for that is a
good thing, sinec it hopefully helps you locate and fix the issue.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 15 '05 #3
<"Alvin Bruney [MVP]" <vapor at steaming post office>> wrote:
Sorry if this appears twice. Our mailserver died with that virus.

I see advice on this newsgroup about initializing strings to null. I
believe it is more prudent code to initialize a string variable to
string.empty instead of null. this leads to more robust code because a
programmer may try to touch this variable without testing it leading to a
null exception. Consider:

string str = null;
[snip]
str.length + 1;// blows here

string str = string.empty
[snip]
str.length + 1;//safe

Yes I know this is wide open for debate, i'm not looking for a fight
either. I'm simply looking to test my theory to see if it holds up hence
the post. I think programmers should always be on the defensive. ???


It depends. If your string variable isn't meant to be used before it's
been assigned another value, then setting it to null is actually better
- precisely because it means you'll get an exception if you try to use
it, and so are likely to fix the bug earlier. Using an empty string
instead, your code will continue but with dodgy data - which in my view
is a bad thing.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4

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

Similar topics

0
by: Doug Farrell | last post by:
Hi everyone, I'm trying to build a program to interface to a SOAP/XML interface provided by one of our vendors. This interface is built with MS SOAP Toolkit 3.0, so I'm guessig they are running...
10
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is...
136
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their...
6
by: Paul | last post by:
Hello, Consider this case: Init(params) does some initialization and there is a function Connect(params). The system starts and is idle until some one calls Connect, as soon as first...
7
by: puzzlecracker | last post by:
Why would this work? - and it does! any thoughts? #include<stdio.h> void init(char **str){ *str="Awesome"; } main(){
0
by: Alvin Bruney [MVP] | last post by:
I believe it is more prudent code to initialize a string variable to string.empty instead of null. this leads to more robust code because a programmer may try to touch this variable without testing...
7
by: dragoncoder | last post by:
Hello experts, I have the following code me. =cat mystring.h #include<iostream> using namespace std; class mystring {
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
2
by: bevis | last post by:
I'm new to sql server and mysql but this seems like it should be a pretty straight forward jdbc connection. But I have spent almost 2 days just trying to get a jdbc connection. Please help if you...
15
by: MartinRinehart | last post by:
The FAQ shows a mod to String.prototype adding trim, trimRight and trimLeft. Flanagan states, "There is a strong argument against extending built- in types with your own methods; if you do so,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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
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.