To wrap or not to wrap?

A

Aaron Fude

Hi,

In my personal development efforts, I frequently wrap basic java
functionality. For example, I have a

String MyIO.urlToString(String url)

or

byte[] MIO.urlToBytes(String url)

etc. These functions catch exceptions and return null if something
goes wrong. I have other functoins that, for example, load database
queries into maps.

My gereneral questions are these. Does everybody pretty much end up
writing convenience wrappers like these for themselves?. If yes, why
aren't utilities like these commonly available as more or less
standard libraries? And if no - why not? Is it a bad idea to use these
and is it for some reason better to, e.g., always form URL's, open
connections, capture exceptions, etc.

Thanks for your opinions!

Aaron
 
S

Stefan Ram

Aaron Fude said:
These functions catch exceptions and return null

You must like the classic C idiom

if( f = fopen( "alpha", "r" ))
{ use( f );
close( f ); }
else
{ handle_failure( "alpha", "r" ); }

more than exception idioms like

try
{ f = fopen( "alpha", "r" );
try
{ use( f ); }
finally
{ close( f ); }}
catch( final Exception exception )
{ handleFailure( "alpha", "r", exception ); }

I also like structured programing, and it is not easy
for me to cope with the exception style. I hope that
I at least have done the above translation correctly.

The above code already looks complicated, but it becomes even
more complicated, when you need to obtain and release
/multiple/ resources. This should be done as a kind of
transaction: When you need n resources, you might have
obtained m already (m < n), but the next attempt might
fail. Then you need to return to a orderly state and
release exactly those resources that have been allocated
so far and report the whole operation to be failed. So
the above patterns need to be nested, which makes the
result even more complicated.

I have invented another style, that use an object to handle
control flow and should take care of the problem to allocate
multiple resources

Here is an example (explanation follows below):

public void digest( final java.io.File file )
{ final de.dclj.ram.system.program.Program program
= new de.dclj.ram.system.program.Program();
try
{
final java.io.FileInputStream fileInputStream =
program.'new java.io.FileInputStream'( file ); /* first attempt */

final java.io.BufferedInputStream bufferedInputStream =
program.'new java.io.BufferedInputStream'( fileInputStream );

final java.security.MessageDigest messageDigest =
program.'new java.security.MessageDigest'( type );

if( program.succeeded() )
{ this.process( bufferedInputStream, messageDigest ); }
else
{ java.lang.System.out.println( program.'opening exceptions'() ); }}

finally
{ program.close();
if( !program.closed() )
{ java.lang.System.out.println( program.'closing exceptions'() ); }}}}

A preprocessor converts everything withing single quotes to
Java names. This is not necessary for this approach, but just
an additional convenience.

The operation »this.process« needs three resources: A file
input stream, a buffered input stream and a message digest.

The object »program« has operations to request the allocations
needed. If the first attempt fails, it will skip the next two
attempts and »program.succeeded()« will be false. The client
above does not have to use »if« or »try« for each attempt.
He can request the exceptions from the program object.

»program.close()« will then close exactly those resources that
have been obtained successfully before, because »program« has
kept track of the release operations required to release
everything that has been allocated successfully using this
program object.

Drawback: Each type of resource needs a special implementation
in »de.dclj.ram.system.program.Program«, and right now there are
only few types implemented. I will add additional code as I
need it. See also:

http://www.purl.org/stefan_ram/html/ram.jar/de/dclj/ram/system/program/Program.html

(with links to the source code.) This is part of the library

http://www.purl.org/stefan_ram/pub/ram-jar
 
A

Arne Vajhøj

Aaron said:
In my personal development efforts, I frequently wrap basic java
functionality. For example, I have a

String MyIO.urlToString(String url)

or

byte[] MIO.urlToBytes(String url)

etc. These functions catch exceptions and return null if something
goes wrong. I have other functoins that, for example, load database
queries into maps.

