Subjective usages of 'this' in C# [closed] - c#

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I come from C++ and normally this is rarely used compared to C#. In my experience, the usage of this is strictly limited to scope and/or name resolution.
I have coworkers that insist that using this everywhere makes code "more clear". They essentially depend on it for documentation purposes. I disagree with this usage as it is very subjective, redundant, and practically useless as far as documentation is concerned.
There are cases where I see this.myClassVariable = 100;. In this case, this serves no real use other than (according to my coworkers) to make it very clear that myClassVariable is not a static. This is just one example.
Personally, where ever there are no ambiguities, I use myClassVariable = 100;. This is more clear and I feel honestly that if your variables are well named, code will be self documenting and 'this' is not needed.
What is the general rule of thumb on using 'this'? I'm asking for use cases that go beyond the obvious requirements (such as resolving ambiguities). There are cases where the usage of this is required for code to compile and I'm not necessarily interested in those cases. How do you guys feel about using this for documentation?

If they want to distinguish static variables from private instance variables, why not use a naming convention to distinguish the two, instead of requiring this? For example, for private instance variables, prefix them with an underscore and name them using camel case (e.g. _myVariable). Then, for static variables, use Pascal case with no prefix (e.g. MyStaticVariable). It allows for simple disambiguation between static and instance variables, and doesn't require the extra key strokes and general "ugliness" required for this.

I personally strongly object to this usage. Makes refactoring very hard - if you want to change a variable to a static or a local, you have to go through all usage points and get rid of this..
This usage was possibly motivated by PHP or Python where it's a must.

Related

