What are the conventions for variable naming in .NET to avoid confusion between parameters and properties? - vb.net

In the example below, what would you name the parameter given that it is used to initialize the property FromDate?
For class constructor methods, I like to have the name of the constructor parameter variable match the name of the property which is being initialized. For example, the parameter "fromDate" is used to initialize the module level variable "_FromDate" with the statement _FromDate = fromDate. Likewise, I could have alternatively written Me.FromDate = fromDate.
Proponents of C#'s case sensitivity would probably say that using a leading lower cased letter for the param variable name, which I believe is MS convention, is an acceptable approach to distinguish it from the Property of the same name but different casing.
However, VB is not case sensitive, which I generally appreciate. In the following example, I am using a param name that matches the property name, 'fromDate," and VB refers to the local instance when there is ambiguity. However, many would probably argue that this "ambiguity" introduces the opportunity for the developer to get confused and not realize which variable is being used. For example, my intent below was to have TWO params passed in, "fromDate" and "toDate" but I accidentily ommited one and as a result, the VB.NET did not warn me of the mistake because it assumed that the statement _ToDate = ToDate was equivalent to _ToDate = Me.ToDate instead of informing me that the variable on the right side of the assignment statement was undeclared.
Public Class Period
Property FromDate As Date
Property ToDate As Date
Public Sub New(ByVal fromDate As Date)
If fromDate > ToDate Then
Throw New ArgumentException("fromDate must be less than or equal to toDate")
End If
_FromDate = fromDate
_ToDate = ToDate
End Sub
End Class
So what is the best solution for VB.NET?
In my judgement, we should have a convention for prefixing all parameter variable with a prefix, but hasn't the use of prefixes been discouraged by Microsoft? For example:
Public Sub New(ByVal paramFromDate As Date, paramToDate As Date)
..or maybe it could be shortened to pFromDate, pToDate...
Whatever approach is taken, I feel that it should be a consistant approach that is used throughout the application.
What do you do?

Use the clearest code possible, which I would suggest is not a prefix. I think using the same name (first letter lowercased) is the clearest code. To avoid the problem encountered I'd rely on a tool, like compiler warnings, FxCop, or ReSharper to alert me that I'm assigning something to itself, since that is almost certainly a mistake in all scenarios.

I know this is against all Microsoft convention, but we use v_ for ByVal parameters, r_ for ByRef parameters and m_ for Module level variables. This allows you to have
m_FromDate = v_FromDate
And you can see straight away what is going on without needing to check the definitions of the variables. I think the biggest argument for non-Hungarian was that modern IDE's allow you to see type on hover over, and changing the type will leave incorrect variables. This scope prefix doesn't clash with that theory and also with CodeRush and ReSharper you can update every instance of a variable if it is required.

Personally, I prefer the _ prefix convention, but there are others I like too. In PL/SQL, my parameters are prefixed with in_, out_, or io_ for in, out, or in/out parameters.
I dislike using only upper and lower cases to distinguish in any language.

Related

a middle approach between Dynamic Typing and Static Typing

I wanted to ask if anyone knows of a programming language where there is dynamic typing but the binding between a name and a type is permanent. Static typing guards your code from assigning a wrong value into a variable, but forces you to declare(and know) the type before compilation. Dynamic typing allows you to assign values with a different type to the same variable one after the other. What I was thinking is, it would be nice to have dynamic typing, but once the variable is bound, the first binding also determines the type of the variable.
For example, using python-like syntax, if I write by mistake:
persons = []
....
adam = Person("adam")
persons = adam #(instead of persons += [adam])
Then I want to get an error(either at runtime or during compilation if possible) because name was defined as a list, and cannot accept values of type Person.
Same thing if the type can not be resolved statically:
result = getData()
...
result = 10
Will generate a runtime error iff getData() did not return an integer.
I know you can hack a similar behavior with a wrapper class but it would be nice to have the option by default in the language as I don't see a good legitimate use for this flexibility in dynamic languages(except for inheritance, or overwriting a common default value such as null/None which could be permitted as special cases).

How to declare variables with a type in Lua

