Use null object as argument to method

Consider the following piece of code

class Foo
    {
    public:
    //...
        bool valueFirstGet(int& value) const
            {
            if(this==nullptr)
                {return 0;}
            value=values[0];
            return 1;
            }
    //...

    private:
        int* values;
        size_t n_values;
    };

int main()
    {
    Foo* obj=findObject("key");
    int value;
    if(!obj->valueFirstGet(value))
        {printf("key does not existn");}

    return 0;
    }

findObject returns nullptr if it cannot find the object. Is it ok to let the member function do the null check instead of its caller. In my code, there are several calls to findObject directly followed by a call to valueFirstGet so leaving the check to the caller makes the code ugly.

EDIT:

Is there a cleaner way to avoid all null checking besides having findObject to throw an exception instead of returning null?

EDIT 2:

What about a static wrapper?

7

The null-check in valueFirstGet can not yield true without there being undefined behavior in the program, because you must dereference a null-pointer (which causes UB) to let that test yield true. The nasty thing about undefined behavior is that any behavior is fully sanctioned and that behavior might change between compiler versions or even optimization levels without notice.

The correct way to go about this is to have the check in the caller or in a helper method. If the findObject/valueFirstGet calls are commonly paired with no further use for the object returned by findObject, you can even do something like this:

bool tryValueFirstGet(const std::string& key, int& value)
{
    Foo* obj=findObject(key);
    return obj && obj->valueFirstGet(value);
}

The short-circuit behaviour of && ensures that valueFirstGet will only be called if the object could be found.

2

A common and useful way to avoid null pointer checking is by using the Null Object pattern. Essentially, instead of using the language’s built-in definition of a null object as “a null pointer you can’t dereference,” you create your own definition with useful null behavior appropriate to your situation. Remember, you’re a programmer. You don’t have to settle for whatever limited facilities are built into the language.

Using the null object pattern for your example might look something like this:

class Foo {
  public:
    int getCount() {
      return n_values;
    }

    int firstValue() {
      return values[0];
    }
}

class NullFoo : public Foo {
  public:
    int getCount() {
      return 0;
    }

    int firstValue() {
      return 0; // Return a useful default if you want, or throw an exception if you want.
    }
}

Then if your findObject doesn’t find the key, it instantiates and returns a NullFoo (or returns a reference to a static object), which can be dereferenced without undefined behavior, and can provide any kind of default behavior you like, including throwing an exception if the situation calls for it.

The nice thing is your regular Foo can be guaranteed to have at least one element, so you can skip a lot of checks there as well. All the checks are done at instantiation time, and polymorphism handles the rest.

7

Summary:

The design problem you’ve presented actually deals with two kinds of issues, thus it involves two classes of possible solutions too.

Is it ok to let the member function do the null check instead of its
caller?

Semantically speaking, it does not make sense. To call an instance method of a null object is logically incorrect because the object does not exist yet.

So that being said, a cleaner solution to this design problem would be to handle the case as clearly as possible by using the exception mechanism available in the language. Let the findObject throw the exception and let the caller routine handles it as needed. This results to a more readable code.

In my code, there are several calls to findObject directly followed
by a call to valueFirstGet so leaving the check to the caller makes
the code ugly.

This is where a wrapper method will come in handy to avoid repeating yourself.

Sometimes, working with large chunks of legacy code, such null checking proves to be helpful. But I will never recommend it for a class being written from scratch.

Also note, that in valueFirstGet() the &value could also be null. I have worked with legacy code, where such situations had to be taken care of, too.

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật