nav search
Data Centre Software Security DevOps Business Personal Tech Science Emergent Tech Bootnotes
BOFH
Lectures

back to article
Mads Torgersen and Dustin Campbell on the future of C#

ratfox Silver badge
Windows

Programming Peter Principle

Every programming language that is working well gets burdened with new features and frameworks until it sucks.

Another version is that programmers have a tendency to write code that is just complicated enough that it still runs, but is unmaintainable.

Andrew Richards

Re: Programming Peter Principle

Although C# is still quite neat given it's a v6 heading towards v7. A lot of recent changes are syntactic simplifications so there's an element of moving towards simplicity rather than complication. (Obviously, YMMV but LINQ, the TPL, async/await, yield return (etc.) all make the older alternatives look awkward.)

Anonymous Coward
Anonymous Coward

Re: Programming Peter Principle

>Every programming language that is working well gets burdened with new features and frameworks until it sucks.

like .Net or Mono? I keed.

Anonymous Coward
Anonymous Coward

Re: like .Net or Mono?

ES6 more like. Trying to retro fit strong types to JavaScript is a horrible and quite stupid idea. Languages are different, stop trying to make them all into wanky C clones!!!

Adam 1 Silver badge

Re: Programming Peter Principle

> Obviously, YMMV but LINQ, the TPL, async/await, yield return (etc.) all make the older alternatives look awkward.)

Perhaps, but it can also hide a bunch of inefficient loops (thinking linq).

I saw the following line a month back

Var myshashset = new hashset<int>();

// Put some numbers in it

if (myhashset.Any(a => a == 5))

DoSomething;

Put a million numbers into your hashset if you want to know why that is such a bad idea.

Another one I saw was two consecutive aggregate functions, which I had to point out to the author that they were iterating their whole dataset twice.

The others though are brilliant.

Dan 55 Silver badge

Null pointers

Maybe it's my C/C++ background but I'm not seeing this one. It's just yet another incorrect value, if you dereference it and expect to find an object or a function and there isn't one then things will explode. You could replace NULL with 0xFFFFFFFF or something and still have the same problem.

hammarbtyp Silver badge

Re: Null pointers

Their suggested solution seemed very much like impolementing a definition of pre and post conditions and Design by Contract. Maybe they should take a leaf out of the Eiffel book

AndrueC Silver badge
Happy

Re: Null pointers

This isn't about the underlying value. In C# NULL (actually 'null') is a keyword. It has a very specific meaning of 'doesn't point to anything'. It's underlying numeric value is already irrelevant. A C# pointer isn't just an integer that the compiler lets you dereference. A pointer is a specific thing and has dedicated semantics. This means it can be tracked through the code using analysis. In

C#/.NET allows for better analysis so the compiler (and the IDE thanks to Roslyn) can understand the concept. What they seem to be suggesting is allowing a variable to have a '?' suffix to indicate that NULL values are permissable. So with this change any code that currently issues the warning 'Possible System.NulReference Exception' wouldn't compile unless the variable had a '?' suffix. That coupled with static analysis would ensure that pointers which should never be null will, in fact, never be null.

Dan 55 Silver badge

Re: Null pointers

Ah. A C++ reference. Well why didn't they say?

ThomH Silver badge

Re: Null pointers

I think they're politely not referencing competitors, to avoid lurid misrepresentations, but what they're describing sounds exactly like optionals in Ceylon or Swift, as also available in Java 8 and via Boost in C++ but in both cases being opt-in. If so then the semantics are fairly easy: any reference/pointer that may be null explicitly says so, and there's some sort of single-statement construct for dereferencing arbitrarily many in sequence or else getting some other result if any is null (depending on language possibly also optionally allowing an exception if any is null).

E.g. in no language in particular, result = dictionary[helper.getAdaptor().getProperty()].or(defaultValue)

...without having to test whether dictionary exists, then whether helper exists, then whether getAdaptor returns non-null, then whether getProperty returns non-null.