My gereneral questions are these. Does everybody pretty much end up
writing convenience wrappers like these for themselves?. If yes, why
aren't utilities like these commonly available as more or less
standard libraries? And if no - why not? Is it a bad idea to use these
and is it for some reason better to, e.g., always form URL's, open
connections, capture exceptions, etc.

I think it is a bad idea.

You should use the exception functionality as it is intended.

Arne
 
A

Aaron Fude

Aaron said:
In my personal development efforts, I frequently wrap basic java
functionality. For example, I have a
String MyIO.urlToString(String url)

byte[] MIO.urlToBytes(String url)
etc. These functions catch exceptions and return null if something
goes wrong. I have other functoins that, for example, load database
queries into maps.
My gereneral questions are these. Does everybody pretty much end up
writing convenience wrappers like these for themselves?. If yes, why
aren't utilities like these commonly available as more or less
standard libraries? And if no - why not? Is it a bad idea to use these
and is it for some reason better to, e.g.,  always form URL's, open
connections, capture exceptions, etc.

I think it is a bad idea.

You should use the exception functionality as it is intended.

Arne- Hide quoted text -

- Show quoted text -


I kind of do. I capture the exception within the function and print
the error message. But wrapping this in a function in my project saves
me hundreds of lines of code, enables me not to have to remember how
things are done at the low level. For example, I have a function
called void playSoundClip(String fileName) and BufferedImage[]
loadImage(String fileName). I don't even remember the package that
deals with playing audio and Eclipse finds my own function for me
immediately.
When you say "should" can you elaborate why. When could this lead to
problem from the development point of view?
 
A

Arne Vajhøj

Aaron said:
Aaron said:
In my personal development efforts, I frequently wrap basic java
functionality. For example, I have a
String MyIO.urlToString(String url)
or
byte[] MIO.urlToBytes(String url)
etc. These functions catch exceptions and return null if something
goes wrong. I have other functoins that, for example, load database
queries into maps.
My gereneral questions are these. Does everybody pretty much end up
writing convenience wrappers like these for themselves?. If yes, why
aren't utilities like these commonly available as more or less
standard libraries? And if no - why not? Is it a bad idea to use these
and is it for some reason better to, e.g., always form URL's, open
connections, capture exceptions, etc.
I think it is a bad idea.

You should use the exception functionality as it is intended.

I kind of do. I capture the exception within the function and print
the error message. But wrapping this in a function in my project saves
me hundreds of lines of code, enables me not to have to remember how
things are done at the low level. For example, I have a function
called void playSoundClip(String fileName) and BufferedImage[]
loadImage(String fileName). I don't even remember the package that
deals with playing audio and Eclipse finds my own function for me
immediately.
When you say "should" can you elaborate why. When could this lead to
problem from the development point of view?

Testing for return values in a deep call stack adds lots of clutter to
the code.

Exceptions was invented to avoid that.

So catching the exception at the low level and convert to a return
value is a bad idea.

Arne
 
T

Tom Anderson

In my personal development efforts, I frequently wrap basic java
functionality. For example, I have a

String MyIO.urlToString(String url)

or

byte[] MIO.urlToBytes(String url)

etc. These functions catch exceptions and return null if something
goes wrong. I have other functoins that, for example, load database
queries into maps.

My gereneral questions are these. Does everybody pretty much end up
writing convenience wrappers like these for themselves?. If yes, why
aren't utilities like these commonly available as more or less
standard libraries? And if no - why not? Is it a bad idea to use these
and is it for some reason better to, e.g., always form URL's, open
connections, capture exceptions, etc.

What everyone else said. Exceptions are a good way to do error handling.
Null returns are not. You're shooting yourself in the foot.

tom

--
For the first few years I ate lunch with he mathematicians. I soon found
that they were more interested in fun and games than in serious work,
so I shifted to eating with the physics table. There I stayed for a
number of years until the Nobel Prize, promotions, and offers from
other companies, removed most of the interesting people. So I shifted
to the corresponding chemistry table where I had a friend. At first I
asked what were the important problems in chemistry, then what important
problems they were working on, or problems that might lead to important
results. One day I asked, "if what they were working on was not important,
and was not likely to lead to important things, they why were they working
on them?" After that I had to eat with the engineers! -- R. W. Hamming
 
