Double check it's really an element



  • Uses the range checking form of accessor/mutators of std::bitset after arguments are explicitly range checked. All calls to Flags::get and set use explicit enum elements (no conversion from int/string). At least he didn't try to catch exceptions (thrown if argument to test/set is out of range).

    As usual, the explanation is "what if someone passes in a bad value?"

    enum Item { A, B, C, MAX_ELEMENT };
    
    class Flags {
    private:
        std::bitset<MAX_ELEMENT> flags;
    
    public: 
        bool get(Item item) {
            if (item >=0 && item < MAX_ELEMENT) {
                return flags.test(item);
            }
            else {
                return false;
            }
        }
    
        bool set(Item item) {
            if (item >=0 && item < MAX_ELEMENT) {
                flags.set(item);
            }
        }
    };
    
    Flags flags;
    
    flags.get(A);
    flags.set(B);

  • Java Dev

    Well, even if the argument to get() and set() is checked automatically, you'd still need to check for MAX_ELEMENT manually. If they're not checked automatically, I don't think it's weird to verify, especially if this class is used in a lot of places.

    I think this may be language confusion? Is there any point in even having MAX_ELEMENT in this language?


Log in to reply