Naming convention for VB.NET private fields - vb.net

Is there an official convention for naming private fields in VB.NET? For example, if I have a property called 'Foo', I normally call the private field '_Foo'. This seems to be frowned upon in the Offical Guidelines:
"Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields."
In C#, you could call the private field 'foo', the property 'Foo', and refer to the private field as 'this.foo' in the constructor. As VB.NET is case insensitive you can't do this - any suggestions?

I still use the _ prefix in VB for private fields, so I'll have _foo as the private field and Foo as the property. I do this for c# as well and pretty much any code I write. Generally I wouldn't get too caught up in "what is the right way to do it" because there isn't really a "right" way (altho there are some very bad ways) but rather be concerned with doing it consistently.
At the end of the day, being consistent will make your code much more readable and maintainable than using any set of "right" conventions.

It's personal preference, although there's widespread support for having some distinction. Even in C# I don't think there's one widely used convention.
Jeff Prosise says
As a matter of personal preference I typically prefix private fields with an underscore [in C#] ... This convention is used quite a lot in the .NET framework but it is not used throughout.
From the .NET Framework Design Guidelines 2nd Edition page 73.
Jeffrey Richter says
I make all my fields private and I prefix my instance fields with "m_" and my static fields with "s_" [in C#]
From the .NET Framework Design Guidelines 2nd Edition page 47. Anthony Moore (BCL team) also thinks using "m_" and "s_" is worth consideration, page 48.

Official guidelines are just that -- guidelines. You can always go around them. That being said we usually prefix fields with an underscore in both C# and VB.NET. This convention is quite common (and obviously, the Official Guidelines ignored).
Private fields can then be referenced without the "me" keyword (the "this" keyword is for C# :)

The design guidelines that you linked specifically state that they only apply to static public and protected fields. The design guidelines mostly focus on designing public APIs; what you do with your private members is up to you. I'm not positive but I'm relatively confident that private members are not considered when the compiler checks for CLS compliance, because only public/protected members come in to play there (the idea is, "What if someone who uses a language that doesn't allow the _ character tries to use your library?" If the members are private, the answer is "Nothing, the user doesn't have to use these members." but if the members are public you're in trouble.)
That said, I'm going to add to the echo chamber and point out that whatever you do, it's important to be consistent. My employer mandates that private fields in both C# and VB are prefixed with _, and because all of us follow this convention it is easy to use code written by someone else.

In VB.NET 4.0, most of you probably know you don't need to explicitly write getters and setters for your Property declarations as follows:
Public Property Foo As String
Public Property Foo2 As String
VB automatically creates private member variables called _Foo and _Foo2. It seems as though Microsoft and the VS team have adopted the _ convention, so I don't see an issue with it.

I don't think there is an official naming convention, but i've seen that Microsoft use m_ in the Microsoft.VisualBasic dll (via reflector).

I still use the _ prefix in VB for
private fields, so I'll have _foo as
the private field and Foo as the
property. I do this for c# as well and
pretty much any code I write.
Generally I wouldn't get too caught up
in "what is the right way to do it"
because there isn't really a "right"
way (altho there are some very bad
ways) but rather be concerned with
doing it consistently.
I haven't found anything better than the "_" for clarify and consistency. Cons include:
Not CLS compliant
Tends to get lost when VB draws horizontal lines across my IDE
I get around the lines by turning those off in the editor, and try not to think too much about the CLS compliance.

I agree with #lomaxx, it's more important to be consistent throughout the team than to have the right convention.
Still, here are several good places to get ideas and guidance for coding conventions:
Practical Guidelines and Best Practices for Microsoft Visual Basic and Visual C# Developers by Francesco Balena is a great book that addresses many of these issues.
IDesign Coding Standards (for C# and for WCF)
The .NET Framework Source Code (in VS2008)

I prefer to use the underscore prefix for private fields. I use lowercase first letter for the method parameters. I follow the guideline of having lowercase camelcase parameters for methods, which I regard as more important than the naming of private fields since it is part of the API for the class. . e.g.
Public Class Class1
Private _foo As String
Public Property Foo() As String
Get
Return _foo
End Get
Set(ByVal value As String)
_foo = value
End Set
End Property
Public Sub New(ByVal foo As String)
_foo = foo
End Sub
End Class
Using this pattern, you won't have any naming conflicts with the private field and your constructor parameter in C# or VB.NET.

I agree most important is not what style one uses but it being consistent.
With that said, the new MS/.NET styling for private fields tends to be _fooVar (underscore followed by a camelCased name)

Related

Why some java methods in core libraries end with numbers?

It's common in a lot of classes in JDK, just a few examples:
java.util.Properties
load0
store0
java.lang.Thread
start0
stop0
setPriority0
Usually they are private native methods (like in Thread class), but sometimes they are just private (Properties class)
I'm just curious if anybody know if there is any history behind that.
I believe they are named like that because equivalent functions with same names exist in the code and just to distinguish between native helper functions and public functions they decided to suffix them with 0.
in java.util.Properties both load, store and load0, store0 exist.
The 0 after the method name is done so to distinguish between public and private methods having same name .
Start function will call the start0 function.
Those functions which ends with 0 is private method.
And those which are not ending with number is public.
You can check in any of the library.
The use of zero suffixes on method names is just a convention to deal with cases where you have a public API method and a corresponding private method. In the Java SE libraries, this is commonly used for the native methods that provide the underlying functionality implemented by the classes. (You can see what is going on by looking at the OpenJDK source code.)
But your questions are:
Why some java methods in core libraries end with numbers?
Because someone thought it would be a good idea. It is not strictly necessary since they typically could have overloaded the public methods instead. And since the zero suffix matters are private, the naming of methods should not be relevant beyond the class and its native implementation.
I'm just curious if anybody know if there is any history behind that.
There is no mention of this convention in the original Java Style Guide. In fact, I think it predates Java. I vaguely recall seeing it in C libraries in 4.x BSD Unix. That was the mid 1980's. And I wouldn't be surprised if they adopted it from somewhere else.

Private and protected methods in Objective-C

What is the recommended way to define private and protected methods in Objective-C? One website suggested using categories in the implementation file for private methods, another suggested trailing underscores, or XX_ where XX is some project-specific code. What does Apple itself use?
And what about protected methods? One solution I read was to use categories in separate files, for example CLASS_protected.h and CLASS_protected.m but this seems like it could get very bloated. What should I do?
There are three issues:
Hiding from compiler.
That is, making it impossible for someone else to #import something and see your method declarations. For that, put your private API into a separate header file, mark that header's role as "Private" in Xcode, and then import it in your project where you need access to said private API.
Use a category or class extension to declare the additional methods.
Preventing collisions
If you are implementing lots of internal goop, do so with a common prefix or something that makes a collision with Apple provided (or third party) provided methods exceedingly unlikely. This is especially critical for categories and not nearly as critical for your leaf node subclasses of existing classes.
Post the link for the site suggesting leading underscores, as they are wrong, wrong, wrong. Leading underscores are used by the system to mark private API and you can run into collisions easily enough.
Hiding from the runtime.
Don't bother. It just makes debugging / crash analysis harder and anyone determined enough to muck around at the runtime will be able to hack your app anyway.
There are no "real" private methods in Objective C, as the run-time will allow, via documented public APIs, access any method in any class by using their string names.
I never do separate interface files for "private" methods, and let the compiler complain if I try to use these any of these methods outside of file scope.
The XX_ seems to be the ad hoc means to create a pseudo namespace. The idea is to read Apple's docs and the docs of any frameworks you might use at any time in the future, and pick an XX prefix that none of these others is ever likely to use.

Declare global variables in Visual Studio 2010 and VB.NET

How do I declare a global variable in Visual Basic?
These variables need to be accessible from all the Visual Basic forms. I know how to declare a public variable for a specific form, but how do I do this for all the forms in my project?
There is no way to declare global variables as you're probably imagining them in VB.NET.
What you can do (as some of the other answers have suggested) is declare everything that you want to treat as a global variable as static variables instead within one particular class:
Public Class GlobalVariables
Public Shared UserName As String = "Tim Johnson"
Public Shared UserAge As Integer = 39
End Class
However, you'll need to fully-qualify all references to those variables anywhere you want to use them in your code. In this sense, they are not the type of global variables with which you may be familiar from other languages, because they are still associated with some particular class.
For example, if you want to display a message box in your form's code with the user's name, you'll have to do something like this:
Public Class Form1: Inherits Form
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
MessageBox.Show("Hello, " & GlobalVariables.UserName)
End Sub
End Class
You can't simply access the variable by typing UserName outside of the class in which it is defined—you must also specify the name of the class in which it is defined.
If the practice of fully-qualifying your variables horrifies or upsets you for whatever reason, you can always import the class that contains your global variable declarations (here, GlobalVariables) at the top of each code file (or even at the project level, in the project's Properties window). Then, you could simply reference the variables by their name.
Imports GlobalVariables
Note that this is exactly the same thing that the compiler is doing for you behind-the-scenes when you declare your global variables in a Module, rather than a Class. In VB.NET, which offers modules for backward-compatibility purposes with previous versions of VB, a Module is simply a sealed static class (or, in VB.NET terms, Shared NotInheritable Class). The IDE allows you to call members from modules without fully-qualifying or importing a reference to them. Even if you decide to go this route, it's worth understanding what is happening behind the scenes in an object-oriented language like VB.NET. I think that as a programmer, it's important to understand what's going on and what exactly your tools are doing for you, even if you decide to use them. And for what it's worth, I do not recommend this as a "best practice" because I feel that it tends towards obscurity and clean object-oriented code/design. It's much more likely that a C# programmer will understand your code if it's written as shown above than if you cram it into a module and let the compiler handle everything.
Note that like at least one other answer has alluded to, VB.NET is a fully object-oriented language. That means, among other things, that everything is an object. Even "global" variables have to be defined within an instance of a class because they are objects as well. Any time you feel the need to use global variables in an object-oriented language, that a sign you need to rethink your design. If you're just making the switch to object-oriented programming, it's more than worth your while to stop and learn some of the basic patterns before entrenching yourself any further into writing code.
Pretty much the same way that you always have, with "Modules" instead of classes and just use "Public" instead of the old "Global" keyword:
Public Module Module1
Public Foo As Integer
End Module
Okay. I finally found what actually works to answer the question that seems to be asked;
"When needing many modules and forms, how can I declare a variable to be public to all of them such that they each reference the same variable?"
Amazingly to me, I spent considerable time searching the web for that seemingly simple question, finding nothing but vagueness that left me still getting errors.
But thanks to Cody Gray's link to an example, I was able to discern a proper answer;
Situation;
You have multiple Modules and/or Forms and want to reference a particular variable from each or all.
"A" way that works;
On one module place the following code (wherein "DefineGlobals" is an arbitrarily chosen name);
Public Module DefineGlobals
Public Parts As Integer 'Assembled-particle count
Public FirstPrtAff As Long 'Addr into Link List
End Module
And then in each Module/Form in need of addressing that variable "Parts", place the following code (as an example of the "InitForm2" form);
Public Class InitForm2
Private Sub InitForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Parts = Parts + 3
End Sub
End Class
And perhaps another Form;
Public Class FormX
Sub CreateAff()
Parts = 1000
End Sub
End Class
That type of coding seems to have worked on my VB2008 Express and seems to be all needed at the moment (void of any unknown files being loaded in the background) even though I have found no end to the "Oh btw..." surprise details. And I'm certain a greater degree of standardization would be preferred, but the first task is simply to get something working at all, with or without standards.
Nothing beats exact and well worded, explicit examples.
Thanks again, Cody
Make it static (shared in VB).
Public Class Form1
Public Shared SomeValue As Integer = 5
End Class
Public variables are a code smell - try to redesign your application so these are not needed. Most of the reasoning here and here are as applicable to VB.NET.
The simplest way to have global variables in VB.NET is to create public static variables on a class (declare a variable as Public Shared).
A global variable could be accessible in all your forms in your project if you use the keyword public shared if it is in a class. It will also work if you use the keyword "public" if it is under a Module, but it is not the best practice for many reasons.
(... Yes, I somewhat repeating what "Cody Gray" and "RBarryYoung" said.)
One of the problems is when you have two threads that call the same global variable at the same time. You will have some surprises. You might have unexpected reactions if you don't know their limitations. Take a look at the post Global Variables in Visual Basic .NET and download the sample project!
small remark: I am using modules in webbased application (asp.net).
I need to remember that everything I store in the variables on the module are seen by everyone in the application, read website. Not only in my session.
If i try to add up a calculation in my session I need to make an array to filter the numbers for my session and for others.
Modules is a great way to work but need concentration on how to use it.
To help against mistakes: classes are send to the
CarbageCollector
when the page is finished. My modules stay alive (as long as the application is not ended or restarted) and I can reuse the data in it.
I use this to save data that sometimes is lost because of the sessionhandling by IIS.
IIS Form auth
and
IIS_session
are not in sync, and with my module I pull back data that went over de cliff.
All of above can be avoided by simply declaring a friend value for runtime on the starting form.
Public Class Form1
Friend sharevalue as string = "Boo"
Then access this variable from all forms simply using Form1.sharevalue
You could just add a new Variable under the properties of your project
Each time you want to get that variable you just have to use
My.Settings.(Name of variable)
That'll work for the entire Project in all forms
The various answers in this blog seem to be defined by SE's who promote strict adherence to the usual rules of object-oriented programming (use a Public Class with public shared (aka static), and fully-qualified class references, or SE's who promote using the backward-compatibility feature (Module) for which the compiler obviously needs to do the same thing to make it work.
As a SE with 30+ years of experience, I would propose the following guidelines:
If you are writing all new code (not attempting to convert a legacy app) that you avoid using these forms altogether except in the rare instance that you really DO need to have a static variable because they can cause terrible consequences (and really hard-to-find bugs). (Multithread and multiprocessing code requires semaphores around static variables...)
If you are modifying a small application that already has a few global variables, then formulate them so they are not obscured by Modules, that is, use the standard rules of object-oriented programming to re-create them as public static and access them by full qualification so others can figure out what is going on.
If you have a huge legacy application with dozens or hundreds of global variables, by all means, use Modules to define them. There is no reason to waste time when getting the application working, because you are probably already behind the 8-ball in time spent on Properties, etc.
The first guy with a public class makes a lot more sense. The original guy has multiple forms and if global variables are needed then the global class will be better. Think of someone coding behind him and needs to use a global variable in a class you have IntelliSense, it will also make coding a modification 6 months later a lot easier.
Also if I have a brain fart and use like in an example parts on a module level then want my global parts I can do something like
Dim Parts as Integer
parts = 3
GlobalVariables.parts += Parts '< Not recommended but it works
At least that's why I would go the class route.
You can pipe the variable in to a file in the output directory and then load that file in the variable.
Imports System.IO
This code writes the file.
Dim somevariable = "an example"
Dim fs As FileStream = File.Create("globalvars/myvar1.var")
Dim filedata As Byte() = New UTF8Encoding(True).GetBytes(somevariable)
fs.Write(filedata, 0, filedata.Length)
fs.Close()
This loads the file in another form.
Dim form2variable
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("globalvars/myvar1.var")
form2variable = filereader
Public Class Form1
Public Shared SomeValue As Integer = 5
End Class
The answer:
MessageBox.Show("this is the number"&GlobalVariables.SomeValue)

Why don't oop languages have a 'read only' access modifier?

Every time I write trivial getters (get functions that just return the value of the member) I wonder why don't oop languages simply have a 'read only' access modifier that would allow reading the value of the members of the object but does not allow you to set them just like const things in c++.
The private,protected,public access modifiers gives you either full (read/write) access or no access.
Writing a getter and calling it every time is slow, because function calling is slower than just accessing a member. A good optimizer can optimize these getter calls out but this is 'magic'. And I don't think it is good idea learning how an optimizer of a certain compiler works and write code to exploit it.
So why do we need to write accessors, read only interfaces everywhere in practice when just a new access modifier would do the trick?
ps1: please don't tell things like 'It would break the encapsulation'. A public foo.getX() and a public but read only foo.x would do the same thing.
EDIT: I didn't composed my post clear. Sorry. I mean you can read the member's value outside but you can't set it. You can only set its value inside the class scope.
You're incorrectly generalizing from one or some OOP language(s) you know to OOP languages in general. Some examples of languages that implement read-only attributes:
C# (thanks, Darin and tonio)
Delphi (= Object Pascal)
Ruby
Scala
Objective-C (thanks, Rano)
... more?
Personally, I'm annoyed that Java doesn't have this (yet?). Having seen the feature in other languages makes boilerplate writing in Java seem tiresome.
Well some OOP languages do have such modifier.
In C#, you can define an automatic property with different access qualifiers on the set and get:
public int Foo { get; private set; }
This way, the class implementation can tinker with the property to its heart's content, while client code can only read it.
C# has readonly, Java and some others have final. You can use these to make your member variables read-only.
In C#, you can just specify a getter for your property so it can only be read, not changed.
private int _foo;
public int Foo
{
get { return _foo; }
}
Actually, no they aren't the same. Public foo.getX() would still allow the internal class code to write to the variable. A read-only foo.x would be read-only for the internal class code as well.
And there are some languages that do have such modifier.
C# properties allow to define read only properties easily. See this article.
Not to mention Objective-C 2.0 property read-only accessors
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html
In Delphi:
strict private
FAnswer: integer;
public
property Answer: integer read FAnswer;
Declares a read-only property Answer that accesses private field FAnswer.
The question largely boils down to: why does not every language have a const property like C++?
This is why it's not in C#:
Anders Hejlsberg: Yes. With respect to
const, it's interesting, because we
hear that complaint all the time too:
"Why don't you have const?" Implicit
in the question is, "Why don't you
have const that is enforced by the
runtime?" That's really what people
are asking, although they don't come
out and say it that way.
The reason that const works in C++ is
because you can cast it away. If you
couldn't cast it away, then your world
would suck. If you declare a method
that takes a const Bla, you could pass
it a non-const Bla. But if it's the
other way around you can't. If you
declare a method that takes a
non-const Bla, you can't pass it a
const Bla. So now you're stuck. So you
gradually need a const version of
everything that isn't const, and you
end up with a shadow world. In C++ you
get away with it, because as with
anything in C++ it is purely optional
whether you want this check or not.
You can just whack the constness away
if you don't like it.
See: http://www.artima.com/intv/choicesP.html
So, the reason wy const works in C++ is because you can work around it. Which is sensible for C++, which has its roots in C.
For managed languages like Java and C#, users would expect that const would be just as secure as, say, the garbage collector. That also implies you can't work around it, and it won't be useful if you can't work around it.

Why are public fields and properties interchangeably binary compatible?

In the day job, I work on a VB6 (I know, but don't mock the afflicted...) application that uses a number of libraries we have written (also in the ever illustrious VB6). One of these supporting libraries had a load of private members exposed via public properties, and I was asked to remove the properties, and promote the private member variables into public fields with the same name as the original properties.
Now, I'm no COM expert, but I was under the impression that each and every exposed item on a class gets it's own GUID. Since we would be going from a situation where each value went from 2 Guids (Property Get and Property Let) to one where they only used the one (the public field), I was expecting this to break binary compatibility - but it seems it hasn't done that.
Can anyone explain why?
No, it hasn't broken compatibility because it hasn't removed the property get and property let methods. It's just that the compiler is now writing them for you.
Isn't this one of the few areas where VB6 is arguably better than .Net?
In .Net public fields behave differently to public properties, and this makes some refactorings difficult and causes confusion.
In VB6 public fields behave exactly like public properties, which is why it's possible to switch without affecting binary compatibility. Behind the scenes, the compiler generates property get and set routines for public fields. In a sense VB6 has automatically implemented properties (now advertised as a "new feature" in VB10)...
I think it's a bit more subtle than that. You get a GUID for the COM interface (not each individual field/method). As I understand it the binary compatibility attempts to work out if the interface your currently compiling is backwards compatible with a reference version of your DLL (assuming you have one) and only changes the GUID if they are not compatible.
I'm therefore also surprised that it has decided removing all the get/set methods is compatible :/