473,395 Members | 1,368 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.

Needlessly Safe Code

I would appreciate your comments on the following two alternatives of a
given method. This isn't a real method, as I'm not concerned about the "real
work" it could be doing, but would like to instead focus our attention on
the [extensive checking] vs [zero checking] implemented in these two
methods.

Safe code that makes few assumptions about its runtime conditions is good,
but what about "needlessly safe"?

Is Version 1 below "needlessly safe" in your opinion?

------------------------------------------------
Version 1 - Extensive "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
if (Directory.Exists(Path.GetDirectoryName(pathToTheF ile)))
{
if (File.Exists(pathToTheFile))
{
// Do something with the file here... open it, whatever...
}
else
{
throw new System.IO.FileNotFoundException("The file was not
found.");
}
}
else
{
throw new System.IO.DirectoryNotFoundException("The directory was not
found.");
}
}

------------------------------------------------
Version 2 - No "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
// Just try to something with the file here - right "off the bat"... open
it, whatever...
// If it cannot be located, then system.IO will throw an exception
// ... therefore I don't need to do all the checking for file/directory
existance
}

Please note that my question isn't about working with files. The code above
just serves to provide an example of "safe coding" vs code that makes
assumptions.

Thanks in advance!

Jun 27 '08 #1
18 1283
On Apr 25, 2:52 pm, "Verde" <A...@B.comwrote:
I would appreciate your comments on the following two alternatives of a
given method. This isn't a real method, as I'm not concerned about the "real
work" it could be doing, but would like to instead focus our attention on
the [extensive checking] vs [zero checking] implemented in these two
methods.

Safe code that makes few assumptions about its runtime conditions is good,
but what about "needlessly safe"?

Is Version 1 below "needlessly safe" in your opinion?

------------------------------------------------
Version 1 - Extensive "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
if (Directory.Exists(Path.GetDirectoryName(pathToTheF ile)))
{
if (File.Exists(pathToTheFile))
{
// Do something with the file here... open it, whatever...
}
else
{
throw new System.IO.FileNotFoundException("The file was not
found.");
}
}
else
{
throw new System.IO.DirectoryNotFoundException("The directory was not
found.");
}

}

------------------------------------------------
Version 2 - No "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
// Just try to something with the file here - right "off the bat"... open
it, whatever...
// If it cannot be located, then system.IO will throw an exception
// ... therefore I don't need to do all the checking for file/directory
existance

}

Please note that my question isn't about working with files. The code above
just serves to provide an example of "safe coding" vs code that makes
assumptions.

Thanks in advance!
Looking at your example, I dont think Version#1 is any more safer than
Version#2. They are both doing the same thing; Version #1 has
redundant code and does not add any additional value than Version #2.
In a broader sense the question is whether to be proactive or
reactive. I think it varies from case to case. For e.g. if i have to
convert 1000 strings to double in a loop and if the 1000 strings are
from a random file, I would prefer using Double.TryParse() to check if
it is a valid double and then parse it. If it were something like the
above example, I would catch the exception.
Jun 27 '08 #2
Verde wrote:
I would appreciate your comments on the following two alternatives of a
given method. This isn't a real method, as I'm not concerned about the "real
work" it could be doing, but would like to instead focus our attention on
the [extensive checking] vs [zero checking] implemented in these two
methods.
[...]

Verde, if I take your example literally there is no difference at all
(except maybe the exact text in the strings). But if the else branches
contained anything else than a throw it would be an entirely different
matter.

Please note that version #1 uses the same strategy as #2 when it comes
to, for example, insufficient rights for the file. Or the unlikely
scenario in which the file is deleted between the Exists check and the
Open.

So for those reasons I would prefer version #1, and maybe put in a
comment like "error checking by the FileStream class"

-HH-
Jun 27 '08 #3
On Apr 25, 2:52 pm, "Verde" <A...@B.comwrote:
I would appreciate your comments on the following two alternatives of a
given method. This isn't a real method, as I'm not concerned about the "real
work" it could be doing, but would like to instead focus our attention on
the [extensive checking] vs [zero checking] implemented in these two
methods.

Safe code that makes few assumptions about its runtime conditions is good,
but what about "needlessly safe"?

Is Version 1 below "needlessly safe" in your opinion?

