The Benefits of Constants

前端 未结 14 1869
南笙
南笙 2021-02-04 07:46

I understand one of the big deals about constants is that you don\'t have to go through and update code where that constant is used all over the place. Thats great, but let\'s s

14条回答
  •  抹茶落季
    2021-02-04 08:26

    One benefit is that if it is truly a constant value, you wouldn't accidentally change it. The constant keeps you from screwing stuff up later. As a variable, anyone could come along and change it later when updating the code.

    It should be clear which values can never change and which values can change. Constants reinforce your intention.


    Real world example from my youth:

    We didn't have a built-in PI value on a system I was working on so someone created a VARIABLE called PI and somewhere along the way, someone (me) modified that value to 3.14519 (or something there abouts) in a procedure I wrote... not the approximation of pi 3.14159). It had been set elsewhere in the code, and all sorts of calculations were off from that point forward. Had that PI been a constant (it was changed later, of course), I wouldn't have been able to make that error... at least not easily.

提交回复
热议问题