Raba - Defend your code RSS 2.0
# Friday, May 12, 2006

In one of my code reviews I saw this piece of code (those two methods are in the same class), IMO, and I believe that most of you will agree with me, this usage of exception is unnecessary.

private void CheckPrivileges()
{
   // check user privileges
   // for authorized user won't do anything.

   // if not authorized:
   throw new UserNotPrivException("user name", "action not allowed");
}

public void DoSomething()
{
   try
   {
      CheckPrivileges();
      // Continue your logic for authorized users.

   }
   catch (UserNotPrivException)
   {
      // showing message box which
      // says that user has no permissions
      ShowMessageBox ("User X has no privileges for this place.");
   }
}

Why ? 

  1. The Exception mechanism is slow
  2. A lot try&catch makes the code harder to read
  3. Why throw exception if you won't use it? and also throwing it between two methods in the same class?

I would have done it like this:

private bool IsUserPrivileged()
{
   // check user privileges
   // for authorized user - return true
   // if not authorized - return false
}

public void DoSomething()
{
   if (!IsUserPrivileged())
   {
      // showing message box which
      // says that user has no permissions
      ShowMessageBox("User X has no privileges for this place.");
      return;
   }

   // Continue your logic for authorized users
}

If you want to check between those two (privileged or not) you can use the bool.
Moreover, when you are not really need the exception data.

Honestly,
I wrote this post before Tech-Ed, but didn't have enough time to publish it, in Tech-Ed, I talked with some other programmers that agreed with my opinion, but I still would like to hear your opinion,
what do you think about it?

Friday, May 12, 2006 11:10:06 AM (GMT Daylight Time, UTC+01:00)  #    Comments [5] - Trackback
.Net | Software Development

Archive
<May 2006>
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910
Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Shani Raba
Sign In
Statistics
Total Posts: 145
This Year: 0
This Month: 0
This Week: 0
Comments: 97
Cool Stuff
Add to Technorati Favorites
Themes
Pick a theme:
All Content © 2012, Shani Raba
DasBlog theme 'Business' created by Christoph De Baene (delarou)