AndrueC Silver badge
Thumb Up

Re: Null pointers

Actually, yes, similar to references. It's been a few years so they'd slipped my mind. But C# pointers are not quite the same because it's a garbage collecting language. They are more akin to smart pointers. We do instantiate a class via new:

var fred=new Person();

but when we pass an object to a method:

kill(fred);

We don't think of it as passing a pointer to fred, we just think of it as passing fred.

And if Kill() wants to take its own copy:

void kill(Person aPerson)

{

_myListOfKilledPeople.Add(aPerson);

...do the actual killing.

}

It's not a problem. Dear old fred will hang around for at least as long as he's needed. The only downside is that we won't know exactly when he finally pops his clogs. On the occasions where that matters using() is the closest we have to RAII, though most people seem to use try/finally instead :(

Pointers generally only crop up in unsafe code eg; talking to the Windows API. But even there p/invoke does a pretty good job of hiding pointers as well:

// C++ (NativeLib.dll)

void print_line(const char* str);

// C#

[DllImport("NativeLib.dll")]

private static extern void print_line(string str);

Andrew Richards

Re: Null pointers

I think they already have: C# supports contracts already...

AndrueC Silver badge
Happy

Re: Null pointers

without having to test whether dictionary exists, then whether helper exists, then whether getAdaptor returns non-null, then whether getProperty returns non-null.

That already exists. It's called the null propagator. It's quite handy actually but feels a little lazy :)

bill.laslo

Re: Null pointers

you can explicitly call the garbage collector on an object etc, then log when it has been collected.

otherwise, yes, the object will just hang around until the gc comes round on its normal pass and you will be none the wiser for it.

Andrew Richards

Re: Null pointers

I think that's closer to what ? does now. E.g. dictionary[helper?.getAdaptor()?.getProperty()]?.or(defaultValue)

Aren't they suggesting a new non-nullable type to complement "type?" ("type!") that would mean constructor have to explicitly instantiate the object as they do for value types?

DrXym Silver badge

Re: Null pointers

The issue with NULL / null / nil (whatever) pointers is you put the caller, or the thing you're calling at risk of failing. Yes it may handle the null, or maybe it'll assume you didn't feed it garbage and promptly crash or throw some fatal exception. This might not be so big a deal for some app on the desktop, but it might be damned serious if this is a drone flying around in the sky.

Some languages like Rust don't even support the concept of NULL for standard application programming. There is literally no such thing. If you have a function which might return nothing, then you have to use a return type such as Option which is basically an enum capable of returning a value called Nothing. Otherwise if something says it returns a Foo, it is guaranteed to return a Foo.

tiggity Silver badge

Re: Null pointers

And (as with so many of these simplifications) you end up with code that is less readable to someone not expert in C#

Example is small dev teams, where (not full blown code review), but someone else just high level sanity checks the code to check it makes sense against spec, the reviewer may not be a C~ guru e,g, may be mainly a Java, Perl, C++ whatever user and so those types of constructs tend to be hassle for mini reviews as they say WTF does this code mean whereas some "if(x == null etc." logic would make sense to them.

