Are string constants overrated? - string

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.

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.

CRM 2011 Plugin - Does using early bound entities for attribute names cause memory issues?

In my plugin code, I use early bound entities (generated via the crmsvcutil). Within my code, I am using MemberExpression to retrieve the name of the property. For instance, if I want the full name of the user who initiated the plugin I do the following
SystemUser pluginExecutedBy = new SystemUser();
pluginExecutedBy = Common.RetrieveEntity(service
, SystemUser.EntityLogicalName
, new ColumnSet(new string[] {Common.GetPropertyName(() => pluginExecutedBy.FullName)})
, localContext.PluginExecutionContext.InitiatingUserId).ToEntity<SystemUser>();
The code for GetPropertyName is as follows
public static string GetPropertyName<T>(Expression<Func<T>> expression)
{
MemberExpression body = (MemberExpression)expression.Body;
return body.Member.Name.ToLower();
}
The code for RetrieveEntity is as follows
public static Entity RetrieveEntity(IOrganizationService xrmService, string entityName, ColumnSet columns, Guid entityId)
{
return (Entity)xrmService.Retrieve(entityName, entityId, columns);
}
My solution architect's comments:
Instead of writing the code like above, why not write it like this (hardcoding the name of the field - or use a struct).
SystemUser pluginExecutedBy = null;
pluginExecutedBy = Common.RetrieveEntity(service
, SystemUser.EntityLogicalName
, new ColumnSet(new string[] {"fullname"})
, localContext.PluginExecutionContext.InitiatingUserId).ToEntity<SystemUser>();
Reason:
Your code unnecessarily creates an object before it requires it (as you instantiate the object with the new keyword before the RetrieveEntity in order to use it with my GetProperty method) which is bad programming practice. In my code, I have never used the new keyword, but merely casting it and casting does not create a new object. Now, I am no expert in C# or .NET, but I like to read and try out different things. So, I looked up the Microsoft.Xrm.Sdk.dll and found that ToEntity within Sdk, actually did create a new Entity using the keyword new.
If the Common.Retrieve returns null, your code has unnecessarily allocated memory which will cause performance issues whereas mine would not?
A managed language like C# "manages the memory" for me, does it not?
Question
Is my code badly written? If so, why? If it is better - why is it? (I believe it is a lot more cleaner and even if a field name changes as long as as the early bound class file is regenerated, I do not have to re-write any code)
I agree that cast does not create a new object, but does my code unnecessarily create objects?
Is there a better way (a completely different third way) to write the code?
Note: I suggested using the GetPropertyName because, he was hard-coding attribute names all over his code and so in a different project which did not use early bound entities I used structs for attribute names - something like below. I did this 3 weeks into my new job with CRM 2011 but later on discovered the magic of MemberExpression. He was writing a massive cs file for each of the entity that he was using in his plugin and I told him he did not have to do any of this as he could just use my GetPropertyName method in his plugin and get all the fields required and that prompted this code review comments. Normally he does not do a code review.
public class ClientName
{
public struct EntityNameA
{
public const string LogicalName = "new_EntityNameA";
public struct Attributes
{
public const string Name = "new_name";
public const string Status = "new_status";
}
}
}
PS: Or is the question / time spent analyzing just not worth it?
Early Bound, Late Bound, MemberExpression, bla bla bla :)
I can understand the "philosophy", but looking at your code a giant alarm popup in my head:
public static Entity RetrieveEntity(IOrganizationService xrmService, string entityName, ColumnSet columns, Guid entityId)
{
return (Entity)xrmService.Retrieve(entityName, entityId, columns);
}
the Retrieve throws an exception if the record is not found.
About the other things, the GetPropertyName is ok, but are always choices, for example I try to use always late bound in plugins, maybe in a project I prefer to use early bound, often there is more than one way to resolve a problem.
Happy crm coding!
Although GetPropertyName is a quite a clever solution I don't like it, and that's entirely to do with readability. To me its far easier to understand what is going on with: new ColumnSet(new string[] {"fullname"}).
But that's pretty much personal preference, but its important to remember that your not just writing code for yourself you are writing it for your team, they should be able to easily understand the work you have produced.
As a side a hardcoded string probably performs better at runtime. I usually hardcode all my values, if the entity model in CRM changes I will have to revisit to make changes in any case. There's no difference between early and late bound in that situation.
I don't understand the point of this function,
public static Entity RetrieveEntity(IOrganizationService xrmService, string entityName, ColumnSet columns, Guid entityId)
{
return (Entity)xrmService.Retrieve(entityName, entityId, columns);
}
It doesn't do anything (apart from cast something that is already of that type).
1.Your code unnecessarily creates an object before it requires it (as you instantiate the object with the new keyword before the
RetrieveEntity in order to use it with my GetProperty method) which is
bad programming practice. In my code, I have never used the new
keyword, but merely casting it and casting does not create a new
object.
I believe this refers to; SystemUser pluginExecutedBy = new SystemUser(); I can see his/her point here, in this case new SystemUser() doesn't do much, but if the object you were instantiating did something resource intensive (load files, open DB connections) you might be doing something 'wasteful'. In this case I would be surprised if changing SystemUser pluginExecutedBy = null; actually yielded any significant performance gain.
2.If the Common.Retrieve returns null, your code has unnecessarily allocated memory which will cause performance issues
I would be surprised if that caused a performance issue, and anyway as Guido points out that function wont return null in any case.
Overall there is little about this code I strongly feel needs changing - but things can be always be better and its worth discussing (e.g. the point of code review), although it can be hard not to you shouldn't be precious about your code.
Personally I would go with hardcoded attribute names and dump the Common.RetrieveEntity function as it doesn't do anything.
pluginExecutedBy = service.Retrieve(SystemUser.EntityLogicalName, localContext.PluginExecutionContext.InitiatingUserId, new ColumnSet(new String[] {"fullname"} ));

