Should you ever do explicit casts in modern Java? – Hashnode – Info Java

No Surveys

We do not allow surveys.

Also, a survey that requires login. lol.

But regards to the subject, I vote for ‘only exceptional cases’. I agree with u/cryptos6 that it is indeed a design weakness. However, there is one use case that I found:

When designing an API through interfaces, you might have two declarations:

public interface Context { ... }
public interface Child { Object doOnContext(Context context); }

In this case, the Child implementation might need to cast the context paremeter to the implementation class in order to execute the operation.

One might wonder: But why don’t we use the Context as a factory for the Child implementation?

Well, the child instance might need to be serializable. In that case, the context cannot be serialized along with the child, and later after deserialization, it needs to be attached again. So instead of creating a reattach method on context, we pass the context as a parameter for the function call.

So in the end, the function implementation might look like this:

public Object doOnContext(Context context){
    ContextImpl impl = (ContextImpl) context;
    ...
}

I think that a thrown ClassCastException is fine in this case, as children should be used on their respective context instances, which is the responsibility of the API caller.

If you need to act based on the type of the parameter, there is also the Visitor pattern for you for other scenarios.

Article Prepared by Ollala Corp

You might also like
Leave A Reply

Your email address will not be published.