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);