S

Stefan Ram

Aaron Fude said:
I kind of do. I capture the exception within the function and print
the error message.

Printing is not a general solution, because it means that
these functions can only be used in console programs and when
printing each exception is wanted.

But the exceptions will not be visible when the program is
using a GUI oder a speech interface. And it will be difficult
to log the exceptions.

This explains, why Java does not uses this as a »general
solution«.

General operations should not assume that the application
has a specific interface and just return values, they should
not do any I/O unless this happens to be their purpose.
 
P

Patricia Shanahan

Aaron said:
Hi,

In my personal development efforts, I frequently wrap basic java
functionality. For example, I have a

String MyIO.urlToString(String url)

or

byte[] MIO.urlToBytes(String url)

etc. These functions catch exceptions and return null if something
goes wrong. I have other functoins that, for example, load database
queries into maps.

My gereneral questions are these. Does everybody pretty much end up
writing convenience wrappers like these for themselves?. If yes, why
aren't utilities like these commonly available as more or less
standard libraries? And if no - why not? Is it a bad idea to use these
and is it for some reason better to, e.g., always form URL's, open
connections, capture exceptions, etc.

Situations in which I would return null due to an exception are really
rare. More usually, either the exception is a disaster and must be let
flow up the stack to something that can deal with it definitively, or
there is a useful value that can be used, and that should be returned.

In letting exceptions flow up the stack, I do sometimes wrap them in
other exceptions. For example, I might wrap a NumberFormatException in
an InputValidationException, adding data such as a line number and
position in line of the string I tried, and failed, to parse as a number.

Patricia
 
R

Roedy Green

etc. These functions catch exceptions and return null if something
goes wrong. I have other functoins that, for example, load database
queries into maps.

You are thinking in C. The advantage of exceptions is you can handle
them at any level that is convenient. By returning null, you force an
explicit check, and you must handle the problem then and there or else
explicitly pass the problem up the call chain.
 
C

Chronic Philharmonic

Aaron Fude said:
Aaron said:
In my personal development efforts, I frequently wrap basic java
functionality. For example, I have a
String MyIO.urlToString(String url)

byte[] MIO.urlToBytes(String url)
etc. These functions catch exceptions and return null if something
goes wrong. I have other functoins that, for example, load database
queries into maps.
My gereneral questions are these. Does everybody pretty much end up
writing convenience wrappers like these for themselves?. If yes, why
aren't utilities like these commonly available as more or less
standard libraries? And if no - why not? Is it a bad idea to use these
and is it for some reason better to, e.g., always form URL's, open
connections, capture exceptions, etc.

I think it is a bad idea.

You should use the exception functionality as it is intended.

Arne- Hide quoted text -

- Show quoted text -


I kind of do. I capture the exception within the function and print
the error message. But wrapping this in a function in my project saves
me hundreds of lines of code, enables me not to have to remember how
things are done at the low level. For example, I have a function
called void playSoundClip(String fileName) and BufferedImage[]
loadImage(String fileName). I don't even remember the package that
deals with playing audio and Eclipse finds my own function for me
immediately.
When you say "should" can you elaborate why. When could this lead to
problem from the development point of view?

Returning null instead of the exception that was originally thrown requires
the caller to check for null every time, or blindly use the null value
(usually causing a NullPointerException which is generally less informative
when it occurs). Using exceptions correctly often results in less code,
because you can just plow ahead as if everything is fine, and catch the
exception where it makes sense in your code (where you can recover from it),
or just let it fly if you can't recover from it. That way, your application
logic is uncluttered with error handling code, and all the error handling
code is in one place (in the catch block). There are always exceptions to
this rule (no pun intended):

1. Exceptions should be, er, exceptional. If they happen all the time, or
very frequently, they're not exceptional, and you should investigate whether
can detect the conditions that are causing the exceptions, and try to
prevent them from happening in the first place. Otherwise, throwing and
handling a flurry of exceptions could introduce a performance penalty.

