VBA Module naming conventions - vba

A quick question about Naming of VBA modules. I've posted this in a few related posts but they are old and evidently unobserved at this point and have gotten no responses. So I ask it here. When naming a module in VBA it defaults to the name "Module#". I usually just add my name to it such that it becomes "Module_MyCodeName". Is it ok to remove the "Module#" name altogether and make it just "MyCodeName"? I've seen many naming things but nothing that actually says "Why yes! You CAN remove "Module" and it will not affect the functionality." I know it's a basic basic basic question but I really don't know. Maybe just a brain fart or something.///

I would suggest the Lezynski prefix m-. Unless you are developing VBA in a team (which you shouldn't) it shouldn't matter though.
I can only imagine how and why you would use mFormating and mGlobalVariables (by the way do consider the CamelCase convention when naming your elements).

Related

Why some developers prefix variables with the word "my"?

I've noticed some of the developers on my team tend to prefix their variables with "my" (i.e. "var myHello = 'Hello World'). These aren't instance variables or anything, just regular variables that reside within a method.
Is there any significance to this naming convention? To me it comes off a little "newbie-ish" -- as if they just graduated from their LOGO class. But these are seemingly seasoned devs so I could be way off.
I totally disagree with you. leaving the fact that judging a person's skill by variable names imply that he's newbie aside, some teams have code standards other than you're used to. For your information - in PERL if you didn't know there's a reserved word my variable and it has nothing to do with coding standards. Maybe he had no better name for that class which is already implemented in the system but he wants to keep things simple? Besides, maybe he likes to reference himself to the code he writes?

What is the point of the lower camel case variable casing convention (thisVariable, for example)?

I hope this doesn't get closed due to being too broad. I know it comes down to personal preference, but there is an origin to all casing conventions and I would like to know where this one came from and a logical explanation as to why people use it.
It's where you go all like var empName;. I call that lower camel, although it's probably technically called something else. Personally, I go like var EmpName. I call that proper camel and I like it.
When I first started programming, I began with the lower camel convention. I didn't know why. I just followed the examples set by all the old guys. Variables and functions (VB) got lower camel while subs and properties got proper camel. Then, after I finally acquired a firm grasp on programming itself, I became comfortable enough to question the tactics of my mentors. It didn't make logical sense to me to use lower camel because it wasn't consistent, especially if you have a variable that consists of one word which ends up being in all lowercase. There is also no validation mechanism in place to make sure you are appropriately using lower vs. upper camel, so I asked why not just use proper camel for everything. It's consistent since all variable names are subject to proper camelization.
Having dug deeper into it, it turns out that this is a very sensitive issue to many programmers when it is brought to question. They usually answer with, "Well, it's just personal preference" or "That's just how I learned it". Upon prodding further, it usually invokes a sort of dogmatic reaction with the person as I attempt to find a logical reason behind their use of lower camel.
So anyone want to shed a little history and logic behind casing of the proper camelatory variety?
It's a combination of two things:
The convention of variables starting with lower case, to differentiate from classes or other entities which use a capital. This is also sometimes used to differentiate based on access level (private/public)
CamelCasing as a way to make multi-word names more readable without spaces (of course this is a preference over underscore, which some people use). I would guess the logic is that CamelCasing is easier/faster for some to type than word_underscores.
Whether or not it gets used is of course up to whomever is setting the coding standards that govern the code being written. Underscores vs CamelCase, lowercasevariables vs Uppercasevariables. CamelCase + lowercasevariable = camelCase
In languages like C# or VB, the standard is to start private things with lowercase and start public/protected things with uppercase. This way, just by looking at the first letter you can tell whether the thing you are messing could be used by other classes and thus any changes need more scrutiny. Also, there are tools to enforce naming conventions like this. The one created/used internally at Microsoft is called StyleCop and is available as a free download.
Historically, well named variables in C (a case-sensitive language) consisted of a single word in lower case. UPPERCASE was reserved for macros.
Then came along C++, where classes are usually CapitalizedAndCamelCased, and variables/functions consisting of several words are camelCased. (Note that C people tend to dislike camelCase, and instead write identifiers_this_way.
From there, it spread.
And, yes, probably other case-sensitive languages have had some influence.
lowerCamelCase I think has become popular because of java and javascript.
In java, it is specifically defined why, that the first word should be a verb with small letters where the remaining words start with a capital letter.
The reason why java chose lowerCamelCase I think depends on what they wanted to solve. Java was launched in 1995 as a language that would make programming easy. C/C++ that was often used was often considered difficult and too technical.
This was something java claimed to solve, more people would be able to program and the same code would work on different hardware. The code was the documentation, you didn't need to comment code, just read and everything would be great.
lowerCamelCase makes it harder to write "technical" code because it removes options to use uppercase and lowercase letters to better describe the code from a technical perspective. Java didn't want to be hard, java was the language to use where everyone could learn to program.
javascript in browsers was created in 10 days by Brendan Eich in 1995. Why javascript selected lowerCamelCase I think is because of java. It has nothing to do with java but it has "java" in its name "javascript".

Are namespace collisions really an issue in Objective-C?

Objective-C doesn't have namespaces, and many (such as CocoaDevCentral's Cocoa Style Guide) recommend prefixing your class names with initials to avoid namespace collision.
Quoting from the above link:
Objective-C doesn't have namespaces,
so prefix your class names with
initials. This avoids "namespace
collision," which is a situation where
two pieces of code have the same name
but do different things.
That makes sense, I suppose. But honestly, in the context of a relatively small app (say, an iPhone game), is this really an issue? Should I really rename MyViewController to ZPViewController? If not, at what point do namespace collisions really become a concern?
If you're writing an application that uses some set of libraries, then you already know what your namespace looks like and you just need to select names that do not conflict with existing available functions.
However, if you are writing a library for use by others, then you should pick a reasonably unique prefix to try to avoid name collisions with other libraries. With only two characters there may still be name collisions, but the frequency will be reduced.
Small apps shouldn't use up all the good names, so won't have a problem with namespaces.
But it is a good idea to get used to the style that languages are generally written in. It makes it easier to read other people's code, and for others to read yours.
E. g., use camelCase variables in Java, but CamelCase vars in C#, hyphen_separated_names in C, etc.
It will make it easier for you to learn in the long run.
I have read (but haven't verified) that Apple has private classes in their frameworks that don't include any prefixes on the names. So if your application classes' names have no prefixes, you risk colliding with those.
I've worked with repositories where classes were not prefixed. (Or only some of the classes were prefixed.)
One thing that I found painful is it's sometimes hard to tell if code was written by someone inside or outside the company. Using a consistent prefix makes it immediately obvious for someone reading the code for the first time.
Keep in mind that code will be read many more times than written.
Also, it can definitely come in handy when using tools like grep and sed.

Anyone else find naming classes and methods one of the most difficult parts in programming? [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.
So I'm working on this class that's supposed to request help documentation from a vendor through a web service. I try to name it DocumentRetriever, VendorDocRequester, DocGetter, but they just don't sound right. I ended up browsing through dictionary.com for half an hour trying to come up with an adequate word.
Start programming with bad names is like having a very bad hair day in the morning, the rest of the day goes downhill from there. Feel me?
What you are doing now is fine, and I highly recommend you stick with your current syntax, being:
context + verb + how
I use this method to name functions/methods, SQL stored procs, etc. By keeping with this syntax, it will keep your Intellisense/Code Panes much more neat. So you want EmployeeGetByID() EmployeeAdd(), EmployeeDeleteByID(). When you use a more grammatically correct syntax such as GetEmployee(), AddEmployee() you'll see that this gets really messy if you have multiple Gets in the same class as unrelated things will be grouped together.
I akin this to naming files with dates, you want to say 2009-01-07.log not 1-7-2009.log because after you have a bunch of them, the order becomes totally useless.
One lesson I have learned, is that if you can't find a name for a class, there is almost always something wrong with that class:
you don't need it
it does too much
A good naming convention should minimize the number of possible names you can use for any given variable, class, method, or function. If there is only one possible name, you'll never have trouble remembering it.
For functions and for singleton classes, I scrutinize the function to see if its basic function is to transform one kind of thing into another kind of thing. I'm using that term very loosely, but you'll discover that a HUGE number of functions that you write essentially take something in one form and produce something in another form.
In your case it sounds like your class transforms a Url into a Document. It's a little bit weird to think of it that way, but perfectly correct, and when you start looking for this pattern, you'll see it everywhere.
When I find this pattern, I always name the function xFromy.
Since your function transforms a Url into a Document, I would name it
DocumentFromUrl
This pattern is remarkably common. For example:
atoi -> IntFromString
GetWindowWidth -> WidthInPixelsFromHwnd // or DxFromWnd if you like Hungarian
CreateProcess -> ProcessFromCommandLine
You could also use UrlToDocument if you're more comfortable with that order. Whether you say xFromy or yTox is probably a matter of taste, but I prefer the From order because that way the beginning of the function name already tells you what type it returns.
Pick one convention and stick to it. If you are careful to use the same names as your class names in your xFromy functions, it'll be a lot easier to remember what names you used. Of course, this pattern doesn't work for everything, but it does work where you're writing code that can be thought of as "functional."
Sometimes there isn't a good name for a class or method, it happens to us all. Often times, however, the inability to come up with a name may be a hint to something wrong with your design. Does your method have too many responsibilities? Does your class encapsulate a coherent idea?
Thread 1:
function programming_job(){
while (i make classes){
Give each class a name quickly; always fairly long and descriptive.
Implement and test each class to see what they really are.
while (not satisfied){
Re-visit each class and make small adjustments
}
}
}
Thread 2:
while(true){
if (any code smells bad){
rework, rename until at least somewhat better
}
}
There's no Thread.sleep(...) anywhere here.
I do spend a lot of time as well worrying about the names of anything that can be given a name when I am programming. I'd say it pays off very well though. Sometimes when I am stuck I leave it for a while and during a coffee break I ask around a bit if someone has a good suggestion.
For your class I'd suggest VendorHelpDocRequester.
The book Code Complete by Steve Mcconnell has a nice chapter on naming variables/classes/functions/...
I think this is a side effect.
It's not the actual naming that's hard. What's hard is that the process of naming makes you face the horrible fact that you have no idea what the hell you're doing.
I actually just heard this quote yesterday, through the Signal vs. Noise blog at 37Signals, and I certainly agree with it:
"There are only two hard things in Computer Science: cache invalidation and naming things."
— Phil Karlton
It's good that it's difficult. It's forcing you to think about the problem, and what the class is actually supposed to do. Good names can help lead to good design.
Agreed. I like to keep my type names and variables as descriptive as possible without being too horrendously long, but sometimes there's just a certain concept that you can't find a good word for.
In that case, it always helps me to ask a coworker for input - even if they don't ultimately help, it usually helps me to at least explain it out loud and get my wheels turning.
I was just writing on naming conventions last month: http://caseysoftware.com/blog/useful-naming-conventions
The gist of it:
verbAdjectiveNounStructure - with Structure and Adjective as optional parts
For verbs, I stick to action verbs: save, delete, notify, update, or generate. Once in a while, I use "process" but only to specifically refer to queues or work backlogs.
For nouns, I use the class or object being interacted with. In web2project, this is often Tasks or Projects. If it's Javascript interacting with the page, it might be body or table. The point is that the code clearly describes the object it's interacting with.
The structure is optional because it's unique to the situation. A listing screen might request a List or an Array. One of the core functions used in the Project List for web2project is simply getProjectList. It doesn't modify the underlying data, just the representation of the data.
The adjectives are something else entirely. They are used as modifiers to the noun. Something as simple as getOpenProjects might be easily implemented with a getProjects and a switch parameter, but this tends to generate methods which require quite a bit of understanding of the underlying data and/or structure of the object... not necessarily something you want to encourage. By having more explicit and specific functions, you can completely wrap and hide the implementation from the code using it. Isn't that one of the points of OO?
More so than just naming a class, creating an appropriate package structure can be a difficult but rewarding challenge. You need to consider separating the concerns of your modules and how they relate to the vision of the application.
Consider the layout of your app now:
App
VendorDocRequester (read from web service and provide data)
VendorDocViewer (use requester to provide vendor docs)
I would venture to guess that there's a lot going on inside a few classes. If you were to refactor this into a more MVC-ified approach, and allow small classes to handle individual duties, you might end up with something like:
App
VendorDocs
Model
Document (plain object that holds data)
WebServiceConsumer (deal with nitty gritty in web service)
Controller
DatabaseAdapter (handle persistance using ORM or other method)
WebServiceAdapter (utilize Consumer to grab a Document and stick it in database)
View
HelpViewer (use DBAdapter to spit out the documention)
Then your class names rely on the namespace to provide full context. The classes themselves can be inherently related to application without needing to explicitly say so. Class names are simpler and easier to define as a result!
One other very important suggestion: please do yourself a favor and pick up a copy of Head First Design Patterns. It's a fantastic, easy-reading book that will help you organize your application and write better code. Appreciating design patterns will help you to understanding that many of the problems you encounter have already been solved, and you'll be able to incorporate the solutions into your code.
Leo Brodie, in his book "Thinking Forth", wrote that the most difficult task for a programmer was naming things well, and he stated that the most important programming tool is a thesaurus.
Try using the thesaurus at http://thesaurus.reference.com/.
Beyond that, don't use Hungarian Notation EVER, avoid abbreviations, and be consistent.
Best wishes.
In short:
I agree that good names are important, but I don't think you have to find them before implementing at all costs.
Of course its better to have a good name right from the start. But if you can't come up with one in 2 minutes, renaming later will cost less time and is the right choice from a productivity point of view.
Long:
Generally it's often not worth to think too long about a name before implementing. If you implement your class, naming it "Foo" or "Dsnfdkgx", while implementing you see what you should have named it.
Especially with Java+Eclipse, renaming things is no pain at all, as it carefully handles all references in all classes, warns you of name collisions, etc. And as long as the class is not yet in the version control repository, I don't think there's anything wrong with renaming it 5 times.
Basically, it's a question of how you think about refactoring. Personally, I like it, though it annoys my team mates sometimes, as they believe in never touch a running system. And from everything you can refactor, changing names is one of the most harmless things you can do.
Why not HelpDocumentServiceClient kind of a mouthful, or HelpDocumentClient...it doesn't matter it's a vendor the point is it's a client to a webservice that deals with Help documents.
And yes naming is hard.
There is only one sensible name for that class:
HelpRequest
Don't let the implementation details distract you from the meaning.
Invest in a good refactoring tool!
I stick to basics: VerbNoun(arguments). Examples: GetDoc(docID).
There's no need to get fancy. It will be easy to understand a year from now, whether it's you or someone else.
For me I don't care how long a method or class name is as long as its descriptive and in the correct library. Long gone are the days where you should remember where each part of the API resides.
Intelisense exists for all major languages. Therefore when using a 3rd party API I like to use its intelisense for the documentation as opposed to using the 'actual' documentation.
With that in mind I am fine to create a method name such as
StevesPostOnMethodNamesBeingLongOrShort
Long - but so what. Who doesnt use 24inch screens these days!
I have to agree that naming is an art. It gets a little easier if your class is following a certain "desigh pattern" (factory etc).
This is one of the reasons to have a coding standard. Having a standard tends to assist coming up with names when required. It helps free up your mind to use for other more interesting things! (-:
I'd recommend reading the relevant chapter of Steve McConnell's Code Complete (Amazon link) which goes into several rules to assist readability and even maintainability.
HTH
cheers,
Rob
Nope, debugging is the most difficult thing thing for me! :-)
DocumentFetcher? It's hard to say without context.
It can help to act like a mathematician and borrow/invent a lexicon for your domain as you go: settle on short plain words that suggest the concept without spelling it out every time. Too often I see long latinate phrases that get turned into acronyms, making you need a dictionary for the acronyms anyway.
The language you use to describe the problem, is the language you should use for the variables, methods, objects, classes, etc. Loosely, nouns match objects and verbs match methods. If you're missing words to describe the problem, you're also missing a full understanding (specification) of the problem.
If it's just choosing between a set of names, then it should be driven by the conventions you are using to build the system. If you've come to a new spot, uncovered by previous conventions, then it's always worth spending some effort on trying extend them (properly, consistently) to cover this new case.
If in doubt, sleep on it, and pick the first most obvious name, the next morning :-)
If you wake up one day and realize you were wrong, then change it right away.
Paul.
BTW: Document.fetch() is pretty obvious.
I find I have the most trouble in local variables. For example, I want to create an object of type DocGetter. So I know it's a DocGetter. Why do I need to give it another name? I usually end up giving it a name like dg (for DocGetter) or temp or something equally nondescriptive.
Don't forget design patterns (not just the GoF ones) are a good way of providing a common vocabulary and their names should be used whenever one fits the situation. That will even help newcomers that are familiar with the nomenclature to quickly understand the architecture. Is this class you're working on supposed to act like a Proxy, or even a Façade ?
Shouldn't the vendor documentation be the object? I mean, that one is tangible, and not just as some anthropomorphization of a part of your program. So, you might have a VendorDocumentation class with a constructor that fetches the information. I think that if a class name contains a verb, often something has gone wrong.
I definitely feel you. And I feel your pain. Every name I think of just seems rubbish to me. It all seems so generic and I want to eventually learn how to inject a bit of flair and creativity into my names, making them really reflect what they describe.
One suggestion I have is to consult a Thesaurus. Word has a good one, as does Mac OS X. That can really help me get my head out of the clouds and gives me a good starting place as well as some inspiration.
If the name would explain itself to a lay programmer then there's probably no need to change it.

Do you follow the naming convention of the original programmer?

If you take over a project from someone to do simple updates do you follow their naming convention? I just received a project where the previous programmer used Hungarian Notation everywhere. Our core product has a naming standard, but we've had a lot of people do custom reporting over the years and do whatever they felt like.
I do not have time to change all of the variable names already in the code though.
I'm inclined for readablity just to continue with their naming convention.
Yes, I do. It makes it easier to follow by the people who inherit it after you. I do try and clean up the code a little to make it more readable if it's really difficult to understand.
I agree suggest that leaving the code as the author wrote it is fine as long as that code is internally consistent. If the code is difficult to follow because of inconsistency, you have a responsibility to the future maintainer (probably you) to make it clearer.
If you spend 40 hours figuring out what a function does because it uses poorly named variables, etc., you should refactor/rename for clarity/add commentary/do whatever is appropriate for the situation.
That said, if the only issue is that the mostly consistent style that the author used is different from the company standard or what you're used to, I think you're wasting your time renaming everything. Also, you may loose a source of expertise if the original author is still available for questions because he won't recognize the code anymore.
If you're not changing all the existing code to your standard, then I'd say stick with the original conventions as long as you're changing those files. Mixing two styles of code in the same file is destroying any benefit that a consistent code style would have, and the next guy would have to constantly ask himself "who wrote this function, what's it going to be called - FooBar() or fooBar()?"
This kind of thing gets even trickier when you're importing 3rd party libraries - you don't want to rewrite them, but their code style might not match yours. So in the end, you'll end up with several different naming conventions, and it's best to draw clear lines between "our code" and "their code".
Often, making a wholesale change to a codebase just to conform with the style guide is just a way to introduce new bugs with little added value.
This means that either you should:
Update the code you're working on to conform to the guideline as you work on it.
Use the conventions in the code to aide future maintenance efforts.
I'd recommend 2., but Hungarian Notation makes my eyes bleed :p.
If you are maintaining code that others wrote and that other people are going to maintain after you, you owe it to everybody involved not to make gratuitous changes. When they go into the source code control system to see what you changed, they should see what was necessary to fix the problem you were working on, and not a million diffs because you did a bunch of global searches and replaces or reformatted the code to fit your favourite brace matching convention.
Of course, if the original code really sucks, all bets are off.
Generally, yes, I'd go for convention and readability over standards in this scenario. No one likes that answer, but it's the right thing to do to keep the code maintainable long-term.
When a good programmer's reading code, he should be able to parse the variable names and keep track of several in his head -- as long as their consistent, at least within the source file. But if you break that consistency, it will likely force the programmer reading the code to suffer some cognitive dissonance, which would then make it a bit harder to keep track of. It's not a killer -- good programmers will get through it, but they'll curse your name and probably post you on TheDailyWTF.
I certainly would continue to use the same naming convention, as it'll keep the code consistent (even if it is consistently ugly) and more readable than mixing variable naming conventions. Human brains seem to be rather good at pattern recognition and you don't really want to throw the brain a curveball by gratuitously breaking said pattern.
That said, I'm anything but a few of Hungarian Notation but if that's what you've got to work with...
If the file or project is already written using a consistent style then you should try to follow that style, even if it conflicts/contradicts your existing style. One of the main goals of a code style is consistency, so if you introduce a different style in to code that is already consistent (within itself) you loose that consistency.
If the code is poorly written and requires some level of cleanup in order to understand it then cleaning up the style becomes a more relevant option, but you should only do so if absolutely necessary (especially if there are no unit tests) as you run the possiblity of introducing unexpected breaking changes.
Absolutely, yes. The one case where I don't believe it's preferable to follow the original programmer's naming convention is when the original programmer (or subsequent devs who've modified the code since then) failed to follow any consistent naming convention.
Yes. I actually wrote this up in a standards doc. I created at my current company:
Existing code supersedes all other standards and practices (whether they are industry-wide standards or those found in this document). In most cases, you should chameleon your code to match the existing code in the same files, for two reasons:
To avoid having multiple, distinct styles/patterns within a single module/file (which contradict the purpose of standards and hamper maintainability).
The effort of refactoring existing code is prone to being unnecessarily more costly (time-consuming and conducive to introduction of new bugs).
Personally whenever I take over a project that has a different variable naming scheme I tend to keep the same scheme that was being used by the previous programmer. The only thing I do different is for any new variables I add, I put an underscore before the variable name. This way I can quickly see my variables and my code without having to go into the source history and comparing versions. But when it comes to me inheriting simply unreadable code or comments I will usually go through them and clean them up as best I can without re-writing the whole thing (It has come to that). Organization is key to having extensible code!
if I can read the code, I (try) to take the same conventions
if it's not readable anyway I need to refactor and thus changing it (depending on what its like) considerable
Depends. If I'm building a new app and stealing the code from a legacy app with crap variable naming, I'll refactor once I get it into my app.
Yes..
There is litte that's more frustrating then walking into an application that has two drasticly different styles. One project I reciently worked on had two different ways of manipulating files, two different ways to implement screens, two different fundimental structures. The second coder even went so far as to make the new features part of a dll that gets called from the main code. Maintence was nightmarish and I had to learn both paradigms and hope when I was in one section I was working with the right one.
When in Rome do as the Romans do.
(Except for index variables names, e.g. "iArrayIndex++". Stop condoning that idiocy.)
I think of making a bug fix as a surgical procedure. Get in, disturb as little as possible, fix it, get out, leave as little trace of your being there as possible.
I do, but unfortunately, there where several developers before me that did not live to this rule, so I have several naming conventions to choose from.
But sometimes we get the time to set things straight so in the end, it will be nice and clean.
If the code already has a consistent style, including naming, I try to follow it. If previous programmers were not consistent, then I feel free to apply the company standard, or my personal standards if there is not any company standard.
In either case I try to mark the changes I have made by framing them with comments. I know with todays CVS systems this is often not done, but I still prefer to do it.
Unfortunately, most of the time the answer is yes. Most of the time, the code does not follow good conventions so it's hard to follow the precedent. But for readability, it's sometimes necessary to go with the flow.
However, if it's a small enough of an application that I can refactor a lot of the existing code to "smell" better, then I'll do so. Or, if this is part of a larger re-write, I'll also begin coding with the current coding standards. But this is not usually the case.
If there's a standard in the existing app, I think it's best to follow it. If there is no standard (tabs and spaces mixed, braces everywhere... oh the horror), then I do what I feel is best and generally run the existing code through a formatting tool (like Vim). I'll always keep the capitalization style, etc of the existing code if there is a coherent style.
My one exception to this rule is that I will not use hungarian notation unless someone has a gun to my head. I won't take the time to rename existing stuff, but anything I add new isn't going to have any hungarian warts on it.