oop - General purpose immutable classes in C# -
i writing code in functional style in c#. many of classes immutable methods returning modified copy of instance.
for example:
sealed class { readonly x x; readonly y y; public class a(x x, y y) { this.x = x; this.y = y; } public setx(x nextx) { return new a(nextx, y); } public sety(y nexty) { return new a(x, nexty); } }
this trivial example, imagine bigger class, many more members.
the problem constructing these modified copies verbose. of methods change 1 value, have pass all of unchanged values constructor.
is there pattern or technique avoid of boiler-plate when constructing immutable classes modifier methods?
note: not want use struct
reasons discussed elsewhere on site.
update: have since discovered called "copy , update record expression" in f#.
for larger types build with
function has arguments default null
if not provided:
public sealed class { public readonly x x; public readonly y y; public a(x x, y y) { x = x; y = y; } public with(x x = null, y y = null) => new a( x ?? this.x, y ?? this.y ); }
then use named arguments feature of c# thus:
val = val.with(x: x); val = val.with(y: y); val = val.with(x: x, y: y);
i find int more attractive approach lots of setter methods. mean null
becomes unusable value, if you're going functional route assume you're trying avoid null
, use options.
if have value-types/structs members make them nullable
in with
, example:
public sealed class { public readonly int x; public readonly int y; public a(int x, int y) { x = x; y = y; } public with(int? x = null, int? y = null) => new a( x ?? this.x, y ?? this.y ); }
note however, doesn't come free, there n
null comparison operations per call with
n
number of arguments. find convenience worth cost (which negligible), if have that's particularly performance sensitive should fall bespoke setter methods.
Comments
Post a Comment