const, final, scope function parameters

Myron Alexander someone at somewhere.com
Sun May 27 15:46:33 PDT 2007


James Dennett wrote:
 > Walter Bright wrote:
 >> I think having to write:
 >>
 >>     mutable int x;
 >>
 >> instead of:
 >>
 >>     int x;
 >>
 >> just isn't going to please people.
 >
 > Maybe not.  It would please me; in C++ right now, I usually
 > have to write "int const x = ...;" whereas if the default
 > were the "safe" form I could write just "int x = ...;".
 > (As usual, "int" is just an example, of course.)
 >
 > Writing
 >
 >   var int x;
 >
 > would be just fine by me; I find it more readable than
 > using "mutable" (and the C++ community already has a
 > similar-but-different meaning for mutable, as you know,
 > so using a different term might be helpful).
 >

James,

Having const default for all variable declarations would be problematic 
in that most variables are expected to be mutable. The whole point of 
variables is that they are variable :)

I think the one exception is strings in that the D implementation is an 
array but conceptually, there is a difference of opinion for whether 
strings are buffers or values. I am firmly on the "string is a value" 
bench and have my wet trout ready to go slap the "other" side when the 
mother of all wars begins :) (Actually, I have a nuke-lee-are trout that 
is const, non-static, and very final ;))


Walter Bright wrote:
> Regan Heath wrote:
>> Walter Bright Wrote:
>>>> Why can't we apply 'scope const final' to function parameters only?
>>> Because it knocks people for a loop - gives a bad first impression.
>>
>> Have these people tried using it, in the beta itself?
> 
> No. But you can't get people to try something they take an instant 
> dislike to.

I am of the opinion that function parameters that are, by default, 
"scope const final" will improve code quality. When coding (even in 
Python and Java), I use that style.

My reasoning is that values passed in are part of the interface state 
and that rebinding, or modifying them can lead to confusion or errors. A 
quick example that actually happened to me:

Two people working on the same code need to modify a method. This method 
is quite long so when the other programmer added some code in the middle 
that modified the parameter value before I used it, on merge, there was 
a problem. The other person did not need to modify the actual parameter 
value but was too lazy to assign it to a temp variable thus the problem. 
(BTW, this is not how I work, it was the team leader's idea of 
"collaboration". We weren't even using CVS, the merge was manual). I 
have seen similar bugs on more than one occasion.

BTW, if I declare a class parameter to be const, what happens if I try 
to call a method that will change the class state?

Regards,

Myron.



More information about the Digitalmars-d mailing list