|
|
|
||
|
I constantly run across code that looks like:
public class FileReader {
...
/**
* <p>Reads the file with the specified name and returns the
* contents in a {@link java.nio.ByteBuffer buffer}.</p>
*
* @param filename the name of the file to read
* @return an allocated (not direct) <code>ByteBuffer</code>
* with the contents of the file
* @throws IOException if an I/O error occurs
*/
public ByteBuffer readFile(final String filename)
throws IOException
{
...
}
...
}
What's wrong with that? you're probably asking yourself. It's even got comments! The title of this entry should give you a little clue. I will spare you the rant and soap box about the proper use of exceptions and attempt to appeal to your common sense: If you, as the developer of the function, couldn't handle or recover from the The interface or contract that you expose should not break encapsulation. The fact that you (as the developer) have I/O issues to deal with doesn't need to be exposed out to the user. What the user cares about is: did the function succeed or not, and if not, are there cases that they can possibly recover from. A more sane interface might look like the following:
public class FileReader {
...
/**
* <p>Reads the file with the specified name and returns the
* contents in a {@link java.nio.ByteBuffer buffer}.</p>
*
* @param filename the name of the file to read
* @return an allocated (not direct) <code>ByteBuffer</code>
* with the contents of the file
* @throws NoSuchFileException if there is no file with the specified
* name
* @throws ReadFailedException if there was any unrecoverable
* problem while reading the file
*/
public ByteBuffer readFile(final String filename)
throws NoSuchFileException, ReadFailedException
{
...
}
...
}
This interface throws two exceptions: What's more is that by not throwing The next time that you are developing an interface, think about how a user will use that interface. Get into their shoes and think about their concerns. And most importantly, make sure that you're not breaking your own encapsulation. |
| Post a comment |
|
|
Unless otherwise expressly stated, all original material of whatever nature created by Rob Grzywinski and included in this weblog and any related pages, including the weblog's archives, is licensed under a Creative Commons License. |