Search code examples
c++namingconventions

How to name method for setting boolean variable


I have boolean variable, which tells me if user has his own text (I have text edit widget in GUI) or if I should load from a file, called hasOwnText.

I am using it only inside of a class, so I don't need any getter, however I need to set it from outside depending on checkBox from GUI. The question is how the method should be named?

I've always named them like setHasOwnText and I don't know it just doesn't seem that good to me. Could it be somehow improved?

Also if my variable is named hasOwnText and if I ever need getter, should I just name it getHasOwnText?

Thank you


Solution

  • There are two common patterns for getters and setters:

    int someValue();              // getter
    void someValue(int newValue); // setter
    

    or alternatively:

    int getSomeValue();
    void setSomeValue(int newValue);
    

    At first, even though you don't need a getter, I'd provide one anyway, by principle. If a user can set a value (be it you yourself or anyone else), she/he might want to know some time later which value she/he actually set a while ago without having to remember separately. For booleans, I'm totally fine with first pattern, too:

    isSomething(true); // or has
    if(isSomething()) { }
    

    With second pattern, while 'get' is replaced with 'is'/'has', I'd still just prepend 'set' prefix:

    setHasSomething(true);
    if(hasSomething()) { }