Getters and Setters are a means to expose properties of classes. They are one-way functions. They either get (return a value) or they set (accept a value), but they don't do both in the same function. Even C# properties which do away the extra get and set functions maintains the one-way operation.
So if I have
Then there is an implied operation upon a property called Foo
. Due to the magic of encapsulation, I don't really care if the internal object is called Foo
. I just know that if I SetFoo()
and then GetFoo()
then there should be some degree of logical linkage between my operations.
So you don't have getters | setters in your example. Yes, I know they are named that way, but that's not what they're doing. The third snippet really shows the deviation from the concept of properties. public Bar setFoo(String foo)
means I set a Foo
but I get a Bar
back? What?!
You need to pick a different verb than 'Set' to use in this case, because the function is not performing a set operation. Something like public Bar AnalyzeFoo(String foo)
may be a more appropriate description of what the function is doing and still hides the fact that there is a really expensive operation on Bar
as part of the function.
A more concrete example may help.
This next example is bad, for the reasons explained above:
public ProfitMargin SetInvoice(Invoice inv)
But this example makes more sense:
public ProfitMargin AnalyzeInvoice(Invoice inv)
I don't know or need to know how expensive of an operation it is to break apart the Invoice
and identify the profit margin; the AnalyzeInvoice()
function takes care of that for me.
A quick note on what I meant with C# properties...
Yes, I still have to define the get & set routines but they are expressed as part of the Property and don't require additional functions like Java used to require.
So in C#, I have:
private ____ xyz
public ____ MyProp {
get { .... return xyz; }
set { .... xyz = value; }
}
Whereas old-school Java required explicit functions:
private ____ xyz;
public ____ GetMyPrep() { ... return xyz; }
public void SetMyPrep(____ value) { ... xyz = value; }
Both work well, and modern IDEs simplify the getter | setter creation. The point is that both approaches are still one-way operations.
setFoo
operates onBar
s, shouldn't it be one ofBar
's methods to begin with? – Mat Feb 08 '13 at 06:42Bar
and add a getBar that returns the cache if possible. That leaves yoursetFoo
sensible while still optimizing perf (and of course, only do this after measuring that the cost ofexpensivegetBar
is really making a difference) – Kate Gregory Feb 08 '13 at 12:37