------------------------------------------------
Version 1 - Extensive "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
if (Directory.Exists(Path.GetDirectoryName(pathToTheF ile)))
{
if (File.Exists(pathToTheFile))
{
// Do something with the file here... open it, whatever...
}
else
{
throw new System.IO.FileNotFoundException("The file was not
found.");
}
}
else
{
throw new System.IO.DirectoryNotFoundException("The directory was not
found.");
}

}

------------------------------------------------
Version 2 - No "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
// Just try to something with the file here - right "off the bat"... open
it, whatever...
// If it cannot be located, then system.IO will throw an exception
// ... therefore I don't need to do all the checking for file/directory
existance

}

Please note that my question isn't about working with files. The code above
just serves to provide an example of "safe coding" vs code that makes
assumptions.

Thanks in advance!
I *THINK* exceptions cause overhead so its better to do the checks..
Jun 27 '08 #4
On Apr 25, 3:27 pm, parez <psaw...@gmail.comwrote:
On Apr 25, 2:52 pm, "Verde" <A...@B.comwrote:
I would appreciate your comments on the following two alternatives of a
given method. This isn't a real method, as I'm not concerned about the "real
work" it could be doing, but would like to instead focus our attention on
the [extensive checking] vs [zero checking] implemented in these two
methods.
Safe code that makes few assumptions about its runtime conditions is good,
but what about "needlessly safe"?
Is Version 1 below "needlessly safe" in your opinion?
------------------------------------------------
Version 1 - Extensive "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
if (Directory.Exists(Path.GetDirectoryName(pathToTheF ile)))
{
if (File.Exists(pathToTheFile))
{
// Do something with the file here... open it, whatever...
}
else
{
throw new System.IO.FileNotFoundException("The file was not
found.");
}
}
else
{
throw new System.IO.DirectoryNotFoundException("The directory was not
found.");
}
}
------------------------------------------------
Version 2 - No "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
// Just try to something with the file here - right "off the bat"... open
it, whatever...
// If it cannot be located, then system.IO will throw an exception
// ... therefore I don't need to do all the checking for file/directory
existance
}
Please note that my question isn't about working with files. The code above
just serves to provide an example of "safe coding" vs code that makes
assumptions.
Thanks in advance!

I *THINK* exceptions cause overhead so its better to do the checks..
I think i thought right..
private void FileTest1(string file)
{

try
{
FileStream fs = File.Open(file, FileMode.Open);
}
catch (Exception)
{
}
}
private void FileTest2(string file)
{

try
{
if (!File.Exists(file))
throw new FileNotFoundException("file not found",
file);
}
catch (Exception)
{
}
}

