I know this question has been asked around a bit, and by the looks of it, there isn't a clear yes or no answer to this question, but still, I'm a little confused about something.
Usually when I program, I follow a few rules about prefixes:
m_ in front of members
p_ in front of properties
s_ in front of static
a_ in front of parameters
l_ in front of local variables
I got a new job right now, and I noticed that prefixes are not used in code. I asked why, and they replied that IDEs do all the work of keeping track of what's a member variable and what's a local variable. Now I'm thinking, that may be so, but isn't it easier to use prefixes anyway?
I mean, if I for example have a member, a static, and a local variable named "robot", would it not be a pain in the ass to reference it when writing a method? This is perhaps an unrealistic example, but I like to have a good rule-set in my head that I can apply consistently, even for unrealistic conditions.
Does this example justify using Hungarian notation?
I think I'll make a pros/cons list and edit it as I learn more about it.
Argument against hungarian:
Class.Robot or Robot
this.robot
robot
No need for Hungarian.
Counter:
There is still an inconsistency, Robot could mean different things in different methods. To stay consistent you should prefix Class or this (or nothing) before each Robot variable.
On top of that, lets say you want to access the static variable Strawberry, how do you know a member variable named Strawberry isn't defined? Maybe it's defined in another file that you can't see, so you might get unexpected results. Now you might say that this is visible via the IDE but I make the argument that using a prefix is superior because you see what you're referencing, while you might miss what the IDE is telling you. You could also use this/Classname prefixes of course but that kind of defeats the purpose of not using a Hungarian notation.
Argument against hungarian:
A violation of this rule occurs when Hungarian notation is used in the naming of fields and variables. The use of Hungarian notation has become widespread in C++ code, but the trend in C# is to use longer, more descriptive names for variables, which are not based on the type of the variable but which instead describe what the variable is used for.
Counter:
The prefixes I mentioned are not based on the type of the variable, the prefixes indeed specify what the variable is used for.
Argument against hungarian:
modern code editors such as Visual Studio make it easy to identify type information for a variable or field, typically by hovering the mouse cursor over the variable name. This reduces the need for Hungarian notation.
Counter:
While this is true, I myself almost never hover with my mouse above a variable name unless an error has occurred. In contrast, with Hungarian notation, you immediately see where your variable is located in the class.
Remark:
Doesn't Microsoft recommend using Hungarian notation for file names? I read that it is a convention to prefix interface files with an I, this is a form of Hungarian notation. While this doesn't directly relate to my question above, it does raise the point that Hungarian notation is sometimes recommended.
No, don't do it. It makes the code harder to read. If you wrote English with every verb with a v_ in front and every noun with n_ that would make the sentence harder to read while adding information that is not useful most of the time.
If your classes are well designed with few responsibilities and short methods it shouldn't be too difficult to figure out what each variable means from the name and the context in which it is used. When it's not obvious and you need to know, it's easy to find out: you can just hover the mouse over the variable name, or press "Go To Definition".
StyleCop has a rule that warns when you use Hungarian notation. The rule description has a little explanation about why that rule exists:
TypeName FieldNamesMustNotUseHungarianNotation
CheckId SA1305
Category Naming Rules
Cause
The name of a field or variable in C# uses Hungarian notation.
Rule Description
A violation of this rule occurs when Hungarian notation is used in the naming of fields and variables. The use of Hungarian notation has become widespread in C++ code, but the trend in C# is to use longer, more descriptive names for variables, which are not based on the type of the variable but which instead describe what the variable is used for.
In addition, modern code editors such as Visual Studio make it easy to identify type information for a variable or field, typically by hovering the mouse cursor over the variable name. This reduces the need for Hungarian notation.
No, do not use Hungarian Notation. First, it's so 1990s. Secondly, you may be assaulted by your co-workers... ;-)
Your robot example:
Class.Robot or Robot
this.robot
robot
No need for Hungarian.
The answer is no, as everyone wrote here already.
First of all: You're not actually using the hungarian notation - or a known variant of it - as you state in the question yourself.
So let's start with the problem that you use a naming convention that is one of your own making and not widely used. This leads to immediate problems as soon as you are exposing your code to the real world - like your new coworkers. You're just inventing a private third (nth?) variant of this prefix notation, with all the problems that forcing something uncommon on other people includes.
Now - is it a change for the better? Are you right, and the other people should adapt to gain from these set of rules?
The consensus here seems to be 'No' and I'm fiercely on that side. Ignoring the standard arguments about the hungarion notation (I dismiss them as 'not entirely relevant'):
Don't reuse names to mean lots of things. The one exception that still seems to be common is to have a constructor taking an argument with the same name as a field:
public Foo(string robot) {
this.robot = robot;
}
If you have trouble managing the sheer number of names in your code, chances are you have too many of those in one place / in scope. You're trying to solve a code smell with a (smelly, according to the consensus here so far) workaround
To reiterate it once: You come to a team of people that don't use your convention (and how could they - it seems it's of your own making..) so you have to adjust to the team. You can argue about personal readability and are free to ask your coworkers to reconsider, but if they disagree with that style: Don't fight it. You're just making yourself miserable if you insist on being right and them being wrong. Don't let this drain your productivity.
but I like to have a good rule-set in my head that I can apply
consistently
Even better than a rule-set in your head, is a rule-set in your IDE/build system:, so you should check out StyleCop
StyleCop will let you configure your coding guidelines how you like, but by default offers a popular alternative to the apps hungarian notation you describe:
fields: this.myField
properties: this.MyProperty
methods: this.MyMethod()
statics: MyClass.MyStaticMethod()
etc.
You'll find endless discussion on this aspect of coding style both on stackoverflow and elsewhere, so I expect this question will be closed as a duplicate....
I for myself have some convention that I follow. It's true that modern IDEs take away a lot of things like this but still I think a little hungarian :). I'm using:
robot_ for attributes (ms recommends to use this.robot but like this I can't forget the this)
camelCase for local variables and private/protected/internal methods
PascalCase for public properties or methods
And that is it :). I think the code looks very weird with all these m_, a_, ... stuff I find it very difficult to read. Hovering over the code in VS gives you hints sure, but I see some additional benefit in using some kind of convention.
I mean even ms uses some kind of hungarian notation in postfixing all async functions with Async or prefixing all interfaces with I
Related
in oCn? What is the rule?
using(SqlConnection oCn = new SqlConnection(
"Server=(local);Database=Pubs;User ID=TestUser1;Password=foo1;")) {
oCn.Open();
...
}
I found that type of naming in this article http://msdn.microsoft.com/en-us/magazine/cc163799.aspx
An entirely obsolete way of saying that "Cn" is an *o*bject.
I am afraid that it is a remainder of some hungarian dialect notation for an object.
In C# and .NET I consider this useless.
EDIT By the way I consider Hungarian notation containing type and/ore scope information useless in C#. I do like Apps Hungarian notation
In this case, "o" means object. It's an attempt at using the "systems" variation of hungarian notation.
There are two types of hungarian: Systems and Apps. Systems uses a prefix to identify the type of data stored. For example, the "i" in iCounter would indicate that the variable was an integer.
Apps hungarian took a completely different approach and specifies that the prefix should indicate the purpose of the data. For example, the "rw" in rwPosition would mean row.
The windows api used Systems hungarian. This led to a large number of other programmers also using it. The unfortunate aspect is that when changes were made to the api, they kept the old variable names even when the actual data type changed. This led to large amounts of confusion as to what data type a parameter to a given API function should be passed. Especially around various handles.
In the .Net coding guidelines, MS explicitly states that hungarian shouldn't be used. The reality is that they are talking about "Systems" hungarian; which I 100% agree with. "Apps" hungarian on the other hand has a ton of uses as you are describing the data, not the type.
At the end of the day just remove the "o". It adds nothing to the program.
Oh, and for interesting reading, check out Joel's take on this at: http://www.joelonsoftware.com/articles/Wrong.html
It probably means object like in some complex type that does not fit well with the same (ridiculous) convention that names strings strMyString and ints iMyInt etc.
This "rule" comes directly from How To Write Unmaintainable Code:
o_apple obj_apple
Use an "o" or "obj" prefix for each instance of the class to show that you're thinking of the big, polymorphic picture.
o is for object,
it's a, not very usefull, convention where by the type of the variable was incuded in the name, so a string was strWhatever. sometimes i even saw obj, i.e. objCn
As #Humberto suggested, appears to be the developer using Hungarian Notation.
When I started working as a programmer 10 years ago, the compagny I worked for was using a similar naming convention. I can't remember what is the convention name but I do remember that all the object instances had the "o" prefix, standing for Object.
If I am accessing a member field, property, or method, I'm never sure when I should prepend it with 'this'.
I am not asking about cases where it is required, like in the case where a local variable has the same name. I am talking about cases where the meaning is exactly the same. Which is more readable? Are there any standards, best practices, or rules of thumb I should be following? Should it just be consistent throughout a class, or an entire code base?
I disagree with StyleCop on this one, and I'm not even sure that StyleCop's opinion should be interpreted as an official Microsoft guideline anyway. It was an internal tool used at Microsoft but not all teams use it, and not all teams use all the rules.
Adding this everywhere is not necessary and often just adds clutter. It does not improve performance and I'm not convinced that adding this all over the code improves readability either.
You might hear arguments that it makes it more clear where the variable is defined, but I would argue that if your class/method is so long and complicated that it is difficult to work out where something is declared then you probably should refactor it anyway. If you use the single responsibility rule and have short functions it should be obvious whether a variable is a member, a function parameter or a local variable.
As you point out, sometimes it is necessary. For example in the constructor if you want to set a private member with the same name as the parameter.
public class Foo
{
private Bar bar;
public Foo(Bar bar)
{
this.bar = bar;
}
}
I recommend using Microsoft's guidelines, as verified by StyleCop: http://blogs.msdn.com/sourceanalysis/
The general rule is, prepend members with "this." when they are defined in the class, unless they are static, in which case you cannot.
Here is the rule directly from StyleCop:
SA1101: The call to {method or property name} must begin with the
'this.' prefix to indicate that the item is a member of the class.
I would say avoid as much as possible, it saves you some(in fact a lot of) typing.
I would depend on Visual Studio more to help me to find where what belongs(never forget F12). I don't use notepad to read my cs files :P
If you follow Microsoft's StyleCop, you should always use prefix class members with the this keyword.
SA1101: PrefixLocalCallsWithThis
TypeName: PrefixLocalCallsWithThis
CheckId: SA1101 Category: Readability Rules
Here's a similar StackOverflow question on the same topic.
I usually access parameters on the current object with this. Given a naming convention for instance variables "m_", this makes it easy to see at a glance what is affected by following statements without knowing their context:
m_Height += 10; // an instance variable
height += 10; // a local variable
this.Height += 10; // a property
In my code, I only use this.<PropertyName> when the property is a member of a base class, not the class I'm currently in.
Of course, not using 'this' at all is another popular choice, since it's unnecessary code being added.
Our coding standards at work state that member variables shouldn't be prefixed with 'm' or'_' or whatever else most people use. I've actually found myself using this.memberVariable all the time. I prefer the clarity over a little extra typing. And as mentioned in other answers, it's necessary when referencing parameters with the same name as member variables.
If you're using Visual Studio and Intellisense. When you type this you get a list of just your class level variables methods etc. Leaving out all the other possible items.
Using VB.Net and C#.Net.
For Example
Am Using More than one form
If am assigning a variables like this.
Dim a, b as integer
Dim c, d as string
This variables cannot be easily understand for everyone(other programmers).
How to assign a Standard Datatype variables,
Standard Variable Means (Everyone can understandable)
And also How to give a standard name for gridview, text boxes, labels etc.
It looks like you are looking for some naming conventions. I've found this document a while back which pretty much describes the most common conventions:
(pdf) http://www.icsharpcode.net/TechNotes/SharpDevelopCodingStyle03.pdf
I hope it helps!
Take a look at MSDN Naming Conventions or Design Guidelines.
To check if you stick to the rules you can use FxCop or StyleCop.
Please. OH please go in a bookstore, find "Clean Code" by Robert C. Martin. and browse the chapter on naming.
One of the comments in the book is how your code should be clear enough to abstract the types. For example, would anyone think that "user_name" is anything else but a string? Or if you need to know if "user_age" is an int or a float their is also something wrong, the code should abstract that.
Avoid prefixes. After a few weeks developers don't see them anymore. It quickly devolves to silly meaningless 2-3 letters that only makes the code harder to read. If you really need to know the type, today's development tool makes it real easy to find it, like hovering the mouse over a variable.
Use pronounceable words. This will easily make all variables easy to understand. Avoid things like usrdobisec (user date of birth in seconds)
Variable names in .net usually don't contain the type, since .Net is strongly typed, so this isn't really necessary.
Control names are sometimes prefixed with a type, for example lbl for a label.
I suggest you choose a variable naming convention and stick to it.
At the very least, give your variables meaningful names and not just a, b, c etc!
This question already has answers here:
Why shouldn't I prefix my fields? [closed]
(25 answers)
Closed 2 years ago.
Before using C#, C++ was my primary programming language. And the Hungarian notation is deep in my heart.
I did some small projects in C# without reading a C# book or other guidelines on the language. In those small c# projects I used something like
private string m_strExePath;
Until I read something from SO that said:
Do not use Hungarian notation.
So why? Am I the only person that has m_strExePath or m_iNumber in my C# code?
Joel Spolsky has a really good article on this topic. The quick summary is that there's two types of Hungarian notation that are used in practice.
The first is "Systems Hungarian" where you specify the variable type using a prefix. Things like "str" for string. This is nearly useless information, especially since modern IDEs will tell you the type anyway.
The second is "Apps Hungarian" where you specify the purpose of the variable with a prefix. The most common example of this is using "m_" to indicate member variables. This can be extremely useful when done correctly.
My recommendation would be to avoid "Systems Hungarian" like the plague but definitely use "Apps Hungarian" where it makes sense to. I suggest reading Joel's article. It's a bit long winded but explains it much better than I could.
The most interesting part of this article is that the original inventor of Hungarian notation, Charles Simonyi, created "Apps Hungarian" but his paper was horribly misinterpreted and the abomination of "Systems Hungarian" was created as a result.
When doing user interface design, I have found it very useful to maintain Hungarian notation. Items like text boxes, labels and drop down lists are much easier to quickly understand and often you get repeating control names:
lblTitle = Label
txtTitle = TextBox
ddlTitle = DropDownList
To me that's easier to read and parse. Otherwise, Hungarian notation doesn't fit in because of the advances in IDE's, specifically Visual Studio.
Also, Joel on Software has an excellent article related to Hungarian notation titled: Making Wrong Code Look Wrong which makes some good arguments for Hungarian notation.
You're not the only person, but I'd say it's relatively uncommon. Personally I'm not a fan of Hungarian notation, at least not in the simple sense that just restates the type information which is already present in the declaration. (Fans of "true" Hungarian notation will explain the difference - it's never bothered me that much, but I can see their point. If you use a common prefix for, say, units of length vs units of weight, you won't accidentally assign a length variable with a weight value, even though both may be integers.)
However, for private members you can pretty much do what you want - agree with your team what the naming convention should be. The important point is that if you want your API to fit in with the rest of .NET, don't use Hungarian notation in your public members (including parameters).
No, you're not the only one who does it. It's just generally accepted that Hungarian notation isn't the best way to name things in C# (the IDE handles a lot o the issues that Hungarian notation tried to address).
Hungarian notation is a terrible mistake, in any language. You shouldn't use it in C++ either. Name your variables so you know what they're for. Don't name them to duplicate type information that the IDE can give you anyway, and which may change (and is usually irrelevant anyway. If you know that something is a counter, then it doesn't matter whether it's an int16, 32 or 64. You know that it acts as a counter, and as such, any operation that's valid on a counter should be valid. Same argument for X/Y coordinates. They're coordinates. It doesn't matter if they're floats or doubles. It may be relevant to know whether a value is in units of weight, distance or speed. It doesn't matter that it's a float.).
In fact, Hungarian notation only came around as a misunderstanding. The inventor had intended for it to be used to describe the "conceptual" type of a variable (is it a coordinate, an index, a counter, a window?)
And the people who read his description assumed that by "type" he meant the actual programming language type (int, float, zero-terminated string, char pointer)
That was never the intention, and it is a horrible idea. It duplicates information that the IDE can better provide, and which isn't all that relevant in the first place, as it encourages you to program at the lowest possible level of abstraction.
So why? Am I the only person that has
m_strExePath or m_iNumber in my C#
code?
No. Unfortunately not. Tell me, what would exePath be if it wasn't a string? Why do I, as a reader of your code, need to know that it is a string? Isn't it enough to know that it is the path to the executable? m_iNumber is just badly named. which number is this? WHat is it for? You have just told me twice that it is a number, but I still don't know what the meaning of the number is.
You're certainly not the only person, but I do hope you're part of a declining trend :)
The problem with Hungarian notation is that it's trying to implement a type system via naming conventions. This is extremely problematic because it's a type system with only human verification. Every human on the project has to agree to the same set of standards, do rigorous code reviews and ensure that all new types are assigned the appropriate and correct prefix. In short, it's impossible to guarantee consistency with a large enough code base. At the point there is no consistency why are you doing it?
Furthermore tools don't support Hungarian notation. That might seem like a stupid comment on the surface but consider refactoring for instance. Each refactoring in a Hungarian naming convention system must be accompanied with a mass rename to ensure that prefixes are maintained. Mass renames are susceptible to all sorts of subtle bugs.
Instead of using names to implement a type system, just rely on the type system. It has automatic verification and tool support. Newer IDE's make it much easier to discover a variable's type (intellisense, hover tips, etc ...) and really remove the original desire for Hungarian Notation.
One downside of Hungarian notation is that developers frequently change the type of variables during early coding, which requires the name of the variable to also change.
unless you are using a text editor rather than the VS IDE there is little value to hungarian notation and it impeeds rather than improves readability
The real value in Hungarian notation dates back to C programming and the weakly typed nature of pointers. Basically, back in the day the easiest way to keep track of the type was to use Hungarian.
In languages like C# the type system tells you all you need to know, and the IDE presents this to you in a very user friendly way so there is simply no need to use Hungarian.
As for good reason to not use it, well there are quite a few. FIrstly, in C# and for that matter C++ and many other langause you often create your own types, so what would be the Hungarian for a "MyAccountObject" type? Even if you can decide on sensible Hungarian notations it still makes the actual variable name slightly harder to read because you have to skip past the "LPZCSTR" (or whatever) at the start. More important is the maintainance cost though, what if you start of with a List and change to another type of collection (something I seem to do a lot at the moment)? You then need to rename all your variables that use that type, all for no real benefit. If you had just used a decent name to begin with you wouldn't have to worry about this.
In your example, what if you created or used some more meaningful type for holding a path (e.g. Path), you then need to change your m_strExePath to m_pathExePath, which is a pain and in this case not actually very helpful.
The only two areas where I currently see any form of Hungarian notation are:
Class member variables, with a leading underscore (e.g. _someVar)
WinForms and WebForms control names (btn for Button, lbl for Label etc)
The leading underscore on member variables seems like it is here to stay with us for a while longer, but I expect to see the popularity of Hungarian on control names to wane.
Most hungarian notation describes what the variable is (a pointer, or a pointer to a pointer, or the contents of a pointer etc. etc.), and what the thing that it points to is (string etc).
I've found very little use for pointers in C#, especially when there's no unmanaged/pinvoke calls. Also, there's no option to use void* so there's no need for hungarian to describe it.
The only left-over from Hungarian that I (and most others in C# land) use, is to preceed private fields with _, as in _customers;
Hungarian notation found its first major use with the BCPL programming language. BCPL is short for Before C Programming Language and is an ancient (designed in 1966), typeless language where everything is a word. In that situation, Hungarian notation can help with naked-eye type-checking.
Many years have passed since then...
Here's what the latest Linux kernel documentation says (bold mine):
Encoding the type of a function into the name (so-called Hungarian
notation) is brain damaged - the compiler knows the types anyway and can
check those, and it only confuses the programmer.
Please also note that there are two types of Hungarian notation:
Systems Hungarian notation: The prefix encodes physical data type.
Apps Hungarian notation: The prefix encodes logical data type.
Systems Hungarian notation is no longer recommended due to type-checking redundancy which is in turn due to advancement in compiler capabilities. However, you may still use Apps Hungarian notation if the compiler doesn't check logical data types for you. As a rule of thumb, Hungarian notation is good if and only if it describes semantics that are not available otherwise.
If Hungarian notation is deep in your and your team's and your company's heart, by all means use it. It is no longer considered a best practice as far as I can read from blogs and books.
If you hold the pointer over the variable in VS it will tell you what type of variable it is, so there is no reason to go with these cryptic variable names, esp as people that are coming from other languages may need to maintain the code and it will be an obstacle to easy reading.
In a language like C# where many of the limitations on variable name length do not exist that were once in languages like C and C++, and where the IDE provides excellent support for determining the type of a variable, Hungarian notation is redundant.
Code should be self-explanatory so names like m_szName can be replaced by this.name. And m_lblName can be nameLabel, etc. The important thing is to be consistent and to create code that is easy to read and maintain - this is the goal of any naming convention so you should always decide what convention you use based on this. I feel that Hungarian notation is not the most readable or the most maintainable because it can be too terse, requires a certain amount of knowledge on what the prefixes mean, and is not part of the language and therefore, hard to enforce and hard to detect when the name no longer matches the underlying type.
Instead, I like to replace Apps Hungarian (prefixes like m_) by referencing this for members, referencing the class name for static variables, and no prefix for local variables. And instead of System Hungarian (including the type of a variable in the variable name), I prefer to describe what the variable is for such as nameLabel, nameTextBox, count, and databaseReference.
At some point, you're likely to have a property
public string ExecutablePath { ... }
(not that you should try to avoid abbreviations like "Exe" too). That being the case, your question might then be moot much of the time as you can use C# 3.0's auto-properties
public string ExecutablePath { get; set; }
you now no longer have to come up with a name for the backing store variable. No name, no question/debate about naming conventions.
Obviously, auto-implemented properties aren't always appropriate.
It depends.
Is it significant enough to add the description of the data type in variable/object name in your method/class?
System Hungarian Notation > Apps Hungarian Notation
If you are designing in procedural language (e.g. C) that has many of global variables or/and lower-API that deals with precise data types and sizes (e.g. C's<stdint.h>where 40+ different data type notations are used to describe int), System Hungarian Notation is more helpful.
Note, however, many modern programmers consider adding type information in variable name is abundant as many of modern IDEs have very convenient tools (e.g. Outline of Eclipse, Symbol Navigator of Xcode, Visual AssistX of Visual Studio, etc.). System Hungarian Notation was widely used in the earlier ages in programming (e.g. FORTRAN, C99) when type information was not readily available as a tool of the IDEs.
System Hungarian Notation < Apps Hungarian Notation
If you are working in higher-level class or method (e.g. user-defined driver class/method for your C# application), notating simple data type may not be sufficient enough to describe the variable/object. Therefore, we use Apps Hungarian Notation in this case.
For example, if the purpose of your method is to retrieve executable path and to display an error message if not found, instead of noting that it is a type of string, we note more significant information to describe the variable/object for programmers to better comprehend the purpose of the variable/obejct:
private string mPathExe;
private string msgNotFound;
It's about efficiency. How much time was wasted assigning the wrong value to a variable. Having accurate variable declarations are about gain in efficiency. It's about readability. It about following the existing patterns. If you want creativity, do user interface design, do system architecture. If your programming, it should be designed to make you team members job easier: not yours. A 2% gain in efficiencies is an extra week each year. That's 40 hours gained. Human productivity gains are made by compounding efficiencies.
I don't care, I always use a combination of Hungarian and Pascal/Camel Case.
Not for data types, but for controls. Because txtName is pretty self-explanatory. Some people will name it NameTextBox which is too long.
lblAge, txtName, rdoTrue, cboCities, lstAccountInfo. Nice and quick and compact
For variables, it's Pascal case for ordinary variables and properties. "firstName = txtFName.Text" (seriously if you can't look at that and realize it's a textbox, sheez). Then I'll use Camel Case for methods
public void PrintNames (string fName, string lName)
{
lblFullName.Text=fName + " " + lName;
}
So yes, I use Hungarian case, so sue me. No one can say they don't know what those variables are and I like being able to see really quickly without having to hover over what type of variable or control it is. When I first started programming I used all caps for every variable so this is a step up. And for pity's sake, do NOT put the opening curly brace at the end of the line. Nice and symmetrical.
Some may feel this question is subjective. But, I feel this is among the most important things to be told to a programmer.
Is this a good function name to check for null values.
1. checkNull()
2. notNull()
3. isNull()
What if I write
checkIfNull()
I do not know how many people share the same feeling as I do, I have spent more time in thinking good names for my functions than writing one.
How do people think of good names? Can the naming be consistent across languages (mainly C++ and Java)
Update:
As I go by the number of updates till now, Most people prefer isNull(). How do you decide upon this that isNull() is the perfect name.
checkNotNull() // throw exception if Null
Is this a good name? Does everyone depend upon their intuition for deciding a name?
The question is about choosing a perfect name!!!
isNull might be a bad example, because:
Object foo = null;
if (foo.isNull()) { // Causes a NullPointerException in Java. }
Otherwise, you've got:
Object foo = null;
if (UtilityClass.isNull(foo) { }
Which seems harder and less clear than just doing:
Object foo = null;
if (foo == null) { }
Like the others, I prefer isNull() (or IsNull(), depending on your language/coding conventions).
Why? Beside it is a widely accepted convention, it sounds nice when you read the code:
if (isNull())
// or
if (foo.isInitialized())
and so on. Almost natural English... :-) Compare to the alternatives!
Like iWerner, I would avoid negative form for making identifiers (variables, methods) names.
Another common convention is to start method/function names with a verb. Now, Sun did not follow this convention in the early days of Java (hence the length() and size() methods, for example) but it even deprecates some of these old names in favor of the verb rule.
If the function throws an exception if it's null, it should be called ThrowIfNull to make it clear that it will throw for you.
IsNull() is a good choice, But additionally it should return a bool.
So that you can check its value in if statment without getting any NullReference exception.
Nowadays it is highly recommended to use the javaBeans convention:
isNull() //if the return type is a primitive
getNull() //if the return type is an object (Like Boolean in java)
For non boolean types access members, you should use get.
For static variable members use the camel case style: "myVar".
For class name use camel case style with capitalized first letter: "MyClass".
And for constant members use uppercase letter with underscore as separator: "MY_CONSTANT".
The answer depends on what your method returns.
If it returns a bool indicating whether the object is null, I would name it IsNull(Thing thing), because it is the least ambiguous formulation - what the method does and what it returns is immediately obvious.
If the method is void but throws if the object is null, I would call it GuardAgainstNull(), or something along these lines.
IMO, CheckNull() is somewhat ambiguous - you don't know by looking at the method if it should return a bool or throw, or what the bool indicates exactly.
I prefer IsNull.
To learn good naming style, study the standard libraries (except in PHP). You should follow the style used by the standard libraries in each language.
For C#, study the Framework Design Guidelines.
personally, I would use
IsNull()
I found this article. Felt like sharing with you guys!
If you're doing a lot of null checking in your code, I think having a pair of methods, i.e.:
IsNull()
IsNotNull()
will lead to the most readable code in the long run.
I know !IsNull() is a standard idiom in curly brace languages, but I think it's much less clear than IsNotNull.
It's too easy to overlook that single "!" character, especially if it's buried in a more complex expression.
It can vary depending on the language you are using - and you tagged a couple to this question. It is important to stay consistent with the standards of the language/library you are coding against. Yes, naming conventions are very important! [There's even a wikipedia entry on it: http://en.wikipedia.org/wiki/Naming_conventions_%28programming%29]
For .Net I found this "cheat sheet" on naming conventions:
http://www.irritatedvowel.com/Programming/Standards.aspx
For your example in C# I'd reccommend : IsNull()
If your company does not specify naming conventions in its coding standards I suggest it's time you add them.
Our company's Java coding standards are basedon the official Java Coding Standards which, I believe, specify names like isNull().
From your example, the notNull() is bad, because you may end up with statements like if(!notNull()) or the like.
I would use IsNull(); there is a precedence in .Net which has a static IsNullOrEmpty() method for the String type. "Is" is my preferred prefix for methods that return a bool. I would not have a negative method "notNull", because this too easily results in double negatives. Instead use the negation operation on a positive method, e.g., !IsNull().
However, a method that only checks for a null value may be overly complicating things; what is wrong with
x == null
Which I think is more readable than
IsNull(x)
Most developers seeing IsNull(x) would wonder if there is some fancy null checking in the IsNull method; if there isn't then "x == null" is probably better.