Best Practices: hasXXX () for possible null return getXXX () methods

This question may seem very simple, but I have not yet found the answer, so I ask the community. As the name implies, I have a class with several getXXX () methods, where some of them can return null. This is documented, and the user of this class should be aware of this fact.

To simplify the use of this class, I had the idea of ​​adding some convenient hasXXX () methods that indicate whether certain fields are set or not. First of all, this seems like a good idea ... but then a Thread security issue arises.

Since instances of this class can be shared between threads, property values ​​can change. Since we all know that check-then-act is possible only if we know that the state does not change after the call to the check method, even if we interrupt by performing our actions with a check-action.

The following occurred to me:

  • Provide a user of this class with a way to β€œlock” an instance for state changes when the check-then-act code is executed.
  • Remove the hasXXX () methods as they are useless for mutable classes.

I do not find this as a rare case, and some members of SO could have addressed this problem earlier and found a solution ...

Foobaerchen

+3
source share
10 answers

- , XXX, getXXX() null.


if ( (x=bar.getXXX()) ) {
   x.foo();
}


if ( bar.hasXXX() ) {
  bar.getXXX().foo();
}

, hasXXX

+10

hasXXX(). , ( , ).

get , , . NullPointerException , . , .

+5

check-then-act , , , .

, getXXX(): , A - , getXXX(), B . , getXXX getYYY, , , .

, . - , - , . , , .

, , . .

+3

, hasXXX() , . , , , , , OO.

+1

++ boost::optional<T>. : boost::none.

+1

, , ... hasXXX().

get, .

0

hasXXX() , null . , hasXXX() , . hasXXX() , getXXX() null, - , - Vulcan!; -)

has/getXXX() , hasXXX() , , , getXXX() null. , /getXXX ().

, , , bigGetXXX(), , hasXXX(), , getXXX() . , null, null... , getXXX(), null.:-) bighasXXX(), , bigGetXXX() null . , . , verybiggetXXX()... , ...

hasXXX(). * .

0

1. getXxx() , (.. null), , .

, , ", null". :

public class Foo
{
    public static final String  NULL_STRING = "Foo.NULL_STRING";

    private String  m_bar;

    public void setBar(String v)
    {
        if (v == null)
            v = NULL_STRING;
        m_bar = v;
    }

    public String getBar()
    {
        return m_bar;
    }
}

, getBar() , (.. , ) NULL_STRING, m_bar . null , .

, (, STRING_NOT_SET) , , null, null .

public class Foo2
{
    public static final String  STRING_NOT_SET = "Foo.STRING_NOT_SET";

    private String  m_bar = STRING_NOT_SET;

    public void setBar(String v)
    {
        m_bar = v;
    }

    public String getBar()
    {
        return m_bar;
    }
}
0

hasXXX():

  • hasXXX() , getXXX() != null, , ,
  • getXXX() , hasXXX() -

OTOH, getXXX(), hasXXX() .

0

Source: https://habr.com/ru/post/1717146/


All Articles