Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Friday, January 13, 2012 6:45 PM
If I have a web form called "CatAlbumes.aspx" and its code in "CatAlbumes.aspx.cs", what is the effect of declaring a variable at a class level in the .cs partial class? See the following code example. Is it treated as a "global variable" which can be accessed from any method? Is this a correct approach?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
public partial class Mantenimiento_CatAlbumes : System.Web.UI.Page
{
// ******************************************************************************
// Variable declared at class level.
// ******************************************************************************
String strMessage = "";
// ******************************************************************************
// * Page Init Event.
// ******************************************************************************
protected void Page_Init(object sender, EventArgs e)
{
}
// ******************************************************************************
// * Page Load Event.
// ******************************************************************************
protected void Page_Load(object sender, EventArgs e)
{
}
// ******************************************************************************
// * Method 1 code.
// ******************************************************************************
protected void Method1()
{
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
public partial class Mantenimiento_CatAlbumes : System.Web.UI.Page
{
String strMessage = "";
// ******************************************************************************
// * Page Init Event.
// ******************************************************************************
protected void Page_Init(object sender, EventArgs e)
{
}
// ******************************************************************************
// * Page Load Event.
// ******************************************************************************
protected void Page_Load(object sender, EventArgs e)
{
}
// ******************************************************************************
// * Method 1 code.
// ******************************************************************************
protected void Method1()
{
}
}
All replies (11)
Friday, January 13, 2012 7:01 PM ✅Answered
Yes...that variable can be accessed from anywhere within the class.
Friday, January 13, 2012 7:11 PM ✅Answered
@ JORGEMAL
your variable is known as a "field"; if declared with "static", it's a static field; otherwise, it's an instance field.
sometimes they're called static variables and instance variables.
simplistically, their scope is the class-body and extends to the class-body of derived classes.
g.
Friday, January 13, 2012 7:34 PM ✅Answered
@ JORGEMAL
Is it treated as a "global variable" which can be accessed from any method?
http://msdn.microsoft.com/en-us/library/ms173109.aspx "Classes and Structs (C# Programming Guide)"
"All methods, fields, constants, properties, and events must be declared within a type;
these are called the members of the class or struct.
In C#, there are no global variables or methods as there are in some other languages.
Even a program's entry point, the Main method, must be declared within a class or struct."
Simplistically, what can be acccessed from where depends on scope.
also simplistically, only those methods with the appropriate scope can access it.
Is this a correct approach?
it's difficult to give a simple answer.
it may be a correct approach if it is needed to be in scope for the entire class-body.
it's likely not to be a correct approach if it is needed in only one method.
g.
Friday, January 13, 2012 7:39 PM ✅Answered
@ JORGEMAL
in a class, private is the default; a better answer is "it depends" ... please study this page;
http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx "Accessibility Levels (C# Reference)"
g.
Saturday, January 14, 2012 1:16 PM ✅Answered
I would disagree with gerry's stance on having nothing as default. Basic language nuances should be known even to a beginner. Raising the lowest common denominator in a team is better than lowering the average. That members of a class are private by default and classes are internal by default are basic C# constructs. Reduntant private here there and everywhere only increase clutter (although maybe not so much as to obfuscate the important parts). If you never accept defaults, where does it end? Will you initialize every non-readonly int to zero in the constructor? Would you initialize every string to a null? What about other member variables? If you don't initialize everything than you're accepting defaults.
As for code comments, Uncle Bob has flogged that horse to death and beyond long long ago. Comments do not make code maintainable - they can rather add to confusion when the maintenance guy sees comments that are slightly different from the code and he has no idea who is correct. If something is complex enough that refactoring still doesn't make it understandable, then it needs documentation. That should be proper separate standardized documentation rather then something that's hidden away in some c# code somewhere. Still, if there are subtle gotchas that can be explained in one line, then a small comment may work quite well. And the benefit of following the previous two steps is that those comments will get noticed rather than hidden behind the hundreds of other unnecessary garbage ones.
Saturday, January 14, 2012 5:11 PM ✅Answered
Int32 gerry = 0; int Heartattack;
The two statements are vastly different depending on if they're inline or are class members. Class members are initialized to defaults. Variable declarations within a method are not. Here, you're not setting a default and the two statements are not equivalent. Simply saying "always assign a 0" is hiding behind ignorance rather than embracing the reason behind why the second gives you an error.
As for reducing the average, making every use redundant keywords (private) and assignments (=0) just so a novice doesn't have to learn language features is IMO the wrong way of going about things.Writing unit tests, such issues do get cleared out within moments rather than living on as redundant legacy in the codebase.
The MSMQ example...if you encountered some more of the guy's code...would you trust the comments (knowing he's selective about them). If some advanced features of MSMQ were to be used, would you think that maybe the comments don't cover those scenarios?
I would suggest you read some of Robert C Martin's (aka Uncle Bob) works were he covers his stance on comments quite vigorously (something like "if I see a comment I delete it"). Comments in the source code quickly fall out of date and over time become confusing at best, harmful at worst.
Unless you're writing the public surface of an API where people won't be able to see your source code, XML comments and sandcastle generated documentation are as useful as a 1910 globe in a 2012 geography class. I used to think different and considered good comments to be good form. I have since discovered refactoring and proper naming to be much more useful.
As for formal documentation, the point is you don't document everything left, right and centre. If something is that complex, it usually points to algorithmic or implementation complexity. Such issues are hardly ever going to be understood properly through code comments as comments in code tell a fragmented story. In such cases, a couple of paragraphs as external documetnation is much more useful and maintainable. It's easier to version (document valid on 2/1/2010) and revisit rather than guessing if a bunch of comments are still relevant. Easier to maintain one file rather that 15 related comments acros 7 files.
Friday, January 13, 2012 7:28 PM
@ JORGEMAL
your variable is known as a "field"; if declared with "static", it's a static field; otherwise, it's an instance field.
sometimes they're called static variables and instance variables.
simplistically, their scope is the class-body and extends to the class-body of derived classes.
g.
I have read that I can declare a variable (of field) as "private" or "public". If I do not specify if it is private or public, is it assumed public?
Regards,
Jorge Maldonado
Friday, January 13, 2012 7:48 PM
My 2 +|- cents on "default" anything:
imho, it's generally best to never use default settings ... the extra typing is minimal and explicit specification lessens the chance that you or someone who has to maintain your code will get bitten by a misunderstood default.
personally, i try to write my code so a beginner can understand it; often my code will contain more comments than code ... not that i'm employing comments as a crutch for badly written code, rather to give myself or some psychopath* a chance to maintain it better.
g.
* http://www.codinghorror.com/blog/2008/06/coding-for-violent-psychopaths.html
Saturday, January 14, 2012 2:10 PM
we'll probably need to agree to disagree.
in 2011, i needed to use some MSMQ code written by another programmer; that programmer had in his code a number of troubleshooting tips related to MSMQ. His thoroughness meant that i did not need to suffer his learning curve whenever i hit one of the road bumps that he'd already been through. OTOH, i also needed to modify a certain aspect of his code that he had not documented and was not easily discoverable from his code ... even he could not recall what he'd done; ultimately, he and i wasted a few hours that could have been avoided had he written a one line comment when the code was still fresh in his mind.
HeartattacK, just how does writting a default explicity lower the average?
Regarding initialization, there is zero harm in initialization, example:
Int32 gerry = 0;
int Heartattack;
Console.WriteLine (gerry);
Console.WriteLine (Heartattack);
Console.WriteLine (Heartattack); gives "Use of unassigned local variable" error.
also, Int32 will always be 32-bits while in c#2015 int might be 2^10 Qubits.
Uncle Bob Martin unclebobmartin
over 22000 Twitter accounts are currently following Uncle Bob, including myself.
Comments do not make code maintainable - they can rather add to confusion when the maintenance guy sees comments that are slightly different from the code and he has no idea who is correct.
the above statement is muddy because it does not begin with the word "inappropriate".
If something is complex enough that refactoring still doesn't make it understandable, then it needs documentation.
Absolutely! ==> Comments are documentation. <==
q.v.: http://msdn.microsoft.com/en-us/library/b2s063f7.aspx "XML Documentation Comments (C# Programming Guide)"
and http://sandcastle.codeplex.com/ "Sandcaste -- Documentation Compiler for Managed Classses"
FWIW, frequently, the "proper separate standardized documentation", no matter how well written, is nowhere to be found.
unless you've lost the source code, source comments never get lost.
g.
Sunday, January 15, 2012 2:00 PM
Simply saying "always assign a 0" is hiding behind ignorance
Ashic, i'm not hiding ... my own practices are based upon 4.5 decades of experience.
BTW, like you, i recognize the rôle of unit tests in general and TDD/technology facing tests in particular.
Absolutely, i would trust the comments that the MSMQ programmer has written for the scenarios that he's covered; i do not expect him to cover scenarios that he has not encountered.
i do read Uncle Bob's books ... both "Clean Code" and "Agile Principles, Patterns, and Practices in c#" are on my ACM Safari Bookshelf.
Specifically, i've read "Chapter 4. Comments" in "Clean Code" ... so i'm well aware of Uncle Bob's stance on comments.
imho, far too many programmers use Uncle Bob as an excuse for not writing comments in situations where writing comments is appropriate behaviour; in "Chapter 4" of "Clean Code", Uncle Bob has a section "Good Comments" in which he writes "Some comments are necessary or beneficia." and gives categories and examples.
g.
P.S.: Ashic, you and i are verging on hijacking this thread; let's not do that; if you want, we can continue this debate in Free For All.
Monday, January 16, 2012 5:52 AM
I'm not saying you are hiding behind ignorance - i'm saying that approach will help juniors hide behind ignorance. Educating them is often better than making it easy for them.
I bring up the comments issue as I saw you mentioned you often have more comments than code. I doubt all of those comments are useful.
Anyway, I think the OPs question has been resolved and there's no point in pursuing this further.