Re: looping through a list, starting at 1
Andreas Leitgeb wrote:
Lew wrote:
Volker Borchert wrote:
if (l instanceof RandomAccess) {
Tests on type like this are an antipattern.
Like many antipatterns there are occasions when one might
consider its use anyway, but it's a red flag that we're
probably going about things the wrong way.
Are marker-interfaces (which RandomAccess is, iirc) already an
antipattern, or is there a different way to check for them,
or are marker-interfaces just one of the occasions where one
would just acknowledge and consciously ignore the red flag?
PS: I fully agree with your judgement *outside* the context
of marker-interfaces, and am eager to learn *inside* that
context.
I would need some time with an SSCCE to know if there's a better way in thi=
s example, but generally even with marker interfaces you want to lock the t=
ype down at compile time rather than with a run-time check. So if it's imp=
ortant that a method use a 'RandomAccess' argument, say, then you might wan=
t to declare it as 'method(RandomAccess arg)' and lock down your type asser=
tions so that only the right type reaches the method. With generics you ca=
n use type intersections so that something has to be both 'List' and 'Rando=
mAccess' (again, say) even to reach the call or the class or whatever.
It's the run-time type check that one often wishes to avoid. Of course, if=
the logic truly requires it, as it sometimes does, then the antipatternnes=
s goes away. I just find that use of 'instanceof' in the world of types an=
d generics frequently signals incompletely thought-out type assertions.
If there were an SSCCE for the particular use case, one might be able to di=
scern a less run-timeish way forward or one might not. I only wished to po=
int out a general principle here.
--
Lew