by louthy · 12y ago · 0 comments
var success = int.TryParse(s, out var x);
I'm a bit 'meh' about Primary constructors, Auto-property initializers, Getter-only auto-properties. It seems a bit messy and incomplete. Personaly I don't use properties anymore and just use readonly fields with constructor initialisation (which is enough to capture the property setting logic). What I would like to have seen in this area is 'readonly' classes, with mechanisms for cloning objects using named parameters for partial updates: readonly class ReadOnlyClass(public int X, public int Y, public int Z)
{
}
Usage: ReadOnlyClass obj = new ReadOnlyClass(1,2,3);
ReadOnlyClass newObj = obj.X = 10;
Instead of the current system for creating immutable classes in C#, which becomes quite unweildy and error prone as the number of fields grows. class ReadOnlyClass
{
public readonly X;
public readonly Y;
public readonly Z;
public ReadOnlyClass(int x, int y, int z)
{
X = x;
Y = y;
Z = z;
}
public ReadOnlyClass SetX(int x)
{
return new ReadOnlyClass(x, Y, Z);
}
public ReadOnlyClass SetY(int y)
{
return new ReadOnlyClass(X, y, Z);
}
public ReadOnlyClass SetZ(int z)
{
return new ReadOnlyClass(X, Y, z);
}
}
Usage: ReadOnlyClass obj = new ReadOnlyClass(1,2,3);
ReadOnlyClass newObj = obj.SetX(10);
I think 'using' static members will be a huge win for creating functions which appear to be part of the language. For example I use the following to do type inference on lambda expressions: static class lamb
{
public static Func<T> da<T>(Func<T> fn)
{
return fn;
}
}
var fn = lamb.da( () => 123 );
I'v tried to make it look like part of the language by making it all lowercase, but it's still a little odd. Being able to 'using' a static class in would be perfect for this kind of stuff. To be used sparingly obviously.Expression bodied members, yes please! So pretty...
public double Dist => Sqrt(X * X + Y * Y);
Typecase and Guarded Cases would be lovely too. Basically anything that enables expression based coding in C#. It would be nice if the LINQ language functions were extended too: count, take, skip, tolist. It's slightly less pretty when having to wrap the expression in brackets to call .ToList();The `using` static is actually really good news. I have seen people who seem to be really mad about it, but sometimes it would be nice to have, for example:
// Something like Scala's 'Predef'
public static class Id<T>
{
public static Func<T, T> Identity { get { return x => x; } }
}
and then do: using Id;
var grouped = list.GroupBy(Identity);
Considering you can already open modules in F# (which are compiled down to static classes), it seems that feature found its way to C#. So maybe there is still hope for pattern matching and tuple support :)Equivalent of F#'s record types would be also awesome, which is what you put as 'readonly class':
type Person = { FirstName : string; LastName : string }
let single = { FirstName = "Jane"; LastName = "Doe" }
let married = { single with LastName = "Smith" }Perhaps C#'s record type could enforce immutability on not just the record but anything it's assigned to (maybe by using 'let'). That would allow the old mutable way to co-exist with language enforced immutability. It doesn't seem like it would clutter up or modify any existing code either, so if you don't like it, you never need to see it.
Not sure how that would work when assigning to a class's member property/field. Perhaps you opt out of immutability (of the reference) with a 'mutable' keyword:
class AClass
{
public mutable ARecordType Value;
}
Functional languages also 'extend' the behaviour of a type by defining functions that work with the type. But with an object-oriented language like C# you'd still expect the functionality to come with the type I think. So I suspect it would have to look something like this: type Vector
{
float X;
float Y;
float Z;
int Length => Math.Sqrt(X*X+Y*Y+Z*Z);
Vector Add( Vector value ) => new Vector { X+value.X,Y+value.Y,Z+value.Z };
}
So it turns the entire class into one big constructor (with everything public by default). All non-expression fields should be provided when you instantiate the object: let obj = new Vector { X=1, Y=2, X=3 };
I'd be very happy with that. Maybe I'll fork the compiler and have a go... if I can just find the time.... gahThere's no clear 'functional programming' benefit to the property syntax, either. Even though the syntax implies that Dist is logically some kind of a Func<double>, I still won't be able to write Func<double> f = Dist, because Dist is of type double.
I'm also concerned about the idea (only 'planned' for now, I believe) for the same syntax for methods which take arguments, though. That feels like it risks pushing developers into the pit of failure by encouraging them to write public methods that contain no parameter validation logic, just evaluation of a return value. It also means that the instant you want to add more complexity to a method you're forced to completely rewrite it in the conventional curly brace syntax.
Then there's the halfway world of using the syntax for a method which takes no arguments:
public double Dist() => Sqrt(X * X + Y * Y);
where now I can write Func<double> f = Dist...public double Dist => Sqrt(X * X + Y * Y);
> I'm also concerned about the idea (only 'planned' for now, I believe) for the same syntax for methods which take arguments, though.
Where's this? I must have missed it. Or could you show what it would look like?
public Point Move(int dx, int dy) => new Point(X + dx, Y + dy);
Which is logically consistent with the property syntax, but as I say, I have my reservations about it.Yes it's enough if the property setting logic is only executed once during the lifetime of the object. So, it only works if they're supposed to be immutable.
Plus, public fields cannot be used for data binding.
Plus, you can't debug nor log whenever a field value is read.
Also, you can end up having to convert it into a property, and this involves various compatibility risks.
Meanwhile, there is no plausible scenario where you realize you must convert a property into a field.
What do you gain instead, with your design choice?
They are. Dig out some of the talks by Rich Hickey on immutability, he tends to put it pretty concisely, better than I ever could. But primarily it's about capturing snapshots of your world at a particular point in time so that you have a consistent view of the world. So all objects should be immutable.
http://www.infoq.com/presentations/Are-We-There-Yet-Rich-Hic...
> Plus, public fields cannot be used for data binding.
JsonConvert.SerializeObject()
JsonConvert.DeserializeObject()
That's all I need, or a .Select(). I don't use WinForms or any of the standard ASP.NET databinding stuff, it's ugly as sin. Even if I did, isn't there a LinqDataSource or something these days? Not sure if that would do the job, but I'd assume it would work with the results of a LINQ expression? Anyway, I don't really need that, and being able to reason about my code is more important.
> Plus, you can't debug nor log whenever a field value is read.
Never caused a problem, there's always the code that reads from it. Stick your breakpoint there. Also when you use immutable structures throughout, your bugs tend to not be in the 'values' (i.e. an immutable structure).
I tend to be breakpointing in the ctor if anything to check the setter logic or input values. Once the object is set, that's it. No need to keep checking.
> Also, you can end up having to convert it into a property, and this involves various compatibility risks.
Fields an properties are incompatible? How?
> What do you gain instead, with your design choice?
* I can pass an object to another method and know it's not going to change it without my permission.
* I don't have to analyse the inner workings of a class to find out how the state is going to be changed when I call a method on it.
* I can pass the same object to two threads running in parallel knowing that there won't be problems with the two threads writing to the same object..
* I can easily write transactional code and 'rollback' when it fails.
* I can write pure functions which makes it easier to test my code.
It's much easier to reason about a data structure if you know they won't change basically. There's huge advantages to that. Personally I find it makes my code more reliable and easier to compose and manage long term.
I agree it's not all sweetness and light using immutability with C#. There's more boilerplate than necessary and there's very little in the language to help the process.
Personally I think it's worth it, YMMV.
YMMV as you say, but I think that your needs are very specific if that's your base principle. Objects in C# are mutable by design, so you're kind of working against the language here. It sounds like your approach is closer to functional programming (but again, I don't know the context)
> I don't use WinForms or any of the standard ASP.NET databinding stuff
Neither WPF, Siverlight... long story short, hardly any popular .NET framework (nothing wrong about that, it just goes to show that your case is not mainstream)
> Fields an properties are incompatible? How?
See http://csharpindepth.com/articles/chapter8/propertiesmatter.... - "Compatibility issues".
> Never caused a problem, there's always the code that reads from it. Stick your breakpoint there
As long as it's only one or two places and as many breakpoints, sure :) life's beatiful then
> I can pass an object to another method and know it's not going to change it without my permission.
Achievable with properties (with private setter), so I wouldn't count it as a benefit.
I see where you're coming from, but to me you are pointing out the advantages of immutability, not choosing fields over properties. I think you are not wrong in preferring immutability, of course - I know it has its perks - but in assuming that one is synonymous with the other. Whereas you can implement immutability with properties just as well (and you can still use a readonly field as the backing field).
Not really. This is for a very large web-based medical practice-management system and tertiary services. It mostly sits on top of stripped-back ASP.NET, but yes it's a framework I developed myself because 9 years ago when this project started ASP.NET was awful.
So yeah, whilst it's non-standard, it's not rocket science, or some bizarre parallel C# universe. I still need to get data from the server to the client in an efficient way, I still have controllers, server pages, database CRUD, etc.
> Objects in C# are mutable by design
Objects are mutable by default, but there also exists a keyword called readonly which has been there since v1.0 of C#, so I would argue that it's just as much of a language feature. It not being the default doesn't make it any less of a valid approach. One of the most used library types is immutable: String.
> It sounds like your approach is closer to functional programming (but again, I don't know the context)
I try to follow that route, yes. Clearly it's not always possible because of the limitations of the language or the .NET framework, and that's fine, I'm not going to be dogmatic over it. I think however that immutability where possible helps code quality overall.
> Fields an properties are incompatible? How? > See http://csharpindepth.com/articles/chapter8/propertiesmatter..... - "Compatibility issues".
That's very interesting, but none of those are really issues for me, and I'd argue they'd be minor issues for most people too:
> You lose binary compatibility
We always compile from source
> You can use a field for ref parameters, whereas you can't (in C# at least) use a property in the same way.
Ref fields are nasty, I wouldn't want to see anyone on my team using them. obviously passing a readonly field to a ref is pretty pointless. So non-issue for me.
> Involving a mutable structs
Don't use mutable structs.
> You lose reflection compatibility
Call GetFields instead of GetProperties. Non-issue internally. I guess if a 3rd party lib didn't support fields then it might be a problem, so far it hasn't been.
> Achievable with properties (with private setter), so I wouldn't count it as a benefit.
No it isn't, because the method you called could call a method on the object you passed, affecting the underlying state of the object. If you work on small code-bases and you understand the implications of every function you call then great, but the added peace of mind knowing that this structure you passed to a method isn't going to be changed (now or by a programmer in the future) is very powerful.
It's also makes method signatures tell you explicitly the behaviour of the code within, which makes it easier to look at the surface of a library to know what it does, i.e.:
MutableState state = new MutableState(...);
MutableLib.DoSomething(state);
// ... any code run after DoSomething is now flying-blind, has state changed?
public class MutableLib
{
public static void DoSomething(MutableState state)
{
// What happens here? Does MutableState get changed? How can you know when the
// method returns 'void' and takes a mutable object? You have to look at the code
// to know for sure.
}
}
Then the immutable version. Notice how the signature to DoSomething is explicit in its purpose. ImmutableState state = new ImmutableState(...);
var newState = ImmutableLib.DoSomething(state);
// ... any code run after DoSomething is entirely aware that state has changed
public static class ImmutableLib
{
public static ImmutableState DoSomething(ImmutableState state)
{
// What happens here? Well it doesn't matter to the caller, they know
// they get a new ImmutableState back, and if they chose to ignore it
// then the original state object they passed in will be unaltered.
}
}
It also allows for free transactional behaviour with rollbacks, which can be super useful: ImmutableState state = new ImmutableState(...);
try
{
var newState = ImmutableLib.DoSomething(state);
newState = ImmutableLib.DoSomethingElse(newState);
newState = ImmutableLib.DoAnotherThing(newState);
// Commit
state = newState;
}
catch
{
// If an exception fires then state won't have changed.
}
> I see where you're coming from, but to me you are pointing out the advantages of immutability, not choosing fields over properties.You're right that I'm primarily arguing for immutability, but I would also argue that properties can't achieve immutability because the object can always change itself. A private property can always be changed by a member function. Clearly you can make classes that are immutable for all intents and purposes by using properties; I just prefer the explicit nature of 'readonly' - it's a language feature to be used in my humble opinion.
There's also the argument that properties are an extra unnecessary abstraction for this case. With a readonly field/property it is only set once, so having a layer of getter/setter logic is unnecessary. You only need that logic once at construction.
So it looks like:
var possibleInt = TryParse(s);
if(!possibleInt.Success)
{
//Fail out early
}
var actualInt= possibleInt.Data;
(Our Reply objects also allow for messages to be passed up, so that various layers can report details of the error they bumped into, and the presentation layer can then display them.)