wood burning stoves*
The moose likes OO, Patterns, UML and Refactoring and the fly likes best way to design this method... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "best way to design this method..." Watch "best way to design this method..." New topic
Author

best way to design this method...

k Oyedeji
Ranch Hand

Joined: Jul 07, 2002
Posts: 96
Hi i am trying to determine if the behaviour i'm considering could be considered as bad design and if there is a better way.
I have a method which expects a string as a parameter however the string must match a value in the object. If it does, an object is created and returned.
The problem is if the string does not match, is it acceptable to throw an exception? What is the correct way to handle such a scenario?
Should exceptions be used for things like this?
Thanks
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
It depends...
What could be a reason for the String not matching? Why would it happen and how would the client code want to react?


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
k Oyedeji
Ranch Hand

Joined: Jul 07, 2002
Posts: 96
the string passed in is supplied by the user,
it may or not match the value. If it does not i would like to return a message to the user informing them that the string does not match. I cant return a string indicating the error because the method is supposed to return an object. So i'm thinking of using exceptions but wasnt sure if this was a good idea.
Fisher Daniel
Ranch Hand

Joined: Sep 14, 2001
Posts: 582
I think you can return a null object to the caller this method. So in the caller method will be checked if the return value is null that mean the string, user was inputed, is not match.
What about this?
thanks
daniel
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I don't think you should use Exceptions for this. IMHO, exceptions should only be used for programming errors and problems you can hardly check for programmatically before calling a method (such as IO errors). (Even for programming errors, I currently tend to write less defensive code and rely on the automated tests for the client to find them.)
You might return null or a Null Object as Daniel pointed out. That might be OK for a small "one shot" application. In a bigger one, that will need to be maintained for some time, I would be worried about the coupling of two concepts in one method: validating the user input and acting based on it.
Therefore, I would probably try to split this functionality into two methods: one that validates the input (and possibly returns a boolean or a more descriptive error description object) and one that processes the input.
That way, you won't get into trouble later, if, for example, you needed to apply more validations before starting the processing (or delay the processing or...)
Did that help?
Michael Zalewski
Ranch Hand

Joined: Apr 23, 2002
Posts: 168
I have no problem with throwing an Exception. Isn't that exactly what the core classes do for example when you parse an number input? Normally, you call Integer.parseInt( inputString), and catch the NumberFormatException if it's thrown.
But there are two suggestions. First, don't just throw an Exception. Make a 'ItemDoesNotExistException', or something that makes sense.
And second, you might consider adding a method boolean exists( String sTestInput) -- this is what Ilja is suggesting in the previous post. Or add a method boolean isValid() to the Object returned, which returns 'false' if the String used to create the object did not match.
Returning a null is OK too. But I don't much like that solution, because nulls cause lots of problems in maintenance.
[ November 22, 2002: Message edited by: Michael Zalewski ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Michael Zalewski:
I have no problem with throwing an Exception. Isn't that exactly what the core classes do for example when you parse an number input? Normally, you call Integer.parseInt( inputString), and catch the NumberFormatException if it's thrown.

Yes, this is what is done in the JDK. In my not so humble opinion not the only rather questionable design choice made by the sun programmers...
k Oyedeji
Ranch Hand

Joined: Jul 07, 2002
Posts: 96
hi
Thanks for the feedback, i like the suggestion which checks if a parameter is valid but this means that this method call would have to be called before calling the second method. The developer would have to remember to call this validation method before calling the second method. This means that it will compile but could cause an error at run time if the programmer forgets to call the validation method first.
By using an exception i can use the compile process to force the programmer to consider what happens if invalid input is passed.
Also i recently read a beginner article on javaworld on exceptions which pointed out that using a try catch block saves the programmer from having to check the result returned is not an error flag every time a method is called.
I realise that use of try and catch blocks can be viewed as similar to using goto in other languages which is often frowned upon. Ilja Preuss is this why using exceptions for this would be a bad idea?
Thanks
Kola
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by k Oyedeji:
Thanks for the feedback, i like the suggestion which checks if a parameter is valid but this means that this method call would have to be called before calling the second method. The developer would have to remember to call this validation method before calling the second method. This means that it will compile but could cause an error at run time if the programmer forgets to call the validation method first.

Yes. Your extensive suite of unit- and acceptance tests will find those errors. You hopefully have one, don't you?
BTW, if you don't trust the programmers to call the method properly, how can you trust them to not simply ignore the exception instead of handling it properly?
By using an exception i can use the compile process to force the programmer to consider what happens if invalid input is passed.

Yes. On the other hand it also makes your code more complex - and complexity is the main reason for both high maintenance costs and high bug rate.
But we certainly want the programmers using the class to consider to not pass invalid input. Could there be another way of doing that?
Also i recently read a beginner article on javaworld on exceptions which pointed out that using a try catch block saves the programmer from having to check the result returned is not an error flag every time a method is called.

Yes, in those cases of operations spanning several method calls (like typical IO for example) I would probably still use exceptions. But this doesn't seem to be the case here, does it?
I realise that use of try and catch blocks can be viewed as similar to using goto in other languages which is often frowned upon. Ilja Preuss is this why using exceptions for this would be a bad idea?

No. Gotos aren't bad generally - after all, even a for-loop is not much more than another syntactical form of a conditional goto. It's only when gotos are used in an unstructured way that they cause harm.
I have a suggestion for you: Try it both ways! It shouldn't take you to long to code both. Compare them to each other - which is easier to read? Which is more likely to be easily extended?
[ December 11, 2002: Message edited by: Ilja Preuss ]
k Oyedeji
Ranch Hand

Joined: Jul 07, 2002
Posts: 96
Thanks for your replies i think i'll do that.
Kola
Wilfried LAURENT
Ranch Hand

Joined: Jul 13, 2001
Posts: 269
If performance is an issue, then the "null" option should be preferred. It is known (well there is not a general consensus on this) that creating and raising an exception is expensive.
W.
k Oyedeji
Ranch Hand

Joined: Jul 07, 2002
Posts: 96
So to summarise, my options are:
1. Return a null value (in which case the value returned needs to be checked)
2. Throw an exception( which may peform worse than other options) and involves writing code to handle it
3. call a function first to validate the passed paramaters
Guys, thanks for the replies. To expand on some of the ideas presented here, can anyone see a problem with creating a method to validate a parameter and changing the second method to expect a different type of parameter say - validatedParameter. Would this be a good idea?
Thanks
[ December 12, 2002: Message edited by: k Oyedeji ]
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
Don't forget there is an option 4: pass in a "default" object which will be returned if the processing fails. I use this pattern a lot, and it allows me to deal with possible faults in a context-sensitive way:

This allows me to choose according to what I need at the time. I might pass in a known (typically static) "empty" object which won't blow up later processing, or maybe null, which can easily be checked after the "convert" call, or maybe there is a more appropriate default value.
As a concrete example, consider the following methods which I use when I need to parse a string into an integer:


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
k Oyedeji
Ranch Hand

Joined: Jul 07, 2002
Posts: 96
Hi
I quite like that last suggestions, it seems a more elegant variation of option 1.
Thank you everyone for your help and insights.

Kola
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Yes, it's a nice solution, if it's appropriate. In fact I think it is a form of generalization of the Null Object pattern, isn't it?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: best way to design this method...
 
Similar Threads
hashCode Question
2 burning questions about URLyBird
Covariant return
'==' operator on String objects
Data Access Object & Value Object