Is it discouraged to down-cast a returned instance to gain functionality
that is not exposed via the returned class type?
This is the basic scenario: A method returns a class of type A, but after
looking at the internal workings of the code it is found safe to assume
that it actually returns B (a subclass of A). Is it then valid to do
something like this? Or would you highly discourage it because it is
accessing protected data (at least):
Assume that you do not maintain this code that implements the method as
well. I.e, your software could ship with a different implementation of
this (well established) method.
Please be thorough in your answer.
A returnedData = executeMethod();
if(returnedData instanceof B)
{
((B)returnedData).someFunctionNotExposedThroughAIsItProtected();
//Use it as B, safe but non OOP and accessing protected functionality?
}else
writeAFallBackOfSomeSort();
No comments:
Post a Comment