Java asserts in interfaces?

K

Ken

Hi. Does anyone know if java asserts can be applied to interface
operations? I ask this in the context of verifying contracts. The
idea is that you'd want to use asserts to define pre and post
conditions for each operation in the interface. Then these asserts
would be automatically applied to any class that implemented the
interface. This would avoid having to physically include the same
assert code in every class that implemented the interface. This is
the same idea behind allowing an interface to have its exceptions
identified--namely, to guanrantee that each implementation will throw
the exceptions associated with the interface.

Thanks for any input,

Ken
 
M

Manish Hatwalne

I don't think it would be allowed.
assert is part of implementation whereas interface by definition does not
have any implementation details in it.

- Manish
 
M

Michael Borgwardt

Ken said:
Hi. Does anyone know if java asserts can be applied to interface
operations?

No.

What you're looking for is part of the programming philosophy called "design by contract".
There are languages that support it fully - Java is not among them.
 
T

Timo Kinnunen

Hi. Does anyone know if java asserts can be applied to interface
operations? I ask this in the context of verifying contracts.

No, but you can simulate it to some extent by providing a concrete wrapper
class which implements the interface and checks the contract before and
after forwarding to the real instance. Then wrap any untrusted incoming
classes into it at your module's boundary.
 
G

Guus Bosman

Hi,

As the other poster pointed out, Java interfaces do not support the assert
keyword.

Additionally, the Java assert keyword should not be used to verify
pre-conditions in public methods.

http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html#preconditions

For private methods it's okay to use ''assert'', but not for public ones
(IllegalArgumentExceptions and NullPointerExceptions should be thrown there,
not AssertionFailedErrors). And obviously, in Java Interfaces only public
methods exist.

Regards,
Guus Bosman
http://www.guusbosman.nl
 

Ask a Question

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

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

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top