Why we need scope(success) if I can write at the end?

Jonathan M Davis jmdavisProg at gmx.com
Fri Jan 21 12:56:09 PST 2011

On Friday, January 21, 2011 05:18:15 tamir wrote:
> or what's the differents between theese two:
> void transactionalCreate(string filename) {
>   string tempFilename = filename - ".fragment";
>   scope(success) {
>     std.file.rename(tempFilename, filename);
>   }
>   auto f = File(tempFilename, "w");
> }
> and:
> void transactionalCreate(string filename) {
>   string tempFilename = filename - ".fragment";
>   auto f = File(tempFilename, "w");
>   std.file.rename(tempFilename, filename);
> }

scope(success) will be run _regardless_ of how you leave that scope (except for 
if an exepction is thrown). So, you can have one line with scope(success) and 
multiple return statements or breaks or continues or whatnot, and that 
scope(success) statement will be run in all cases. If you didn't use 
scope(success), then you'd have to duplicate that code at every point that the 
scope could be exited successfully.

Now, if there's only one way to exit a particular scope successfully, then 
scope(success) is less useful. However, even in cases like that it can improve 
code maintanence and readability when it comes to stuff like resources. For 
instance, if you were to open a file at the beginning of a function, having a 
scope(success) statement immediately following it makes it clear that closing 
the function has been taken care of, whereas without the scope statement, you'd 
have to worry about putting it at the end of the function separate from where 
the file was opened. Having them together makes the code clearer. Now, a file 
isn't the best example, since you'd want success(exit) in that case, and the 
File struct std.stdio deals with it anyway through its destructor, but the 
example should give you the basic idea.

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list