Mansukhdeep Thind wrote:Are you sure about that Amit?
Are you sure that a base type can be cast into a subtype?
You are missing the important part of my post above, it clearly says that the type cast should be done to the object class used while setting the attribute.
Did I say set an Object and cast it to String during get?
When in doubt of the incoming type, I would not cast without the instanceof check.
Mansukhdeep Thind wrote:But I still follow a thumb rule that one must do the instanceof check irrespective of the degree that one is sure what type of Object it is, just to be on the safer side.
I'd say that "it depends". Doing that sort of check everywhere can make the code bloated and harder to read. If the code is under close control, and it's reasonably known that a scoped attribute will be a String, then the check could be superfluous.
This is especially true when it's a bug if the value is anything other than the expected type. Just let the ClassCastException happen and bubble its way out to the error handler where the developer can clearly see that there is a problem in the code that needs fixing.
But sure, when the type cannot be known, or there is something concrete to do locally if the type is incorrect, then do the check.
Agreed Bear. More of a design question rather than a technical one. Ideally, one should design his application schema model in a manner where it is clearly outlined what the class hierarchies are. Minimal instanceof checks are the sign that your design is good. Although certain methods , like the famous java.lang.Object.equals(Object object), impose that restriction on the developer just because of its signature. you have to know what type that passed object is before comparing it with another one.
If you really mean that, will you do one thing Matt? Learn a little bit of basic java everyday. Study from Head First Java. Once your basics are solid, you will be able to resolve such issues without our help. Wouldn't that be great? :wink: You are always welcome anytime Matt. :beerchug: Make notes and come back with as many doubts as possible.