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

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;
}

Related

Do we need this keyword in .net 4.0 or 4.5

I am currently reviewing code written in c#, visual studio 2012.
In lot of places, the code is written using this key word, for ex:
this.pnlPhoneBasicDtls.Visible = true;
this.SetPhAggStats(oStats);
There are many other places where the controls of the page are referred using this key word.
Can somebody advise do we really need to use this here?
Any consequences of removing this keyword?
Thanks in advance..
No, "this" is optional. It's usually included in code generated by a tool and by people who feel the need to be explicit or who want to differentiate it from an argument to the method.
Its Optional you can use the
Property directly like pnlPhoneBasicDtls.Visible = true;
The this keyword is usually optional.
It's sometimes used to disambiguate fields from arguments if the same name is being used for both, for example:
void Main()
{
var sc = new SomeClass();
sc.SomeMethod(123);
Console.WriteLine(sc.thing);
}
public class SomeClass
{
public int thing;
public void SomeMethod(int thing)
{
this.thing = thing + 1;
}
}
In the example above it does make a difference. Inside SomeMethod, this.thing refers to the field and thing refers to the argument.
(Note that the simpler assignment thing = thing is picked up as a compiler error, since it is a no-op.)
Of course, if you use ReSharper then any unnecessary this. (together with unused using statements, unreachable code, etc.) will be greyed out and you can remove them very quickly. The same is probably true of similar tools like CodeRush.

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).

How Does "Use" work in groovy?

Hi I have the following Code Snippet;
class StringCalci
{
static def plus(Integer self, Integer Operand)
{
return self.toInteger() * Operand.toInteger()
}
}
use (StringCalci)
{
println("inside the Use method!")
println( 12 + 3 )
}
println(12+3)
I was been shocked to see the use of Use in groovy. The thing is this I can add methods to the Class at run-time(my own methods).when I was looking at the above code, I was Thinking how does Groovy make things possible like this! The use of println inside the Use is multiplying the two given numbers(because I have Override the plus method) , where as the outside println adds it! My question is how does Groovy recognise the println executes in Use and println outside the Use. Is Use is a keyword/method? I need to understand behind the scenes of this process.. Please let me know :)
Thanks in Advance :)
Welcome to the wonderful world of dynamic languages where everything is possible and nothing is certain!
This feature is called Categories. As for the implementation:
use is in fact not a keyword but a method which the Groovy runtime adds to the Object class, which makes it available everywhere.
I think the functionality is implemented mainly in the class GroovyCategorySupport
Judging from the Javadoc, it's based on keeping a map of overriden methods in a ThreadLocal which is then consulted for every method call.
yeah, that's not so great for performance, but so are pretty much all the dynamic "magic" features that Groovy and similar languages offer (and there's lots of them).

Are string constants overrated?

