Are there any downsides to marking all variables you don't modify const?

前端 未结 6 2057
清歌不尽
清歌不尽 2021-01-07 16:24

After much googling I\'ve found a lot about marking functions and their parameters as const, but no guide on marking variables as const.

He

6条回答
  •  既然无缘
    2021-01-07 16:33

    I can think of at least two downsides:

    • verbosity: more words, more symbols to process, ...
    • inertia: if you need to modify it, you'll have to go and remove this const

    and both are worth it.


    Verbosity is an often heard argument against explicitness, however people often mistake reading speed with understanding speed. There is a balance to be found between verbosity and explicitness, certainly, too verbose may drown out useful information but too implicit/terse may not present information that has to be reconstructed/inferred/deduced/.

    Personally, I use a strongly typed statically checked language so that the compiler picks out my mistake as early as possible; annotating with const is both giving information to the reader and the compiler. I judge it worth the extra 6 symbols.

    As for inertia, removing const is probably only a small cost of the change... and it repays itself by forcing you to go through all the places where it's used and review the surrounding code to ensure it's actually alright to remove this const. Suddenly modifying a particular piece of data in a code path where it previously was immutable requires ensuring that no part of the code path (or its callers) accidentally relied on this immutability.

提交回复
热议问题