The point of const, scope, and other attributes

Walter Bright newshound2 at digitalmars.com
Wed May 11 05:02:31 UTC 2022


The original D did not have them.

Many people who have written D code without them, and then added them. Then they 
noticed that although those attributes are meant to prevent bugs, adding them to 
existing code did not find any bugs. So what is the point?

A small anecdote. Before the backend was recently converted to D, I was invited 
to try out one of the good C++ bug checkers. I thought great, this will find 
bugs in the backend.

While it generated about a thousand false positives, it didn't find a single bug.

But I realized that I was running the checker over code that had already been 
thoroughly debugged through a lot of usage. Of course it didn't find anything. 
All the memory corruption bugs, bad casts, etc., had already been squeezed out.

The point of the checker was to find bugs in fresh code, and find them before 
even trying to run the code. The checker saves you the trouble of finding those 
bugs yourself. It saves you the trouble caused by shipping those bugs.

---

Another story. Back when I was programming in C, and was inexperienced, my code 
had a lot of bugs in it. I made every mistake, over and over. Having a memory 
corruption bug was a depressingly routine problem, and they were always hard to 
debug. But, over time, and endless experience, I gradually learned to avoid 
writing those bugs. I can't even recall the last time I wrote a memory 
corruption bug. (Of course, saying this, tomorrow for sure I'll make that mistake!)

But this is really doing things the hard way. I'm lazy, I like the easy way.

---

There are other reasons for the attributes, such as making code more 
understandable. A `const` parameter tells you the function doesn't modify that 
argument, or what it points to. A `scope` parameter tells you the function 
doesn't save a copy of it, so the caller can confidently delete the data. And so on.


More information about the Digitalmars-d mailing list