Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Where shoul I throw RuntimeException

11 views
Skip to first unread message

dimka

unread,
May 20, 2009, 1:58:47 AM5/20/09
to
Hi all!
I want to know, where can I use runtime exceptions?
For example, I have method like this:
public String getNameById(long id) {
Connection connection = null;
Statement st = null;
try {
connection = getConnection();
st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT NAME WHERE id=" + id);
if (!rs.next()) {
//--->Here, I can return null, throw RuntimeException, throw
catched exception<---
}
return rs.getString(1);
} catch (SQLException e) {
//--->Here, I can return null, throw RuntimeException, throw
catched exception<---
} finally {
closeConnectionAndStatement(st, connection);
}
}

In this example, I can return null and describe this in javadoc for
method. But, when other developer use this method, he cann't get id
from somewhere, he must know that object with this id exist...
Ever, when I should make a choice, I cann't choose right answer :(
What do you think about this?

Antti Järvinen

unread,
May 20, 2009, 2:40:19 AM5/20/09
to
dimka <doom...@gmail.com> writes:
> Hi all!
> I want to know, where can I use runtime exceptions?
> For example, I have method like this:
> public String getNameById(long id) {
...

> In this example, I can return null and describe this in javadoc for
> method. But, when other developer use this method, he cann't get id
> from somewhere, he must know that object with this id exist...
> Ever, when I should make a choice, I cann't choose right answer :(
> What do you think about this?

This is c++ -paper but applies well here too:

http://chaos.troll.no/~shausman/api-design/api-design.pdf

About the actual question about if you should communicate nonexistence
via
- null pointer returning
- checked exception
- unchecked (runtime) exception
is your choise and all are technically possible. I'd say it more depends
on how your api will be used by others ; you could actually ask the
end users what they want. My personal preference here would be
the first option, null pointer but the checked exception is good candidate
also if you like writing try/catch blocks instead of if() statements.
I'd say that unchecked exceptions are a no-no because they're not
self-documenting as checked exceptions that you either need to catch
or pass to upper level (again as checked exceptions). For really
unexpected situations go on with unchecked exceptions, I've used them
in situations where the whole application is in such a state that
it needs to be killed due to big internal mess.. :)

--
Costello the Warrior St:18/09 Dx:14 Co:18 In:8 Wi:12 Ch:7 Neutral
Dlvl:16 $:0 HP:129(129) Pw:52(52) AC:-6 Xp:14/83896 T:19462 Satiated

charlesbos73

unread,
May 20, 2009, 7:03:50 AM5/20/09
to
On May 20, 6:58 am, dimka <dooma...@gmail.com> wrote:
> Hi all!
> I want to know, where can I use runtime exceptions?

If it's "where can I use unchecked exception versus
instead of checked exception?" the answer is "mostly
everywhere". Note the "mostly". Hard to argue with
that ;)


> What do you think about this?

Take a look at how other have "solved" that problem
instead of re-inventing another broken "I query my
SQL DB by hand" piece of code.

I'd start with Spring's very cleanly designed
JDBC abstraction layer.

The amazing Spring framework's philosophy explicitely
states the following:

- "OO design is more important than any implementation
technology, such as J2EE"

- "Checked exceptions are overused in Java. A framework
shouldn't force you to catch exceptions you're unlikely to
be able to recover from."

Instead of diving into a code-writing frenzy, read on
how others have dealt with that exact same issue.

To me using Java's null as a return value from a method
and using checked exception are basically the anti-thesis
of OO.

That's what I think about this, but it's unlikely to
be an appreciated view on this newsgroup by those
who worship every piece of crap that made it into
Java and who affectionate passionately the GOTO-style
programming provided by checked exceptions, etc.