Potentially cryptic fragments of code (be it C#. perl, whatever language) can cause grief in multi disciplinary dev teams, even simple stuff like C# null coalesce can cause readability grief.

I'm a big fan of a bit of extra typing so the code can be read by a non expert in that language but who is heavily involved in the spec the code is supposed to meet.

But obv. YMMV, what is "readable" is a very different matter if a big C# only dev team

AndrueC Silver badge
Boffin

Re: Null pointers

And (as with so many of these simplifications) you end up with code that is less readable to someone not expert in C#

Yup, what goes around comes around. I've been programming since the 80s and when I started brevity was key because of scarce resources. Then verbosity gained the upper hand because resources were relatively plentiful and it made maintenance easier. Now it seems we're going back to brevity apparently in order to hide complexity from people (at least I assume that's what's behind it).

But obv. YMMV, what is "readable" is a very different matter if a big C# only dev team

Very true. LINQ can produce code that's only readable if you understand LINQ (or possible SQL). But a C# programmer who isn't familiar with LINQ is arguably not a very good C# programmer.

Plus some shorts bypass useful control. I still don't like the use of {}s for class construction in C#. I'd rather have multiple ctors are ctors with optional parameters.

Anonymous Coward
Anonymous Coward

Re: Null pointers

>>Ah. A C++ reference. Well why didn't they say?

>I think they're politely not referencing competitors,

You aren't talking about Microsoft in general because when they want to release a new OS or product it sure isn't C# (few cases aside) they are using. They need something fit for purpose.

JLV Silver badge

Re: Null pointers

I would argue that if you are doing a technical code review in a technical capacity then you ought to familiarize yourself with pointer/reference semantics for the language at hand.

But I also think that you are 110% right about readability. For such a core feature, I find it encouraging that they are willing to flag it as something they want to do, yet will defer until they have the feature and syntax better figured out. Easier to add stuff to a language than to take it out and harder yet to correct bad syntactic choices later on.

Rob Gr

Re: Null pointers

I've a background in C/C++ and find it utterly stunning that someone else from that background cannot see the damage done by null.

C++ mitigates it by having a reference type that cannot be easily initialised to null (its still possible to subvert), Rust improves the situation further. True, it just comes down to checking, but its like all other compile-time checks - if it helps prevent errors then some progress has been made.

Have a look at the C++ Core Guidelines to see how seriously some C++ luminaries take the state of affairs.

Rob Gr

Re: Null pointers

A C++ reference you cannot subvert...

int a = nullptr;

int& b = *a; // Should not be possible

Rob Gr

Re: Null pointers

There is a difference.

With an explicit "if (a == null)" before the usage, there is a chance a will become null before the usage actually occurs in the presence of multiple threads. Unless I'm mistaken, the null-conditional operators avoid that potential issue.

so

a?.DoSomething();

is actually equivalent to..

var x = a;

if (x == null)

x.DoSomething();

Rob Gr

Re: Null pointers

They already did that with Spec#, many of the ideas from Spec#, Sing# (Singularity's C#) and Midori now seem to be migrating to mainstream C#. A good thing.

Rob Gr

Re: Null pointers

References in C++ are pretty much the same thing.

Rob Gr

Re: Null pointers

The difference is that its easy to subvert a reference:

int *p = nullptr;

int& r = *p;

p = 5; // OOPS!

Rob Gr

Re: Null pointers

Actually, they had a couple of very interesting projects: Singularity and Midori, that used enhanced forms of C# to produce managed, safe O/S. Very, very interesting work, and some of the most radical O/S research in recent years.

1Rafayal

It will be interesting to see where c# will go over the next few years, specifically with regards to the cloud and Azure etc.

Pure Windows apps have been dead/dying for quite some time now and the uptake of Linux on Azure is probably making MS think quite carefully about what it wants to do next and with which tools..

selina.davis

If Microsoft plays their cards right, they may end up with a case for continuing to use c# for a considerable amount of time.

As someone else mentioned on this thread, its getting more Delphi like all the time, not a bad thing either..

jeffdyer

Native code, nested functions, cross platform?

Smells like Delphi.

Anonymous Coward
Anonymous Coward

I think you mean: Stinks like Delphi.

Anonymous Coward
Anonymous Coward

You may be right, unluckily without Anders and in Embarcadero gnomes hands, Delphi is slowly rotting away... and its cross platform efforts are quite comical (unlike its Windows support which was fairly strong, years ago...)

But it's still funny to see Pascal old features being introduced as new features in C#.

MacroRodent Silver badge

Algol

But it's still funny to see Pascal old features being introduced as new features in C#.

If you mean nested functions, they were already in Algol 60. Pascal of course copied them from it, Pascal being basically a modernized version of Algol 60 (where "modern" = "circa 1970").

LDS Silver badge

Re: Algol

Right, but Anders created TurboPascal, not TurboAlgol :-)

