简体   繁体   中英

How do you break a nested method calling in different objects?

The situation is as follwing

student.studentsPhone.studentsAccount.topUp(xxx)

student is an object that has the method studentsPhone which returns the a variable of type Phone and the phone object has a method studentsAccount which returns the a variable of type Account that finally has the required method.

So my question is if I have a student object and no phone, I will get a null pointer exception. Is there a way to cut the line where we wanted? bare in mind that I don't want to instantiate everything in the main class. I will just instantiate the Student class.

I though of several approaches

  1. Move the method up the heirarchy, but the other objects won't be of any use really

  2. in the studentsPhone method I say if (Phone == null) return; but its not void and there are other methods after studentPhone

You can use ternary operator for this, something like:

String result =  student != null ? (student.studentPhone != null ? (student.studentPhone.studentsAccount != null ? student.studentPhone.studentsAccount.topUp(xxx) :"return"): "return") : "return"

or like:

boolean isNotNull = student != null ? (student.studentPhone != null ? (student.studentPhone.studentsAccount != null ? true : false): false) : false;

if(isNotNull){
    student.studentPhone.studentsAccount.topUp(xxx);
}

You could throw your own type of runtime exception if there is no phone. Wrap your code in a try/catch block, catching your own exception and then carry on with the rest of your function

void doSomeThing() {
    Phone getStudentPhone() {
        if(phone == null) {
            throw new noPhoneException();
        }
        return phone;
    }
}

try {
    student.getStudentPhone().studentsAccount.topUp(xxx);
} catch(noPhoneException e) {
    // say something about no phone existing
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM