Re: message to nil? (very basic question)
Re: message to nil? (very basic question)
- Subject: Re: message to nil? (very basic question)
- From: Andy <email@hidden>
- Date: Tue, 22 Jan 2002 19:25:59 -0500
Hsu wrote:
>
>
I've often wished for a "special" java syntax indicating that I'd like a
>
particular method invocation to be eaten by null...
>
>
myObject:doSomethingWhereIDontCareIfTheReceiverIsNil(arg1);
>
There is one special case where you can do this:
private static final SomeObject _obj = new SomeObject();
... later...
instead of writing
foo(SomeObject obj) {
if (obj != null && obj.equals(_obj)) {
obj.doSomething();
}
}
//write instead
foo(SomeObject obj) {
if (_obj.equals(obj)) {
obj.doSomething();
}
}
ie, *always* call equals (or compareTo or whatever) on the instance
variable you know isn't null (due to your class invariants) and not on
the argument.
This idiom is really nice
instead of somePontentiallyNullString.equals("Hello")
do instead "Hello".equals(somePontentiallyNullString);
ie, it takes advantage of the fact string literals are objects in java,
so you always get false if somePontentiallyNullString is null, and you
don't risk a NullPointerException.
(of course, "Hello" should probably be a constant variable, not hardcoded).
Of course, if the argument is supposed to never be null, you shouldn't
hide the fact it is using this idiom! IllegalArgumentException is the
right response.
Its nothing like as powerful as messaging nil (and arguably not as
dangerous) but it does cover a lot of common .equals() cases.
--
AndyT (lordpixel - the cat who walks through walls)
A little bigger on the inside
I think we finally found the killer app for Flash: animated stick men