Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given the below snippet:

Super Class implementation:

@Override
    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");
            if(!success){
                this.presenter.error(receivedData.getString("reason"));
            }
        }catch (JSONException ex){
            ex.printStackTrace();
            this.presenter.error("An error occurred");
        }
    }

Sub-Class Implementation::

@Override
    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();
        if(sentData!=null){
            sentData.clear();
            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?

like image 567
Paul Okeke Avatar asked Aug 21 '16 01:08

Paul Okeke


1 Answers

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).

like image 138
Thilo Avatar answered Oct 13 '22 00:10

Thilo