Remix.run Logo
almostgotcaught 2 days ago

> Invariants are functions that run at the start and end of every public member function

these are just runtime assertions

EDIT: how am i getting downvoted for copy-pasting literally what the article verifies?

LorenDB 2 days ago | parent | next [-]

Yes, but they are guaranteed to run at the beginning and end. C/C++ asserts need to handle any return path, whereas D has functionality to mark statements to run at the end of any return path while only being written once.

See also the scope(exit) feature.

almostgotcaught 2 days ago | parent [-]

You can accomplish the same exact thing with

https://en.cppreference.com/w/cpp/experimental/scope_exit.ht...

WalterBright a day ago | parent [-]

The idea for scope-exit came from Andrei Alexandrescu. See https://dlang.org/articles/exception-safe.html

He demonstrated it with C++ templates, but the D one is far more straightforward.

jayd16 2 days ago | parent | prev | next [-]

I think there's something to be said about them running automatically that is lost when you say they're just asserts.

almostgotcaught 2 days ago | parent [-]

i don't get it - if do

  int foo(int a) {
    assert(a > 5);
    int b = a * 10;
    assert(b > 50);
    return b;
  }
do you think those asserts don't "run automatically"?
gblargg 2 days ago | parent [-]

You define the invariants once for the class and they are run around every public function. Done manually you'd probably use a helper object that calls the invariants in its constructor and destructor (have to handle exceptions) that you have to add to every public function's definition.

readthenotes1 2 days ago | parent | prev [-]

Maybe it's the editorial "just"?

Like: software programs can't be that difficult to create properly because they are just 1s and 0s.

johnisgood 2 days ago | parent [-]

This is not the first time someone getting down-voted for using the word "just". I do not know if this really is warranted, however.