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

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 1243
Steven Blair <st**********@btinternet.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**********@btinternet.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();
GetProductDetails();
return "whatever output";
}
catch (Exception ex)
{
LogException(ex);
return "whatever output";
}
}
--->8---

Where ParseMessage() and GetProductDetails() 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**********@btinternet.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 WrappedException : Exception
{
private object _source;

public WrappedException(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 WrappedException(ex, source);
}
}

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

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

Wrap("source 2", delegate
{
Method4();
Method5();
});
}
catch (WrappedException 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********@gmail.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
Pa********@gmail.com wrote:
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).


If you have transactional semantics for your business logic, (for
example, you can only add stuff to your basket if it is in stock, and
the two go together relatively atomically), you can take advantage of
exceptions and properly structured try/catch blocks to roll-back any
changes.

The try/catch blocks would look somewhat like:

---8<---
// do stuff A
try
{
// do stuff B
}
catch
{
// roll back stuff A
throw;
}
--->8---

Whether this would make your business code simpler, I don't know.

-- Barry
May 12 '06 #11

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

Similar topics

4
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
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...
16
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 ...
6
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...
2
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...
3
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...
12
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...
4
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...
5
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...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
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
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...

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.