2. If the code is poorly organized, the exception handling code could be
just as intrusive as the constant checking for error return values. Well
organized exception handling is a bit of an art that you learn by
experience.

Finally, there is nothing wrong with wrapping other method calls if there is
a sequence of instructions that you use repeatedly from all over your
application. In fact, that is a situation that screams for a subroutine. You
should totally do that.
 
J

java_killer

Hi,

In my personal development efforts, I frequently wrap basic java
functionality. For example, I have a

String MyIO.urlToString(String url)

or

byte[] MIO.urlToBytes(String url)

etc. These functions catch exceptions and return null if something
goes wrong. I have other functoins that, for example, load database
queries into maps.

My gereneral questions are these. Does everybody pretty much end up
writing convenience wrappers like these for themselves?. If yes, why
aren't utilities like these commonly available as more or less
standard libraries? And if no - why not? Is it a bad idea to use these
and is it for some reason better to, e.g., always form URL's, open
connections, capture exceptions, etc.

Thanks for your opinions!

Aaron

Hi,
I have no idea about Java. This is just a test. Thanks for your
patient.
 
S

Stefan Ram

Chronic Philharmonic said:
Returning null instead of the exception that was originally thrown requires
the caller to check for null every time, or blindly use the null value

I assume that one wants to copy a file and thus needs to open
a file for reading and a file for writing and then invoke a
copy operation.

I now will write this once in the C style with zero checking
and once in the Java style with a try statement.

Does the try-style look more readable? Can it be simplified?
(Possibly I was not using the simplest way to write it.)

if( f = fopen( "alpha", "r" ))
{ if( g = fopen( "beta", "w" ))
{ if( copy( g, f ))report( "Copy failed." );
close( g ); }
else report( "Can't open beta for writing." );
close( f ); }
else report( "Can't open beta for writing." );

try
{ f = fopen( "alpha", "r" );
try
{ g = fopen( "beta", "w" );
try
{ copy( g, f ); }
catch( final Exception exception )
{ report( "Copy failed." ); }
finally
{ close( g ); }}
catch( final Exception exception )
{ report( "Can't open beta for writing." ); }
finally
{ close( f ); }}
catch( final Exception exception )
{ report( "Can't open alpha for reading." ); }
 
C

Chronic Philharmonic

Stefan Ram said:
I assume that one wants to copy a file and thus needs to open
a file for reading and a file for writing and then invoke a
copy operation.

I now will write this once in the C style with zero checking
and once in the Java style with a try statement.

Does the try-style look more readable? Can it be simplified?
(Possibly I was not using the simplest way to write it.)

if( f = fopen( "alpha", "r" ))
{ if( g = fopen( "beta", "w" ))
{ if( copy( g, f ))report( "Copy failed." );
close( g ); }
else report( "Can't open beta for writing." );
close( f ); }
else report( "Can't open beta for writing." );

try
{ f = fopen( "alpha", "r" );
try
{ g = fopen( "beta", "w" );
try
{ copy( g, f ); }
catch( final Exception exception )
{ report( "Copy failed." ); }
finally
{ close( g ); }}
catch( final Exception exception )
{ report( "Can't open beta for writing." ); }
finally
{ close( f ); }}
catch( final Exception exception )
{ report( "Can't open alpha for reading." ); }

Without specifically rewriting your logic, I can only say that this isn't
how my exception handlers typically look. I tend to use one big try block,
with several catch blocks at the end, to deal with things that I can deal
with, or let the exception fly if I can't deal with it, or if I want the
exception itself to report the failure. I don't usually concern myself with
reporting things like "copy failed" at the granular level.

It is difficult for me to provide examples of what I mean that fit in a
single method or code snippet, because structured exception handling is more
of an architectural endeavor, requiring a more holistic approach to error
handling. I could send you the source code to my WxService project
(http://mysite.verizon.net/Karl_Uppiano/wxservice.html) if you're
interested.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top