473,799 Members | 3,290 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this structure good for methods?

Looking for some opinions on the structure of this method, namely the
way errors are handled and reported:

http://pastebin.com/711366

My view is this is quite a good method of trapping and moving through a
flow of data.

Anyone suggest a better way?

Steven

*** Sent via Developersdex http://www.developersdex.com ***
May 11 '06 #1
10 1270
Steven Blair <st**********@b tinternet.com> wrote:
Looking for some opinions on the structure of this method, namely the
way errors are handled and reported:

http://pastebin.com/711366

My view is this is quite a good method of trapping and moving through a
flow of data.

Anyone suggest a better way?


I strongly suggest you look up exceptions, exception handling, and see
how they work.

-- Barry
May 11 '06 #2
I know about exceptions.
They are used frequently in my applications (when required)
But this cod example, in my opinion is not suitable for wrapping around
try, catch blocks.
None of the methods in the example will throw an exception.

*** Sent via Developersdex http://www.developersdex.com ***
May 11 '06 #3
Steven Blair <st**********@b tinternet.com> wrote:
I know about exceptions.
They are used frequently in my applications (when required)
But this cod example, in my opinion is not suitable for wrapping around
try, catch blocks.
None of the methods in the example will throw an exception.


You don't know that - more importantly, you shouldn't know that, by
principle of encapsulation. Somebody modifying the code a year later may
throw an exception, or may in some other way break this invariant.

I, personally, would write your code like this:

---8<---
public override string ProcessMessage( )
{
try
{
ParseMessage();
GetProductDetai ls();
return "whatever output";
}
catch (Exception ex)
{
LogException(ex );
return "whatever output";
}
}
--->8---

Where ParseMessage() and GetProductDetai ls() throw exceptions if there
is an error - and I would even prefer not catching the exception at all,
and letting another method further up the call stack catch the
exception.

-- Barry
May 11 '06 #4
the problem is, this method could end up having a number og other
methods calls in it.

I just dont think:

try
{
//Method1
//Method2
//Method3
//Method4
//Method5
//Method6
}
catch(Exception )
{
//Which method threw the exception?
}
I am not sure this is the best structure.

*** Sent via Developersdex http://www.developersdex.com ***
May 11 '06 #5
Steven Blair <st**********@b tinternet.com> wrote:
the problem is, this method could end up having a number og other
methods calls in it.

I just dont think:

try
{
//Method1
//Method2
//Method3
//Method4
//Method5
//Method6
}
catch(Exception )
{
//Which method threw the exception?
It is in the stack trace associated with the exception, so if you log
the exception you do in fact know which method it occurred in.
}

I am not sure this is the best structure.


That's by design, of course: one of the goals of exception handling is
to centralize your error handling. If you need to know the source of the
exception, you could attribute the exception at the point it's thrown.
If that won't work out, you could consider adding another layer of
indirection:

---8<---
class App
{
delegate void Method();

class WrappedExceptio n : Exception
{
private object _source;

public WrappedExceptio n(Exception inner, object source)
: base(inner)
{
_source = source;
}

public object Source
{
get { return _source; }
}
}

static void Wrap(object source, Method method)
{
try
{
method();
}
catch (Exception ex)
{
throw new WrappedExceptio n(ex, source);
}
}

static void Main()
{
try
{
Wrap("source 0", delegate { Method0(); });

Wrap("source 1", delegate
{
Method1();
Method2();
});

Wrap("source 2", delegate
{
Method4();
Method5();
});
}
catch (WrappedExcepti on ex)
{
Log(ex.Source);
}
}
}
--->8---

That's totally off the top of my head, use at your own risk, etc.

-- Barry
May 11 '06 #6
I'm going to ask a stupid question, because I've been wondering for a
while... if exceptions are to be thrown in exceptional circumstances,
is there any pattern for dealing with situations where you need to
return information on the status of a procedure?

An example might be a login screen where your UI needs to report that
a) login was successful, b) the password was incorrect, or c) the
username was not recogised.

Barring the security implications of this, is there any better way than
returning an enum? What if you need to return data from a method, but
you also want information on the state of that method? Are you back to
the OP's technique?

What if you don't want to throw an exception because, as in the example
above, certain classes of error are expected and aren't fatal to an
app?

Would a class to wrap the command make sense in this situation?

I humbly await enlightenment.

May 12 '06 #7
Pa********@gmai l.com wrote:
if exceptions are to be thrown in exceptional circumstances,
What counts as exceptional is of course up to debate, and different
languages down the years have had different penalties for exceptions, so
I don't think there's a universal consensus on this.
is there any pattern for dealing with situations where you need to
return information on the status of a procedure?
A reasonable pattern can be seen in Int32.TryParse( ) and friends.
An example might be a login screen where your UI needs to report that
a) login was successful, b) the password was incorrect, or c) the
username was not recogised.
I think it's reasonable in this case to have a method returning boolean
here - in particular, because revealing the exact nature of the
authentication failure is a security weakness. A malicious attacker can
validate usernames without knowing passwords if the response is
different for unknown usernames versus incorrect passwords.
Barring the security implications of this, is there any better way than
returning an enum?
It entirely depends on how much information you need. If you need lots
of information, it may warrant a rich object graph.
What if you don't want to throw an exception because, as in the example
above, certain classes of error are expected and aren't fatal to an
app?
If an error is expected, then you'll want to test for it imperatively -
but you'll still want your mainline case to throw exceptions if the
caller didn't call the corresponding "test" routine. One of the nicer
things about exceptions is that they're harder to ignore than return
values.
Would a class to wrap the command make sense in this situation?
It depends on the circumstances - whatever reduces the total effort of
producing a correct and maintainable implementation that satisfies the
requirements should suffice, I reckon :).
I humbly await enlightenment.


Methinks you protest too much!

-- Barry
May 12 '06 #8
I suppose TryParse is a reasonable example where you have a state and a
possible return value, only they're swapped around. My question, I
suppose, is what do you do if you have more than two possible states
for a method?

An enum seems right, but I'm wondering if maybe I'm seeing a problem
that doesn't exist. Meditate on this, I shall.

I think the answer, basically, is bool/out for forgiving methods,
enum/out for forgiving methods with more than two final states; and for
the remainder, use exceptions, or split the method up so you don't have
the requirement to return two sets of information, or use a command
wrapping class with State and Value properties.

That's quite a few options to have open for the rare case when I want
to do this. I should stop worrying and learn to love the code.

I think I avoid exceptions too much, I have some deep unfounded fear of
errors in the system, especially errors that cause a magic goto :)

I also think I'm either not quite grokking something, or I'm not asking
the right question. I'll stop hijacking the thread, anyway.

-- flinky wisty pomm

May 12 '06 #9
In fact, one last hijack, if people will indulge it, with a more
concrete example.

I have an ecommerce application, www.WidgetStore.com with a whole bunch
of stored procs to CRUD, each of which returns error codes to denote
success or reasons for failure.

J Random User tries to add a Widget to his shopping cart, but while he
was making coffee, some other user bought the last one. The proc for
updating carts and stock quantities fails because business logic is
violated (you can only add a product to your cart if it is in stock).

Now, it FEELS intuitively wrong to throw an exception to handle this
situation, and there're myriad examples I could give where business
logic is violated in an expected situation, and there is no failure of
code.

Is this mere superstition, or is another pattern more suited to this
kind of state reporting?

May 12 '06 #10

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

Similar topics

4
4819
by: plork | last post by:
I'm trying to code a tree structure using javascript, the nodes of the tree are generated from a sql table. Has anyone some code for this? Cheers
10
8669
by: gmtonyhoyt | last post by:
It's been mentioned to me that, in standard c, that you can have structures behave very much like classes in relation to something to do with function calls within a structure. Now, I didn't get the details, but does someone have a clue of what this person perhaps was talking about? Do you think he just ment something such as function pointers? Or could I, much like a C++ Class, call a class function that has access to the structure...
16
2508
by: Duncan Mole | last post by:
Hi, This is probably an easy one but it iy first bit of p/invoke. I am trying to use the following C struct in a call: typedef struct { BYTE SRB_Cmd; BYTE SRB_Status, BYTE SRB_HaId;
6
1403
by: JSheble | last post by:
Are there any reasons why I shouldn't or couldn't use a structure as a property in a class? Specifically since structures are value types and objects are reference types? I have a Shipping object that has 4 different types of addresses. Initially, I created 4 instances of an Address object, but seem inefficient to me since the Address itslef doesn't really have (or need) and methods... I was thinking a structure would be more...
2
5274
by: wg | last post by:
I am new the C# coming from a VB6 world. In VB6 I have serveral applications where I create a UDT in a module then make an array of the UDT. All modules and forms could access this. Now I am attempting to do this in C#. I would like to create a Structure then an array of that, (ex. Variable.Name, Variable.Value). But I need several classes to have access to the data. It must be an array because I update some of the values. Another...
3
1231
by: Jim Langston | last post by:
I am attempting to map the variables in a class or structure to use with MySQL. I got something to work but I'm not happy with it. Here is a snippet showing what I'm not happy with: class COffsetMap { public: COffsetMap() {} virtual ~COffsetMap() {} void SetBase( void* Base ) { Base_ = reinterpret_cast<char*>( Base ); }
12
2431
by: Sam Kong | last post by:
Hi, JavaScript hides its memory structure. I know that numbers, booleans, null and undefined are value types (value is directed saved in a variable). I want to know: - How JavaScript distinguishes value types from reference types by seeing the variable content?
4
1728
by: eBob.com | last post by:
In my class which contains the code for my worker thread I have ... Public MustInherit Class Base_Miner #Region " Delegates for accessing main UI form " Delegate Sub DelegAddProgressBar(ByVal uiform As Form1, ByRef si As MTCC02.Form1.SiteRunOpts, _ ByVal numitems As Integer) #End Region
5
1563
by: jc | last post by:
RE: Two Classes with the same Data Structure.. saving code? Inheriting a structure? I have two classes. One in Inherits System.Collections.CollectionBase, the other does not, but they both have the identical structure and properties. the only difference between them is there methods and that one is a collection class and the other is not. currently the code starts like this:
0
10484
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
10251
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
10228
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
9072
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...
1
7565
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5463
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...
1
4141
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
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.