Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [eclipse-dev] [cross-project-issues-dev] org.eclipse.equinox.common has added generics to API in org.eclipse.core.runtime package

Am 20.02.2015 um 19:20 schrieb Daniel Megert:
> My advice is to go with the explicit version where one has to add the
> @SuppressWarnings("unchecked").

My advice: Avoid @SuppressWarnings(), especially at the method level.

Without the Class.cast() trick, I suggest this code:

    @SuppressWarnings("unchecked")
    T tmp = (T) result;
    return tmp;

That way, the suppression doesn't leak into code where you might not
want it (like when someone else changes the code some more two years
from now).

But since the Java API offers a solution where you don't have to tell
the compiler to back off, use Class.cast():

1. It throws the exception at the first place where Java can detect it.
Someone else mentioned "it will be thrown soon" but that's not
necessarily true: If you chain generics calls like this one, there might
be an arbitrary number of calls and code between the assignment and when
you'll see an exception (and I've even seen code where such results were
assigned to fields making it almost impossible to connect the dots).

2. Compiler warnings are there for a reason.
@SuppressWarnings("unchecked") doesn't tell much since it can be applied
to dozens of problems. Class.cast() shows intent.

3. Class.cast() owns the problem instead of relying on "someone else
will fix it for me ... eventually ... I hope ... maybe ... who cares"

4. You save 1-2 lines of code.

Regards,

-- 
Aaron "Optimizer" Digulla a.k.a. Philmann Dark
"It's not the universe that's limited, it's our imagination.
Follow me and I'll show you something beyond the limits."
http://blog.pdark.de/


Back to the top