mercredi 4 septembre 2019

Avoid null pointers while accessing objects in a tree hierarchy of classes

I have to work with a tree based hierarchy of objects where I need to access the deepest element that contains the data required by the application. I'm not sure if the previous statement explains in its best the problem itself so its better to present it with an example. Given the following scenario:

class A {
private:
    B* _b;
public:
    B* getB() {return _b;}
}

class B {
private:
    C* _c;
public:
    C* getC() {return _c;}
}

class C {
private:
    int _n;
public:
    int getN() {return _n;}
}

The desired operation would be to access n via A. So I would call the following:

A foo;
foo.getB()->getC()->getN();

The problem comes when any of the parts of the path are null we end up having a core dump. In the above scenario if B is null we end up in a core dump scenario.

Therefore I seek help and advice on any strategy or pattern that I can use to avoid this core dumps scenarios. If the path is extremely big I end up checking every single pointer if its valid and end up having really ugly code and also risk that I might have missed checking a part of the path. Note: I do not have access to change the implementation of the getters as they are generated code and I do not have access to change the generator.

Aucun commentaire:

Enregistrer un commentaire