Is it possible to create variables to be a specific type in Lua?
E.g. int x = 4
If this is not possible, is there at least some way to have a fake "type" shown before the variable so that anyone reading the code will know what type the variable is supposed to be?
E.g. function addInt(int x=4, int y=5), but x/y could still be any type of variable? I find it much easier to type the variable's type before it rather than putting a comment at above the function to let any readers know what type of variable it is supposed to be.
The sole reason I'm asking isn't to limit the variable to a specific data type, but simply to have the ability to put a data type before the variable, whether it does anything or not, to let the reader know what type of variable that it is supposed to be without getting an error.
You can do this using comments:
local x = 4 -- int
function addInt(x --[[int]],
y --[[int]] )
You can make the syntax a = int(5) from your other comment work using the following:
function int(a) return a end
function string(a) return a end
function dictionary(a) return a end
a = int(5)
b = string "hello, world!"
c = dictionary({foo = "hey"})
Still, this doesn't really offer any benefits over a comment.
The only way I can think of to do this, would be by creating a custom type in C.
Lua Integer type
No. But I understand your goal is to improve understanding when reading and writing functions calls.
Stating the expected data type of parameters adds only a little in terms of giving a specification for the function. Also, some function parameters are polymorphic, accepting a specific value, or a function or table from which to obtain the value for a context in which the function operates. See string.gsub, for example.
When reading a function call, the only thing known at the call site is the name of the variable or field whose value is being invoked as a function (sometimes read as the "name" of the function) and the expressions being passed as actual parameters. It is sometimes helpful to refactor parameter expressions into named local variables to add to the readability.
When writing a function call, the name of the function is key. The names of the formal parameters are also helpful. But still, names (like types) do not comprise much of a specification. The most help comes from embedded structured documentation used in conjunction with an IDE that infers the context of a name and performs content assistance and presentations of available documentation.
luadoc is one such a system of documentation. You can write luadoc for function you declare.
Eclipse Koneki LDT is one such an IDE. Due to the dynamic nature of Lua, it is a difficult problem so LDT is not always as helpful as one would like. (To be clear, LDT does not use luadoc; It evolved its own embedded documentation system.)

Should I explicitly declare my variables in VB6

I'm writing some code in Visual Basic 6 and I have noticed that I don't even need to declare variables for things to work.
The following (explicit declaration):
Dim foo As String
foo = "Bar"
Seems to work just as well as this (implicit declaration):
Dim foo
foo = "Bar"
Or this (no declaration):
foo = "Bar"
I know in C# I need to declare a variable before I use it, and that implicit and explicit declarations are both acceptable. I also know that in Python, you don't declare your variables at all before you use them.
In regards to Visual Basic 6 (and by extension VBA) which is proper?
Thanks
It's a good HABIT.
There is a VB option called Option Explicit. With that set to ON, then VB forces you to declare a variable before you use it: no more
foo = "Bar"
That helps with mistyping the variable name later in your code... without that, you can typso the variable name, your program compiles but won't work, and it's HARD to dig that out.
In Tools/Options, Editor tab, check the Require Variable Declaration checkbox. This will automatically add Option Explicit to every new code module.
I would say this is more than a best practice; I think of it as a requirement for programmer sanity. The setting is persistent; once set, it stays enabled. Microsoft made it an option because some older versions of VB didn't have the feature, which also explains why it was disabled by default.
Should I explicitly declare my variables in VB6?
Yes. Why?
Not just because it is a good habit or it is a must but because of only one main reason which I have mentioned in this post as well.
VB defaults the variable to being type Variant. A Variant type
variable can hold any kind of data from strings, to integers, to long
integers, to dates, to currency etc. By default “Variants” are the
“slowest” type of variables.
AND
As I mentioned earlier, If you do not specify the type of the
variable, VB defaults the variable to being type Variant. And you
wouldn’t want that as it would slow down your code as the VB Compiler
takes time to decide on what kind of variable you are using. Variants
should also be avoided as they are responsible for causing possible
“Type Mismatch Errors”.
Topic: To ‘Err’ is Human (See Point 3)
Link: http://siddharthrout.wordpress.com/2011/08/01/to-err-is-human/
The above link also covers other parts related to coding that one can/should take care of.
HTH
I highly reccomend that you always declare your variables. This can be forced by setting Option Explicit in each code module. You can let VB6 do that automatically for you by going to Tools->Options, in the Editor tab check Require variable declaration.
If you don't use Option Explicit, then a variable will be automatically created for you each time you reference a previously unknown variable name. This is a very dangerous behavior, because if you mistype a variable name, an empty variable will be created for you, causing unexpected behavior of your code.
You don't have to declare the type of your variables but I would also recommend that you do that. The default type of a variable is Variant, which has a small performance overhead and create some problems if you are creating COM objects for use by C++ or C# (if anybody does that anymore).

Ocaml naming convention

