In C#, with extension methods, you can replace this line of code:
TimeSpan interval = TimeSpan.FromMinutes(4);
with this one:
TimeSpan interval = 4.Minutes();
Extension method being:
public static TimeSpan Minutes(this int minutes)
{
return TimeSpan.FromMinutes(minutes);
}
The second example is interesting because of the extension method on the integer literal, which is valid, but looks strange (even more so because adding a period after a integer literal has two different meanings: becoming double literal and member access). The second example also reads almost like english (even though the first one does as well albeit in a different way).
Is it a bad practice to use language features in such way as to increase brevity and readability, but “abusing” the language? (I prefer answers that deal with WHY you consider one better than the other, and not only WHICH ONE you prefer.)
Personally I find the second way more like the usual object-oriented way of thinking in which you state the object first and then access its member operation to perform.
Similarly to how we do with ToString
:
StringBuilder str = new StringBuilder();
// ... append something to the builder
String result = str.ToString();
and we don’t do
Strong result = String.From(str);
Of course, one could argue that this is simply how the API/Framework was designed.
Additional note:
This can also be stretched toward some other examples of achieving brevity:
String str = String.Format("{0} + {1} = {2}", op1, op2, op3);
changed to:
String str = "{0} + {1} = {2}".FormatWith(op1, op2, op3);
0
Is brevity in writing code beneficial when it requires using language constructs in a strange way?
Hell no.
Brevity is not a desirable trait. The time it takes to type in code is not a meaningful thing to optimize, since we so infrequently write code as opposed to read/debug/modify it. The time it takes the parser to read your code (or the size it takes on disk) is trivial.
Readability is a desirable trait, but it does not necessarily follow that brevity leads to readability. After all, the time spent understanding what we read isn’t mostly spent on seeing characters, but parsing them into meaning. Doing weird things will take far longer to understand in general. This is well known as the Principle of Least Astonishment (or Surprise) in design circles.
Now sometimes, using weird constructs makes things more readable/efficient/robust once people learn them and get used to them. That is a trade-off like any other worth evaluating. But your examples all make things hard to read to do nothing more than save a few characters.
10