What is the correct jargon for a class that has no functions but is used to store data [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Is there any special jargon word for a class that has no functions but is used to store data?
One of the examples is Data Transefer Object (DTO), although it, of course, still can have methods.
Plain old data structure (POD) seems to be an appropriate term. Though rarer than POJO/POCO, from what I've seen, it seems to be the best fit for your criteria.
There is no standard term for C# because this practice is pretty rare. I call such classes (or structs) "records", for no particularly good reason.
I see a lot of flamewars and a high rated incorrect answer here. So I'll chime in with my not entirely correct but close enough answer.
A JavaBean is a special data encapsulation object in Java. In C# I'm not entirely aware of the name but they do have a structure (rather than a class) which I'm accustomed to using for similar types of tasks.
Another term you may wish to use is Entity. Java has "persistance entities" which are effectively JavaBeans with an annotation. My advice would be to be consistent with whichever you choose to use.
As mentioned this isn't a perfect answer but it should be close enough.
http://en.wikipedia.org/wiki/JavaBeans
http://docs.oracle.com/javaee/5/tutorial/doc/bnbqa.html
http://msdn.microsoft.com/en-us/library/vstudio/ah19swz4.aspx
http://msdn.microsoft.com/en-us/library/system.data.entity(v=vs.103).aspx
I mostly refer to them as container classes. Maybe the term you're looking for, because it doesn't sound very functional. But they often have getters/setters.
Utility class is also a nice term. Utility class which stores xyz data for use with bla.
Do you mean something like this?
public class Foo {
public int a;
public String b;
}
I don't think there's a specific term for a (public) class like that in Java. Except maybe "bad practice".
If your platform has a decent JIT compiler, there's no good reason to write code like that. At least make the fields private and provide getters and/or setters. A decent JIT compiler will optimize simple getters and setters so that there is no performance overhead.
The key point is that you should never let code like that appear in a API that is exposed outside of a single compilation unit. Why? It exposes the implementation details of the class and forces other code to depend on them.
If the class is an private inner class the above code could be reasonable, though I'd be more comfortable if the fields were final and there was a constructor. Especially if the compilation unit was large.
Your question is tagged C# and Java, but I've found most people understand if you call them structs (from C).
Note that in C++, structs may have functions too, but I don't think this is idiomatic.

What are the performance costs of introducing a CLR type (class or interface)? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Even though .Net allows dynamic invocation (e.g. with reflection, C# dynamic keyword), but when using a language such as C# we sometimes feel it is necessary to use static typing, in order to prove that our program is correct, and will not have typing issues at runtime.
Sometimes this results in us introducing interfaces or base classes that fee like they are just for purpose of explaining to the compiler that 'Yes, I know all the objects I pass to this context are going to be understand invoke Method X with arg Y - here, I will prove it to you using an interface definition!' (For example - .net internally uses IReadChunkBytes interface to allow passing either SteamReadChunkBytes or BufferReadChunkBytes objects to some method or other.)
Other times we create classes or types to serve other purposes which are do not feel very usefully type-y, such as being unique identifiers (a bit like enums) with small attached behavior, or to hold a set of constants, etc.
I'm interested in better understanding what the compiletime, runtime, and other costs are going to be when I face such design decisions where I am asking 'should I define a new type or interface just in order to solve this problem?' Obviously there will be two sides to the cost and benefit in each such comparison, but in general we should hopefully see the same costs for 'define new type' in each such comparison/disucssion. How do we quantify these costs?
The performance and/or space costs of statically creating a new interface or class are always negligible. Don't think about it too much in this sense. In contrast, reflection and late binding can cause serious performance problems. You should use static typing pretty much at every opportunity.
The costs associated with creating a new class or interface aren't performance costs. They're more human costs. Here is a list of some considerations you should make before adding a new class or interface. At any rate, using late binding or reflection is probably not going to help your program. These are last-resort techniques.
Program complexity. While this is often not the case, a general rule of the thumb is that every class adds additional complexity to your application, and thus makes it harder to understand during run time, pass on to new project members, remember, and diagram. Changes become more difficult to implement.
If you really don't feel like a class is necessary, perhaps it isn't. Maybe there are other ways to solve your problem, such as using more dynamic classes. Perhaps you can use inheritance or other techniques to reduce repetitions.
Almost everything has some runtime cost. The only exception would be things like empty space. The reason is that almost everything gets record in IL image, even local variable names, parameter names, constants. So at least there will be disk cost, virtual memory space cost, working space cost.
In terms of CPU, more metadata will slow down program startup, token resolution, JIT/NGEN.
But sometimes adding types can have positive impact on performance too.
Using dynamic over strong types is more likely to give you performance issues. So if you are fine with using dynamic for most of your objects you may not need to worry about cost of creating static types.
Side note: if you prefer dynamic typing C# may not be the best language to work with. And it would be harder to get good samples as most C# code is targeting strongly typed objects.

Coding standards for C++ and C# [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a rather theoretical question. My company has a working standard (documented) that is rather extensive regarding C++ but is almost none existent when it comes to C#, where the only directive is that the coding standard should follow Microsoft's style guidelines for C#. MSDN does have guidelines, but this causes a rather large difference between code in both languages in our companies' code.
Here are a few coding standards we have for C++ (nothing new mind you):
Class member names should start with m_ and proceed in camel case i.e. bool m_isValid;
Method params should start with _ i.e. and proceed in camel case void Foo(bool _isValid);
local variables are regular camel case i.e. bool isValid;
This makes for very readable code when reading long functions, since you immediately know what is a member, what is a parameter, and what is a local variable.
Now when it comes to C#... The usual practice is camel case for all three. It is much harder to read, and you have to hover over the variable or click it to know which one it is.
If it where your decision, would you enforce the same coding standards for both languages? Would you enforce most of the same coding standards? Or would you go with a different language different standards approach?
Thanks...
If it where your decision, would you enforce the same coding standards for both languages?
Absolutely not. I'd follow the normal conventions for C#. If you try to make code in language look like code in another, you're likely to start using idioms from that language too... and end up speaking C# with a C++ accent.
This makes for very readable code when reading long functions
So wherever possible, avoid creating long methods... I very rarely find it a problem to have all three kinds of variable using the same conventions - whereas long methods end up being painful whatever conventions are used.
I've worked in different companies and some like hungarian notation and some don't. Coding style is more of a matter of opinion so I would do what's most suited to how you and your team like to develop.

Can anyone give me a REALLY good reason to use CLR type names instead of C# type names (aliases) in code (as a general practice)? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
We have a bit of a battle going on in our development team over this. I would love to hear what others think about this.
In the actual code? No, not unless you're going to have lots of people working on the code who are familiar with .NET but not with C#.
In member names? Absolutely. For instance, suppose Convert.ToSingle had been called Convert.ToFloat - that would be totally confusing for F# developers, for whom "float" means "64 bit floating point".
My general rule is C# aliases for implementation, CLR types for member names.
If you want to find some arguments in favour of using the CLR type names everywhere, Jeff Richter recommends that in "CLR via C#". (If you haven't already got it, buy a copy regardless of this matter - it's a wonderful book.) I didn't agree with the arguments he put forward, but there are some there, anyway.
I generally use the C# alias when declaring a variable, but the CLR types for the static members. I guess I just like the visual distinction it provides.
(Although it's not a particularily strong reason) I prefer type names over aliases because of IntelliSense standard coloring.
My previous development team adopted this practice because of the mix of C# and Visual Basic.NET developers. It was decided that the CLR types would make it easier for the C# and VB.NET people to communicate.
I think that almost the only time it makes sense to always use the CLR type names is in a mixed-language shop. One other possibility is if you are planning to switch from the current language to another one in the near future. In that case I would go with the CLR type names.
Other than that, there really isn't a strong motivating reason to choose one methodology over the other. It's far more important that you come to a consensus one way or another and make sure everyone is following the "standard".
I think it makes sense to consistently use the CLR type names when calling static type member methods, as you have to do that on enums anyway. So for declaration, use the C# type names, but when calling static members, use the CLR types. This makes it easier to read and more consistent imho. Since, you can't write:
MyEnum value = enum.Parse(typeof(MyEnum), "value");
which would fit better with:
int i = int.Parse("1");
long l = long.parse("1");
You'd rather write:
int i = Int32.Parse("1");
long l = Int64.Parse("1");
MyEnum value = Enum.Parse(typeof(MyEnum), "value");
Nope. I can't. It seems to me that the aliases are there to be used :)

What naming conventions do you use in C#? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
As a beginning programmer, I'm trying to settle on a standard naming convention for myself. I realize that it's personal preference, but I was trying to get some ideas from some of you (well a LOT of you) who are much smarter than myself.
I'm not talking about camel notation but rather how do you name your variables, etc. IMHO, var_Quantity is much more descriptive than Q or varQ. However, how do you keep the variable from becoming too long. I've tried to be more descriptive with naming my controls, but I've ended up with some like "rtxtboxAddrLine1" for a RadTextBox that holds address line 1. Too me,that is unmanageable, although it's pretty clear what that control is.
I'm just curious if you have some guides that you follow or am I left up to my own devices?
Some basic rules can be found here. And much more extended rules can be found here. These are the official guidelines from the Microsoft framework designers.
As for your example, the variable should should be called simply quantity.
In this case, I think you'd be better off naming it as primaryAddressLine or firstAddressLine. Here's why - rtxt as a prefix uselessly tells you the type. Intellisense will help you with the type and is immune to changes made to the actual object type. Calling it firstAddressLine keeps it away from the (poor) convention of using 1, 2, 3...on the end of variable names to indicate that for some reason you needed more of them instead of a collection.
Name it for what it represents/how it's meant to be interpreted or used not for its data type, and in naming it don't abbreviate if you don't need to.
The Guidelines for Names is the best starting point. But as in other areas of life, once you know the rules, you begin to know where it's reasonable to break them.
I never use the old Hungarian notation that calls things strFirstName, intCount, and the like; but I still use it on controls: txtFirstName, btnVerifyData, etc. Reasons include:
I'm not that likely to change the type of a control
If I do change the type of a control, I'll have to change a lot of things, not just the name, so changing the name too is no big deal
They're far easier to find with Intellisense.
In addition, I'm quite likely to do the same thing to many of the TextBoxes or ComboBoxes on a page or form, whereas I'm not likely to do something to all the ints or strings referred to on a page or form. So it helps to be able to quickly find all the TextBoxes with their txt prefix.
There are others, though, that adamantly oppose Hungarian even in this case, and I'm sure they have their reasons. Regardless of your personal style, you may find yourself working on a team that has a very different style. In which case, just do what they do; it's very, very rarely worth making an issue of it. The only time I'd do so is if their style leads to a lot of bugs, but off the top of my head I can't think of a case that would cause that.
There are a few good coding standards documents available online - David Lance wrote one:
http://weblogs.asp.net/lhunt/attachment/591275.ashx
I'd recommend that you use Microsoft's own guidelines as a starting point. Typically, most companies start there (in my experience, anyway).
http://msdn.microsoft.com/en-us/library/czefa0ke(VS.71).aspx
The more descriptive the better, you will find that the length isn't as important as remembering what that control/variable did five years down the road.
For .NET API design (and some general C# guidelines) check Krzysztof Cwalina and Brad Abrams' Framework Design Guidelines
Regards,
tamberg
I generally try to follow the microsoft guidelines, with a few very old habits thrown in.
So, I still can't get out of the habit of prefixing privates with an underscore _privateMember.
I'm old, and that got burnt into my brain.
As far as prefixing control widgets, I have found that if you get too descriptive, it can become painful, in the case of changing the UI down the track.
e.g. you have something called ddlProductLine for a dropdown list, and then that has to change to a radio button group, your prefixing convention starts to be more PITA than helpful.
When you have a lot of widgets to work with, sometimes a more generic prefix like uiCtl can help with the clutter, but still make sense if you have to change widget type.

Categories

Resources