by flukus · 10y ago · 0 comments
It's great to finally have tuples, but the c/java style syntax is showing it's age compared to something like scala which has return type declarations at the end, which I find much more readable.
Literal improvements will be a godsend for writing database migrations.
Ref returns and locals look like a source of constant headaches. It's much harder to reason with code when the data can be modified by random others bits of code. Currently I can look for all references to an array to find everywhere that modifies it now I can't.
> Out variables seem like a mis-feature, especially when they are adding a better alternative (Tuples) in the same release.
Out variables are really great when working with existing code that predates Tuples (for example, the entire BCL). We don't just introduce language features that will only work well for new code. We also want to make the experience of coding against existing APIs feel better.
> Ref returns and locals look like a source of constant headaches.
That 'headache' has to be weighed against the needs of some parties to write very fast code and to have as little overhead as possible. ref returns enables a much more pleasant coding experience that enables these sorts of speedups in these specialized scenarios.
> It's much harder to reason with code when the data can be modified by random others bits of code.
There is a simple solution to this of course, don't expose your data through ref returns :)
For many (likely most) developers, ref returns simply won't be something that ever hits their radar. Similar to stackallocs and other esoteric features, this is really a targeted improvement for people who really like working in .Net but are finding it hard to squeeze out essential perf in some core scenarios.
The .net runtime supports this features fantastically. We wanted to make it available to people who like the power and safety of C#, but occasionally need some low level hooks to get that extra perf boost as well.
I disagree on this point. If there is a language feature that has been superseded by a better alternative, continuing to add sugar to the old feature only serves to perpetuate its use.
It embiggens the language while providing relatively little value in return. Furthermore, it adds confusion as to what should be considered idiomatic.
Tuples and deconstruction are so clearly better than out variables, I would have thought it would make more sense to deprecate the "out" feature entirely. Or, at the very least, not make it easier to use them.
Awkward and outdated features should be painful to use.
I also felt that this was a very odd addition. Even odder, the article doesn't even list tuples and deconstruction first.
With tuples especially, it's even worse, because the method name gets squished between two very similarly looking ()s, which is very different from how methods have historically looked in code. If I were scanning code fast, I'm not sure I would even read it as a function declaration.
C++ adopted its "auto ... -> ..." syntax a while ago - granted, they had a forcing function in form of decltype(), but many people also use it for readability reasons with complex return types. I hope C# follows suit; or, better yet, comes up with a unified type-after-name syntax a la ES6, that can be used everywhere in the language, while retaining existing syntax for back-compat purposes.
public TResult SomeMethod() where TResult : (string name, int id)
public SomeMethod(bool b) -> (string name, int id) { ... }
However, this may be undesirable due to confusion with => for lambdas and expression-bodied methods, especially in: public SomeMethod(bool b) -> (string name, int id) => ...
: is the next obvious candidate, and would unify the syntax with TypeScript and many other languages. But given that it's already used for labels and named arguments, I'm not sure there's enough room there to reuse it also for types.:: is another decent choice in terms of familiarity coming from other languages (Fortran, Haskell etc). But, unfortunately, it's already taken for extern alias, and I don't think this could be easily disambiguated in many contexts.
Now, if this is narrowly scoped to method return type only (i.e. we're not trying to invent a syntax that could later be used in a similar way to swap the type and the name in other places, like arguments and variables), and only as a fallback for when the usual "Type Name" arrangement has poor readability, perhaps take a hint from Ada and reuse "return"?
public SomeMethod(bool b) return (string name, int id) { ... }
A tad verbose, but if it's intended to be used sparingly, primarily with tuple-returning methods and deeply nested generics, I think that's okay - tuples themselves are pretty verbose when components are named.Or maybe borrow "as" from VB? It looks like it could be extended to other kinds of declarations in the future in a straightforward manner, without conflicting with its existing use for casts:
// Just for method return types
public SomeMethod(bool b) as (string name, int id) { ... }
// For everything
public SomeMethod(b as bool) as (name as string, id as int) {
var x as float;
TryFoo(out var y as bool);
...
switch (obj) {
case foo as Foo:
...
}
}I'm worried this could result in a loss of focus, you can't make everyone happy all the time. c# is a fantastic language to develop applications in (web or desktop) but it's never going to be the fastest language around or be a systems level language. For me some of the other features listed here (like immutable records) would be a much better fit for where c# excels already.
One of the reasons we are stuck with C and C++ is because other language vendors, including Microsoft, dropped the ball regarding performance of type safe languages.
Do you think C++ would have been kept around if Java and the CLR had been AOT compiled to native code with focus on compiler optimisations since day one?
I really appreciate the efforts of the .NET team in adopting the Midori lessons in the standard .NET stack.
Consider virtual generic methods, for example. If your set of types is not statically bound, you can't allocate the appropriate number of vtable slots in advance, because you don't know all the instantiations.
There are many pieces of code that you probably use every day that go to great lengths to squeeze as much power as possible. Why not help these folks help us? I'm glad there is more focus on performance because we all benefit. (Hoping to see more on the CLR side.)
Rust or D seem like the best bet here
Try OCaml.
Note: it's not like you can just sprinkle 'ref' on the return type of your methods willy nilly. Like 'ref'/'out' parameters, it requires you to do very specific things to keep your code safe/legal. As such, it's unlikely to just be added by people because, by and large, most code won't be equipped to actually handle it properly.
The codebases that will want to use this are already ones that have done a lot of work that makes them amenable to ref. i.e. game engines where you have large arrays of structs that you want to operate on in an efficient manner and whatnot.
You can't retro-fit multiple-returns (via Tuples) onto existing library functions, so for places where you're forced into using out parameters, this is a slight improvement.
TReturn Foo(T1 param1, out T2 param2)
can be called as if it were (TReturn, T2) Foo(T1 param1)
You'd need a keyword to trigger this kind of overload resolution at the call site to ensure back compatibility - maybe you'd have to call (var x, var y) = out Foo(param);
or something. That way all that legacy library code gets a free upgrade to your new language feature.Since the C# team decided not to do that, you can actually implement a version of this at a library level, by static importing a family of generic methods like this:
Func<TParam, (T1, T2)> Tuplify<TParam,T1,T2>(Func<TParam, out T1, T2> outFunc) {...}
for every pattern of out params you want to convert, then you can just call (var x, var y) = Tuplify(Foo)(param);Scala or .... VB.net!
-Anthony D. Green, Program Manager, Visual Basic
IEnumerable<Student> GetStudents(SqlCommand cmd)
{
var rdr = cmd.ExecuteReader(); //select * from student left join courses on...
var memo = new Dictionary<int, Student.Completion>(); //Completion lets us add courses to a student
while(rdr.Read())
{
if(!memo.TryGetValue(rdr.GetInt32("student_id"), var out complete)
memo.Add(new Student(rdr out complete).ID, complete);
complete.AddCourse(rdr); //might be a no-op
}
return from kv in memo select kv.Value.Student; //each student object is unmodifiable.
} if(!memo.TryGetValue(rdr.GetInt32("student_id"), var out complete)
memo.Add(new Student(rdr out complete).ID, complete);
I think I understand your point, but I found this code really hard to read. You don't use the first var out complete in the TryGetValue, right? And the Student c'tor returns itself as an out parameter?If I understand you correctly, you like this because you don't have to declare a new student before you add it? I.e. the alternative would be
if(!memo.ContainsKey(rdr.GetInt32("student_id")))
var student = new Student(rdr);
memo.Add(student.ID, student);
I guess I would prefer this over the former. Also, why not enforce your student ID constraint in SQL instead of putting everything in a dictionary only to take it back out again? That would simplify your code to the point of just being a map from rdr->Student. Furthermore, if all I had was the Student c'tor, I would never guess that was the intent of the out parameter. This seems more anti-pattern than pattern.I would rather put a simple IEnumerable in front of SqlDataReader so that you could just do:
foreach(var row in rdr) yield return new Student(row)
This doesn't obviate your use case, however, which is to inline a variable where it's needed in multiple places in that line because you can save yourself an explicit declaration. In this case, however, I think that the increased readability justifies the explicit declaration.> You don't use the first var out complete in the TryGetValue, right?
There is only one complete variable; we declare it in TryGetValue, and it's definitely used in the last line of the while statement, but might first be used after the if statement.
> And the Student c'tor returns itself as an out parameter?
The Student constructor does not return itself as an out parameter, rather it returns an object that can modify an internal list of courses.
The idea is that when we iterate through a result set from a database, some of the rows are going to correspond to a new student object, and some are going to correspond to a course that belongs to the student. Crucially, we are only allowed modify the Student object (or whatever) during iteration, and the collection that we return will only contain immutable/unmodifiable Student objects.
I've used this technique to populate deeply nested structures (lots of joins and nested joins) using only one query.
> I would rather put a simple IEnumerable in front of SqlDataReader so that you could just do:
> foreach(var row in rdr) yield return new Student(row)
Just to be clear, the reason that I cannot do that is because the Student object might not be completely "hydrated" until we finish iterating through the result set, because it might contain a bunch of nested objects that also need to be instantiated from one or more DB records.> Also, why not enforce your student ID constraint in SQL instead of putting everything in a dictionary only to take it back out again?
I'm not quite sure I understand this (which is probably my fault), but rest assured that we use nothing but SQL (specifically, DDL) to enforce data integrity.
Back to this code:
if(!memo.TryGetValue(rdr.GetInt32("student_id"), var out complete)
memo.Add(new Student(rdr out complete).ID, complete);
There's a parens missing on the end of the if, correct? Also I can't parse the student c'tor: new Student(rdr out complete)
I was assuming there is a comma in there somewhere. Does this compile? What does "out" do here? I thought you were getting a new out variable, but that's not correct since you wouldn't be able to name it the same in the same scope.Also, I don't see how "complete" is ever non-null. If the ID isn't in the dictionary, then TryGetValue returns false and "complete" is null. Then you add the null "complete" to the dictionary, and throw away the Student object (which apparently does other side effects) once you have its id? If ID is in the dictionary, you get back what you inserted, which is still null.
And then you call .AddCourse on the possibly null reference? I'm lost.
Can you post the code again? Maybe I'm just missing something due to a syntax error.
Can you elaborate on this; both how it helps and why you're using C# for database migrations?
Each migration gets a number, typically time encoded. If I was to write one now it would have the attribute [Migration(201608251157)]. With the new literals this will become [Migration(20160825_1157)], amazing how much readability a single underscore can make.
I hope there are better examples of Scala's syntactical advantages than this one, because it seems like the 'egyptian-style' vs 'next line style' brace bracket debate...