EricOuellet

Bullshit !!!

Hey in regards about quicker feedback due to going open source... There is a MAJOR BUG that make VISUAL STUDIO 2015 CRASH 1-4 times a day since Update 2. The bug had been reported at Microsoft Connect on April 2 : https://connect.microsoft.com/VisualStudio/feedback/details/2544045/low-memory-detected-full-solution-analysis-disabled-for-this-solution-on-roslyn-code-analyzer-enabled-projects. AND we are still working with THAT shitty environment that crash now and then !!! WAKE UP MICROSOFT !!! Probably that they pay too much their managers and they don't care about users !!! Who will want to continue to develop with Microsoft product when they don't give a shit at their users.

Tim Anderson

Re: Bullshit !!!

You need to look here https://github.com/dotnet/roslyn/issues/10365 where there is a lot of discussion and a fix (thanks to @drpizza on twitter for pointing this out)

Sceptic Tank
Unhappy

Functions returning multiple values.

Functions returning multiple values ?!? Can somebody just kill me now? Python has this questionable "feature". Oh what joy to read someone else's poorly written code with nonexistent naming conventions vommiting out values into other poorly named variables.

Another thing: since we're making changes already, can we please have a proper destructor that is called at predictable times?

JLV Silver badge
Meh

Re: Functions returning multiple values.

It's a feature in Python. You don't have to use it and in fact few seem to.

Personally, while I find it convenient sometimes to return multiple values into a tuple, I agree that it is a code smell. So I usually create an object instance on the fly, assign my values onto it as attributes and then return a single value.

There is a fine line between a language/framework pragmatically promoting clean and robust code on one hand. And uselessly nannying assumed-to-be-competent programmers on the other. A crappy coder will find a way to be crappy in almost any language.

I would argue that work on making pointers/references more robust falls squarely on the side of generally useful language engineering.

While a certain language which requires declaring exception throws on each and every function's signature comes to mind for an example of the second outcome.

Multiple return values? Meh, probably not a very necessary complication in most cases, but easy enough to avoid.

find users who cut cat tail

Re: Functions returning multiple values.

Python functions can return tuples. And lists. And dictionaries, strings, sets, numbers, iterators, ... and all other types of objects. Tuple is just one of them and there is nothing special about returning tuples. You do not have to write the parentheses around the tuple in the return statement -- but that is true also in a number of other places.

Timmy B Silver badge

Re: Functions returning multiple values.

"Functions returning multiple values ?!? Can somebody just kill me now?.... "

Indeed. Why not have the function return a struct or class instance. I don't get why you would want two variables out like this. I suppose if you really wanted to push it you could argue a very minor memory benefit and speed difference. But if you're going that route lets forget OOP entirely.

Adam 1 Silver badge

Re: Functions returning multiple values.

It's not a mountain different to current techniques like int.TryParse() returning both the success and the value if it was successful or dictionary.TryGetValue returning both whether the object exists in the dictionary and the object itself when it does.

On more than one occasion I have created a class that inherits tuple and named item 1 and 2 via getter methods and named constructor parameters. It works nicely but can be very verbose.

Frumious Bandersnatch Silver badge

Re: Functions returning multiple values.

Perl subs (and some builtins) have this too, via the ability to return a list. You can aid readability firstly by properly documenting the calling convention, but also by using constants to simulate enums. For example:

use strict;

use warnings;

use constant {

Dev => 0, Ino => 1, Mode => 2, Nlink =>3, Uid => 4, Gid => 5, Rdev => 6,

Size =>7, Atime => 8, Mtime => 9, Ctime => 10, Blksize => 11, Blocks => 7

};