It's easy to lose track of odd numbers like 0, 1, or 5. I used to be very strict about this when I wrote low-level C code. As I work more with all the string literals involved with XML and SQL, I find myself often breaking the rule of embedding constants in code, at least when it comes to string literals. (I'm still good about numeric constants.)
Strings aren't the same as numbers. It feels tedious and a little silly to create a compile-time constant that has the same name as its value (E.g. const string NameField = "Name";), and although the repetition of the same string literal in many locations seems risky, there's little chance of a typo thanks to copying and pasting, and when I refactor I'm usually doing a global search that involves changing more than just the name of the thing, like how it's treated functionally in relation to the things around it.
So, let's say you don't have a good XML serializer (or aren't in the mood to set one up). Which of these would you personally use (if you weren't trying to bow to peer pressure in some code review):
static void Main(string[] args)
{
// ...other code...
XmlNode node = ...;
Console.WriteLine(node["Name"].InnerText);
Console.WriteLine(node["Color"].InnerText);
Console.WriteLine(node["Taste"].InnerText);
// ...other code...
}
or:
class Fruit
{
private readonly XmlNode xml_node;
public Fruit(XmlNode xml_node)
{
this.xml_node = xml_node;
}
public string Name
{ get { return xml_node["Name"].InnerText; } }
public string Color
{ get { return xml_node["Color"].InnerText; } }
public string Taste
{ get { return xml_node["Taste"].InnerText; } }
}
static void Main(string[] args)
{
// ...other code...
XmlNode node = ...;
Fruit fruit_node = new Fruit(node);
Console.WriteLine(fruit_node.Name);
Console.WriteLine(fruit_node.Color);
Console.WriteLine(fruit_node.Taste);
// ...other code...
}
A defined constant is easier to refactor. If "Name" ends up being used three times and you change it to "FullName", changing the constant is one change instead of three.
For something like that it depends on how often the constant is used. If it's just in one place as per your example, then hard-coding is fine. If it's used in many different places, definitely use a constant. One typo could lead to hours of debugging if you're not careful, because your compiler isn't going to notice that you typed "Tsate" instead of "Taste", while it WILL notice that you typed fruit_node.Tsate instead of fruit_node.Taste.
Edit:
I see now that you mentioned copying and pasting, but if you're doing that you may also be losing the time you save by not creating a constant in the first place. With intellisense and auto-completion, you could have the constant out there in a few keystrokes, instead of going through the trouble of copy/paste.
As you probably guessed. The answer is: it depends on the context.
It depends on what the example code is part of. If it's just part of a small throw away system then hard coding the constants may be acceptable.
If it's part of a large, complex system and the constants will be used in mulitple files, I'd be more drawn to the second option.
As in many matters of programming, this is a matter of taste. The "laws" of proper programming were created from experience -- many people have been burned by global variables causing namespace or clarity problems, so Global Variables Are Evil. Many have used magic numbers, only to later discover that the number was wrong or needed changing. Text search is ill-suited to changing these values, so Constants In Code Are Evil.
But both are permitted, because sometimes they aren't evil. You need to make the decision yourself -- which leads to clearer code? Which is going to be better for maintainers? Does the reasoning behind the original rule apply to my situation? If I had to read or maintain this code later, how would I rather that it were written?
There is no absolute law of good coding style, because no two programmers' minds works exactly alike. The rule is to write the clearest, cleanest code that you can.
Personally, I'd load the fruit from the XML file in advance - something like:
public class Fruit
{
public Fruit(string name, Color color, string taste)
{
this.Name = name; this.Color = color; this.Taste = taste;
}
public string Name { get; private set; }
public Color Color { get; private set; }
public string Taste { get; private set; }
}
// ... In your data access handling class...
public static FruitFromXml(XmlNode node)
{
// create fruit from xml node with validation here
}
}
That way, the "fruit" isn't really tied to the storage.
I'd go with the constants. It is a little more work, but there is no performance impact. And even if you usually copy/paste the values, I've certainly had instances where I changed code when I typed and didn't realize that Visual Studio had focus. I'd much prefer these resulted in compile errors.
For the example given, where the Strings are used as keys to a map or dictionary, I would lean toward use of an enum (or other object) instead. You can often do much more with an enum than with a constant string. In addition, if some code is commented out, IDE's will often miss that when doing a refactor. Also, references to a String constant that are in comments may or may not be included in a refactor.
I will make a constant for a string when the string will be used in many locations, the string is long or complicated (such as a regex), or when a properly-named constant will make the code more obvious.
I prefer my typos, incomplete refactorings, and other bugs of this sort to fail to compile rather than to just fail to operate properly.
Like many other refactorings, it's an arguably optional additional step that leaves you with code that's less risky to maintain and is more easily grokked by the "next guy". If you're in a situation that rewards that kind of thing (most that I'm in do), go for it.
Yeah, pretty much.
I think developers in statically typed languages have an unhealthy fear of anything at all dynamic. Pretty much every line of code in a dynamically typed language is effectively a string literal, and they've been fine for years. For instance, in JavaScript technically this:
var x = myObject.prop1.prop2;
Is equivalent to this:
var x = window["myObject"]["prop1"]["prop2"]; // assuming global scope
But it is definitely not a standard practice in JavaScript to do this:
var OBJ_NAME = "myObject";
var PROP1_NAME = "prop1";
var PROP2_NAME = "prop2";
var x = window[OBJ_NAME][PROP1_NAME][PROP2_NAME];
That would just be ridiculous.
It still depends though, like if a string is used in numerous places and it's rather cumbersome/ugly to type ("name" vs. "my-custom-property-name-x"), then it's probably worth making a constant, even within a single class (at which point it's probably good to be internally consistent within the class and make all the other strings constants too).
Also, if you actually intend for other external users to interact with your library using these constants, then it's also a good idea to define publicly accessible constants and document that users should use those to interact with your library. However, a library which interacts via magic string constants is usually a bad practice and you should consider designing your library in such a way that you don't need to use magic constants to interact with it in the first place.
I think in the specific example you gave, where the strings are relatively simple to type and there are presumably no external users of your API who would expect to work with it using those string values (i.e. they're just for internal data manipulation), readable code is far more valuable than refactorable code, so I would just put the literals directly inline. Again, this is assuming I understand your exact use case specifically.
One thing nobody seemed to notice is that as soon as you define a constant, its scope becomes something to maintain and think about. This actually does have a cost, it's not free like everyone seems to think. Consider this:
Should it be private or public in my class? What if some other namespace/package has a need for the same value, should I now extract the constant to some global static class of constants? What if I now need it in other assemblies/modules, do I extract it further? All these things make the code less and less readable, harder to maintain, less pleasant to work with, and more complicated. All in the name of refactorability?
Usually, these "great refactorings" never occur, and when they do they require a complete rewrite anyway, with all new strings. And if you had been using some shared module before this great refactoring (as in the above paragraph) which didn't have these new strings which you now need, what then? Do you add them to the same shared module of constants (what if you don't have access to the code for this shared module)? Or do you keep them local to you, in which case there are now multiple scattered repositories of string constants, all at different levels, running the risk of duplicated constants all over the code? Once you get to this point (and believe me I've seen it), refactoring becomes moot, because while you'll get all your usages of your constants, you'll miss other people's usages of their constants, even though these constants have the same logical value as your constants and you're actually trying to change all of them.

Using getters within class methods

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.

Resources