←back to thread

207 points mfiguiere | 2 comments | | HN request time: 0.924s | source
Show context
stickfigure ◴[] No.43539275[source]
Great! Now can we make `final` the default for all fields, variables, and parameters?

(yes yes, I know, that would break syntax... but please come up with something to discourage mutability)

replies(5): >>43539333 #>>43539950 #>>43540550 #>>43541493 #>>43543176 #
magicalhippo ◴[] No.43539333[source]
Const-ness in C++ is something I miss in other languages. Being immediate able to see that this function or method couldn't mutate the object made it so much easier to reason about the code.

Yeah I know there's ways around it, but then the author known what they told the other party to expect.

replies(3): >>43539580 #>>43540000 #>>43555589 #
pjmlp ◴[] No.43555589[source]
D goes one step further, as const is transitive.
replies(1): >>43566426 #
1. jstimpfle ◴[] No.43566426[source]
const is weird and I see no way of getting it right. Making const transitive in the way described in tha Dlang reference certainly sounds weird. It prevents totally valid use cases. Why wouldn't I have a const pointer to a mutable thing?

The real problem is that it's not defined what is an object, and where, in a web of memory-objects pointing to each other, a conceptual object begins and ends. It's arbitrary. Also, what is const from one standpoint is not const from another. It's fluid. Type systems generally don't play well with that. The weirdness of the original `strstr()` C API showcases that problem well.

The only thing that makes some sense here is to keep it simple -- any struct-like thing is an individual object. Embedded objects of course inherit const-ness, but pointed-to objects do not.

I think the C++ model is also somewhat right -- any class can define individually through which indirections const-ness follows through. But the C++ way causes lots and lots of boilerplate.

In any case, my solution is to use const very sparingly, it can hardly be gotten right in practice beyond basic use. Being more rigid of const may have prevents 2-3 bugs in my life, but cost sooo much more time and required many rewrites to make it fit somehow.

I use const mostly for

    - static const data
    - some string-slice datatypes (these are often initialized from static const data like string literals).
    - read-only function parameters passed by reference (Foo const *thing).
replies(1): >>43567308 #
2. pjmlp ◴[] No.43567308[source]
Hence why D has two approaches with similar semantics, const and immutable.

And also allows to alias non const references to the same data.

Thus the data can be modified by a mutable reference, owned by a specific part of the code, while everyone else only gets to see the const chain.