print "This dir's mode is ", (stat ".")[Mode], "\n";

Of course, Perl is a pretty pathological language. You can even modify the type of thing returned (via something like wantarray) depending on the calling context. Loads of scope to shoot yourself in the foot.

Michael Wojcik Silver badge

Re: Functions returning multiple values.

Tuples are prominent features of a number of programming languages, such as the ML family (including OCaml, Haskell, and F#). For the most part, they don't cause any particular maintenance problems.

Poor programmers (which appear to constitute the majority of programmers) can write unmaintainable code in any language. And will.

erikj

The Billion Dollar Mistake

If anyone has time to view it, InfoQ has a video of Sir Tony's "Null References: The Billion Dollar Mistake" talk from QCon London in 2009 here: https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare

The whole talk is good (if you're into languages) and the bit where he talks about inventing the Null Reference (and how Java's minders came to a similar conclusion 30 years later) starts at 8:30. The criticism of null pointers is talked about at 19:00. Warning: Here is a luminary computer scientist trying to get an engaging rise out of a room of software architects. No dryer humor will you find on this planet.

Anonymous Coward
Anonymous Coward

Personally, and I know I'll get down voted to hell for this, I prefer VB.Net syntax - why the feck should a modern compiler need squiggly brackets and semi-colons to tell it where statements begin and end, that's so old fashioned. Language functionality wise, for an average developer like myself, there's very little difference between the two languages - if you can do it in C# you can do it in VB.Net and visa-versa. But it seems C# gets all the love. I think it's the mis-placed association with VB6/VBA in some people's minds but VB.Net is a different animal. As somebody suggested on another site, MS should have called it V# !!.

Anonymous Coward
Anonymous Coward

No down vote from me, but I think it may have to do with the background of the people using the language and the ability to read/understand the code when used in larger projects. I find brackets and semicolons clearly define where things start and stop in a very visually available way. I prefer those squiggles and semicolons. :)

Michael Wojcik Silver badge

C-like punctuation-heavy programming-language syntax isn't any more "old fashioned" than VB's word-based syntax is.

From the very beginning, higher-level programming language design involved choosing among these and other alternatives for syntax. And those choices were made by analogy with other programming languages and with other systems of representation.

Some early programming languages, such as FORTRAN and ALGOL, were influenced by mathematical and formal notations. They also noted the storage limitations of the machines they ran on, the line length imposed by input mechanisms such as punched cards, and other constraints. Those favored punctuation-heavy syntax. The C family falls in this category.

Other languages, such as COBOL and (to some extent) LISP, took their cues from other sources and generally preferred words over punctuation. This family came to include BASIC and Pascal and their descendants.

Then there are languages which aren't consistently one way or the other, such as various scripting languages - the Bourne shell and descendants (e.g. "case ... esac" but also "$((...))"), for example, or Perl - a mishmash of every idea Larry Wall could think of at the time.

These days, the languages I use most often are punctuation-heavy C and OO COBOL, which largely avoids the stuff. I don't think either has a clear advantage in syntax under any obvious metric, such as readability or maintainability. (OO COBOL probably does have a small readability advantage if you're reading code in some environment that doesn't do syntax highlighting and brace matching, but most developers seem to use syntax-parsing editors these days.)

Some languages, such as OCaml, arguably use punctuation constructs that are too obscure - they're hard for infrequent users to remember, and completely opaque to those who don't know the language, because they don't have analogues in, say, English or common mathematical notation. That, I think, is a design failure. But it's also relatively rare. C# has some constructs (the "verbatim string", for example) which are probably a mistake, but for the most part it sticks to things that should be recognizable to practitioners.

Rob Gr

Absolutely, because Function and End Function is so much of an improvement

POST COMMENT House rules

Not a member of The Register? Create a new account here.

  • Enter your comment

  • Add an icon

The Register - Independent news and views for the tech community. Part of Situation Publishing