Search code examples
c++stlnaming-conventionsnaming

Why is STL "empty" member function not called "isEmpty"?


Kindly check std::vector from cplusplus.com.

It says it has an empty() member function:

empty
Test whether vector is empty (public member function )
http://www.cplusplus.com/reference/vector/vector/empty/
Signature : bool empty() const;

To me, empty meaning should have been to remove all elements from this container. However, it's a testing function which checks if the container is empty. I checked all other containers, and all use empty the same way.

Why does stl not use isEmpty() instead ?


Solution

  • Case Style

    To remain consistent with the naming convention of the C++ standard library, I would have actually baptised the member function you are referring to as is_empty() instead of isEmpty(). That is, following the snake case naming convention instead of the camel case one. We can see this convention in other member functions, e.g., push_back() and pop_back().


    Note that there is a member function called clear() that does empty the container. Perhaps the reason for omitting the verb (i.e., the is of a hypothetical is_empty), and therefore requiring less typing, was this separation of names for querying whether the container is empty (i.e., empty()) and emptying the container (i.e., clear()).

    Otherwise, if the word "empty" would have been used instead, for both the query and the update, the verb would have been probably part of the name of the member function for querying, since both member functions have no parameters. Therefore overloading wouldn't have been possible. The member functions would have been then likely called empty() and is_empty() for emptying the container and for querying whether it is empty, respectively.


    [[nodiscard]] attribute

    In these cases where the name of a member function corresponds to both an adjective and a verb (e.g., member functions with the name empty, clear or clean), using the C++17's [[nodiscard]] attribute can be very useful to signal misbehavior.

    For example, empty() as in std::vector – a member function that performs a query, and therefore, returns a value – can be marked [[nodiscard]], so that if the return value is not used, the compiler issues a warning. This warning signals that the programmer may have used empty() as if it did empty the container, but it actually queries whether the container is empty.

    Note, however, that the compiler is not required to issue a warning.