Once again, I'm the lucky one happening to be using
Java to do real OOP (as in "translating a wonderful
OOD into Java") while most people are using it as
a glorified hybrid between Visual Basic and PHP
(to query relational DBs of course... Mindboggling :)


Arved Sandstrom

unread,
May 20, 2009, 10:25:26 AM5/20/09
to
charlesbos73 wrote:
[ SNIP ]

> To me using Java's null as a return value from a method
> and using checked exception are basically the anti-thesis
> of OO.

Would you care to point out why you believe that returning a null from a
method is an anti-OOP thing to do? I've run across articles where people
express that viewpoint, but I don't know what your reason is.

If nothing else, null expresses the concept of no object. If a method is
being asked to return a reference to an object, and there is no object
that can be returned, guess what? You return null. There is nothing more
appropriate to return. I imagine you probably have some system where you
avoid doing this, but it'll be artificial and clumsy.

Checked exceptions have problems, sure. The biggest problem is that bad
programmers swallow them, and the program breaks. Are checked exceptions
an _antithesis_ of OOP? Hardly. Reputable commentators who argue against
having checked exceptions don't go so far as to say that - they just say
they don't much like checked exceptions.

> That's what I think about this, but it's unlikely to
> be an appreciated view on this newsgroup by those
> who worship every piece of crap that made it into
> Java and who affectionate passionately the GOTO-style
> programming provided by checked exceptions, etc.

Here's a newsflash. If you had uniformly unchecked exceptions, and you
therefore were able to choose when and where to deal with them, how is
this not GOTO-style programming?

As for folks on this NG "worshipping every piece of crap" that is in
Java, you must be reading threads very selectively. Not one frequent
poster has failed to point out, from time to time, features of the
language that they don't like, that they think can be improved, or
features that they think should be added.

> Once again, I'm the lucky one happening to be using
> Java to do real OOP (as in "translating a wonderful
> OOD into Java") while most people are using it as
> a glorified hybrid between Visual Basic and PHP
> (to query relational DBs of course... Mindboggling :)

I'm happy for you that you are able to do "real" OOP in Java and the
rest of us cannot. I'll have to revisit all the Java coding I've done
since 1998 and examine it closely to see why it isn't object-oriented.
Perhaps if you posted some code snippets for us we'd be able to see what
we've been doing wrong.

As far as accessing RDBMS's goes, I guarantee you that if you post
typical code that you use in an OODBMS environment to manipulate
persistent objects, it'll look very similar to the code _I_ use to
manipulate persistent objects in a JPA environment. So please tell me
what's better about what you are doing.

AHS

Lew

unread,
May 20, 2009, 10:42:45 AM5/20/09
to
dimka wrote:
> I want to know, where can I use runtime exceptions?

Runtime exceptions - trap conditions the client programmer should have
known better than to cause. Example - NullPointerException for a null
argument. The programmer should not pass a null argument, and will
fix the code if they discover this exception.

Checked exceptions - trap conditions in order to force the client code
to deal with it, usually not due to misuse of the call but to
situations outside of the client code's control. Example -
SQLException for an unexpected database state. There really is
nothing wrong with the code, the database just happened to be in a
different state this time. The API writer anticipated this, and put
the exception into the method signature to make sure that the client
code handles these "expected exceptions". It is unlikely that such
code will be rewritten just because this exception happens, and
there's no need or desire to halt the program for it.

Return a default value such as 'null' - when it makes sense in the
business logic that the condition is not exceptional but maps cleanly
to the range of the method. Example - returning 'null' if a record is
not found. "Not found" is a normal and expected result of a search,
and the client code will have conditional logic for this eventuality.

> In this example, I can return null and describe this in javadoc [sic] for


> method. But, when other developer use this method, he cann't get id
> from somewhere, he must know that object with this id exist...

One period suffices to end a sentence.

If the method returns 'null' for an ID, doesn't that mean that no
object with this ID exists?

> Ever, when I should make a choice, I cann't choose right answer :(

The right answer is the one you decide is right.

The Zen answer is, "Do what makes sense for the situation." It might
be different each time.

Part of the business of the API writer, even for use in one's own
client code, is to determine how clients will use the API, and prevent
abuse of the API.

--
Lew

Lew

unread,
May 20, 2009, 11:00:30 AM5/20/09
to
charlesbos73 wrote:
>> To me using Java's null as a return value from a method
>> and using checked exception are basically the anti-thesis [sic]
>> of OO.
>

Arved Sandstrom wrote:
> Would you care to point out why you believe that returning a null from a
> method is an anti-OOP thing to do? I've run across articles where people
> express that viewpoint, but I don't know what your reason is.
>

If that were true, wouldn't returning any value be antithetical to
OOP?

> If nothing else, null expresses the concept of no object. If a method is
> being asked to return a reference to an object, and there is no object
> that can be returned, guess what? You return null. There is nothing more
> appropriate to return. I imagine you probably have some system where you
> avoid doing this, but it'll be artificial and clumsy.
>

'null' is sometimes used to signify something like "UNKNOWN" in a
three-valued logic, and often as a sentinel value. I agree that
there's nothing inherently un-OOPish about sentinel values. Their
signal characteristic is that they be out of band for the range of the
method; 'null' fulfills that condition sweetly.

> Checked exceptions have problems, sure. The biggest problem is that bad
> programmers swallow them, and the program breaks. Are checked exceptions
> an _antithesis_ of OOP? Hardly. Reputable commentators who argue against
> having checked exceptions don't go so far as to say that - they just say
> they don't much like checked exceptions.
>

I assess that people who dislike checked exceptions are those who
write client code that is forced to handle them. That is, of course,
the reason why checked exceptions exist - to force client code to deal
with them. Checked exceptions are an API writer's friend.

Client-code authors should embrace checked exceptions; when they're
defined appropriately, they strongly assist client code in anticipated
and handling certain conditions.

>> That's what I think about this, but it's unlikely to
>> be an appreciated view on this newsgroup by those
>> who worship every piece of crap that made it into
>> Java and who affectionate passionately the GOTO-style
>> programming provided by checked exceptions, etc.
>

Begging the question, straw-man argument and ad hominem remarks.

> Here's a newsflash. If you had uniformly unchecked exceptions, and you
> therefore were able to choose when and where to deal with them, how is
> this not GOTO-style programming?
>
> As for folks on this NG "worshipping every piece of crap" that is in
> Java, you must be reading threads very selectively. Not one frequent
> poster has failed to point out, from time to time, features of the
> language that they don't like, that they think can be improved, or
> features that they think should be added.
>

One of the distinguishing aspects of the Java programmers' culture is
that we don't drink the Kool-Aid. We're a curmudgeonly lot, all of us
convinced we could have designed it better and vocal in our opinions
of how to improve it. I know of few if any other programming
languages with a more devotedly whiny constituency.

>> Once again, I'm the lucky one happening to be using
>> Java to do real OOP (as in "translating a wonderful
>> OOD into Java") while most people are using it as
>> a glorified hybrid between Visual Basic and PHP
>> (to query relational DBs of course... Mindboggling :)
>

> I'm happy for you that you are able to do "real" OOP in Java and the
> rest of us cannot. I'll have to revisit all the Java coding I've done
> since 1998 and examine it closely to see why it isn't object-oriented.
> Perhaps if you posted some code snippets for us we'd be able to see what
> we've been doing wrong.
>
> As far as accessing RDBMS's goes, I guarantee you that if you post
> typical code that you use in an OODBMS environment to manipulate
> persistent objects, it'll look very similar to the code _I_ use to
> manipulate persistent objects in a JPA environment. So please tell me
> what's better about what you are doing.

The short answer is that what he's doing isn't actually better, just
another way.

--
Lew

Roedy Green

unread,
May 20, 2009, 2:23:58 PM5/20/09
to
On Tue, 19 May 2009 22:58:47 -0700 (PDT), dimka <doom...@gmail.com>
wrote, quoted or indirectly quoted someone who said :

see http://mindprod.com/jgloss/exception.html

You can throw them anywhere, so you might as well throw them as soon
as you discover the trouble.
--
Roedy Green Canadian Mind Products
http://mindprod.com

"If people become accustomed to lying, they will unconsciously commit every possible wrong deed. Before they can act wickedly, they must lie, and once they begin to lie they will act wickedly without concern."
~ Gautama Buddha

I V

unread,
May 20, 2009, 2:37:28 PM5/20/09
to
On Wed, 20 May 2009 08:00:30 -0700, Lew wrote:
> I assess that people who dislike checked exceptions are those who write
> client code that is forced to handle them. That is, of course, the
> reason why checked exceptions exist - to force client code to deal with
> them. Checked exceptions are an API writer's friend.

I'm kind of theoretically skeptical about Java's checked exceptions,
although the problem isn't the checking, but having to specify them,
which forces code that otherwise doesn't need to know about exceptions to
deal with them. The fact that exceptions propagate through layers until
they reach the appropriate level at which to handle them is one of their
advantages; forcing the author to specify exceptions at every level gets
in the way of that, cluttering the intermediate layers. The compiler
knows (or, could work out) what exceptions a method could throw, and it
could check they get handled without requiring they are specified
explicitly.

Having said that, I haven't actually found specifying exceptions to be as
much as a problem as I would have imagined. I'm coming round to the view
that the distinction between checked and unchecked exceptions reflects a
pretty real distinction between those exceptions that should be handled
close to where they occur, and those that don't.

Lew

unread,
May 20, 2009, 3:03:17 PM5/20/09
to
I V wrote:
> I'm kind of theoretically skeptical about Java's checked exceptions,
> although the problem isn't the checking, but having to specify them,
> which forces code that otherwise doesn't need to know about exceptions to
> deal with them.
>

That makes exactly as much sense as complaining that 'Baz foo( Bar
arg )' forces client code to use an argument of type 'Bar' and to deal
with a return type of 'Baz' when it otherwise wouldn't have to deal
with them.

The whole *point* of checked exceptions is to force client code to
deal with them.

> The fact that exceptions propagate through layers until


> they reach the appropriate level at which to handle them is one of their
> advantages; forcing the author to specify exceptions at every level gets
> in the way of that, cluttering the intermediate layers. The compiler

But that is the point of checked exceptions. If the API writer didn't
want the client to deal with them, he'd have used a runtime exception.

Checked exceptions exist for the very purpose of making client code
deal with them. Complaining that they do what they're designed to do
is very strange.

> knows (or, could work out) what exceptions a method could throw, and it
> could check they get handled without requiring they are specified
> explicitly.
>

That is a simplistic suggestion. The compiler cannot know what
subtypes' overrides might throw, and this suggestion wouldn't let the
API writer control exceptions as part of the method signature.
Remember that one of the design principles of Java is to support
strong typing and the concomitant type safety. Checked exceptions are
representative of that philosophy.

> Having said that, I haven't actually found specifying exceptions to be as
> much as a problem as I would have imagined. I'm coming round to the view
> that the distinction between checked and unchecked exceptions reflects a
> pretty real distinction between those exceptions that should be handled
> close to where they occur, and those that don't.

This is a false dichotomy.

The difference isn't where they're handled but whether the client code
should be forced to handle them. The rule of thumb is that runtime
exceptions require a code change in the client to eliminate them,
checked exceptions do not.

--
Lew

Thomas Pornin

unread,
May 20, 2009, 3:27:03 PM5/20/09
to
According to I V <ivl...@gmail.com>:

> The compiler knows (or, could work out) what exceptions a method could
> throw

Actually it cannot, in all generality. Consider this:

class A {

int foo()
{
return 42;
}
}

class B extends A {

int foo()
{
throw new RuntimeException();
}
}

class C {

static void bar(A a)
{
System.out.printf("%d\n", a.foo());
}
}

Here, the C.bar() method receives as argument a reference to an object
under the guise of "A". That object is an instance of A or a subclass
thereof (e.g. an instance of B). The compiler is fully aware that
A.foo() does not throw any exception. But when compiling C, the compiler
does not know whether it gets a "true" instance of A, or an instance of
a subclass, where the (overridden) foo() method may throw exceptions.
The B class could be written days or months _after_ C was compiled, and
yet the compiled C should be able to handle a reference to a B instance.

With checked exceptions, we get this:

class A {

int foo()
throws IOException
{
return 42;
}
}

class B extends A {

int foo()
throws IOException
{
throw new IOException();
}
}

(I am using IOException because this is, in my domain, the number 1
checked exception which has to be handled somewhere.)

Note that in order to make this code compilable, the A.foo() MUST be
declared with a "throws IOException" although that specific method
surely cannot throw an IOException. This highlights the difference
between the declaration ("throws IOException") and the possibility
that the method may actually throw such an exception.


Just as a reminder, the exception-checking mechanism is applied by the
compiler but not enforced by the JVM. It is possible to escape the
mechanism by some recompilation (in the example above, compile C with
regards to the definition of A which does not feature the "throws
IOException", then modify A and recompile it along with B in their
IOException-throwing variants, and load everything in an application).
Even with an application whose source code is all compiled in one go,
you can still throw uncontrolled checked exception with
Class.newInstance().


--Thomas Pornin

Tom Anderson

unread,
May 20, 2009, 6:34:34 PM5/20/09
to

I think that method should throw SQLException.

It definitely should not return null - that's almost never a good idea. It
shouldn't throw a RuntimeException, because that won't force the callers
to face up to the possiblity of failure. It could throw another checked
exception, perhaps a domain-specific one like DimkaDataLayerException,
rather an an SQLException. But what is certain - although others, who
labour in ignorance or sin, may disagree - is that it should throw a
checked exception. If there is a real possibility of failure, callers
should be made aware of it, and be made to prepare for it.

tom

--
I could tell you a great many more particulars but suppose that you are
tired of it by this time. -- John Backhouse, Trainspotter Zero

Lew

unread,
May 20, 2009, 11:21:16 PM5/20/09
to
Tom Anderson wrote:
> ...
> But what is certain
> - although others, who labour in ignorance or sin, may disagree - is
> that it should throw a checked exception.

Amen.

> If there is a real possibility
> of failure, callers should be made aware of it, and be made to prepare
> for it.

Spoken like a good API designer.

--
Lew

Karl Uppiano

unread,
May 21, 2009, 1:58:48 AM5/21/09
to

"I V" <ivl...@gmail.com> wrote in message
news:4a14...@news.x-privat.org...

> On Wed, 20 May 2009 08:00:30 -0700, Lew wrote:
>> I assess that people who dislike checked exceptions are those who write
>> client code that is forced to handle them. That is, of course, the
>> reason why checked exceptions exist - to force client code to deal with
>> them. Checked exceptions are an API writer's friend.
>
> I'm kind of theoretically skeptical about Java's checked exceptions,
> although the problem isn't the checking, but having to specify them,
> which forces code that otherwise doesn't need to know about exceptions to
> deal with them. The fact that exceptions propagate through layers until
> they reach the appropriate level at which to handle them is one of their
> advantages; forcing the author to specify exceptions at every level gets
> in the way of that, cluttering the intermediate layers. The compiler
> knows (or, could work out) what exceptions a method could throw, and it
> could check they get handled without requiring they are specified
> explicitly.

If you don't know how to deal with a checked exception, then you ignore it,
and declare that your method might "throw" it. Or you catch it, and re-throw
it as something that you want your API to throw. How else will you tell
*your* callers about it?

> Having said that, I haven't actually found specifying exceptions to be as
> much as a problem as I would have imagined. I'm coming round to the view
> that the distinction between checked and unchecked exceptions reflects a
> pretty real distinction between those exceptions that should be handled
> close to where they occur, and those that don't.

Yes, the Java designers were very thoughtful in realizing that there are
situations where you want checked exceptions, and ones where you don't. My
quibble is in the choice of the Java API making some exceptions checked that
I think should be unchecked, and vice versa -- e.g., we had a discussion
here about InterruptedException a while back. Not everyone agreed with me.
Most peculiar, mama!

Giovanni Azua

unread,
May 21, 2009, 6:20:08 AM5/21/09
to
Hi Dimka,

Some time ago I came across a quote that said something like "if your
country is ruled by a committee, be in that committee" being an expat from a
communist country this quote sounded very unpleasant to me but I think it
fits your question very well. Whenever I find myself in this same kind
dilemma I many times just dive into the Sun JDK API looking for similar
contexts and patterns to resolve the very same problem, they are the
"committee". You might also decide not to comply with the committee e.g. I
don't think that IllegalArgumentException should be used in the JDK in the
way it does now, the right tool should be assertions, because assertions
were added later to the language, I think from 1.4.x most likely this is a
backward compatibility issue.

"dimka" <doom...@gmail.com> wrote in message
> public String getNameById(long id) {
>
If there would be anything to throw even if it is a RuntimeException
subclass, you should make it explicit in the method declaration as "throws
XXXException" this will get documented in the javadocs and give your clients
some clue of what could go wrong.

> Connection connection = null;
> Statement st = null;
> try {
> connection = getConnection();
> st = connection.createStatement();
> ResultSet rs = st.executeQuery("SELECT NAME WHERE id=" + id);
> if (!rs.next()) {
> //--->Here, I can return null, throw RuntimeException, throw
> catched exception<---
>

See how Sun's JPA API resolves a similar issue:
http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html#find(java.lang.Class,%20java.lang.Object)

In this case they just return null. Now, beware that returning null is one
of the main causes of the very profane NullPointerException. There are ways
around it e.g. using the NullObject pattern but in this case that you return
a String the most sensitive thing to do would be returning null.
http://en.wikipedia.org/wiki/Null_Object_pattern

> }
> return rs.getString(1);
> } catch (SQLException e) {
> //--->Here, I can return null, throw RuntimeException, throw
>

If you see a catch, it is not a good idea to firstly just think what to
re-throw. You should rather first think hard what can you do at that point
to recover to fulfill the client's request. This is precisely the definition
of "Robustness" in Software Engineering "Robustness is the ability of
software systems to react appropriately to abnormal conditions" abnormal
conditions being Exceptions see Object Oriented Software Construction by
Bertrand Meyer.

Now, if there is nothing you can really do and you must really throw or
re-throw an exception, then from the design prospective it is not a good
idea to let the client of this code deal with inners of the persistence API,
the SQLException. You should rather throw to the client a more "service"
level-like exception e.g. PersonNotFoundException or at most DaoException

More on checked vs unchecked:

In EJB 3.0 the choice of checked vs. unchecked exceptions has strong
semantics compared to how it was before i.e. checked exceptions are assumed
by the EJB 3 specification to be "application exceptions" and when thrown
they will not rollback the transaction. Unchecked exceptions are assumed
"system exceptions" and when thrown they will cause the transaction to
rollback and even get the container to discard the Bean instance without not
even chance for disposal lifecycle callbacks i.e. @PreDestroy

I am not particularly fond of checked exceptions but I think this would be a
valid strategy to decide what the type of an exception should be. In a
"design by contract" approach a method would look like:

pre-conditions: conditions that the client must respect for the method to
fulfill its service e.g. arg1 must not be null
Method(arg1)
class-invariants: conditions that should be invariant during the lifetime of
an instance of the class
post-conditions: conditions or guarantees of the service offered by the
method e.g. in the case above that the name was found and is a valid name
not an empty string

Checked exceptions: because they force the client of the routine to handle
it, I would only make the client handle situations that they have control of
i.e. the pre-condition. The client is responsible for passing valid input,
so if they do not, they must be ready to fix it and retry. But notice that
the committee in this case decided IllegalArgumentException should be
unchecked and I don't blame them for that.

Unchecked exceptions: to signal that the Method could not fulfill its
promise, the client can do little about this, exactly the situation depicted
above. What can the client of "getNameById" possibly do with a SQLException?
nothing! If the client tried to fix it that would mean that the client would
be trying to do "getNameById"'s job in some way and this would break the
clean distribution of concerns leading to:

- tangled code: the client will not only implement business logic but also
low level persistence non-functional concerns
- scattered code: the same non functional concern is spread across many
disparate parties: Client, Dao, etc the right recipe for a nice spaghetti.

HTH,
Best regards,
Giovanni


Lew

unread,
May 21, 2009, 9:13:44 AM5/21/09
to
Giovanni Azua wrote:
> Some time ago I came across a quote that said something like "if your
> country is ruled by a committee, be in that committee" being an expat from a
> communist country this quote sounded very unpleasant to me but I think it
> fits your question very well. Whenever I find myself in this same kind
> dilemma I many times just dive into the Sun JDK API looking for similar
> contexts and patterns to resolve the very same problem, they are the
> "committee". You might also decide not to comply with the committee e.g. I
> don't think that IllegalArgumentException should be used in the JDK in the
> way it does now, the right tool should be assertions, because assertions
> were added later to the language, I think from 1.4.x most likely this is a
> backward compatibility issue.

That is very wrong. Assertions are not exceptions and cannot nor should not
be used for argument checking on public methods.

> If there would be anything to throw even if it is a RuntimeException
> subclass, you should make it explicit in the method declaration as "throws
> XXXException" this will get documented in the javadocs and give your clients
> some clue of what could go wrong.

No. It is useless to declare runtime exceptions in the signature, though it's
wise to Javadoc them.

Null makes sense in this particular case.

> In this case they just return null. Now, beware that returning null is one
> of the main causes of the very profane NullPointerException.

"Profane"?

> There are ways
> around it e.g. [sic] using the NullObject pattern but in this case that you return

> a String the most sensitive thing to do would be returning null.

Sometimes.

> http://en.wikipedia.org/wiki/Null_Object_pattern
...


> I am not particularly fond of checked exceptions but I think this would be a

I am particularly fond of checked exceptions.

> valid strategy to decide what the type of an exception should be. In a
> "design by contract" approach a method would look like:
>
> pre-conditions: conditions that the client must respect for the method to
> fulfill its service e.g. arg1 must not be null
> Method(arg1)
> class-invariants: conditions that should be invariant during the lifetime of
> an instance of the class
> post-conditions: conditions or guarantees of the service offered by the
> method e.g. in the case above that the name was found and is a valid name
> not an empty string

These are enforced by exception, proven by assertion.

--
Lew

Giovanni Azua

unread,
May 21, 2009, 9:58:34 AM5/21/09
to

"Lew" <no...@lewscanon.com> wrote in message
news:gv3k29$1oo$1...@news.albasani.net...

>> don't think that IllegalArgumentException should be used in the JDK in
>> the way it does now, the right tool should be assertions, because
>> assertions were added later to the language, I think from 1.4.x most
>> likely this is a backward compatibility issue.
>
> That is very wrong. Assertions are not exceptions and cannot nor should
> not be used for argument checking on public methods.
>
because ... ?

> No. It is useless to declare runtime exceptions in the signature, though
> it's wise to Javadoc them.
>

That must be why it is the standard in the JDK, see e.g. this same method
declares throws IllegalArgumentException and IllegalStateException both
RuntimeExceptions
http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html#find(java.lang.Class,%20java.lang.Object)

Giovanni


Eric Sosman

unread,
May 21, 2009, 10:47:33 AM5/21/09
to
Giovanni Azua wrote:
> "Lew" <no...@lewscanon.com> wrote in message
> news:gv3k29$1oo$1...@news.albasani.net...
>>> don't think that IllegalArgumentException should be used in the JDK in
>>> the way it does now, the right tool should be assertions, because
>>> assertions were added later to the language, I think from 1.4.x most
>>> likely this is a backward compatibility issue.
>> That is very wrong. Assertions are not exceptions and cannot nor should
>> not be used for argument checking on public methods.
>>
> because ... ?

Because they can be turned off at run-time, leaving you
with no validity-checking at all.

Here's a little experiment you might want to try. See
if you can explain why the compiler is happy with the first
method but complains about the second:

int method1(int x) {
if (x > 0) return x;
throw new IllegalArgumentException("bad x");
}

int method2(int x) {
if (x > 0) return x;
assert false : "bad x";
}

--
Eric....@sun.com

Giovanni Azua

unread,
May 21, 2009, 11:52:57 AM5/21/09
to
Hi Eric,

"Eric Sosman" <Eric....@sun.com> wrote
>> because ... ?
> Because they [assertions] can be turned off at run-time, leaving you with
> no validity-checking at all.
>
In general I disagree with this rule "do not use assertions to check the
parameters of a public method":
http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#usage-conditions

These would be the possible scenarios interacting with an API:

1-. Human to software interaction: end-user enters data
2-. External system to software interaction: binary interoperability of
separate components e.g. MOM
3-. Software to software interaction: a library e.g. JDK is being used to
develop some application

In cases #1 and #2 it is necessary to use exceptions e.g.
IllegalArgumentException to deal with *Input Validation*. This is because #1
and #2 are the front-line layers that deal with input outside the control of
the application. These are the "filter modules" to the outside world. Using
assertions to deal with Input Validation indeed would be wrong and "wishful
thinking" as Bertrand Meyer calls it.

Now point #3 is the case of application interacting with a library e.g. JDK.
There is no external wrong input to deal with but only programming errors, a
precondition violation is a programming error in the client of the routine
or class. Programming errors must be discovered during testing and debugging
cycles when assertions are enabled and not in production.

I just want to stress that there is a difference between Input Validation
and preconditions checks (assertions):
"Object Oriented Software Construction 2nd Edition" Bertrand Meyer, page 345
"Assertions are not an input checking mechanism".

I also included a note on this, see "Defensive Programming Approach":
http://perfectjpattern.sourceforge.net/design-notes.html

Best regards,
Giovanni


Eric Sosman

unread,
May 21, 2009, 12:38:41 PM5/21/09
to

In the context of a public method, I think any difference
between validation and precondition checking pretty much vanishes.
The writer of a public method (or protected) method has no control
over the method's callers, and can't even enumerate them (the
trouble with code re-use is that people re-use code). The argument
values provided by those callers are just as untrustworthy as data
read from any uncontrolled source, and should be given the same
kinds of screening. And, I believe, should provoke the same kind
of response if the screening detects anomalies.

Thought experiment: Should the array-accessing operation treat
the index value as an input to be validated, or as a precondition
whose validity has been established during the testing phase and
need not be checked thereafter? That is, would you be in favor of
checking indices with an assert-like mechanism that could be turned
off once the code had passed enough tests? Surely it's a programming
error if the code generates an invalid index; should the detection
of that error be suppressable?

Your distinction between validation and precondition checking
is, I think, a reasonable one to draw in private and package-
private methods. But a public or protected method is too "exposed"
to take advantage of such a distinction, and should IMHO treat all
inputs as coming from "the outside."

--
Eric....@sun.com

Giovanni Azua

unread,
May 21, 2009, 1:23:14 PM5/21/09
to
Hello Eric,

"Eric Sosman" <Eric....@sun.com> wrote in message


> Thought experiment: Should the array-accessing operation treat
> the index value as an input to be validated, or as a precondition
> whose validity has been established during the testing phase and
> need not be checked thereafter? That is, would you be in favor of
> checking indices with an assert-like mechanism that could be turned
> off once the code had passed enough tests? Surely it's a programming
> error if the code generates an invalid index; should the detection
> of that error be suppressable?
>

To be honest I'd personally prefer to spare all the worthless and expensive
validations and hence the [substantial?] performance overhead resulting from
this Defensive Programming approach when I know my code is throughly tested.
I really prefer here the C++ way, they assume you know what you are doing.
On the other hand, If you know your Java code is not well tested then you
would still have the choice to run it -ea in production ... though it would
be a very lame acknowledgement.

> Your distinction between validation and precondition checking
> is, I think, a reasonable one to draw in private and package-
> private methods. But a public or protected method is too "exposed"
> to take advantage of such a distinction, and should IMHO treat all
> inputs as coming from "the outside."
>

I believe this is a decision of the API or public method designer to make,
of whether the API in question is supposed to be exposed to "the outside" or
not. I find that the decision made in JDK to go for the defensive
programming approach is by all means very pragmatic but hinders those who
actually know what they are doing.

Best regards,
Giovanni


Lew

unread,
May 21, 2009, 2:33:47 PM5/21/09
to
Eric Sosman wrote:
>> Because they [assertions] can be turned off at run-time, leaving you with
>> no validity-checking at all.
>

Because, also, that is not the purpose of assertions. Assertions do
not validate, they prove that validation has been done.

> In general I disagree with this rule "do not use assertions to check the

> parameters of a public method":http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#usage-...

Then you are mistaken, and are completely misusing assertions.

Assertions exist to prove invariants. They are to prove that things
under the API writer's control have been handled, e.g., that an
exception has been thrown to prevent a bad parameter. They do not and
cannot substitute as public variable validators.

Giovanni Azua wrote:
> These would be the possible scenarios interacting with an API:
>
> 1-. Human to software interaction: end-user enters data
> 2-. External system to software interaction: binary interoperability of
> separate components e.g. MOM
> 3-. Software to software interaction: a library e.g. JDK is being used to
> develop some application
>
> In cases #1 and #2 it is necessary to use exceptions e.g.
> IllegalArgumentException to deal with *Input Validation*. This is because #1
> and #2 are the front-line layers that deal with input outside the control of
> the application. These are the "filter modules" to the outside world. Using
> assertions to deal with Input Validation indeed would be wrong and "wishful
> thinking" as Bertrand Meyer calls it.
>
> Now point #3 is the case of application interacting with a library e.g. JDK.
> There is no external wrong input to deal with but only programming errors, a
> precondition violation is a programming error in the client of the routine
> or class. Programming errors must be discovered during testing and debugging
> cycles when assertions are enabled and not in production.
>

While the principle is true, that does not change the fact that
assertions are not the right way to validate input. Exceptions
validate, assertions prove.

> I just want to stress that there is a difference between Input Validation
> and preconditions checks (assertions):
> "Object Oriented Software Construction 2nd Edition" Bertrand Meyer, page 345
> "Assertions are not an input checking mechanism".
>
> I also included a note on this, see "Defensive Programming Approach":http://perfectjpattern.sourceforge.net/design-notes.html

If that note promotes the same misconception about assertions that you
are spreading here, then you should study up on them and revise your
note.

Read and study Sun's little tutorial on the matter:
<http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html>

Among other things, it teaches:
> There are also a few situations where you should not use them:
> * Do not use assertions for argument checking in public methods.
> Argument checking is typically part of the published specifications
> (or contract) of a method, and these specifications must be obeyed
> whether assertions are enabled or disabled. Another problem with
> using assertions for argument checking is that erroneous arguments
> should result in an appropriate runtime exception (such as
> IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException).
> An assertion failure will not throw an appropriate exception.
>
> * Do not use assertions to do any work that your application
> requires for correct operation.
> Because assertions may be disabled, programs must not assume that the
> boolean expression contained in an assertion will be evaluated.
> Violating this rule has dire consequences.

Suggesting otherwise does a huge disservice to anyone who believes
you.

--
Lew

Lew

unread,
May 21, 2009, 2:43:33 PM5/21/09
to
Giovanni Azua wrote:
> To be honest I'd personally prefer to spare all the worthless and expensive
> validations and hence the [substantial?] performance overhead resulting from
> this Defensive Programming approach when I know my code is throughly tested.
> I really prefer here the C++ way, they assume you know what you are doing.
> On the other hand, If you know your Java code is not well tested then you
> would still have the choice to run it -ea in production ... though it would
> be a very lame acknowledgement.
>

This is an erroneous argument. No matter how well tested your code
is, you cannot test other people's code that they haven't yet
written. All you can do is put in validation checks, using exceptions
or default return values. You use assertions to prove that your
validation checks are correct, as part of your thorough testing, not
as a replacement for validation checks.

Calling someone's code "lame" because they programmed against someone
else's future misuse is in itself quite lame.

> I believe this is a decision of the API or public method designer to make,
> of whether the API in question is supposed to be exposed to "the outside" or
> not. I find that the decision made in JDK to go for the defensive
> programming approach is by all means very pragmatic but hinders those who
> actually know what they are doing.

An API writer has the responsibility to enforce proper use of the code
in the public, your disingenuous redefinition of the word "public"
notwithstanding. Structure does not "hinder" those who "know what
they are doing", a set one excludes oneself from by misrepresenting
the purpose of assertions. On the contrary, structure supports those
who know what they're doing by providing guarantees of certain
behaviors, sparing the client code from having to do such thing on the
API's behalf.

Also, merely characterizing argument checking and such techniques as
"defensive programming" and then disparaging it by arrogating some
special knowledge to oneself puts the cart before the horse. Properly-
written APIs are pre-emptive programming, not defensive - they rigidly
enforce a contract on which client code can then rely. This is not
some psychological condescension to less-experienced programmers, as
you falsely present it. It's rigorous coding to prevent bugs as a
safety guarantee to all future use of the API, even if it is strictly
within a single project. It is properly the province of a method or
class to enforce its own invariants, and not be all loosey-goosey on
the client code only then to blame the other programmer in the event
of error. It is the proper allocation of responsibility to do what
you so disparagingly call "defensive programming".

As those who actually know what they are doing well know.

--
Lew

Lew

unread,
May 21, 2009, 2:52:04 PM5/21/09
to
Side note: in my earlier poast the single-">" quote are from Giovanni
Azua, not Eric Sosman unless specified to be from the Sun document on
assertions.

Giovanni Azua wrote:
>> In general I disagree with this rule "do not use assertions to check the
>> parameters of a public method":
>> <http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html>
>

I was astounded to realize that you were citing the same document that
disproves your comments about assertions that I cited via a different
link. Your link is the more modern one. You should read that
document again until you realize why they say what they say.

Lew wrote:
> Then you are mistaken, and are completely misusing assertions.

Giovanni Azua wrote:
>> I also included a note on this, see "Defensive Programming Approach":http://perfectjpattern.sourceforge.net/design-notes.html

Based on what you write here, and on a few things I read on that site,
I am going to keep a good healthy distance from the "Perfect
JPattern".

--
Lew

Giovanni Azua

unread,
May 21, 2009, 5:02:38 PM5/21/09
to

"Lew" <l...@lewscanon.com> wrote in message

> This is an erroneous argument. No matter how well tested your code
> is, you cannot test other people's code that they haven't yet written.
>
LOL indeed you can't, they should test it themselves :)

> All you can do is put in validation checks, using exceptions
> or default return values. You use assertions to prove that your
> validation checks are correct, as part of your thorough testing, not
> as a replacement for validation checks.
>

I think this is wrong. Besides, assertions were introduced in Java as an
"informal" design by contract:
"While the assert construct is not a full-blown design-by-contract facility,
it can help support an informal design-by-contract style of programming."
http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html

You need to understand design-by-contract and judging by your explanations I
think you don't.

> Calling someone's code "lame" because they programmed against someone
> else's future misuse is in itself quite lame.
>

No. I said lame because enabling -ea in production would mean that the code
was not tested well and would be quality-wise inadequate to roll into
production. It is in fact not uncommon to see projects rolled into
production with -ea enabled and it is always rooted by concerns about the
lack of quality.

> An API writer has the responsibility to enforce proper use of the code
> in the public, your disingenuous redefinition of the word "public"

> [snip]


> "defensive programming" and then disparaging it by arrogating some
> special knowledge to oneself puts the cart before the horse. Properly-

> [snip]
>
Fallacies, you are a notorious master in this area. It is a pity because you
keep undermining what would otherwise be very interesting discussions. I
don't mind if you don't understand some of the arguments, I am happy to
clarify and help but your rhetorical behavior is far from useful.

> Based on what you write here, and on a few things I read on that site,
> I am going to keep a good healthy distance from the "Perfect
> JPattern".
>

I don't think you even read properly what I wrote, because the design notes
explain that PerfectJPattern complies to the JDK design principles explained
under http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html
therefore if you are saying that because of what I wrote there you don't
want to use it, it does not really make much sense.

Another very different thing is how I believe validation and assertions
should be used based on what I know about design-by-contract and this was
the main topic being discussed.

Best regards,
Giovanni


Eric Sosman

unread,
May 21, 2009, 5:18:30 PM5/21/09
to
Giovanni Azua wrote:
> Hello Eric,
>
> "Eric Sosman" <Eric....@sun.com> wrote in message
>> Thought experiment: Should the array-accessing operation treat
>> the index value as an input to be validated, or as a precondition
>> whose validity has been established during the testing phase and
>> need not be checked thereafter? That is, would you be in favor of
>> checking indices with an assert-like mechanism that could be turned
>> off once the code had passed enough tests? Surely it's a programming
>> error if the code generates an invalid index; should the detection
>> of that error be suppressable?
>>
> To be honest I'd personally prefer to spare all the worthless and expensive
> validations and hence the [substantial?] performance overhead resulting from
> this Defensive Programming approach when I know my code is throughly tested.
> I really prefer here the C++ way, they assume you know what you are doing.
> On the other hand, If you know your Java code is not well tested then you
> would still have the choice to run it -ea in production ... though it would
> be a very lame acknowledgement.

Checking array indices for validity is "worthless?"

Testing can prove code to be bug-free?

How long was the voyage from your planet?

>> Your distinction between validation and precondition checking
>> is, I think, a reasonable one to draw in private and package-
>> private methods. But a public or protected method is too "exposed"
>> to take advantage of such a distinction, and should IMHO treat all
>> inputs as coming from "the outside."
>>
> I believe this is a decision of the API or public method designer to make,
> of whether the API in question is supposed to be exposed to "the outside" or
> not.

If the API is not to be exposed, it has to be private or at the
very least package-private. Anything that's public or protected *is*
exposed, and there's no way to prevent or even limit the exposure.
Yes, the designer has the freedom to choose the level of exposure he
thinks is appropriate -- but if he tags a method as `public', he's
voted for wide-open exposure and should code accordingly.

--
Eric....@sun.com

Eric Sosman

unread,
May 21, 2009, 5:21:07 PM5/21/09
to
Lew wrote:
> Eric Sosman wrote:
>> [...]

>> In general I disagree with this rule "do not use assertions to check the
>> parameters of a public method":http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#usage-...

That was Giovanni Azua's statement, not mine.

--
Eric....@sun.com

Lew

unread,
May 21, 2009, 5:53:34 PM5/21/09
to
Lew wrote:
>> All you can do is put in validation checks, using exceptions
>> or default return values.  You use assertions to prove that your
>> validation checks are correct, as part of your thorough testing, not
>> as a replacement for validation checks.
>

Giovanni Azua wrote:
> I think this is wrong.
>

It is a paraphrase of what Sun's document says. It is also consistent
with every expert document on assertions that I've seen, not limited
to the Java implementation thereof. Sun's document explicitly teaches
that assertions are not to be used to check argument validity for
public methods. I've quoted the relevant text from that document
upthread.

One pattern is to assert after possibly throwing an exception.

if ( arg == null )
{
throw new NullPointerException( "Null arg not allowed." );
}
assert arg != null;

Giovanni Azua wrote:
> Besides, assertions were introduced in Java as an "informal" design by contract:

Assertions are part of a *formal* design-by-contract methodology.

> "While the assert construct is not a full-blown design-by-contract facility,
> it can help support an informal design-by-contract style of programming."http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html
>

That supports what I'm saying.

> You need to understand design-by-contract and judging by your explanations I
> think you don't.
>

Huh?

Your judgment is awry. I'm explaining how asserts support design by
contract, in conjunction with exceptions and other mechanisms.

Lew wrote:
>> Calling someone's code "lame" because they programmed against someone
>> else's future misuse is in itself quite lame.
>

Giovanni Azua wrote:
> No. I said lame because enabling -ea in production would mean that the code
> was not tested well and would be quality-wise inadequate to roll into
> production. It is in fact not uncommon to see projects rolled into
> production with -ea enabled and it is always rooted by concerns about the
> lack of quality.
>

You need evidence to support that those concerns are the reason to
leave assertions enabled.

Enabling assertions in production, while not usually necessary, is
not /prima facie/ evidence of poor code quality.

You also invalidate your own earlier claim that assertions can be used
to validate inputs in a public method. If assertions are disabled in
production, as you and I agree they normally should be, they will not
work as a validation mechanism.

Lew wrote:
>> An API writer has the responsibility to enforce proper use of the code
>> in the public, your disingenuous redefinition of the word "public"
>> [snip]
>> "defensive programming" and then disparaging it by arrogating some
>> special knowledge to oneself puts the cart before the horse.  Properly-
>> [snip]
>

Giovanni Azua wrote:
> Fallacies, you are a notorious master in this area. It is a pity because you
> keep undermining what would otherwise be very interesting discussions. I
>

I'm only "undermining" your incorrect statements. I don't agree that
allowing misinformation to stand is synonymous with "interesting".

An API writer does have the responsibility to enforce proper use of
the library. That is not fallacy, that's a well-dcoumented best
practice. Are you seriously suggesting that an API writer not ensure
that the API fulfill its contract? Such a claim would violate a basic
tenet of design-by-contract.

You labeled careful programming "defensive programming" - that was
your label, and then you disparaged it. That is not fallacy. Many
would say that "defensive programming" is a good thing.

You disagree that disparaging "defensive programming" puts the cart
before the horse. Fine, but that doesn't establish that I am in any
way being "notorious". Your use of such a pejorative without
addressing the actual points I made is a logical fallacy in and of
itself.

Giovanni Azua wrote:
> don't mind if you don't understand some of the arguments, I am happy to
> clarify and help but your rhetorical behavior is far from useful.
>

Nice piece of arrogant condescension there. Thank you ever so very
much for your oh-so-kind offer. I understood your arguments
perfectly, thank you, as my responses clearly show.

The fact that I disagree with some of your points, and have provided
substantive evidence in support of my claims, does not betray a lack
of understanding of the arguments, at least not on my part. That you
have to resort to such /ad hominem/ rhetoric on your part indicates
that you do not have a strong argument.

So far your only actual refutation of my point is to state that you do
not agree with the material in the Sun document that explains the
correct use of assertions. I think I'll go with Sun and other writers
on that issue. All the rest of your arguments have boiled down to
attaching a favorable label like "design-by-contract" to your
statements, even though those statements directly contradict some of
the principles embodied in that label.

> I don't think you even read properly what I wrote, because the design notes
> explain that PerfectJPattern complies to the JDK design principles explained
> underhttp://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html

Your notes aver that it complies with those standards. It's another
question whether it actually does.

> therefore if you are saying that because of what I wrote there you don't
> want to use it, it does not really make much sense.

I am saying that because you wrote that assertions should be used to
check public-method arguments, rather than to confirm that such a
check worked, I do not trust your insights. I am saying that because
you wrote that design-by-contract implies that code should not enforce
that contract, I do not trust your insights. In other words, I am
saying that because what you wrote is patently incorrect, I would not
trust your code.

> Another very different thing is how I believe validation and assertions
> should be used based on what I know about design-by-contract and this was
> the main topic being discussed.

You have not really said things that cohere with the principles of
design-by-contract, a concept I understand very well, thank you. What
you have said, that assertions can and should be used to check
argument validity in public methods, is flat-out wrong. You also said
that APIs do not need to perform rigorous checks to enforce their own
contract, but should rely on client programmers being people who
"actually know what they are doing", which is directly antithetical to
the design-by-contract philosophy. I pointed out that design-by-
contract actually calls for APIs to rigorously enforce the promises
that they make; that's little more than a paraphrase of a basic design-
by-contract tenet.

So go ahead and disparage my understanding and make unsupported claims
that you are following principles that your every utterance
contradicts. You have made a couple of extremely inaccurate
characterizations regarding the use of assertions and design-by-
contract that I have refuted with evidence and example. Your
responses attack my comprehension but leave my conclusions
unchallenged by anything stronger than, "I disagree with the experts
you've cited".

Summary:

Assertions are neither intended for nor effective at run-time
validations for public arguments. Their purpose is to prove
invariants.

Design-by-contract calls for an API to enforce its own promises, not
to depend on expertise inaccurately claimed by a proponent and
demanded of putative client programmers. The statements otherwise
contradict the principles of design-by-contract.

Assertions do, as you say, support design-by-contract, but not by
enforcing the contract, rather by proving that enforcement was
successful.

--
Lew

Lew

unread,
May 21, 2009, 5:59:09 PM5/21/09
to
Lew wrote:
>>> [...]
>>> In general I disagree with this rule "do not use assertions to check the
>>> parameters of a public method":
<http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html>
>

Eric Sosman <Eric.Sos...@sun.com> wrote:
>      That was Giovanni Azua's statement, not mine.

That is why I wrote in a follow-up:
> Side note: in my earlier post the single-">" quote are from


> Giovanni Azua, not Eric Sosman unless specified to be from
> the Sun document on assertions.

I apologize for the misattribution. I trusted the automatic quoting
mechanism and forgot to double-check it.

Of course you would not have said anything so fundamentally mistaken.

--
Lew

Giovanni Azua

unread,
May 21, 2009, 6:05:12 PM5/21/09
to
"Eric Sosman" <Eric....@sun.com> wrote

> Checking array indices for validity is "worthless?"
>
Using defensive validation I respectfully disagree with you, in my view it
is not more optimal than using assertions or design-by-contract. The
defensive validation alternative is very pragmatic but comes at a cost:
performance.

> Testing can prove code to be bug-free?
>

Indeed it can't, but neither can doing input validation in every API layer
nor defensive programming. There is no silver bullet solution for this
problem but correct use of either approach will minimize the risk.

--
Giovanni

Eric Sosman

unread,
May 21, 2009, 6:27:27 PM5/21/09
to
Lew wrote:
> [...]

> Giovanni Azua wrote:
>> No. I said lame because enabling -ea in production would mean that the code
>> was not tested well and would be quality-wise inadequate to roll into
>> production. It is in fact not uncommon to see projects rolled into
>> production with -ea enabled and it is always rooted by concerns about the
>> lack of quality.
>
> You need evidence to support that those concerns are the reason to
> leave assertions enabled.
>
> Enabling assertions in production, while not usually necessary, is
> not /prima facie/ evidence of poor code quality.

Also, if assertions are misused as validators, it's quite likely
that you'll need to enable assertions in class BugFree in order to
catch misuses originating in class BugRidden. I don't see how this
would tag BugFree with the "lame" label (beyond the lameness inherent
in its misuse of assertions, that is).

--
Eric....@sun.com

Giovanni Azua

unread,
May 21, 2009, 6:54:02 PM5/21/09
to

"Lew" <l...@lewscanon.com> wrote

>> You use assertions to prove that your validation checks
>> are correct
>
> It is a paraphrase of what Sun's document says. It is
> also consistent with every expert document on assertions
>
No, it is not part of the document I referred to:
http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html

> Assertions are part of a *formal* design-by-contract
> methodology.
>

Not true, design-by-contract has e.g. subcontracting inheritance semantics,
and assertions do not
http://archive.eiffel.com/doc/manuals/technology/contract/page.html see "8-
Contracts and Inheritance". If you knew design-by-contract you would also
know that. This is why I said it is informal support quoted directly from
the document above "While the assert construct is not a full-blown

design-by-contract facility, it can help support an informal
design-by-contract style of programming".

>> You need to understand design-by-contract and judging by your

>> explanations I
>> think you don't.
>>
>Huh?
>

Indeed you don't.

>You also invalidate your own earlier claim that assertions can be used
>to validate inputs in a public method. If assertions are disabled in
>production, as you and I agree they normally should be, they will not
>work as a validation mechanism.
>

This proofs just one more time that you don't understand the concept of
what's being discussed. Assertions are enabled while testing so, when you
are sure that such public method will under no circumstance ever receive a
e.g. null value then you roll into production with assertions disabled
because the assertion check is not necessary in production e.g. some
filtering API layer way above may ensure this.

>I'm only "undermining" your incorrect statements. I don't agree that
>allowing misinformation to stand is synonymous with "interesting".
>

No, you are only deceiving big time.

I would sincerely recommend anyone interested in the topic to look into the
authoritative source and make your own conclusions rather than following the
Lew's simplified summary of what is what:
http://www.amazon.com/Object-Oriented-Software-Construction-Prentice-Hall-International/dp/0136291554/ref=sr_1_1?ie=UTF8&s=books&qid=1242945595&sr=8-1

--
Giovanni


Giovanni Azua

unread,
May 21, 2009, 7:04:32 PM5/21/09
to

"Eric Sosman" <Eric....@sun.com> wrote

> Also, if assertions are misused as validators, it's quite likely
>
I never suggested this, in fact, the first thing I did was to break down the
cases: real input validation vs. preconditions check

> that you'll need to enable assertions in class BugFree in order to
> catch misuses originating in class BugRidden. I don't see how this
> would tag BugFree with the "lame" label

Can't happen because you tested BugRidden too, remember? unless we are
talking meta-programing here, are we?

--
Giovanni


Seamus MacRae

unread,
May 21, 2009, 8:26:58 PM5/21/09
to
Giovanni Azua wrote:
> Hi Eric,
>
> "Eric Sosman" <Eric....@sun.com> wrote
>>> because ... ?
>> Because they [assertions] can be turned off at run-time, leaving you with
>> no validity-checking at all.
>>
> In general I disagree with this rule "do not use assertions to check the
> parameters of a public method":
> http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html#usage-conditions
>
> These would be the possible scenarios interacting with an API:
>
> 1-. Human to software interaction: end-user enters data
> 2-. External system to software interaction: binary interoperability of
> separate components e.g. MOM
> 3-. Software to software interaction: a library e.g. JDK is being used to
> develop some application
>
> In cases #1 and #2 it is necessary to use exceptions e.g.
> IllegalArgumentException to deal with *Input Validation*.

I disagree. Input validation (of interactive applications) should occur
using conditionals and divergent behavior in the presentation layer. For
instance if (i > 99) JOptionPane.blahblahblah("Size is too big; maximum
99")etc.etc.etc.return; else
somethingInBusinessLayer.doSomethingWith(i); (maybe make it localizable
by using message bundle).

IllegalArgumentException, and other RuntimeExceptions, should be thrown
by your public methods when there's a bug in the code, generally
indicated by a precondition violated. If the promise can't be kept
(postcondition violated) despite preconditions being met throw a checked
exception (IOException for example). Asserts can be used in private
methods to check preconditions, and throughout to check invariants and,
before returning but after any checked exception throws haven't
happened, postconditions.

DAL methods that get data from the outside world also need to deal with
errors or invalid data. Files not found or in an unexpected format, for
instance. When the DAL fails that's generally a postcondition failure;
IOException is a good generic exception to throw. It could be a
precondition failure (wrong file name, say) but if the file name came
from other external data, I say that's still in IOException territory.

The general pattern should be:

If the error is in code and the preconditions were met or the method is
private to my code, I should use an assert.

If the error is in calling code and the method is part of a public API,
I should use a RuntimeException. If it's a precondition violation and an
argument is bad, IllegalArgumentException is good. If it's a
precondition violation and the precondition violated has to do with the
object's internal state rather than an argument, IllegalStateException
is good.

If the error is in user input, the user interface should be used, rather
than exceptions, to handle it, and the bad input should never reach the
business layer. (If it ever does, the business layer should throw
IllegalArgumentException or similar as per the above.)

If the error is in other external-source data, IOException or a similar
checked exception should be used. If there are errors in taking actions
that involve the filesystem, network, interprocess communications,
databases, or similarly, a checked exception should be used. The DAL can
try to work around the problem but should throw a checked exception up
to the business layer if it can't make headway with a request. The base
type of these last exceptions should probably be your own
general-purpose DAL exception type or else IOException. Catch something
else and rethrow using a constructor that takes a "cause" if need be.

At least, this is my opinion, as a longtime Java developer.

> Using assertions to deal with Input Validation indeed would be wrong
> and "wishful thinking" as Bertrand Meyer calls it.

Agreed here.

> Now point #3 is the case of application interacting with a library e.g. JDK.
> There is no external wrong input to deal with but only programming errors, a
> precondition violation is a programming error in the client of the routine
> or class. Programming errors must be discovered during testing and debugging
> cycles when assertions are enabled and not in production.

This is debatable. The currently generally used best practices use
RuntimeException rather than assertions, but this tradition was
established before Java had assertions. The case could be made, but then
it would make sense to replace most or all RuntimeExceptions (and
Errors) with asserts and just have AssertionError, VMError, OOME, and
(checked) Exception. Well, were it not for backwards compatibility.

Seamus MacRae

unread,
May 21, 2009, 8:32:57 PM5/21/09
to
Giovanni Azua wrote:
> Hello Eric,
>
> "Eric Sosman" <Eric....@sun.com> wrote in message
>> Thought experiment: Should the array-accessing operation treat
>> the index value as an input to be validated, or as a precondition
>> whose validity has been established during the testing phase and
>> need not be checked thereafter? That is, would you be in favor of
>> checking indices with an assert-like mechanism that could be turned
>> off once the code had passed enough tests? Surely it's a programming
>> error if the code generates an invalid index; should the detection
>> of that error be suppressable?
>>
> To be honest I'd personally prefer to spare all the worthless and expensive
> validations and hence the [substantial?] performance overhead resulting from
> this Defensive Programming approach when I know my code is throughly tested.
> I really prefer here the C++ way, they assume you know what you are doing.

The C++ way leads to buffer overflow vulnerabilities and thence to madness.

When security is at stake, un-disablable runtime checks are desired. So,
RuntimeException rather than assert there for sure.

Also, premature optimization is the root of all evil. You'd really only
want to be able to turn off validations in innermost loops and
oft-called methods anyway (and still validate everything just before
going into the loops). Even validation in innermost loops is probably
not an issue. If the code has array accesses, is thoroughly tested, and
is bug-free, for example, the bounds check should never fire, and modern
CPUs typically do pipelining and branch prediction, so ...

Lew

unread,
May 21, 2009, 8:37:33 PM5/21/09
to
Lew wrote:
>> No. It is useless to declare runtime exceptions in the signature, though
>> it's wise to Javadoc them.

Giovanni Azua wrote:
> That must be why it is the standard in the JDK, see e.g. [sic] this same method

> declares throws IllegalArgumentException and IllegalStateException both
> RuntimeExceptions
> http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html#find(java.lang.Class,%20java.lang.Object)

That method does not declare runtime exceptions.

Note that the exceptions are Javadoced, as I said is wise, and not in the
signature. Compare with
<http://java.sun.com/javase/6/docs/api/java/io/File.html#createNewFile()>
which declares one exception and Javadocs two, the first being checked and the
other not.

--
Lew

Lew

unread,
May 21, 2009, 8:49:27 PM5/21/09
to
Eric Sosman wrote

>> that you'll need to enable assertions in class BugFree in order to
>> catch misuses originating in class BugRidden. I don't see how this
>> would tag BugFree with the "lame" label

Giovanni Azua wrote:
> Can't happen because you tested BugRidden too, remember? unless we are
> talking meta-programing here, are we?

Again, every client for all time must be bug free to obviate the need for the
API to validate, and there's no way to guarantee that. The purpose of
guarding input is to validate inputs from future unpredictable sources. In
order for the API, and that means any public or protected method of a public
class, to adhere to the principles of design-by-contract, that API must
enforce the contract.

--
Lew

Seamus MacRae

unread,
May 21, 2009, 8:53:58 PM5/21/09
to
Giovanni Azua wrote:
> "Lew" <l...@lewscanon.com> wrote

>> I'm only "undermining" your incorrect statements. I don't agree that
>> allowing misinformation to stand is synonymous with "interesting".
>
> No, you are only deceiving big time.

Ah. I see that "Lew" has managed to turn yet another thread into an
incipient flamewar. Not only has be called Giovanni a liar twice (in
<5e807185-c860-4264...@p4g2000vba.googlegroups.com>,
using the terms "disingenuous" and "misrepresenting"), but now Giovanni
has been sufficiently provoked to turn right around and call "Lew" one.

That other thread started flaming big-time after, and only after, "Lew"
began to participate heavily, too; until then it had been only
moderately uncivil here and there and it has maybe calmed back down some
since he left it.

Seamus MacRae

unread,
May 21, 2009, 9:03:50 PM5/21/09
to
Lew wrote:
> Lew wrote:
>>>> [...]
>>>> In general I disagree with this rule "do not use assertions to check the
>>>> parameters of a public method":
> <http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html>
>
> Eric Sosman <Eric.Sos...@sun.com> wrote:
>> That was Giovanni Azua's statement, not mine.
>
> That is why I wrote in a follow-up:
>> Side note: in my earlier post the single-">" quote are from
>> Giovanni Azua, not Eric Sosman unless specified to be from
>> the Sun document on assertions.
>
> I apologize for the misattribution. I trusted the automatic quoting
> mechanism and forgot to double-check it.

Perhaps instead of manually rearranging the attributions like you often
do (but sometimes forget to do), you should let your newsreader do it?

In the earlier post your newsreader would've made

Giovanni wrote:
> Eric Sossman wrote:
> > Thing Eric wrote

insert your text here

> Stuff Giovanni wrote
> Stuff Giovanni wrote
> Stuff Giovanni wrote

more comments here.

You went to do your usual edits to change to

Eric Sossman wrote:
> > Thing Eric wroe

inserted text

Giovanni wrote:
> Stuff Giovanni wrote
> Stuff Giovanni wrote
> Stuff Giovanni wrote

and forgot to insert the "Giovanni wrote:".

Most of us just let the newsreader attribute as it usually does. I don't
see the point in rearranging things, except maybe if far down a long
post you have a deeply nested quoted bit you don't want to trim and it's
not the case that it's the same two people alternating at least to that
depth. And then it might be better to *copy* some of the attributions
from the top, rather than *move* them.

Lew

unread,
May 21, 2009, 9:18:10 PM5/21/09
to
Giovanni Azua wrote:
> "Lew" <l...@lewscanon.com> wrote
>>> You use assertions to prove that your validation checks
>>> are correct
>> It is a paraphrase of what Sun's document says. It is
>> also consistent with every expert document on assertions
>>
> No, it is not part of the document I referred to:
> http://java.sun.com/j2se/1.5.0/docs/guide/language/assert.html

That document says:
"... place an assertion at any location you assume will not be reached."

That would be a place that your validation checks force to be bypassed if
input is invalid.

> void foo() {
> for (...) {
> if (...)

Here is the validation check.

> return;
> }
> assert false; // Execution should never reach this point!

Here is the assertion that proves the validation check is correct.

> }

And later,
> public BigInteger modInverse(BigInteger m) {
> if (m.signum <= 0)
> throw new ArithmeticException("Modulus not positive: " + m);

Here is the validation check.

> ... // Do the computation
> assert this.multiply(result).mod(m).equals(ONE) : this;

And here is the assertion that proves it.

> return result;

As you can see, my description of assertions as proof of a validation step is
a paraphrase of the information in that document.

>> Assertions are part of a *formal* design-by-contract
>> methodology.
>>

> Not true, design-by-contract has e.g. [sic] subcontracting inheritance semantics,

Interestingly, that same website, at
<http://archive.eiffel.com/doc/online/eiffel50/intro/language/invitation-07.html>
says,
> Eiffel encourages software developers to express formal properties
> of classes by writing assertions

As you can see, while assertions certainly can be used informally, they are
also part of a formal approach. As you would know if you yourself knew about
design-by-contract, or even thoroughly read the very sources you cite.

> Contracts and Inheritance". If you knew design-by-contract you would also
> know that.

Clearly I do know design-by-contract, as evidenced by the very authorities to
whom you yourself appeal.

>>> You need to understand design-by-contract and judging by your
>>> explanations I
>>> think you don't.
>>>
>> Huh?
>>
> Indeed you don't.

And yet I have been able to support my claims with direct evidence instead of
/ad hominem/ attacks, even using your own authorities.

Consider
<http://c2.com/cgi/wiki?DesignByContract>
> Design By Contract (DbC) is a software correctness methodology.
> It uses preconditions and postconditions to document
> (or programmatically assert)

Note well!

> the change in state caused by a piece of a program.

>> You also invalidate your own earlier claim that assertions can be used
>> to validate inputs in a public method. If assertions are disabled in
>> production, as you and I agree they normally should be, they will not
>> work as a validation mechanism.
>>
> This proofs just one more time that you don't understand the concept of
> what's being discussed. Assertions are enabled while testing so, when you
> are sure that such public method will under no circumstance ever receive a

> e.g. [sic] null value then you roll into production with assertions disabled

But you can never be sure of that! You have no control over how client code
will call the method. No matter how much you test a method that should not
accept a 'null', it could still happen in production, and if you do not
protect against that with an actual runtime check, your code will bomb.

That's the reason why assertions do not protect public methods, and why the
Sun document and everyone who "actually knows what they're doing" decries your
advice.

> because the assertion check is not necessary in production e.g. [sic] some

> filtering API layer way above may ensure this.

Design-by-contract, as evidenced by the authorities cited, would have the
preconditions and postconditions enforced by the API code itself.

Lew:


>> I'm only "undermining" your incorrect statements. I don't agree that
>> allowing misinformation to stand is synonymous with "interesting".

Giovanni:


> No, you are only deceiving big time.

I keep providing evidence, source after source, and you keep insulting me.

> I would sincerely recommend anyone interested in the topic to look into the
> authoritative source and make your own conclusions rather than following the
> Lew's simplified summary of what is what:
> http://www.amazon.com/Object-Oriented-Software-Construction-Prentice-Hall-International/dp/0136291554/ref=sr_1_1?ie=UTF8&s=books&qid=1242945595&sr=8-1

Allow me to cite yet more authoritative sources:
<http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ317_005.htm>
<http://en.wikipedia.org/wiki/Assertion_(computing)>
particularly
<http://en.wikipedia.org/wiki/Assertion_(computing)#Assertions_in_design_by_contract>

Note that the Wikipedia article's Java example does exactly what I describe:
validates a condition with the 'if' statement, then proves it with the 'assert'.

<http://en.wikipedia.org/wiki/Assertion_(computing)#Assertions_in_design_by_contract>

and, of course,
<http://en.wikipedia.org/wiki/Design_by_contract>

So far every authority, including those you've cited, has supported what I've
said. DbC is about having the code "ensure" (as Eiffel would say) that the
contract is met. Your suggestion, that disabled assertions can do that, is
false on the face of it.

Now do try to argue on the basis of logic and evidence instead of name-calling
henceforth, hm?

--
Lew

Lew

unread,
May 21, 2009, 9:21:20 PM5/21/09
to
Giovanni Azua wrote:
> "Eric Sosman" <Eric....@sun.com> wrote
>> Checking array indices for validity is "worthless?"
>>
> Using defensive validation I respectfully disagree with you, in my view it
> is not more optimal than using assertions or design-by-contract. The

Design-by-contract requires what you call "defensive validation".

> defensive validation alternative is very pragmatic but comes at a cost:
> performance.

Performance at the expense of correctness is a pig in a poke.

>> Testing can prove code to be bug-free?
>>
> Indeed it can't, but neither can doing input validation in every API layer
> nor defensive programming. There is no silver bullet solution for this
> problem but correct use of either approach will minimize the risk.

Unfortunately, what you recommend, Giovanni, is incorrect use of DbC.

--
Lew

Seamus MacRae

unread,
May 21, 2009, 9:44:09 PM5/21/09
to
Lew wrote:
> And yet I have been able to support my claims with direct evidence
> instead of /ad hominem/ attacks, even using your own authorities.

Actually, you have supported your claims with direct evidence *as well
as* /ad hominem/ attacks. Better than just the latter, at least, though
not better than just the former.

> But you can never be sure of that! You have no control over how client
> code will call the method. No matter how much you test a method that
> should not accept a 'null', it could still happen in production, and if
> you do not protect against that with an actual runtime check, your code
> will bomb.

Worth noting is that if you detect the "null" and throw an exception
like IllegalArgumentException, the code will still bomb. :)

> So far every authority, including those you've cited, has supported what
> I've said. DbC is about having the code "ensure" (as Eiffel would say)
> that the contract is met. Your suggestion, that disabled assertions can
> do that, is false on the face of it.

I don't believe he ever claimed that *disabled* assertions can do that.
I believe he claimed that code still under development could use
*enabled* assertions instead of RuntimeExceptions to do that, and I
myself note that production code will still bomb, whether it catches a
RuntimeException in a precondition check, an AssertionError (asserts
still on), or a RuntimeException from bounds checking, null
dereferencing, or other errors.

In Java, disabled assertions plus lack of precondition checking
exception throwing leads to one bad result: some bugs that would have
caused immediate crash with a RuntimeException stack trace now cause
logic errors that may corrupt data or cause other trouble before people
realize something is wrong.

This is my reason for preferring RuntimeException, and because stack
traces may be more useful to the developers (leading closer to real
source of error sometimes).

In C or a similar language, validation in production code is truly
crucial: an error is likely to create vulnerabilities like buffer
overruns, and it is *very* easy for errors to quietly corrupt data
rather than crash overtly and immediately. It's a shame C's the language
with the least support for this: no exceptions, little else.

C also has a difference wrt asserts. If a library is compiled with
asserts off, you compile your code with asserts on, and you test your
code, the asserts in your code are on but any in the library are off.
The library asserts therefore can't catch you violating library function
preconditions.

Java asserts are turned on in the JVM, and the system classloader then
doesn't strip assertion code from loaded classes. So asserts still have
zero runtime memory or CPU penalty when disabled (except for a slight
loss of speed during classloading, which is not normally going to occur
repeatedly in a performance hotspot). The thing is, library class
asserts will be enabled too if the system classloader loads them and the
JVM is running with asserts enabled, not just asserts in your own code.
So library asserts COULD guard against precondition violations in
library methods during your testing.

But I still favor RuntimeException, both because it'll work with older
Javas and because when the code is in production and if asserts are then
off sometimes a quick crash will take the place of silent data
corruption or wrong answers that way.

> Now do try to argue on the basis of logic and evidence instead of
> name-calling henceforth, hm?

Words for the wise. I suggest you both follow that advice.

Eric Sosman

unread,
May 21, 2009, 10:00:26 PM5/21/09
to

Ah. So all we need is a suitable predicate, like

assert
callerAndCallersCallersAllTheWayUpTheStackHaveBeenThoroughlyTestedAndTheTestsWereComprehensiveAndTheResultsWereProperlyScrutinizedAndEverythingIsCopaceticAndGodsInHisHeavenAllsRightWithTheWorldOhAndByTheWayItsThreadSafeToo()
: "Danger, Will Robinson!";

The implementation of the predicate is left as an exercise.
Don't forget to test it ...

--
Eric Sosman
eso...@ieee-dot-org.invalid

Eric Sosman

unread,
May 21, 2009, 10:06:34 PM5/21/09
to

Seems to me, Lew, that you and I have disagreed on a
few occasions. Glad to hear they weren't fundamental ...

(More than forty years since I was first paid to write
code, and I *still* make mistakes. My longevity and success
are due mostly to the fact that I tend not to repeat them, or
at any rate not often. But the population of potential mistakes
is quite large, and I doubt I'll live long enough to make all
of them and have the opportunity to say "Never again!" for
every single one. Ars longa, vita brevis.)

--
Eric Sosman
eso...@ieee-dot-org.invalid

Lew

unread,
May 21, 2009, 11:46:08 PM5/21/09
to
Lew wrote:
>> Of course you would not have said anything so fundamentally mistaken.

Eric Sosman wrote:
> Seems to me, Lew, that you and I have disagreed on a
> few occasions. Glad to hear they weren't fundamental ...

Then I must have been wrong.

All kidding aside, encountering intelligent, reasoned and well-argued
disagreement is one of the most powerful ways to learn.

Where I have worked, while they have formal code reviews, in the press of
deadlines they tend to happen after code has been released to a build. I am
in the habit of seeking those fellow developers who most consistently disagree
with my programming style and ideas and simultaneously provide the most
compelling arguments for their positions, and showing them my code in its
early stages. One of two things happen - I modify my code in the direction
they suggest or I don't, being more certain of my approach than ever in the
latter case. The former happens somewhat more often.

Lately I've noticed that those same individuals that I seek for reasoned
opposition have the same habit. Occasionally they come to me for disagreement
also.

I could generalize and suggest that those practitioners who seek truth, even
at the expense of having to give up a cherished idea sometimes, benefit royally.

--
Lew

Seamus MacRae

unread,
May 22, 2009, 1:06:05 AM5/22/09
to

Large butt, short life???

Seamus MacRae

unread,
May 22, 2009, 1:07:26 AM5/22/09
to
Lew wrote:
> Lew wrote:
>>> Of course you would not have said anything so fundamentally mistaken.
>
> Eric Sosman wrote:
>> Seems to me, Lew, that you and I have disagreed on a
>> few occasions. Glad to hear they weren't fundamental ...
>
> Then I must have been wrong.
>
> All kidding aside, encountering intelligent, reasoned and well-argued
> disagreement is one of the most powerful ways to learn.
>
> Where I have worked, while they have formal code reviews, in the press
> of deadlines they tend to happen after code has been released to a
> build. I am in the habit of seeking those fellow developers who most
> consistently disagree with my programming style and ideas and
> simultaneously provide the most compelling arguments for their
> positions, and showing them my code in its early stages. One of two
> things happen - I modify my code in the direction they suggest or I
> don't, being more certain of my approach than ever in the latter case.
> The former happens somewhat more often.
>
> Lately I've noticed that those same individuals that I seek for reasoned
> opposition have the same habit. Occasionally they come to me for
> disagreement also.

Do you ask them whether they want five minutes or the full half hour?

John B. Matthews

unread,
May 22, 2009, 8:03:28 AM5/22/09
to
In article <gv5brp$ntg$3...@news.eternal-september.org>,
Seamus MacRae <smacr...@live.ca.nospam> wrote:

> Ars longa, vita brevis

<http://en.wikipedia.org/wiki/Ars_longa,_vita_brevis>

--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>

Giovanni Azua

unread,
May 22, 2009, 12:42:03 PM5/22/09
to
Hi Seamus,

"Seamus MacRae" <smacr...@live.ca.nospam> wrote
> [snip]


> That other thread started flaming big-time after, and only after, "Lew"
> began to participate heavily, too; until then it had been only moderately
> uncivil here and there and it has maybe calmed back down some since he
> left it.
>

yes, here another one that didn't read the sign :]

I think it is a mistake to try to discuss anything with a Troll, all the
evidence shows what the underlying intentions actually are. After reading
all the deceits and insults no wonder why he needs to hide his true
identity.

Best regards,
Giovanni


Giovanni Azua

unread,
May 22, 2009, 12:45:00 PM5/22/09
to
Hi Seamus,

"Seamus MacRae" <smacr...@live.ca.nospam> wrote


>> So far every authority, including those you've cited, has supported what
>> I've said. DbC is about having the code "ensure" (as Eiffel would say)
>> that the contract is met. Your suggestion, that disabled assertions can
>> do that, is false on the face of it.
>
> I don't believe he ever claimed that *disabled* assertions can do that. I
> believe he claimed that code still under development could use *enabled*
> assertions instead of RuntimeExceptions to do that, and I myself note that
> production code will still bomb, whether it catches a RuntimeException in
> a precondition check, an AssertionError (asserts still on), or a
> RuntimeException from bounds checking, null dereferencing, or other
> errors.
>

Thank you for the clarification but unfortunately I don't think it will
help, it is what it is.

Best regards,
Giovanni


Seamus MacRae

unread,
May 22, 2009, 12:52:33 PM5/22/09
to

Who, "Lew"?

Giovanni Azua

unread,
May 22, 2009, 1:26:33 PM5/22/09
to
Hello Seamus,

"Seamus MacRae" <smacr...@live.ca.nospam> wrote


> I disagree. Input validation (of interactive applications) should occur
> using conditionals and divergent behavior in the presentation layer. For
> instance if (i > 99) JOptionPane.blahblahblah("Size is too big; maximum
> 99")etc.etc.etc.return; else somethingInBusinessLayer.doSomethingWith(i);
> (maybe make it localizable by using message bundle).
>

I don't disagree here. The "filtering layer" API e.g. service layer is not
supposed to replace this conditionals in the presentation layer. I think
this very same example is even explained in the book I cited before.

Assuming a multiple layer design you could rely on assertions to check for
preconditions in inner layers of the design. Analogous to the Java access
modifiers it would mean having a presentation tier, an application service
layer "exposed" that validates input, other inner layers e.g. could be the
data access layer "protected" would be a good candidate for use of
assertions for pre-conditions, java util etc would also be assertions-based
e.g. this is how Eiffel is.

> This is debatable. The currently generally used best practices use
> RuntimeException rather than assertions, but this tradition was
> established before Java had assertions. The case could be made, but then
> it would make sense to replace most or all RuntimeExceptions (and Errors)
> with asserts and just have AssertionError, VMError, OOME, and (checked)
> Exception. Well, were it not for backwards compatibility.
>

I don't think AssertionError should be handled. As I said before I disagree
that the "do not use assertions to check the parameters of a public method"
must be the rule for all cases. However, I think it should be the rule for
"exposed" API layers e.g. the application service layer, mostly depend on
the specific API.

Best regards,
Giovanni


Lew

unread,
May 22, 2009, 1:31:33 PM5/22/09
to
Giovanni Azua wrote:
> I think it is a mistake to try to discuss anything with a Troll, all the
> evidence shows what the underlying intentions actually are. After reading
> all the deceits and insults no wonder why he needs to hide his true
> identity.

I agree completely.

--
Lew

Giovanni Azua

unread,
May 22, 2009, 1:44:43 PM5/22/09
to

"Giovanni Azua" <brav...@hotmail.com> wrote in message

> I don't disagree here. The "filtering layer" API e.g. service layer is not
> supposed to replace this conditionals in the presentation layer. I think
> this very same example is even explained in the book I cited before.
>
> Assuming a multiple layer design you could rely on assertions to check for
> preconditions in inner layers of the design. Analogous to the Java access
> modifiers it would mean having a presentation tier, an application service
> layer "exposed" that validates input, other inner layers e.g. could be the
> data access layer "protected" would be a good candidate for use of
> assertions for pre-conditions, java util etc would also be
> assertions-based e.g. this is how Eiffel is.
>
The page 13 of these slides depict what I meant:
http://se.inf.ethz.ch/teaching/ss2005/0250/lectures/oosc_13_dbc_1up.pdf

There are some notes on defensive programming in page 17.

All course slides are here:
http://se.inf.ethz.ch/teaching/ss2005/0250/index.html#slides

I really enjoyed that course :)

Best regards,
Giovanni

Giovanni Azua

unread,
May 22, 2009, 1:47:07 PM5/22/09
to

"Seamus MacRae" <smacr...@live.ca.nospam> wrote
> Who, "Lew"?
>
lol whom else? :) by now he even agreed to this lol.

Best!
Giovanni


Giovanni Azua

unread,
May 22, 2009, 3:09:19 PM5/22/09
to

"Tom Anderson" <tw...@urchin.earth.li> wrote in message
> It definitely should not return null - that's almost never a good idea. It
> shouldn't throw a RuntimeException, because that won't force the callers
> to face up to the possiblity of failure. It could throw another checked
> exception, perhaps a domain-specific one like DimkaDataLayerException,
> rather an an SQLException. But what is certain - although others, who
> labour in ignorance or sin, may disagree - is that it should throw a
> checked exception. If there is a real possibility of failure, callers
> should be made aware of it, and be made to prepare for it.
>
I don't think that the first thing one should figure out is what to throw or
rethrow. It is like the first thing that crosses your mind when you get a
client is to point the right "cannons" at him. Just thinking what is the
right cannon caliber "checked" or "unchecked" should not be the idea behind
serving a client. One should rather think hard to serve the client i.e.
require less and ensure more.

From my experience, the farther the exception gets the less likely any layer
will be able to recover and do anything sensible with it.

--
Giovanni

Lew

unread,
May 22, 2009, 3:12:35 PM5/22/09
to
On May 22, 1:47 pm, "Giovanni Azua" <brave...@hotmail.com> wrote:
> "Seamus MacRae" <smacrae...@live.ca.nospam> wrote> Who, "Lew"?

>
> lol whom else? :) by now he even agreed to this lol.
>
> Best!
> Giovanni

I agree that trolls are problematic in a discussion. They ignore
evidence, even if it comes from the same authorities they themselves
profess to respect. They issue personal attacks against those who
disagree with them, resorting to epithets like "notorious", in lieu of
responding to the actual points. They ignore the logic of the
opposing viewpoint, resorting instead to character assassination
attempts. They use disparagement and doublespeak instead of logic and
evidence. They completely ignore points made that disagree with those
they proffer, attaching labels to their own reasoning like "Design by
Contract" even when the labels refer to concepts that contradict their
own points. When authoritative evidence is provided that the labels
do not apply to their own points, they merely reiterate the label, not
explaining how the contrary evidence might fail to apply to their
statements. Then they repeat the cycle of attempted ridicule and
character defamation in lieu of discussion of the logic of the
argument. Often they will employ the psychological technique of
projection, attribution of their own behaviors to those who disagree
with their conclusions.

In this discussion I and others have consistently provided evidence,
reasoning and logic, in agreement with other expert opinions, some
from those you yourself profess to hold as authoritative, that refute
some of your statements. It is in every piece of explanatory
literature that Design-by-Contract (DbC) involves establishment of
invariant, preconditions and postconditions in code with validation
logic to ensure that the contract is met. It is shown by
authoritative source and by reasoning through to consequences how
merely testing public methods internally cannot replace use of actual
runtime code to enforce such contracts. Likewise various respondents
in this thread have pointed out how the Java 'assert' construct cannot
substitute for if tests and possible exceptions to enforce contracts
of API methods. None of these respondents, myself included, have
attempted to disparage anyone's character or behavior in this
discussion, limiting our points to the facts.

The Usenet record makes it clear who has resorted to /ad hominem/
tactics, mere repetition of conclusions in lieu of supporting logic or
evidence, simple disagreement with sources authoritative even by their
own definition without evidence for such disagreement, and name
calling.

I agree with you that trolls are difficult to reason with, that DbC is
an important and effective development technique when properly
applied, that assertions should normally be disabled in production.

It is a matter of fact that in-development testing of public methods
without DbC enforcement clauses in their logic will not prevent bugs
in client code of those methods. It is a matter of fact that
assertions by themselves cannot enforce or guarantee correctness of
code. It is a matter of fact that experts at Sun and Eiffel have made
statements that agree with those conclusions. It is a matter of fact
that assertions play an important role in certain formal procedures of
code development and testing, including those proffered by Bertrand
Meyer.

It is a matter supported by evidence and logic in this discussion and
by referenced authorities that runtime checks involving constructs
other than 'assert', such as 'if' clauses and thrown exceptions, must
exist in production code in order to adhere to the principles of DbC.
It is a matter of fact that no argument other than simple disagreement
and /ad hominem/ attack has been offered in this thread to contradict
that conclusion.

--
Lew
Yes, that is my real name. The last name is Bloch, if you care.

Lew

unread,
May 22, 2009, 5:49:37 PM5/22/09
to
On May 22, 1:44 pm, "Giovanni Azua" <brave...@hotmail.com> wrote:
> The page 13 of these slides depict what I meant:http://se.inf.ethz.ch/teaching/ss2005/0250/lectures/oosc_13_dbc_1up.pdf
>
> There are some notes on defensive programming in page 17.
>

Now I see what you meant and where you got your terminology.

Your view: API clients should guarantee preconditions.

If the Java method Math.sqrt() relied on that, what would it return
for 'Math.sqrt( -1 )'?

According to you, that would never happen. How do you guarantee
that? What would the result be?

My view, what you like to call "defensive programming": either the
method throws an exception or it tests the value and returns a
suitable value. The actual Java method 'Math.sqrt(double)' does the
latter; it returns 'Double.NaN'.

The method must handle the illegal input. No amount of concern for
"performance" relieves it of responsibility to handle a negative
input.

The problem with the Eiffel view of DbC, reflected in your remarks,
for Java is that programs cannot afford to fail in weird ways if a
client violates the contract. The supplier must handle whatever input
the client gives it; that's the nature of an exported API (i.e., all
public and protected methods). The usual Java mechanism to let a
client know it has violated its contract is a runtime exception such
as NPE. Sometimes it can do what the slides call a "tolerant"
approach, return a suitable value, as with 'Math.sqrt(double)'. You
just cannot prevent all future code written by all future programmers
from providing an illicit input.

Consider the Java method 'Arrays.binarySearch()'
static <T> int binarySearch( T[] a, int fromIndex, int toIndex, T
key,
Comparator<? super T> c )
et al.

Within the code there is an explicit check that 'fromIndex' is not
greater than 'toIndex'. From what you said, all client code should
enforce that, and relieve the library routine of the supposed
inefficiency of that check. How is it more efficient for a gazillion
callers to do a check centralized in one place in the 'Arrays' class,
as a private method, that alerts clients to their violation of the
contract via an 'IllegalArgumentException'?

How would you do it instead?

--
Lew

Tom Anderson

unread,
May 22, 2009, 8:35:38 PM5/22/09
to
On Fri, 22 May 2009, Giovanni Azua wrote:

> "Tom Anderson" <tw...@urchin.earth.li> wrote in message
>> It definitely should not return null - that's almost never a good idea. It
>> shouldn't throw a RuntimeException, because that won't force the callers
>> to face up to the possiblity of failure. It could throw another checked
>> exception, perhaps a domain-specific one like DimkaDataLayerException,
>> rather an an SQLException. But what is certain - although others, who
>> labour in ignorance or sin, may disagree - is that it should throw a
>> checked exception. If there is a real possibility of failure, callers
>> should be made aware of it, and be made to prepare for it.
>
> I don't think that the first thing one should figure out is what to
> throw or rethrow. It is like the first thing that crosses your mind when
> you get a client is to point the right "cannons" at him. Just thinking
> what is the right cannon caliber "checked" or "unchecked" should not be
> the idea behind serving a client. One should rather think hard to serve
> the client i.e. require less and ensure more.

That's an admirable sentiment - if a method can recover from an exception,
then yes, it absolutely should (probably - there are times when it would
not be a good idea). My assumption in this thread has been that we're
talking about the times when it can't.

> From my experience, the farther the exception gets the less likely any
> layer will be able to recover and do anything sensible with it.

To a point - sometimes, the only sensible thing to do is to give up. Log
the exception, report failure to the user, whatever. That's a decision
that can only be made at the top level, and such errors can be escalated
to the top level most easily by throwing an exception.

tom

--
Everyone has to die sooner or later, whether they be killed by germs,
crushed by a collapsing house, or blown to smithereens by an atom bomb. --
Mao Zedong

Seamus MacRae

unread,
May 22, 2009, 10:30:27 PM5/22/09
to
Lew wrote:
> On May 22, 1:47 pm, "Giovanni Azua" <brave...@hotmail.com> wrote:
>> "Seamus MacRae" <smacrae...@live.ca.nospam> wrote> Who, "Lew"?
>>
>> lol whom else? :) by now he even agreed to this lol.
>>
>> Best!
>> Giovanni
>
> I agree that trolls are problematic in a discussion. They ignore
> evidence, even if it comes from the same authorities they themselves
> profess to respect.

Or even each other?

> They issue personal attacks against those who disagree with them

> resorting to epithets like "notorious", in lieu of responding to
> the actual points.

Just like you?

> They ignore the logic of the opposing viewpoint, resorting instead
> to character assassination attempts.

Just like the invading hordes from comp.lang.lisp?

> They use disparagement and doublespeak instead of logic and evidence.

Just like you AND the invading hordes?

> They completely ignore points made that disagree with those
> they proffer

Seen a lot of that here lately, too.

> Then they repeat the cycle of attempted ridicule and character
> defamation in lieu of discussion of the logic of the argument.

You know, this sounds awfully familiar, but in reference to a different
thread and a certain invading horde. :)

> Often they will employ the psychological technique of
> projection, attribution of their own behaviors to those who disagree
> with their conclusions.

This seems familiar too!

> None of these respondents, myself included, have attempted to
> disparage anyone's character or behavior in this discussion, limiting
> our points to the facts.

Correction: "None of these respondents, "Lew" excluded, have attempted

to disparage anyone's character or behavior in this discussion, limiting

our points to the facts." The very post you just wrote, "Lew",
disparages Giovanni's character and behavior, as do the two I cited
previously as expressing an implication that he was a liar.

> The Usenet record makes it clear who has resorted to /ad hominem/
> tactics

Yes -- both of you.

> It is a matter of fact that no argument other than simple disagreement
> and /ad hominem/ attack has been offered in this thread to contradict
> that conclusion.

I'm not sure that's entirely true.

Giovanni Azua

unread,
May 23, 2009, 8:39:50 PM5/23/09
to
Hi Lew,

I acknowledge I read your email and I am really sorry it got this bad though
looking more into the positive side I hope this heat peak will turn the page
on insults and keep discussions at a mutually respectful and professional
level. As a side note, I just wanted to add that my retribution came only
after my many times biting my tongue to the several provocative and
unrespectful ways that you used to defend your arguments. I think your
"provocations" are the kick you use to trigger a fast throughout reply but
it is pushy and kind of defeats the purpose of the discussion at least for
me. I also noted you many times wrongly assumed I was either lying or being
arrogant while I really wasn't, I think improving in tolerance will help a
lot, maybe specially a bit more towards us non English native speakers e.g.
I sometimes end up picking the slightly wrong adjective, "worthless" turned
into a flame when I meant something more like "unnecessary" validation and
it is funny because I would like to defend an argument without having to
spend two hours looking in a dictionary for a neutral and politically
correct adjective ... it is a challenge but ok a good training too. If I may
recommend, I would say try to "ask first then shoot" rather than the other
way around.

Another side note, I personally don't like to have technical discussion
threads that are many pages long and defending many small unit of arguments
in parallel within a single thread each of these units also somehow spiced
with "toned" remarks that need lot of soft-skill efforts, it is a full time
job to respond to one of these. In general to improve the quality of the
discussion I think it is best to keep it short and well focused rather than
exploding exponentially as the threads that you get actively involved
usually tend to become. Well if you have to, then perhaps would be
preferable to have a separate reply for each of these topics or even create
a brand new thread. This is why I might have left some of your technical
valid points unanswered or just missed them. Also as a reader, I quickly
timeout if I see a very dense discussions specially toned with "uncivil"
remarks, it is a waste of time and energy.

Getting back into the original technical topic I think it is not completely
correct to discuss about assertions and look only into the documentation
pages at Sun and only into what they recommend to be the rules in this
regard. Assertions were introduced in Java as Sun itself claims as an
"informal design-by-contract style of programming". If we really are talking
about DbC then we should look into the source. Not doing so would be like
trying to understand how Java works by looking at the Microsoft VisualJ++
documentation. This is why I continuously kept referring to Bertrand Meyer
and his books and teaching materials, it is a fact that he is the
authoritative voice in the subject. The book I cited covers nicely the main
topic of this discussion, I wish I could quote at least some small excerpts
here but I guess that would be illegal. I think understanding how DbC works
from the source will help make better use of assertions in Java.

I will later respond to your other specific technical replies.

Best regards,
Giovanni

Seamus MacRae

unread,
May 23, 2009, 9:30:53 PM5/23/09
to
Giovanni Azua wrote:
> The book I cited covers nicely the main topic of this
> discussion, I wish I could quote at least some small excerpts
> here but I guess that would be illegal.

No, quoting small excerpts in a noncommercial usage for commentary and
criticism would be fair use. The four traditional factors used to judge
if a use is fair are:
* Nature and character of the use -- noncommercial for commentary and
criticism, in this case, which favors a finding of fair use.
* Nature of the copyrighted work -- in this case, already published and
factual rather than fictional, both of which favor a finding of fair
use.
* Proportion of the work excerpted -- short quotes from a large book
favor a finding of fair use.
* Effect of the use on the potential market -- such quotes do not
compete with the complete book, and may in fact have the effect of
promoting it, which also favors a finding of fair use.

http://fairuse.stanford.edu/Copyright_and_Fair_Use_Overview/chapter9/9-b.html
has more information.

If you publish the work containing the quotations outside of the United
States, your mileage may vary, but it is highly unlikely that quoting
the book nonextensively while discussing and even promoting it in an
obscure usenet thread will lead to a lawsuit, and the above should give
you a clear conscience should you do so, even if you reside elsewhere
than the United States.

Lew

unread,
May 23, 2009, 10:32:12 PM5/23/09
to
Giovanni Azua wrote:
> Getting back into the original technical topic I think it is not completely
> correct to discuss about assertions and look only into the documentation
> pages at Sun and only into what they recommend to be the rules in this
> regard. Assertions were introduced in Java as Sun itself claims as an
> "informal design-by-contract style of programming".

Sun says that they can be used in such a manner, not that they were introduced
for that purpose only. Assertions have been part of formal reasoning about
computer programming since at least 1969 and C.A.R. Hoare's work.
<http://en.wikipedia.org/wiki/Hoare_logic>

> If we really are talking
> about DbC then we should look into the source. Not doing so would be like
> trying to understand how Java works by looking at the Microsoft VisualJ++

Assertions as a formal computer-programming mechanism predate Eiffel and
Bertrand Meyer's work generally. My interest was in assertions primarily; as
I understood it you introduced DbC in order to justify certain claims about
assertions.

> documentation. This is why I continuously kept referring to Bertrand Meyer
> and his books and teaching materials, it is a fact that he is the
> authoritative voice in the subject. The book I cited covers nicely the main

But not the only or even primary authoritative voice on the subject of
assertions, which topic is where our subthread began.

> topic of this discussion, I wish I could quote at least some small excerpts
> here but I guess that would be illegal. I think understanding how DbC works

Quoting small parts of a work falls under "fair use" in most jurisdictions of
which I'm aware. You should cite the source and, if feasible, link to it, of
course.

> from the source will help make better use of assertions in Java.

Assertions are part of DbC, but the converse isn't necessarily true. "Design
by Contract" is a trademarked phrase referring to one company's particular
advice for a specific style of programming in a particular language. I am not
so certain that it applies universally to all languages, for example, Java,
nor do I agree with all of your interpretation of it. As I have shown
upthread, even the authorities you cite don't completely support all your
claims. You also threw away authoritative remarks from sources you cited
yourself, to whit, the Sun document on the correct use of assertions.

The semantics of Eiffel's "ensure" and "require" don't have an exact parallel
in Java, AFAIK. Even Eiffel's examples, however, have idioms that seem
similar to what I've been recommending in this thread for Java programmers.

The facts are still facts. No amount of testing of a public method for a
subset of possible inputs to that method can stop a client method from passing
other inputs. A method must have some way of handling all possible input.

In Java, there are two possible responses to out-of-the-ordinary inputs -
return a reasonable value or throw an exception. It requires a method to do
one of three things - use an algorithm that accepts all possible inputs, such
as addition of two 'int' values does; branch after test to a different
algorithm for some subset of inputs, as a 'sqrt()' method might use for
negative input to return 'Double.NaN'; or branch after test to an
exception-throwing block. It just isn't possible for an exported method to
force client code to do those things for it, and even if it were, it wouldn't
be more efficient as the test would still happen somewhere anyway.

--
Lew

0 new messages