Let’s say we have the following block of code:
if (thing instanceof ObjectType) {
((ObjectType)thing).operation1();
((ObjectType)thing).operation2();
((ObjectType)thing).operation3();
}
All the typecasting makes the code look ugly, is there a way of declaring ‘thing’ as ObjectType inside that block of code? I know I could do
OjectType differentThing = (ObjectType)thing;
and work with ‘differentThing’ from then on, but that brings some confusion to the code. Is there a nicer way of doing this, possibly something like
if (thing instanceof ObjectType) {
(ObjectType)thing; //this would declare 'thing' to be an instance of ObjectType
thing.operation1();
thing.operation2();
thing.operation3();
}
I am pretty sure this question has been asked in the past, I couldn’t find it though. Feel free to point me to the possible duplicate.
No, once a variable is declared, the type of that variable is fixed. I believe that changing the type of a variable (potentially temporarily) would bring far more confusion than the:
approach you believe to be confusing. This approach is widely used and idiomatic – where it’s required at all, of course. (This is typically a bit of a code smell.)
Another option is to extract a method: