Hungarian in VBA okay?

2019-03-28 07:22发布

问题:

I don't use hungarian (str, int) prefixes in .Net, but I still find it useful in VBA, where it is more difficult to see types.

Is this bad? Unnecessary? Maybe I'm missing something.

I'd really appreciate any feedback. I've been wondering for a while.

Thanks everybody.

回答1:

I always use one and two letter prefixes in VBA. I'm sure I'm the only one that's going to admit that, but I figured somebody needed to be the contrarian.

Of the 18 million lines of VBA code I've written, I've collaborated on about 1,000. If nobody else sees my code, then I'm free to use a convention that I like. If someone else will be working on your code, you should agree on a convention.

I like that it lets me keep my variable names shorter. I could use FileNumber and FileName or I could use lFile and sFile. I don't find one more or less readable than the other. It also helps me use reserved words as variables. If I want to use Replace as a variable name, I can't. But I can use sReplace or lReplace.



回答2:

I would say that this kind of Hungarian notation is the root of all evils in almost every language. Some people say it is handy for extremely dynamic languages. But no, I think that prefixing the type-abbreviation onto a variable name is redundant in 99% of all cases and just leads to ugly code.

see Why Shouldn't I Use Hungarian Notation?



回答3:

I'd advise going for something a little higher-level than just types so that you can see what the purpose of things are. Thus, instead of calling something a string, call it a name or an address, and instead of an int, call it a count or a coordinate or ...

(I prefer to use suffixes to prefixes, but that's a matter of style and taste.)



回答4:

If the style at your company is set to use Hungarian notation then there is no problem using it - a policy is a policy. There are plenty of tools that help enforce coding naming conventions (like Stylecop for C#) so you can move on if you are allowed.

Basically having standards is a good idea - but what those standards are depends on the company you work for. If you have some authority you could attempt to impose the standards that MS are currently promoting - but if you have a lot of legacy code that will involve a lot of expensive refactoring with little material benefit.

I would recommend that you move away from Hungarian notation for new projects (possibly by utilising a code analysis tool) but be pragmatic about legacy code.