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

spir denis.spir at gmail.com
Fri Jan 21 16:08:28 PST 2011


On 01/21/2011 09:56 PM, Jonathan M Davis wrote:
> 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

I just realised scope(success) can avoid 2 kinds of bugs, one common, 
one naughty:
* at first coding time, simply forgetting releasing resources (one 
thinks at that when accessing it, but then, it's easy to forget), or any 
other exit task
* at maintenance time, opening a new exit point for a function (new 
return), and forgetting the exit task there

Denis
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list