CodeSOD: Static State

This post was originally published on this site

The Daily WTF

Today’s Anonymous submitter was reviewing some C++ code, and saw this perfectly reasonable looking pattern.

class SomeClass { public: void setField(int val); int getField(); }

Now, we can talk about how overuse of getters and setters is itself an antipattern (especially if they’re trivial- you’ve just made a public variable with extra steps), but it’s not wrong and there are certainly good reasons to be cautious with encapsulation. That said, because this is C++, that getField should really be declared int getField() const- appropriate for any method which doesn’t cause a mutation to a class instance.

Or should it? Let’s look at the implementation.

void SomeClass::setField(int val) { setGetField(true, val); } void SomeClass::getField() { return setGetField(false); }

Wait, what? Why are we passing a boolean to a method called setGet. Why is there a method called setGet? They didn’t go and make a method that both sets and

To read the full article click on the 'post' link at the top.