I am just wondering if there is a way to simplify this code:
var myStr = GetThatValue();
myStr = myStr.Substring(1, myStr.Length - 2); // remove first and last chars
into this:
// how to get hold of GetThatValue return value?
var myStr = GetThatValue().Substring(1, hereWhat.Length - 2);
I though about this keyword but it does not work in this context. It will reference the class instance as expected.
Nope. The alternative is this:
var myStr = GetThatValue().Substring(1, GetThatValue().Length - 2);
Which, as you can see, invokes GetThatValue() twice. So if that operation is expensive or returns different values then it probably shouldn't be re-invoked.
Even if it's not an expensive operation, this is exactly a textbook case of what variables are for... storing values.
It's possible to have a scenario where this is perfectly acceptable, though. Consider C#'s properties, which are really just syntactic sugar over classic getter/setter methods. If we look at those getters in a traditional Java sense, we might have something like this:
private thatValue;
public string GetThatValue() { return someString; }
// later...
var myStr = GetThatValue().Substring(1, GetThatValue().Length - 2);
In this case it's not an expensive operation, nor would it return different values. (Threading notwithstanding.) In this case there's no discernible logical difference between using the variable vs. the method, as the method is simply a wrapper for a class-level variable.
In fact, this approach is often used when the getter has some logic which should always wrap the access to that variable, even for private-only members.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With