Strict mode

bearophile bearophileHUGS at lycos.com
Thu Sep 24 03:17:22 PDT 2009


In some dynamic/scripting languages the basic programming modality is quite relaxed, this may help the programmer to quickly write a 10 lines long script. But when they want to write longer programs of 200 or 2000+ lines, some of such languages offer a "strict mode" that imposes more constraints and helps avoid/fix bugs.

(Python for example doesn't have a strict mode, it has a single modality, that's more strict than basic Perl, but less strict than for example Java and quite less strict than Ada. While for example JavaScript is a mess, its management of global/local variables is broken.)

The C language isn't very strict. D language is designed to be compatible with C, and often it just disallows some unsafe things of C.

So "SafeD" modules may also be in strict mode, disallowing some things that are valid C that can be used in unsafe D modules.

One of the several things that can be mode more strict in D are the retrieval of variable names in global/local scopes, and class attributes.

For example Ruby forces to prepend class attribute names with @. Most programmers use some name convention for them, or "this.". Good IDEs give different colors to class attributes. Replacing programmers conventions with something standard and compiler-enforced may be positive.

Another possible idea: in strict mode functions must have an annotation that lists what variables are used from an outer scope, and if they are read, written or both.

In this example the function "foo" has an input variable "n", returns a tuple of int and double, and it uses variables "a" and "b" found in an outer scope, "a" is just read and "b" is read and written (the parentheses around the multiple output arguments are compulsive, they avoid troubles):

(int,double) foo(in int n) {
    outer in int a;
    outer inout int b;
    
    double tot = 0.0;   
    foreach (i, 0 .. n) {
        b[i] += a[i];
        tot += b[i];
    }
    return (n, tot);
}

Inside this function if you try to a variable "c" found in an outer scope you have a compilation error. Outer variables have to be listed before their usage.

Using many global/outer variables is bad programming practice that leads to messy programs (so generally it's probably better to just add to such "foo" function "a" and "b" among its input/ref arguments), but if you want to use them, then it's better to list that they come from outside. This helps for example when you want to translate some strict D code to another language.

There are other ways to make the language more strict, for example disallowing some automatic casts, etc. (C# already has some of this, for example float => double requires a cast. I don't remember if D2 requires this already).

Bye,
bearophile



More information about the Digitalmars-d mailing list