Using getters within class methods - getter

If you have a class with some plain get/set properties, is there any reason to use the getters within the class methods, or should you just use the private member variables? I think there could be more of an argument over setters (validation logic?), but I'm wondering just about getters.
For example (in Java) - is there any reason to use option 2?:
public class Something
{
private int messageId;
public int getMessageId() { return this.messageId; }
public void setMessage(int messageId) { this.messageId = messageId; }
public void doSomething()
{
// Option 1:
doSomethingWithMessageId(messageId);
// Option 2:
doSomethingWithMessageId(getMessageId());
}
}

Java programmers in general tend to be very consistent about using getter methods. I program multiple languages and I'm not that consistent about it ;)
I'd say as long as you don't make a getter it's ok to use the raw variable - for private variables. When you make a getter, you should be using only that. When I make a getter for a private field, my IDE suggests that it replace raw field accesses for me automatically when I introduce a getter. Switching to using a getter is only a few keystrokes away (and without any chance of introducing errors), so I tend to delay it until I need it.
Of course, if you want to stuff like getter-injection, some types of proxying and subclassing framworks like hibernate, you have to user getters!

With getters you wont accidentally modify the variables :) Also, if you use both getters and the "raw" variable, your code can get confused.
Also, if you use inheritance and redefined the getter methods in child classes, getter-using methods will work properly, whereas those using the raw variables would not.

If you use the getter method everywhere - and in the future perform a code-search on all calls of getMessageId() you will find all of them, whereas if you had used the private ones, you may miss some.
Also if there's ever logic to be introduced in the setter method, you wont have to worry about changing more than 1 location for it.

If the value that you are assigning to the property is a known or verified value, you could safely use the private variable directly. (Except perhaps in some special situations, where it would be obvious why that would be bad.) Whether you do or not is more a matter of taste or style. It's not a performance issue either, as the getter or setter will be inlined by the compiler if it's simple enough.
If the value is unknown to the class, you should use the property to set it, so that you can protect the property from illegal values.
Here's an example (in C#):
public class Something {
private string _value;
public string Value {
get {
return _value;
}
set {
if (value == null) throw new ArgumentNullException();
_value = value;
}
}
public Something() {
// using a known value
_value = "undefined";
}
public Something(string initValue) {
// using an unknown value
Value = initValue;
}
}

If you use the getter you're ensuring you'll get the value after any logic/decisions have been applied to it. This probably isn't your typical situation but when it is, you'll thank yourself for this.

Unless I have a specific use case to use the internal field directly in the enclosing class, I've always felt that it's important to use access the field the same way it is accessed publicly. This ensures consistency in the return values across the board should there ever be any need to add some post-processing to the field via the getter method, or property. I feel like it's perfectly fine to access the raw field if you want its raw value for one reason or another.
More often than not, the getter encapsulation is plain and simple boilerplate code -- you're most likely not returning anything other than the field's value itself. However, in the case where you may want to change the way the data is presented at some point in the future, it's one less refactoring you have to make internally.

Related

Spock- Capture method arguments in private method call of class under test

I am trying to test my Service class below
#Service
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
public class TaskTemplateService {
#NonNull
TaskTemplateRepository taskTemplateRepository;
public void doStuff() {
List<MyObject> list;
doOtherStuff(list)
}
private void doOtherStuff(List <MyObject>) {
//do stuff
}
}
When I am testing the real TaskTemplate, how can I capture what is passed to doOtherStuff?
You cannot and why would you?
Good testing means to specify the behaviour of a unit's public interface. Private methods ought to be covered via testing this way indirectly. If this is not possible then either you have dead, unreachable code or a design problem and should refactor.
BTW, the technical reason that you cannot mock/stub private methods is that most mocking tools, also the built-in feature of Spock, use dynamic proxies (DP) in order to implement mocking. DP technically are subclasses, but private methods can never be extended or even seen by subclasses or being called by them or from other classes, hence the term "private". Consequently, a mock subclass cannot check interactions with private methods.
How exactly you ought to redesign your class in order to make it testable really depends on why you want to "capture" the method argument, as you say. Do you need to replace it by a mock? Do you need to modify or verify the content of the original object?
If the object has a central meaning and you need to replace or verify it, why not make it injectable instead of creating it as a local variable, hermetically sealing it off from the outside world and making it untestable?
Or maybe in your case you could make the private method protected or package-scoped in order to make it testable. Then at least a mock could be created for it and you could capture the argument or stub the result.
I am mostly speculating here because the answer really depends on what is behind //do stuff, i.e. the very information you are hiding in your sample code.

Pass a dynamic variable in a static parameter of a method in C# 4