Ignore certain TypeScript compile errors?

I am wondering if there is a way to ignore certain TypeScript errors upon compilation?
I basically have the same issues most people with large projects have around using the this keyword, and I don't want to put all my classes methods into the constructor.
So I have got an example like so:
TypeScript Example
Which seems to create perfectly valid JS and allows me to get around the this keyword issue, however as you can see in the example the typescript compiler tells me that I cannot compile that code as the keyword this is not valid within that scope. However I don't see why it is an error as it produces okay code.
So is there a way to tell it to ignore certain errors? I am sure given time there will be a nice way to manage the this keyword, but currently I find it pretty dire.
== Edit ==
(Do not read unless you care about context of this question and partial rant)
Just to add some context to all this to show that I'm not just some nut-job (I am sure a lot of you will still think I am) and that I have some good reasons why I want to be able to allow these errors to go through.
Here are some previous questions I have made which highlight some major problems (imo) with TypeScript current this implementation.
Using lawnchair with Typescript
Issue with child scoping of this in Typescript
https://typescript.codeplex.com/discussions/429350 (And some comments I make down the bottom)
The underlying problem I have is that I need to guarantee that all logic is within a consistent scope, I need to be able to access things within knockout, jQuery etc and the local instance of a class. I used to do this with the var self = this; within the class declaration in JavaScript and worked great. As mentioned in some of these previous questions I cannot do that now, so the only way I can guarantee the scope is to use lambda methods, and the only way I can define one of these as a method within a class is within the constructor, and this part is HEAVILY down to personal preference, but I find it horrific that people seem to think that using that syntax is classed as a recommended pattern and not just a work around.
I know TypeScript is in alpha phase and a lot will change, and I HOPE so much that we get some nicer way to deal with this but currently I either make everything a huge mess just to get typescript working (and this is within Hundreds of files which I'm migrating over to TypeScript ) or I just make the call that I know better than the compiler in this case (VERY DANGEROUS I KNOW) so I can keep my code nice and hopefully when a better pattern comes out for handling this I can migrate it then.
Also just on a side note I know a lot of people are loving the fact that TypeScript is embracing and trying to stay as close to the new JavaScript features and known syntax as possible which is great, but typescript is NOT the next version of JavaScript so I don't see a problem with adding some syntactic sugar to the language as people who want to use the latest and greatest official JavaScript implementation can still do so.
The author's specific issue with this seems to be solved but the question is posed about ignoring errors, and for those who end up here looking how to ignore errors:
If properly fixing the error or using more decent workarounds like already suggested here are not an option, as of TypeScript 2.6 (released on Oct 31, 2017), now there is a way to ignore all errors from a specific line using // #ts-ignore comments before the target line.
The mendtioned documentation is succinct enough, but to recap:
// #ts-ignore
const s : string = false
disables error reporting for this line.
However, this should only be used as a last resort when fixing the error or using hacks like (x as any) is much more trouble than losing all type checking for a line.
As for specifying certain errors, the current (mid-2018) state is discussed here, in Design Meeting Notes (2/16/2018) and further comments, which is basically
"no conclusion yet"
and strong opposition to introducing this fine tuning.
I think your question as posed is an XY problem. What you're going for is how can I ensure that some of my class methods are guaranteed to have a correct this context?
For that problem, I would propose this solution:
class LambdaMethods {
constructor(private message: string) {
this.DoSomething = this.DoSomething.bind(this);
}
public DoSomething() {
alert(this.message);
}
}
This has several benefits.
First, you're being explicit about what's going on. Most programmers are probably not going to understand the subtle semantics about what the difference between the member and method syntax are in terms of codegen.
Second, it makes it very clear, from looking at the constructor, which methods are going to have a guaranteed this context. Critically, from a performance, perspective, you don't want to write all your methods this way, just the ones that absolutely need it.
Finally, it preserves the OOP semantics of the class. You'll actually be able to use super.DoSomething from a derived class implementation of DoSomething.
I'm sure you're aware of the standard form of defining a function without the arrow notation. There's another TypeScript expression that generates the exact same code but without the compile error:
class LambdaMethods {
private message: string;
public DoSomething: () => void;
constructor(message: string) {
this.message = message;
this.DoSomething = () => { alert(this.message); };
}
}
So why is this legal and the other one isn't? Well according to the spec: an arrow function expression preserves the this of its enclosing context. So it preserves the meaning of this from the scope it was declared. But declaring a function at the class level this doesn't actually have a meaning.
Here's an example that's wrong for the exact same reason that might be more clear:
class LambdaMethods {
private message: string;
constructor(message: string) {
this.message = message;
}
var a = this.message; // can't do this
}
The way that initializer works by being combined with the constructor is an implementation detail that can't be relied upon. It could change.
I am sure given time there will be a nice way to manage the this keyword, but currently I find it pretty dire.
One of the high-level goals (that I love) in TypeScript is to extend the JavaScript language and work with it, not fight it. How this operates is tricky but worth learning.

Why do we use _ in variable names?

I have seen variables like _ image and was wondering what _ meant?
It doesn't mean anything. It is rather a common naming convention for private member variables to keep them separated from methods and public properties. For example:
class Foo
{
private int _counter;
public int GetCounter()
{
return _counter;
}
public int SetCounter(int counter)
{
_counter = counter;
}
}
In most languages _ is the only character allowed in variable names besides letters and numbers. Here are some common use cases:
Separating words: some_variable
Private variables start with underscores: _private
Adding at the end to distinguish from a built-in name: filter_ (since filter is a built-in function)
By itself as an unused variable during looping: [0 for _ in range(n)]
Note that some people really don't like that last use case.
Some people use it to indicate that they are variables rather than (say) method names. Or to make it obvious that they're instance variables rather than local variables. Sometimes you see extra prefixes, e.g.
private int m_age; // Member (instance) variable
private static int g_maxAge; // Global (static) variable
It's just a convention. I was going to say "there's nothing magic about _" but that's not quite true - in some languages a double underscore is reserved for "special" uses. (The exact usage depends on the language of course.)
EDIT: Example of the double underscore rule as it applies to C#. From the C# 4 spec, section 2.4.2:
Identifiers containing two consecutive underscore characters (U+005F) are reserved for use by the implementation. For example, an implementation might provide extended keywords that begin with two underscores.
The underscore in variable names is completely optional. Many programmers use it to differentiate private variables - so instance variables will typically have an underscore prepended to the name. This prevents confusion with local variables.
_ usually means something private or internal. In C++ standard libraries all implementation specific variables must start with _.
Usually it separates class fields from the variables. To avoid using this in code constructions.
class MyClass {
private int _myIntField;
private void setMyIntField(int value2Set) {
_myIntField = value2Set;
}
}
Well Underscore character(_) begin with your variable name is discouraged but it is legal and some people use it to identify as an private variable and some for naming it in caching variable. Go through with this link too.
The use of two underscores (`__') in identifiers is reserved for the compiler's internal use according to the ANSI-C standard.
Underscores (`_') are often used in names of library functions (such as "_main" and "_exit"). In order to avoid collisions, do not begin an identifier with an underscore.
In most languages, it doesn't actually affect the functionality of the code, but is often used to denote reserved or internal names.
It is common in some languages to name your instance variable _image or image_ and then make the public method used to access it image().
Similarly, some names like __FILE__ are used in some languages to denote a special variable or constant created by the interpreter or compiler; such names are often reserved to encourage programmers to avoid using those names in their own programs in case the names are used in future versions of the language.
To avoid reserved keywords, or in reserved keywords, making them more easily avoided.
A single underscore is discouraged and reserved in JavaSE9.
Another use case (mainly in javascript) is when you need to assign the current instance this to a local variable we write as below
var _this = this;
If you need to create a local temporary object reference, to differentiate between the actual needed reference, we create as below
List<Employee> employeeList = new ArrayList<>();
for (Employee _employee : employeeList) {}
So if we follow this best practice, every time you see a variable with _ , we come to a conclusion that its being used to solve some business need at that particular method.
Basically it is telling that the developer should provide the definition . In short it defines it does not have any definition .

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