Returning nulls

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • anonymous.user0@gmail.com

    #1

    Returning nulls

    Whats the common/best practice for returning a "Does not exist/not
    found" result from a function. Imagine I've got a function:

    myObjectType GetById(long id);

    where the object may or may not be found. Currently, I just return a
    null. But this muddies up the calling code with null checks and stuff.
    Example:
    I've got an Appoinment class, that has a property Doctor of class
    Doctor. This property is lazily loaded, so I only store the id of the
    doctor in the Appointment class (doctor_id).

    public property Doctor Doctor{
    get{
    if(doctor == null){doctor =
    DoctorManager.G etById(doctor_i d)}
    return doctor;
    }
    set{
    doctor = value;
    if(value != null){doctor_id = value.id;}
    else{doctor_id = 0;}
    }
    }

    Now, when using the Doctor property in Appointment class, I always have
    to check if the Doctor is null. This can be ugly when doing something
    like displaying the Appointment information.

    private void showAppointment (Appointment apt){
    txtTime.Text = ...
    if(apt.Doctor != null){
    txtRoom.Text = apt.Doctor.Offi ceNumber;
    txtDoctorName.T ext = apt.Doctor.Name ;
    }
    etc...
    }

    I was thinking of creating a static Doctor instance in the Doctor class
    that represents a Null Doctor like this:
    public class Doctor{
    public static readonly Doctor NullDoctor = new Doctor("Null
    Doctor name", "Null Doctor Office",...);
    ...
    }

    and in the GetById() functions, returning the NullDoctor if none is
    found. This of course, would cause me to change my Doctor Property to
    something like this:
    public property Doctor Doctor{
    get{
    if(doctor == null || doctor = Doctor.NullDoct or)
    {doctor = DoctorManager.G etById(doctor_i d)}
    return doctor;
    }
    set{
    doctor = value;
    if(value != null){doctor_id = value.id;}
    else{doctor_id = 0;}
    }
    }

    Pros/Cons for each approch?

Working...