Paul Okeke Paul Okeke - 2 years ago 83
Java Question

How to stop/exit a sub-classed method process from its super class method in java

Given the below snippet:

Super Class implementation:

public void onDone(String taskName, JSONObject receivedData, @Nullable HashMap<String, String> sentData) {
//checks the status for all done process decides to call the presenter failed or success
try {
boolean success = receivedData.getString("status").equals("success");
}catch (JSONException ex){
this.presenter.error("An error occurred");

Sub-Class Implementation::

public void onDone(@NonNull String taskName, @NonNull JSONObject receivedData,
@Nullable HashMap<String, String> sentData) {
super.onDone(taskName, receivedData, sentData);
//the expected data has been received we should act upon it
//this DAO should know all the type of taskName it can handle and if it finds any that doesn't
//matches any of its command let it exit
Log.e(TAG, "Response : "+receivedData);
Toast.makeText(this.presenter.getContext(), "Done with task", Toast.LENGTH_LONG).show();
sentData = null;

What i want is that as soon as the super.onDone method detects an error, the process should end there and shouldn't bother running the body of the sub class method, is that possible in JAVA?

Answer Source

You could either

  • have the method throw an Exception (probably requires bigger refactoring to then deal with the exception)

  • have the method return false (change the return type from void to boolean) and check the status in your subclass before proceeding. You could also return a more detailed status code.

  • have the superclass set its processing status to an instance variable (this.wentWell = true) that the subclass can then check. The downside of this is that it introduces mutable state and is not threadsafe.

  • (this is getting increasingly bad design): Have the superclass update the HashMap it received with some extra information for the subclass to pick up (sentData.put("wentWell", "true")). This is similar to how, say, a servlet filter passes data along by setting "request attributes". Depends on that map being updatable (which not be the case), potentially opens remote exploits via data injection (you are putting internal processing logic flags into a data structure that may be coming directly from who knows where).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download