I've been bothered by this line of code I've written and I've been a bit confused into what should be written instead.
class SomeClass
{
IBeneficiary _latestBeneficiary => new Beneficiary(Iban, Name);
}
In context, the field represents the latest version of a beneficiary object that is about to be created, and I want this variable to represent its latest possible version considering whatever is inside those public properties.
Here are my assumptions and thought process, I'm thinking there is something wrong in there otherwise I wouldn't have an issue.
So, clearly, this is a field. It's a field because it is a private variable I'm keeping inside my class, and to recognize it, I add an underscore as a prefix.
That field always returns the latest IBeneficiary
possible consideringIban and Name (irrelevant here). Those properties are public and are classic MyProperty SomeProperty { get; set; }
defined in the class.
I've defined a field with a property getter, the =>
. This is confusing because it's not the expected behaviour of a field to always return something new. Or is it?
I feel like this then should be a function, something like
IBeneficiary CreateLatestBeneficiary (MyProperty param1, MyOtherProperty param2)
{
return new Beneficiary(param1, param2);
}
Or even name it GetLatestBeneficiary
, but in both cases this looks and feels like a really simple getter, so I'd rather have a property with a single getter, that does exactly this, like the following. Right?
IBeneficiary LatestBeneficiary
{
get
{
return new Beneficiary(Iban, Name);
}
}
But a private property is pretty much a field. Isn't it?
And with that in mind we're back to square one, using a field.
I feel like somewhere in there, one of my statements is wrong.
Are private properties okay ? Or is a property by definition something public, with at least a getter ? Or is it okay for a field to not be a plain old variable ?
Ultimately, how would you write this line of code yourself?