This is what I am trying to do:
public void method(int myVal, string myOtherVal)
{
// doing something
}
dynamic myVar = new SomeDynamicObjectImplementer();
method(myVar.IntProperty, myVar.StringProperty);
Note that my properties are also DynamicObjects. My problem is that the TryConvert method is never called and that I get a runtime error saying the method signature is invalid.
The following is working great:
string strVar = myVar.StringProperty;
int intVar = myVar.IntProperty;
And I would like to avoid
method((int)myVar.IntProperty, (string)myVar.StringProperty);
Is it possible to override something in DynamicObject to allow this? (or something else)
Thank you
The problem is your assumption that it will try a dynamic implicit convert on arguments of an dynamic invocation to make a method call work, this is not true.
When your arguments aren't statically typed, it will use the runtime type to find the best matching method (if the runtime type matches the static rules for implicit conversion to the argument type this will work too), since your your IntProperty,StringProperty seem to be returning a DynamicObject rather than an Int and a String or something that could statically be converter implicitly, this lookup will fail.
If SomeDynamicObjectImplementer could actually return an Int for IntProperty and a String for StringProperty your method call for without casting would actually work. It's also probably a better dynamic typing practice if you data type is based on the actually type of data rather than usage using try convert. You could add actually implicit convert methods for every possible type that you could return to that returned DynamicObject type, but that could cause strange resolution issues to depending on how much you are overloading.
However, another option to keep your dynamic implementation the same is to mix a little controlled static typing in, you can use ImpromputInterface (in nuget) to put an interface on top of a dynamic object, if you do that then the TryConvert method would be called on your returned DynamicObjects.
public interface ISomeStaticInterface{
int IntProperty {get;}
string StringProperty {get;}
}
...
var myVar = new SomeDynamicObjectImplementer().ActLike<ISomeStaticInterface>();
method(myVar.IntProperty, myVar.StringProperty);
Instead of using myVar.IntProperty can't you just put them in variables first, like you already did, and then use then for your method?
so method(intVar , strVar); seems fine. At least more elegant than casting.
Of course, if you're already certain your object will have IntProperty and StringProperty, why not just make an actual object with those properties instead?
Why are you doing the cast?
method(myVar.IntProperty, myVar.StringProperty);
should compile.
If the two properties must be the types suggested by the names then they shouldn't be dynamic.

Why can't I add Contract.Requires in an overridden method?

I'm using code contract (actually, learning using this).
I'm facing something weird to me... I override a method, defined in a 3rd party assembly. I want to add a Contract.Require statement like this:
public class MyClass: MyParentClass
{
protected override void DoIt(MyParameter param)
{
Contract.Requires<ArgumentNullException>(param != null);
this.ExecuteMyTask(param.Something);
}
protected void ExecuteMyTask(MyParameter param)
{
Contract.Requires<ArgumentNullException>(param != null);
/* body of the method */
}
}
However, I'm getting warnings like this:
Warning 1 CodeContracts:
Method 'MyClass.DoIt(MyParameter)' overrides 'MyParentClass.DoIt(MyParameter))', thus cannot add Requires.
[edit] changed the code a bit to show alternatives issues [/edit]
If I remove the Contract.Requires in the DoIt method, I get another warning, telling me I have to provide unproven param != null
I don't understand this warning. What is the cause, and can I solve it?
You can't add extra requirements which your callers may not know about. It violates Liskov's Subtitution Principle. The point of polymorphism is that a caller should be able to treat a reference which actually refers to an instance of your derived class as if it refers to an instance of the base class.
Consider:
MyParentClass foo = GetParentClassFromSomewhere();
DoIt(null);
If that's statically determined to be valid, it's wrong for your derived class to hold up its hands and say "No! You're not meant to call DoIt with a null argument!" The aim of static analysis of contracts is that you can determine validity of calls, logic etc at compile-time... so no extra restrictions can be added at execution time, which is what happens here due to polymorphism.
A derived class can add guarantees about what it will do - what it will ensure - but it can't make any more demands from its callers for overridden methods.
I'd like to note that you can do what Jon suggested (this answers adds upon his) but also have your contract without violating LSP.
You can do so by replacing the override keyword with new.
The base remains the base; all you did is introduce another functionality (as the keywords literally suggest).
It's not ideal for static-checking because the safety could be easily casted away (cast to base-class first, then call the method) but that's a must because otherwise it would violate LSP and you do not want to do that obviously. Better than nothing though, I'd say.
In an ideal world you could also override the method and call the new one, but C# wouldn't let you do so because the methods would have the same signatures (even tho it would make perfect sense; that's the trade-off).

magic GET and SET for object initialization question

I would like to know the best practice for a class oriented DDD.
Since i am doing domain validation in custom setters named ChangeX(string x) i might be pushed to use this as property.
public virtual string example { get;
private set; }
However, that not very good since it disable me from using the object initialization feature such as :
new Object { Example = "Some example"
}
So i though why not passing the custom set into the property set ? like this
public virtual string Example { get {
return Example; } set {
ChangeExample(value); } }
Is this can lead to any problems ? it is against best practices ?
Thanks.
Real problem here is using setters as such. Why do You need them?
When You use setters, You lose isolation - You can modify state of objects from outside w/o them knowing that. That leads to procedural code.
In contrast - You should ask objects to do something (not just modify their state) that would eventually might lead to them changing their own state.
I think this solution is fine. One reason to have setters is to make sure your under laying fields never hold incorrect values.