private void RunFileTest()
{

int times = 5000;

string file="C:\\some.txt";

Stopwatch sw1 = new Stopwatch();

sw1.Start();
for (int i = 0; i < times; i++)
{
FileTest1(file);
}
sw1.Stop();

Stopwatch sw2 = new Stopwatch();

sw2.Start();
for (int i = 0; i < times; i++)
{
FileTest2(file);
}
sw2.Stop();
// MessageBox.Show(string.Format("Test1 Result {0} \nTest2
Result {1}", sw1.Elapsed.TotalSeconds, sw2.Elapsed.TotalSeconds));
label6.Text = string.Format("Test1 Result {0} \nTest2
Result {1}", sw1.Elapsed.TotalSeconds, sw2.Elapsed.TotalSeconds);
}

Output
label6.Text "Test1 Result 27.383811 \nTest2 Result 25.5081203"
string
Jun 27 '08 #5
Throwing/Catching is EXTREMELY costly. Do the checks, but if you're
on a timetable there is a limit to the amount of validation you can do
before you just need to put in the try/catch block and call it done.
I know we use try/catch on every entry point (user event) since those
will cause the app to explode.
Jun 27 '08 #6
"parez" <ps*****@gmail.comwrote in message
news:b8**********************************@m36g2000 hse.googlegroups.com...
On Apr 25, 2:52 pm, "Verde" <A...@B.comwrote:
>I would appreciate your comments on the following two alternatives of a
given method. This isn't a real method, as I'm not concerned about the
"real
work" it could be doing, but would like to instead focus our attention on
the [extensive checking] vs [zero checking] implemented in these two
methods.

Safe code that makes few assumptions about its runtime conditions is
good,
but what about "needlessly safe"?

Is Version 1 below "needlessly safe" in your opinion?

------------------------------------------------
Version 1 - Extensive "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
if (Directory.Exists(Path.GetDirectoryName(pathToTheF ile)))
{
if (File.Exists(pathToTheFile))
{
// Do something with the file here... open it, whatever...
}
else
{
throw new System.IO.FileNotFoundException("The file was not
found.");
}
}
else
{
throw new System.IO.DirectoryNotFoundException("The directory was
not
found.");
}

}

------------------------------------------------
Version 2 - No "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
// Just try to something with the file here - right "off the bat"...
open
it, whatever...
// If it cannot be located, then system.IO will throw an exception
// ... therefore I don't need to do all the checking for file/directory
existance

}

Please note that my question isn't about working with files. The code
above
just serves to provide an example of "safe coding" vs code that makes
assumptions.

Thanks in advance!

I *THINK* exceptions cause overhead so its better to do the checks..

Doing the test makes absolutely no sense (please read Jeroen's answer),
there is no guarantee whatsoever that you will be able to open the file
after the test, the file may no longer exist, or may not be accessible due
to security or sharability constraints.

Willy.

Jun 27 '08 #7
"parez" <ps*****@gmail.comwrote in message
news:0d**********************************@a1g2000h sb.googlegroups.com...
On Apr 25, 3:27 pm, parez <psaw...@gmail.comwrote:
>On Apr 25, 2:52 pm, "Verde" <A...@B.comwrote:
I would appreciate your comments on the following two alternatives of a
given method. This isn't a real method, as I'm not concerned about the
"real
work" it could be doing, but would like to instead focus our attention
on
the [extensive checking] vs [zero checking] implemented in these two
methods.
Safe code that makes few assumptions about its runtime conditions is
good,
but what about "needlessly safe"?
Is Version 1 below "needlessly safe" in your opinion?
------------------------------------------------
Version 1 - Extensive "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
if (Directory.Exists(Path.GetDirectoryName(pathToTheF ile)))
{
if (File.Exists(pathToTheFile))
{
// Do something with the file here... open it, whatever...
}
else
{
throw new System.IO.FileNotFoundException("The file was not
found.");
}
}
else
{
throw new System.IO.DirectoryNotFoundException("The directory was
not
found.");
}
}
------------------------------------------------
Version 2 - No "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
// Just try to something with the file here - right "off the bat"...
open
it, whatever...
// If it cannot be located, then system.IO will throw an exception
// ... therefore I don't need to do all the checking for
file/directory
existance
}
Please note that my question isn't about working with files. The code
above
just serves to provide an example of "safe coding" vs code that makes
assumptions.
Thanks in advance!

I *THINK* exceptions cause overhead so its better to do the checks..

I think i thought right..
private void FileTest1(string file)
{

try
{
FileStream fs = File.Open(file, FileMode.Open);
}
catch (Exception)
{
}
}
private void FileTest2(string file)
{

try
{
if (!File.Exists(file))
throw new FileNotFoundException("file not found",
file);
}
catch (Exception)
{
}
}

private void RunFileTest()
{

int times = 5000;

string file="C:\\some.txt";

Stopwatch sw1 = new Stopwatch();

sw1.Start();
for (int i = 0; i < times; i++)
{
FileTest1(file);
}
sw1.Stop();

Stopwatch sw2 = new Stopwatch();

sw2.Start();
for (int i = 0; i < times; i++)
{
FileTest2(file);
}
sw2.Stop();
// MessageBox.Show(string.Format("Test1 Result {0} \nTest2
Result {1}", sw1.Elapsed.TotalSeconds, sw2.Elapsed.TotalSeconds));
label6.Text = string.Format("Test1 Result {0} \nTest2
Result {1}", sw1.Elapsed.TotalSeconds, sw2.Elapsed.TotalSeconds);
}

Output
label6.Text "Test1 Result 27.383811 \nTest2 Result 25.5081203"
string

25 seconds to test 500 times if a file exists? This seems like impossible,
it should be less than a second even on the slowest system.

Willy.
Jun 27 '08 #8
"Willy Denoyette [MVP]" <wi*************@telenet.bewrote in message
news:u0**************@TK2MSFTNGP03.phx.gbl...
"parez" <ps*****@gmail.comwrote in message
news:0d**********************************@a1g2000h sb.googlegroups.com...
>On Apr 25, 3:27 pm, parez <psaw...@gmail.comwrote:
>>On Apr 25, 2:52 pm, "Verde" <A...@B.comwrote:

I would appreciate your comments on the following two alternatives of
a
given method. This isn't a real method, as I'm not concerned about the
"real
work" it could be doing, but would like to instead focus our attention
on
the [extensive checking] vs [zero checking] implemented in these two
methods.

Safe code that makes few assumptions about its runtime conditions is
good,
but what about "needlessly safe"?

Is Version 1 below "needlessly safe" in your opinion?

------------------------------------------------
Version 1 - Extensive "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
if (Directory.Exists(Path.GetDirectoryName(pathToTheF ile)))
{
if (File.Exists(pathToTheFile))
{
// Do something with the file here... open it, whatever...
}
else
{
throw new System.IO.FileNotFoundException("The file was not
found.");
}
}
else
{
throw new System.IO.DirectoryNotFoundException("The directory
was not
found.");
}

}

------------------------------------------------
Version 2 - No "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
// Just try to something with the file here - right "off the
bat"... open
it, whatever...
// If it cannot be located, then system.IO will throw an exception
// ... therefore I don't need to do all the checking for
file/directory
existance

}

Please note that my question isn't about working with files. The code
above
just serves to provide an example of "safe coding" vs code that makes
assumptions.

Thanks in advance!

I *THINK* exceptions cause overhead so its better to do the checks..

I think i thought right..
private void FileTest1(string file)
{

try
{
FileStream fs = File.Open(file, FileMode.Open);
}
catch (Exception)
{
}
}
private void FileTest2(string file)
{

try
{
if (!File.Exists(file))
throw new FileNotFoundException("file not found",
file);
}
catch (Exception)
{
}
}

private void RunFileTest()
{

int times = 5000;

string file="C:\\some.txt";

Stopwatch sw1 = new Stopwatch();

sw1.Start();
for (int i = 0; i < times; i++)
{
FileTest1(file);
}
sw1.Stop();

Stopwatch sw2 = new Stopwatch();

sw2.Start();
for (int i = 0; i < times; i++)
{
FileTest2(file);
}
sw2.Stop();
// MessageBox.Show(string.Format("Test1 Result {0} \nTest2
Result {1}", sw1.Elapsed.TotalSeconds, sw2.Elapsed.TotalSeconds));
label6.Text = string.Format("Test1 Result {0} \nTest2
Result {1}", sw1.Elapsed.TotalSeconds, sw2.Elapsed.TotalSeconds);
}

Output
label6.Text "Test1 Result 27.383811 \nTest2 Result 25.5081203"
string


25 seconds to test 500 times if a file exists? This seems like impossible,
it should be less than a second even on the slowest system.

Willy.


Sure, I mean 5000 times .....

Willy.

Jun 27 '08 #9
On Apr 25, 4:03 pm, "cfps.Christian" <ge0193...@otc.eduwrote:
Throwing/Catching is EXTREMELY costly. Do the checks, but if you're
on a timetable there is a limit to the amount of validation you can do
before you just need to put in the try/catch block and call it done.
I know we use try/catch on every entry point (user event) since those
will cause the app to explode.
1) The comparison of failures is insufficient. You should also compare
the happy path.
2) Its a trade off. For processing 5000 files, the above approach is
suitable. For a handful of files, the performance overhead of failure
scenarios is negligible. In fact not having the check would improve
the happy path performance.
3) I fully agree with Jereon's post above. Your example still does not
show a valid recovery and hence the check is useless as if the file
got deleted just after File.Exists returned true, you will still get
an exception.
Jun 27 '08 #10
On Apr 25, 4:19 pm, "Willy Denoyette [MVP]"
<willy.denoye...@telenet.bewrote:
"parez" <psaw...@gmail.comwrote in message

news:0d**********************************@a1g2000h sb.googlegroups.com...
On Apr 25, 3:27 pm, parez <psaw...@gmail.comwrote:
On Apr 25, 2:52 pm, "Verde" <A...@B.comwrote:
I would appreciate your comments on the following two alternatives of a
given method. This isn't a real method, as I'm not concerned about the
"real
work" it could be doing, but would like to instead focus our attention
on
the [extensive checking] vs [zero checking] implemented in these two
methods.
Safe code that makes few assumptions about its runtime conditions is
good,
but what about "needlessly safe"?
Is Version 1 below "needlessly safe" in your opinion?
------------------------------------------------
Version 1 - Extensive "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
if (Directory.Exists(Path.GetDirectoryName(pathToTheF ile)))
{
if (File.Exists(pathToTheFile))
{
// Do something with the file here... open it, whatever...
}
else
{
throw new System.IO.FileNotFoundException("The file was not
found.");
}
}
else
{
throw new System.IO.DirectoryNotFoundException("The directory was
not
found.");
}
}
------------------------------------------------
Version 2 - No "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
// Just try to something with the file here - right "off the bat"...
open
it, whatever...
// If it cannot be located, then system.IO will throw an exception
// ... therefore I don't need to do all the checking for
file/directory
existance
}
Please note that my question isn't about working with files. The code
above
just serves to provide an example of "safe coding" vs code that makes
assumptions.
Thanks in advance!
I *THINK* exceptions cause overhead so its better to do the checks..
I think i thought right..
private void FileTest1(string file)
{
try
{
FileStream fs = File.Open(file, FileMode.Open);
}
catch (Exception)
{
}
}
private void FileTest2(string file)
{
try
{
if (!File.Exists(file))
throw new FileNotFoundException("file not found",
file);
}
catch (Exception)
{
}
}
private void RunFileTest()
{
int times = 5000;
string file="C:\\some.txt";
Stopwatch sw1 = new Stopwatch();
sw1.Start();
for (int i = 0; i < times; i++)
{
FileTest1(file);
}
sw1.Stop();
Stopwatch sw2 = new Stopwatch();
sw2.Start();
for (int i = 0; i < times; i++)
{
FileTest2(file);
}
sw2.Stop();
// MessageBox.Show(string.Format("Test1 Result {0} \nTest2
Result {1}", sw1.Elapsed.TotalSeconds, sw2.Elapsed.TotalSeconds));
label6.Text = string.Format("Test1 Result {0} \nTest2
Result {1}", sw1.Elapsed.TotalSeconds, sw2.Elapsed.TotalSeconds);
}
Output
label6.Text "Test1 Result 27.383811 \nTest2 Result 25.5081203"
string

25 seconds to test 500 times if a file exists? This seems like impossible,
it should be less than a second even on the slowest system.

Willy.
hehe.. I was changing the numbers around... i pasted wrong code..
anyways it is 5000
"Test1 Result 27.7139862 \nTest2 Result 25.6947071"

I must have changed the number...
Jun 27 '08 #11
On Apr 25, 5:11 pm, parez <psaw...@gmail.comwrote:
On Apr 25, 4:19 pm, "Willy Denoyette [MVP]"

<willy.denoye...@telenet.bewrote:
"parez" <psaw...@gmail.comwrote in message
news:0d**********************************@a1g2000h sb.googlegroups.com...
On Apr 25, 3:27 pm, parez <psaw...@gmail.comwrote:
>On Apr 25, 2:52 pm, "Verde" <A...@B.comwrote:
I would appreciate your comments on the following two alternatives of a
given method. This isn't a real method, as I'm not concerned about the
"real
work" it could be doing, but would like to instead focus our attention
on
the [extensive checking] vs [zero checking] implemented in these two
methods.
Safe code that makes few assumptions about its runtime conditions is
good,
but what about "needlessly safe"?
Is Version 1 below "needlessly safe" in your opinion?
------------------------------------------------
Version 1 - Extensive "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
if (Directory.Exists(Path.GetDirectoryName(pathToTheF ile)))
{
if (File.Exists(pathToTheFile))
{
// Do something with the file here... open it, whatever...
}
else
{
throw new System.IO.FileNotFoundException("The file was not
found.");
}
}
else
{
throw new System.IO.DirectoryNotFoundException("The directory was
not
found.");
}
}
------------------------------------------------
Version 2 - No "runtime environment" Checking
------------------------------------------------
public void DoSomethingWithAFile(string pathToTheFile)
{
// Just try to something with the file here - right "off the bat"...
open
it, whatever...
// If it cannot be located, then system.IO will throw an exception
// ... therefore I don't need to do all the checking for
file/directory
existance
}
Please note that my question isn't about working with files. The code
above
just serves to provide an example of "safe coding" vs code that makes
assumptions.
Thanks in advance!
>I *THINK* exceptions cause overhead so its better to do the checks..
I think i thought right..
private void FileTest1(string file)
{
try
{
FileStream fs = File.Open(file, FileMode.Open);
}
catch (Exception)
{
}
}
private void FileTest2(string file)
{
try
{
if (!File.Exists(file))
throw new FileNotFoundException("file not found",
file);
}
catch (Exception)
{
}
}
private void RunFileTest()
{
int times = 5000;
string file="C:\\some.txt";
Stopwatch sw1 = new Stopwatch();
sw1.Start();
for (int i = 0; i < times; i++)
{
FileTest1(file);
}
sw1.Stop();
Stopwatch sw2 = new Stopwatch();
sw2.Start();
for (int i = 0; i < times; i++)
{
FileTest2(file);
}
sw2.Stop();
// MessageBox.Show(string.Format("Test1 Result {0} \nTest2
Result {1}", sw1.Elapsed.TotalSeconds, sw2.Elapsed.TotalSeconds));
label6.Text = string.Format("Test1 Result {0} \nTest2
Result {1}", sw1.Elapsed.TotalSeconds, sw2.Elapsed.TotalSeconds);
}
Output
label6.Text "Test1 Result 27.383811 \nTest2 Result 25.5081203"
string
25 seconds to test 500 times if a file exists? This seems like impossible,
it should be less than a second even on the slowest system.
Willy.

hehe.. I was changing the numbers around... i pasted wrong code..
anyways it is 5000
"Test1 Result 27.7139862 \nTest2 Result 25.6947071"

I must have changed the number...
its not the check..
its the

if (!File.Exists(file))
throw new FileNotFoundException("file not found",
file);
Jun 27 '08 #12
On Fri, 25 Apr 2008 11:52:50 -0700, Verde <A@B.comwrote:
I would appreciate your comments on the following two alternatives of a
given method. This isn't a real method, as I'm not concerned about the
"real
work" it could be doing, but would like to instead focus our attention on
the [extensive checking] vs [zero checking] implemented in these two
methods.
For better or worse, we can only focus on this specific example. There
are characteristics about the example that may or may not apply generally.

Willy and Jeroen have offered half of the answer, and they are correct as
far as they go. But even those answers make the assumption that doing the
checking isn't harmful. IMHO, that's not correct. In particular, not
only is it possible that when you check the status and find it okay, only
to have that change after the fact, it's also possible to check the status
and find it _not_ okay, only to have _that_ change after the fact.

Depending on what you do immediately after the check, this may or may not
have a significant chance of leading to a false negative (failure). If
you are calling something that opens the file right away, it _probably_
wouldn't be an issue. But if you're doing some other things in
preparation to open the file, it's entirely possible that by the time you
got around to trying to open the file it'd be fine even though it wasn't
when you made the check.

The chances of these false positives and false negatives are extremely low
in any case. But they still exist, and for that reason the checks are not
only unnecessarily redundant, they can cause an error when none would have
occurred otherwise.

Now, this is specific to interacting with the file system. That's a bit
of a specific example, because your program has no control over the state
of the file system. That's why things can change between statements in
your own code. In a different situation, in which the state is known to
be stable, it might indeed be worthwhile to check the state before
attempting an operation that might throw an exception. Especially since,
as "parez" points out, handling a thrown exception is expensive; you
definitely wouldn't want to generate a lot of exceptions in code that's a
bottle-neck in your program.

But in the file system case, it's a really bad idea to do that sort of
checking. Just attempt the operation you want and see if it works or not.

Pete
Jun 27 '08 #13
Verde...The first example uses the TESTER-DOER idiom. On a multi user,
multi
threaded, multi tasking system, the safe idiom is to catch the exception
if the
file does not exist or is locked.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Jun 27 '08 #14
Now, this is specific to interacting with the file system. That's a
bit of a specific example, because your program has no control over
the state of the file system. That's why things can change between
statements in your own code. In a different situation, in which the
Well, I think you've just explained why it applies to any namespace shared
asynchronously, not just the filesystem.
state is known to be stable, it might indeed be worthwhile to check
the state before attempting an operation that might throw an
exception. Especially since, as "parez" points out, handling a
thrown exception is expensive; you definitely wouldn't want to
generate a lot of exceptions in code that's a bottle-neck in your
program.
But in the file system case, it's a really bad idea to do that sort of
checking. Just attempt the operation you want and see if it works or
not.
Pete

Jun 27 '08 #15
On Mon, 28 Apr 2008 06:41:47 -0700, Ben Voigt [C++ MVP]
<rb*@nospam.nospamwrote:
>Now, this is specific to interacting with the file system. That's a
bit of a specific example, because your program has no control over
the state of the file system. That's why things can change between
statements in your own code. In a different situation, in which the

Well, I think you've just explained why it applies to any namespace
shared
asynchronously, not just the filesystem.
I don't fully understand your use of "namespace" here, but yes...I didn't
mean to say that this sort of reasoning applies _only_ to the filesystem.
Just that the example, using the filesystem, is subject to the reasoning.

I agree, the same sort of concerns would apply to any resources that are
not completely under the control of the application.

I suppose for that matter it also applies to asynchronous resources that
are completely under the control of the application but which are used in
an unsynchronized way. But IMHO that's just plain buggy code. :)

Pete
Jun 27 '08 #16
Peter Duniho wrote:
On Mon, 28 Apr 2008 06:41:47 -0700, Ben Voigt [C++ MVP]
<rb*@nospam.nospamwrote:
>>Now, this is specific to interacting with the file system. That's a
bit of a specific example, because your program has no control over
the state of the file system. That's why things can change between
statements in your own code. In a different situation, in which the

Well, I think you've just explained why it applies to any namespace
shared
asynchronously, not just the filesystem.

I don't fully understand your use of "namespace" here, but yes...I
didn't mean to say that this sort of reasoning applies _only_ to the
filesystem. Just that the example, using the filesystem, is subject
to the reasoning.
"namespace" is the term used for filenames, PIDLs, device names, URIs, etc
"address space" for pointers
>
I agree, the same sort of concerns would apply to any resources that
are not completely under the control of the application.

I suppose for that matter it also applies to asynchronous resources
that are completely under the control of the application but which
are used in an unsynchronized way. But IMHO that's just plain buggy
code. :)
Something has got to be used asynchronously.

But here, think of the double-checked locking (anti-)pattern... it's almost
exactly the same as the case in question (and in that pattern as well, the
first check can return a wrong result).
>
Pete

Jun 27 '08 #17
cfps.Christian wrote:
Throwing/Catching is EXTREMELY costly.
If exceptions are only used for something exceptional, then their
performance should be fine.

Arne
Jun 27 '08 #18
mgsram wrote:
For e.g. if i have to
convert 1000 strings to double in a loop and if the 1000 strings are
from a random file, I would prefer using Double.TryParse() to check if
it is a valid double and then parse it.
That should depend on whether you are expecting non parsable
values or not.

Arne
Jun 27 '08 #19

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

Similar topics

42
by: Irmen de Jong | last post by:
Pickle and marshal are not safe. They can do harmful things if fed maliciously constructed data. That is a pity, because marshal is fast. I need a fast and safe (secure) marshaler. Is xdrlib the...
9
by: Jody Gelowitz | last post by:
I am trying to find the definition of "Safe Printing" and cannot find out exactly what this entitles. The reason is that I am trying to print contents from a single textbox to no avail using the...
9
by: Andy Chang | last post by:
Hi, If I have this function void DoSomething(int& index) { ::Sleep(10000); DoSomethingWith(index); } Is the variable index thread safe? Meaning that if I call this from two
2
by: Jeff Chan | last post by:
I have read the documentation from msdn to try to understanding the concept of "Type safe". Would someone give me an example of code segment illustrating what is *Non* type safe? Many Thanks,...
0
by: gm | last post by:
Immediately after generating the Access application from the Source Safe project I get: "-2147467259 Could not use ''; file already in use." If Access database closed and then reopened I get:...
15
by: Laser Lu | last post by:
I was often noted by Thread Safety declarations when I was reading .NET Framework Class Library documents in MSDN. The declaration is usually described as 'Any public static (Shared in Visual...
4
by: George2 | last post by:
Hello everyone, Here is Bjarne's exception safe sample, http://www.research.att.com/~bs/3rd_safe.pdf template <class Tclass Safe {
7
by: bvdp | last post by:
I'm finding my quest for a safe eval() quite frustrating :) Any comments on this: Just forget about getting python to do this and, instead, grab my set of values (from a user supplied text file)...
3
by: =?Utf-8?B?anBhdHJjaWs=?= | last post by:
Don't see any official notice that compiled library dll's loaded in the BIN directory of an asp.net website need to be thread safe, but concurrent visits to the same web site sure bear this out....
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:
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: 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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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...

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.