9 Replies Latest reply: Jan 13, 2013 12:13 PM by TPD-Opitz RSS

    calling object without checking for null

    csckid
      Consider the example below. To check/get the value of Student.firstName I have to check for student nulls, then firstName nulls. Is there better way to write this?

      I have noticed that, if I write private Student student = new Student() in User class, then I won't need to check whether student is null. But one of my friend said it is not good to initialize since it takes space. Any suggestion?
      Class User{
        private Student student;
       //getters and setters
      }
      
      Class Student{
        private String firstName;
        private Date myDate;
        private ArrayList<Long> ids;
       //getters and setters
      }
      
      
      User user = new User();
      if(user.getStudent() !=null && user.getFirstName()!=null && user.getStudent().getFirstName().equals("he")){
        System.out.println("great job");
      }
        • 1. Re: calling object without checking for null
          TPD-Opitz
          If you want to initialize the variable with a default you should declare a constant
          class Student [
           public static final Student DUMMY_STUDENT = new Student();
          }
          But if every user will have it's unique Student you better pass the Student object as a constructor parameter the final keyword makes the compiler check for initialisation (but also prevents changing the referenced object):
          class User {
            private final Student student; // assign an object only once
            User(Student student) {
               this student = student;
            }
          }
          Also you should not access the student field in user directly. You should better use a getter method.

          bye
          TPD
          • 2. Re: calling object without checking for null
            csckid
            student object does not has to be initialize all the time.
            • 3. Re: calling object without checking for null
              rp0428
              Before you drop your money in a coke machine do you check to make sure there really is a coke machine? Or do you just drop your money into thin air and hope for the best?

              Same thing applies to your student class. How can you get a first name if there isn't a student to begin with?
              • 4. Re: calling object without checking for null
                csckid
                My objective of this thread is to know better ways to avoid checking for null, or a better way to check for null, instead of writing too many conditional check.

                I have to check null values for student first and then null check for firstname.
                if(user.getStudent() !=null && user.getStudent().getFirstName()!=null && user.getStudent().getFirstName().equals("he")){
                  System.out.println("great job");
                }
                • 5. Re: calling object without checking for null
                  TPD-Opitz
                  look for a better design.

                  When Users do not nessesarily contain Students, why do you ask users for student details?

                  if not every User needs a Student you maybe better do the other way around?

                  bye
                  TPD
                  • 6. Re: calling object without checking for null
                    csckid
                    My actual scenario is not the thing I have mentioned in thread. I gave an example to grab my problem easily.

                    please ignore syntax and any other error, I just typed it without even caring the logics
                    class SearchOption{
                         Student student;
                         Registration registration;
                         ..
                    //    getters and setters
                    }
                    class Student{
                       String firstName;
                       String lastName;
                       String address;
                       String State;
                       Date birthday;
                     //many other fields with getters and setters
                    }
                     class Registration{
                      int departmentId;
                      int registrationId;
                      Date startDate;
                      Date endDate;
                     //many other fields with getters and setters
                    }
                    
                    
                    //searchStudent method prepare a query based on fields which are not empty 
                    void searchStudents(SearchOption searchOption){
                        String sql = "select * from ";
                        if(searchOption.getStudent() !=null{ sql += " Students";}
                        if(searchOption.getStudent() !=null && searchOption.getStudent().getFirstName() !=null && !searchOption.getStudent().getFirstName().equals("")){
                            sql += " student.firstName like '" +searchOption.getStudent().getFirstName() ;
                        }
                        ...like this it checks which fields are not empty and prepare a query
                    
                    
                    }
                    • 7. Re: calling object without checking for null
                      rp0428
                      >
                      I have to check null values for student first and then null check for firstname.
                      >
                      Correct - you can't ask someone that doesn't exist for their first name; commen sense.
                      >
                      My objective of this thread is to know better ways to avoid checking for null, or a better way to check for null, instead of writing too many conditional check.
                      >
                      You have to either check for null or trap the exception that will occur if you don't check and you get a null. Checking for null is best.
                      But you don't have to check the same thing for null multiple times like you do here
                          if(searchOption.getStudent() !=null{ sql += " Students";}
                          if(searchOption.getStudent() !=null && searchOption.getStudent().getFirstName() !=null && !searchOption.getStudent().getFirstName().equals("")){
                      In that code why are you checking 'searchOption.getStudent()' for null multiple times. Just make the call once and do one check:
                      Student searchStudent = searchOption.getStudent();
                      
                      if (searchStudent != null) {
                        sql := " Students";
                        -- check first name for null and, if not null, get the first name and add it to the query
                        --anything else that needs to be done if there actually IS a student in the search criteria 
                      }
                      • 8. Re: calling object without checking for null
                        csckid
                        ok so I guess I must check for null everytime, which is kinda hectic job.

                        I thought that I might have to write a function that checks for null, so I would pass everything into that function and that function will never send an exception
                        • 9. Re: calling object without checking for null
                          TPD-Opitz
                          Or you try another design approach...

                          bye
                          TPD