Are there any reasons not to use "this" ("Self", "Me", ...)?

I read this answer and its comments and I'm curious: Are there any reasons for not using this / Self / Me ?
BTW: I'm sorry if this has been asked before, it seems that it is impossible to search for the word this on SO.
Warning: Purely subjective answer below.
I think the best "reason" for not using this/self/me is brevity. If it's already a member variable/function then why redundantly add the prefix?
Personally I avoid the use of this/self/me unless it's necessary to disambiguate a particular expression for the compiler. Many people disagree with this but I haven't ever had it be a real sticking point in any group I've worked for.
I think most of the common scenarios have been covered in the two posts already cited; mainly brevity and redundancy vs clarity - a minor addition: in C#, it is required to use "this" in order to access an "extension method" for the current type - i.e.
this.Foo();
where Foo() is declared externally as:
public static void Foo(this SomeType obj) {...}
It clarifies in some instances, like this example in c#:
public class SomeClass
{
private string stringvar = "";
public SomeClass(string stringvar)
{
this.stringvar = stringvar;
}
}
If you use StyleCop with all the rules on, it makes you put the this. in. Since I started using it I find my code is more readable, but that's personal preference.
I think this is a non-issue, because it only adds more readability to the code which is a good thing.
For some languages, like PHP, it is even mandatory to prefix with $this-> if you need to use class fields or methods.
I don't like the fact that it makes some lines unnecessarily longer than they could be, if PHP had some way to reference class members without it.
I personally find that this.whatever is less readable. You may not notice the difference in a 2-line method, but wait until you get this.variable and this.othervariable everywhere in a class.
Furthermore, I think that use of this. was found as a replacement for a part of the much hated Hungarian notation. Some people out there found out that it's still clearer for the reader to see that a variable is a class member, and this. did the trick. But why fool ourselves and not use the plain old "m_" or simply "_" for that, if we need the extra clarity? It's 5 characters vs. 2 (or even 1). Less typing, same result.
Having said that, the choice of style is still a matter of personal preference. It's hard to convince somebody used to read code in a certain way that is useful to change it.
well, eclipse does color fields, arguments and local variables in different colors, so at least working in eclipse environment there is no need to syntactically distinguish fields in order to specially mark them as "fields" for yourself and generations to come.
It was asked before indeed, in the "variable in java" context:
Do you prefix your instance variable with ‘this’ in java ?
The main recurrent reason seems to be:
"it increases the visual noise you need to sift through to find the meaning of the code."
Readability, in other word... which I do not buy, I find this. very useful.
That sounds like nonsense to me. Using 'this' can make the code nicer, and I can see no problems with it. Policies like that is stupid (at least when you don't even tell people why they are in place).
as for me i use this to call methods of an instantiated object whereas self is for a static method
In VB.NET one of the common practice I use is the following code :
Class Test
Private IntVar AS Integer
Public Function New(intVar As Integer)
Me.Intvar = intvar
End Function
End Class
Not all the time but mostly Me / this / self is quite useful. Clarifies the scope that you are talking.
In a typical setter method (taken from lagerdalek's answer):
string name;
public void SetName(string name)
{
this.name = name;
}
If you didn't use it, the compiler wouldn't know you were referring to the member variable.
The use of this. is to tell the compiler that you need to access a member variable - which is out of the immediate scope of the method. Creating a variable within a method which is the same name as a member variable is perfectly legal, just like overriding a method in a class which has extended another class is perfectly legal.
However, if you still need to use the super class's method, you use super. In my opinion using this. is no worse than using super. and allows the programmer more flexibility in their code.
As far as I'm concerned readability doesn't even come into it, it's all about accessibility of your variables.
In the end it's always a matter of personal choice. Personally, I use this coding convention:
public class Foo
{
public string Bar
{
get
{
return this.bar;
}
/*set
{
this.bar = value;
}*/
}
private readonly string bar;
public Foo(string bar)
{
this.bar = bar;
}
}
So for me "this" is actually necessary to keep the constructor readable.
Edit: the exact same example has been posted by "sinje" while I was writing the code above.
Not only do I frequently use "this". I sometimes use "that".
class Foo
{
private string bar;
public int Compare(Foo that)
{
if(this.bar == that.bar)
{
...
And so on. "That" in my code usually means another instance of the same class.
'this.' in code always suggests to me that the coder has used intellisense (or other IDE equivalents) to do their heavy lifting.
I am certainly guilty of this, however I do, for purely vanity reasons, remove them afterwards.
The only other reasons I use them are to qualify an ambiguous variable (bad practice) or build an extension method
Qualifying a variable
string name; //should use something like _name or m_name
public void SetName(string name)
{
this.name = name;
}

Resources