I am wondering if there exists already some naming conventions for Ocaml, especially for names of constructors, names of variables, names of functions, and names for labels of record.
For instance, if I want to define a type condition, do you suggest to annote its constructors explicitly (for example Condition_None) so as to know directly it is a constructor of condition?
Also how would you name a variable of this type? c or a_condition? I always hesitate to use a, an or the.
To declare a function, is it necessary to give it a name which allows to infer the types of arguments from its name, for example remove_condition_from_list: condition -> condition list -> condition list?
In addition, I use record a lot in my programs. How do you name a record so that it looks different from a normal variable?
There are really thousands of ways to name something, I would like to find a conventional one with a good taste, stick to it, so that I do not need to think before naming. This is an open discussion, any suggestion will be welcome. Thank you!
You may be interested in the Caml programming guidelines. They cover variable naming, but do not answer your precise questions.
Regarding constructor namespacing : in theory, you should be able to use modules as namespaces rather than adding prefixes to your constructor names. You could have, say, a Constructor module and use Constructor.None to avoid confusion with the standard None constructor of the option type. You could then use open or the local open syntax of ocaml 3.12, or use module aliasing module C = Constructor then C.None when useful, to avoid long names.
In practice, people still tend to use a short prefix, such as the first letter of the type name capitalized, CNone, to avoid any confusion when you manipulate two modules with the same constructor names; this often happen, for example, when you are writing a compiler and have several passes manipulating different AST types with similar types: after-parsing Let form, after-typing Let form, etc.
Regarding your second question, I would favor concision. Inference mean the type information can most of the time stay implicit, you don't need to enforce explicit annotation in your naming conventions. It will often be obvious from the context -- or unimportant -- what types are manipulated, eg. remove cond (l1 # l2). It's even less useful if your remove value is defined inside a Condition submodule.
Edit: record labels have the same scoping behavior than sum type constructors. If you have defined a {x: int; y : int} record in a Coord submodule, you access fields with foo.Coord.x outside the module, or with an alias foo.C.x, or Coord.(foo.x) using the "local open" feature of 3.12. That's basically the same thing as sum constructors.
Before 3.12, you had to write that module on each field of a record, eg. {Coord.x = 2; Coord.y = 3}. Since 3.12 you can just qualify the first field: {Coord.x = 2; y = 3}. This also works in pattern position.
If you want naming convention suggestions, look at the standard library. Beyond that you'll find many people with their own naming conventions, and it's up to you to decide who to trust (just be consistent, i.e. pick one, not many). The standard library is the only thing that's shared by all Ocaml programmers.
Often you would define a single type, or a single bunch of closely related types, in a module. So rather than having a type called condition, you'd have a module called Condition with a type t. (You should give your module some other name though, because there is already a module called Condition in the standard library!). A function to remove a condition from a list would be Condition.remove_from_list or ConditionList.remove. See for example the modules List, Array, Hashtbl,Map.Make`, etc. in the standard library.
For an example of a module that defines many types, look at Unix. This is a bit of a special case because the names are mostly taken from the preexisting C API. Many constructors have a short prefix, e.g. O_ for open_flag, SEEK_ for seek_command, etc.; this is a reasonable convention.
There's no reason to encode the type of a variable in its name. The compiler won't use the name to deduce the type. If the type of a variable isn't clear to a casual reader from the context, put a type annotation when you define it; that way the information provided to the reader is validated by the compiler.

Use same name for local variable and function

In VBA, I want to use a name for a local variable that I'd also like to use for a function name. The problem I'd that the function name formatting always changes to the local variable formatting.
Any way to prevent that?
I highly recommend not using the same name for disambiguation purposes. Also, if VBA is not case sensitive, it may not know whether you are referring to the function or the variable and thus give a runtime error (I don't think it is compiled per se, but it goes to a proprietary p-code intermediate.)
Often when you'd like the names to be similar, it can be useful to prepend an underscore to one, such as a local variable. Thus I recommend you name the function FunctionName and the variable _FunctionName if you want to go that route.
If you want to try having the same name for each, you will likely need to edit the code outside of the IDE that is reformatting your code. In an editor that doesn't try to auto-format, you may be able to force it. Then whether it compiles or not is the question.
In Visual Basic, each function already has a variable named after the function. Assigning a value to this variable is the only way to set a return value for this function.
Therefore, declaring yet another variable of the same name creates ambiguity. You cannot do so. It results in the Duplicate declaration in current scope error.
And if by "local" variable you meant a module-level variable, then you cannot do it either: Ambiguous name detected: %s.
And if you are asking about a situation when a function and a variable of the same name belong to different scopes, then VBA will use the case of the line that was edited last. So if you declare a function and then declare a variable in another module, the function name will change case. But if you then return to the function, change its casing back and press Enter, the variable, in its turn, will change its casing to match the function name.