Link Details

Link 277849 thumbnail
User 429382 avatar

By ppow
via javablogging.com
Published: Nov 03 2009 / 17:23

Sometimes it seems like you're making improvement to the code by adding a helper method. Sometimes you're wrong.
  • 13
  • 2
  • 1293
  • 500

Comments

Add your comment
User 270877 avatar

killerweb replied ago:

0 votes Vote down Vote up Reply

Author really doesn't know what he is talking about. Both approaches can cause the same exact issue:
Map<String, Set<String>> phonebook = (Map<String, Set<String>>) session.getAttribute("phonebook");
or
Map<String, Set<String>> phonebook = cast(session.getAttribute("phonebook"));
Both are unchecked and the solution the author offers does nothing more than use specific approach to solve one casting type.

IMHO the cast solution is fine since any casting done off generic getters won't be caught no matter what solution. Stop sweating the small stuff, and build systems that have better data validation, rather than trying to solve casting issues.

User 388005 avatar

Hardcoded replied ago:

0 votes Vote down Vote up Reply

The author is right. Sure, in your example there's no difference. But thats only when casting a generic Object to anything.
The cast method will cast anything to anything without compiler errors. And that's what the author wants to say.
Try to compile this:
Integer number = 123;
String value = cast(number);

vs this:
Integer number = 123;
String value = (String)number;

Ok, you may say that those examples are constructed and no one would do something like this - not on purpose, right.
But how many times did you change the type of a variable? With a normal cast, the compiler would find bad casts. But it won't with the generic method, leaving pitfalls for the runtime.

User 429382 avatar

ppow replied ago:

0 votes Vote down Vote up Reply

The idea was not to prove that cast() is much worse that normal casting, but that there is a safer way to solve the problem with usage of wrapper. This way you get more control and safety over casting.

Add your comment


Html tags not supported. Reply is editable for 5 minutes. Use [code lang="java|ruby|sql|css|xml"][/code] to post code snippets.