The keyword const
is used to describe that a member variable, method or function cannot modify the state. This is defined to disallow modifying the state in places where it's unsuitable or inappropriate. Language features like this can be useful for things like strings, such as in const char *
but in almost every other place, it's a bad idea.
Assuming the Programmer is stupid
const
is like many object-oriented language features that burden developers more than it assists. It is a quick, cheap way to describe that a state should not be modified in a certain context, and letting the compiler enforce it. While it may be beneficial in enterprise environments to enforce standards and be able to easily identify culprits attempting to sabotage a project or codebase, compiler features are not the way to deal with this.
In many ways, it assumes the programmer is not intelligent enough to understand why a state should not be modified in a certain context to avoid problems in the first place. This further brings to question if the programmer was trained up correctly and understands the codebase they're working on. If they have been hired to develop and create features or fix issues in a codebase, some of the standards being enforced may be over-the-top.
Often I feel that compilers treat me poorly by themselves. C# is a prime example, which attempts to enforce optional nullability
on member variables that haven't been initialised with a value (besides primitive types). This enforcement behaviour dictates that everyone should use RAII (or Resource Acquisition Is Initialisation), which is arguably slower that leaving values uninitialised in domains where it's necessary (see any REST API, Networking, etc.).
RAII is an object-oriented concept that dictates that for every object created, all their values must be initialised with a default value. This can be useful where default behaviours can be quickly created and logic is performed with default values. This can be useful for trivial tasks, but such trivial tasks need not be burdened by RAII by enforcing it. It should be optional.
In many ways, const
is the same. It is an enforcement policy, rather than a meaningful definition of something, and that by its own merit makes the keyword a painful experience for everyone who otherwise doesn't advocate for it. There are many other such like enforcement policies by compilers, dictating what a programmer can and cannot do. It claims the programmer is stupid. It points out you can't modify a state, which means you must find ways to modify the state and makes you wonder why you put the const
keyword there in the first place.
There are few places where it's necessary, but most of the time, it isn't.