by thoth · 11y ago · 0 comments
Yes it is a contrived example, yes you can write "better" C#, but this is a short example for illustrative purposes.
I bet if somebody wrote a blog post about Djikstra's letter "GOTO considered harmful" 45+ years ago, attempting to illustrate it with more examples, it would have collected similar comments: nothing wrong with GOTO, I can use it correctly; that example of spaghetti GOTO code is poor and not idiomatic; the example code is too simple and nobody would write it that way; yes it takes discipline to use GOTO without ill effects but nobody would accidentally/maliciously subvert my GOTO hierarchy; etc. Meanwhile, the original point about structuring code using different techniques to help avoid problems (and avoid GOTO) would be lost.
It's like people are overly defensive about language features (or lack thereof) as if writing extra boilerplate and not letting the compiler help is a badge of honor.
EDIT: clarity
class Range {
public int From {get;}
public int To {get;}
public Range(int from, int to) {
Assert(from <= to);
From = from; To = to;
}
}Your proposed problem might be better solved with the Option type and a simple guard to return None if out of range.
>comically easy to avoid using a standard OO approach
This is an ironic statement given that your code, as written, is circumvented by subclassing Range and side-stepping its constructor. I suppose you actually meant "sealed class"... but we're getting off in the weeds again, missing the fundamental point of the post.
You are the second one who says this. I must admit that I do not understand how this would be possible. The properties are not virtual, and not writable for anything but the base constructor. To my knowledge, it's impossible avoid the base classes constructor by subclassing. I'm pretty sure you can actually circumvent the assert, but you would have to use the heavy weapons in the reflection API.
class Range
{
public int From { get; }
public int To { get; }
public Range(int from, int to)
{
Assert(from <= to);
From = from; To = to;
}
}
class LolRange : Range
{
public LolRange() : base(0,1)
{
From = 1; To = 0;
}
}
Error CS0200 Property or indexer 'Program.Range.From' cannot be assigned to -- it is read only
Error CS0200 Property or indexer 'Program.Range.To' cannot be assigned to -- it is read only