Question

Besides reserved words, is it a questionable practise to give member functions or variables identifiers which are the same as (or similar to) STL or C standard library names? What are the drawbacks of using such names? In which cases such practice is unacceptable?

To better illustrate:

class Example
{
public:
    size_t size();
    bool empty();
    void erase(ctype end);
    int memset(const Example &);
private:
    typedef int lower_bound;
    std::vector<lower_bound> stack;
};
Was it helpful?

Solution

In the sample code you provided the only questionable choice of name is memset, as it will not be obvious to users what e.memset(b) means. In case it is not obvious what this means is thatÑ as long as the names are clear for the user this is a good thing.

Now the problem comes with the fact that names that are well known may convey more meaning than what the word actually means. For example you might write a container type like:

class MyContainer {
   // ...
   void add(const Element& e);
      // Adds 'e' to the container
   bool isEmpty() const;
      // Returns true if the container is empty
   void empty();
      // Removes all elements from the container
};

While there is nothing inherently wrong with the choice of names, but in a container people expect empty() to be a check that returns whether the container is empty. That would make it a poor choice for a function that does anything different as it generates confusion.

So basically it is fine to use the same identifiers, as long as the use is not in conflict and won't be confusing to other developers.

OTHER TIPS

The reason why it might be considered good practice is uniformity. You want users to be able to have a familiar interface and to not "get in their way" so to speak. In other words, you can go ahead and model your classes after the standard library. The problem, in my opinion, with libraries is verbose names and interfaces. It really isn't necessary unless you pollute the global namespace, which you should not be doing anyway. You would only want to deviate in your naming convention if your functions had unexpected side effects or did things adversely from how users generally expect them to be implemented. See Erase-remove idiom for an example of how your users might try to use your erase function and expect it to work this way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top