3 ms·
I have a distaste for all of these examples, which comes from the existence of a side-effecting operation: calling do_something() necessitates the need to call
by gregmac 4y ago
I have a distaste for all of these examples, which comes from the existence of a side-effecting operation: calling do_something() necessitates the need to call a cleanup function, which means there's some state being changed but hidden behind the internals of these methods. It is really easy to call this incorrectly which says to me it's just a badly-designed API.
In C# the idiomatic way would be to have each of these 3 things be defined in a class using IDisposable, which is similar to D's scope() -- the declaring class gets a cleanup method when the variable goes out of scope, no matter how that happens.
I assume there's some interaction between these classes, but IMHO that should be explicitly defined and so the code would look something like:
public void foo(int bar) {
using var something = new Something(bar)
if (something.do()) {
using var stuff = new Stuff(bar);
if (stuff.init()) {
using var stuff2 = new Stuff2(bar); // two "stuff"s looks dumb but this is example code
if (stuff2.prepare()) {
return do_the_thing(something, stuff, stuff2, bar);
}
}
}
return null;
}
There's actually several ways to structure this code which would result in something that looks better than the above, but being example code and not knowing how `something` and `stuff` interact, it's hard to write this nicely. I'd probably aim for something much more concise like:
public void foo(int bar) {
using var something = new Something(bar);
using var stuff = new Stuff(something);
using var stuff2 = new Stuff2(stuff);
return stuff2.prepare() ? do_the_thing(stuff2) : null;
}
In the above, I assume stuff2.prepare() calls everything it needs to on the dependent objects, but how I'd structure this for real entirely depends on what they're actually doing.
- marcosdumay 4y agoIn C# it's customary just to wave away the worst kinds of problem that C and D developers try to handle, and let the runtime kill your program. (This is more an artifact of why people pick their languages than anything inherent on the languages themselves.) But rest assured, your C# code is full of global state hidden on its runtime and is subject to the same kinds of errors people are discussing here.
- hgsgm 4y ago"hidden on its runtime" keeps it out of the rest of thr program.
- marcosdumay 4y agoThe entire program still has the same failure modes. If you wanted to handle them, you would get the same problems.