On Wednesday, January 03, 2018 17:27:38 Marc via Digitalmars-d-learn wrote: > for a safe programming, since C/C++ times I try to make thing > const as possible. locals, parameters etc anything which isn't > going to change. > How do you do that in D? immutable everywhere? > > for example: > > foreach(Field field; fields) { > > > > immutable string htmlOutputfile = genHTMLFilename(); > > do you use immutable here? > > and on: > > Field fromFile(in string filename) { > > do you use in here if filename isn't going to change? > > I'm trying to make my own const nazi guide for D, if anyone would > like to give your opinion on this, I would be glad.
Well, D's const is far more restrictive than C++'s const (and immutable even more so). So, I think that you'll find that if you slap const and immutable everywhere, you're going to have a fair bit of difficulty. Feel free to use them as much as you can get away with, but a lot of us have basically given up on using const much, because it just doesn't work in far too many cases (e.g. ranges and const don't work together at all; ranges need to be mutated to iterate). const and immutable are transitive and don't have backdoors (casting away const to mutate is undefined behavior in D, unlike C++). This means that they they provide real guarantees but also that a lot of places where folks would happily use const in C++ simply can't use const in D, either because the transitivity makes something const that wouldn't have been const in C++, or because in C++, you'd use a backdoor like mutable, and that doesn't work in D. To use const or immutable in D, the objects have to not need to mutate in any way shape or form. "Logical" const simply isn't a thing in D. In general, I'd advise using immutable over const, since it provides better optimization opportunities and allows passing objects across threads if need be, but that can often mean having to design your types differently so that they can properly function as immutable. So, good luck, but I don't know very many people who try and use const everywehre in D like you might in C++, because it's often too much of a pain to make it work if it's even possible, and if you're using ranges and templates all over the place like many of us do, it's even worse. - Jonathan M Davis