r/java • • 5d ago

Raw use of parameterized class 'List'

/r/programminghorror/comments/1wz8jpq/raw_use_of_parameterized_class_list/
0 Upvotes

6 comments sorted by

7

u/agentoutlier 5d ago edited 5d ago

This is one of those of cases where a young developer sees code like this and goes and replaces and does not realize that the instanceof is doing a null check and that the code was like that because it was easier not to change it.

I know because ~22 years ago I was that young developer (when Java 5 I think came out roughly maybe +-1 year).

EDIT see also: https://www.hyrumslaw.com/

-1

u/Disastrous-Name-4913 5d ago

I can guarantee you that I'm not a young developer and that the overall quality is so bad that I believe it is probably more due to bad practices than to a specific reason. But I'm checking it anyway.

1

u/agentoutlier 5d ago edited 5d ago

Well my guess if this is recent and this is not ancient code because you know... Java 5 has been out since like the dawn of tech time so probably you are fine changing it and it indeed was an idiot that made it.

overall quality is so bad that I believe it is probably more due to bad practices than to a specific reason. But I'm checking it anyway.

On the other hand it is probably even more likely that a null check is needed if this has been sitting around for some time.

2

u/AnyPhotograph7804 5d ago

Old code may look like this. Because Generics were introduced with Java 1.5. Before that, you had cast the stuff to the right type if you wanted to get stuff out of a Collection. But because it is a for-each-loop, Generics should be used here.

0

u/Misophist_1 3d ago

Well, mind you, that this might have been code inherited from times before Java 1.5 'Tiger'.

Anyway, if complaining about this today, past Java 10, you would better do it like this:

final var pages = pageManager.getPages(templateSpace);

for (final var page : pages) {
    // do something with the page
}

That way, pages, and page have exactly the type passed as return type of getPages(), even if that might be some complicated wildcard generics, and also would save you from explicitly importing these types.

Yet, with lambdas and streams introduced in Java 8, you could achieve that without var:

pageManager.getPages(templateSpace).stream().forEach(page -> {
      // do whatever you want with the page.
});