Simplification of @trusted

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Jun 17 19:04:27 UTC 2021


On Thu, Jun 17, 2021 at 11:25:44AM -0700, Walter Bright via Digitalmars-d wrote:
> On 6/17/2021 8:59 AM, H. S. Teoh wrote:
> > What are the actual advantages of code being marked pure?  I'm all
> > for generalizing pure, but does it bring enough actual benefits to
> > be worth the effort?
> > 
> > I'm not talking about theoretical benefits, but actual benefits that
> > the compiler can actually make use of to emit better code.  I used
> > to be a big fan of pure, but in practice I've found that it doesn't
> > make *that* much of a difference in terms of codegen.  Maybe I'm
> > missing something, in which case I'd love to be enlightened.
> 
> You're right it doesn't make that much difference in code quality.
> What it *does* provide is:
> 
> 1. makes it easy to reason about
> 
> 2. makes unit testing easy
> 
> Just think about trying to unit test a function that side-loads
> various globals.

I guess, as a side-effect of the way I usually code, which is to avoid
globals unless I absolutely cannot get around it, I'm not really seeing
the benefits of adding `pure` to my function declarations. :-D  Almost
all of my code is already pure anyway, it's just more work to tag them
with `pure`.  So if it doesn't bring significant additional benefits,
I'm not seeing it as pulling its own weight.

On a tangential note, when it comes to unittests, you're right that
globals make things hard to test.  The same also applies for code that
modify the state of the environment, e.g., the filesystem. In Phobos
there used to be (still are?) unittests that create temporary files,
which makes them hard to parallelize and occasionally prone to random
unrelated breakage.  In my own code, I sometimes resort to templatizing
filesystem-related functions/types so that I can test the code using a
mock-up filesystem instead of the real one, e.g.:

	// Original code: hard to test without risking unwanted
	// interactions with the OS environment
	auto manipulateFile(File input) {
		...
		auto data = input.rawRead(...);
		...
	}

	// More testable code
	auto manipulateFile(File = std.stdio.File)(File input) {
		...
		auto data = input.rawRead(...);
		...
	}

	unittest {
		struct MockupFile {
			... // mockup file contents here
			void[] rawRead(...) { ... }
		}

		// Look, ma!  Test a filesystem-related function without
		// touching the filesystem!
		assert(manipulateFile(MockupFile(...)) == ...);
	}


T

-- 
Life is complex. It consists of real and imaginary parts. -- YHL


More information about the Digitalmars-d mailing list