Naming guidelines - Naming generic objects - coding-style

MSDN Guidelines states that class names should be Pascal cast with no special prefix, such as "C".
It is also states that names of class members, such as proprties and fields, should also be Pascal cast.
So, names ambiguity may arise in the case of a naming generic object.
for example, consider a class named "Polynom". An object instantiate from this class shuold be named "Polynom" also. Polynom = new Polynom.
Is it?

I think a more common guideline (that I have seen Microsoft themselves follow) is to name variables, including instances, camel-cased (lower first, upper all other words: variableName). So in your case, it would be polynom = new Polynom. Of course, I wouldn't actually name a variable polynom unless it had a very obvious use and only for a local space. Otherwise a variable name should describe what it does, not what type it is.
All that said, the most important part of any naming convention is not what casing goes where but that you are consistent with it. Find something that works for you and stick to it!
[Quick edit: re-reading your question again, I see that you're mainly concerned about Properties. In this case, yes, it is very common to Pascal case them, so Polynom would be resonable. But since this is a property that would be exposed to the user (otherwise why is it a property?) Please don't name it Polynom!!! Do something more descriptive, we have intellisense if we want to know the type.]

You may often see
PolyNom polyNom = new PolyNom();
Although most of the time this is not the most readable code. Is it just any old polyNom, or is it for a specific purpose. Steve McConnell sites in Code Complete that the optimal variable name length for debugging (reading code) is 10-16 characters, with 8-20 characters being about the same (pg. 262 second ed.) this gives you a lot of room to more accurately describe exactly what your variable is.

Related

Idiomatic way of naming Getters in Go

The Effective go has following advice on naming of getters:
Go doesn't provide automatic support for getters and setters. There's
nothing wrong with providing getters and setters yourself, and it's
often appropriate to do so, but it's neither idiomatic nor necessary
to put Get into the getter's name. If you have a field called owner
(lower case, unexported), the getter method should be called Owner
(upper case, exported), not GetOwner. The use of upper-case names for
export provides the hook to discriminate the field from the method. A
setter function, if needed, will likely be called SetOwner. Both names
read well in practice:
Source: https://golang.org/doc/effective_go.html#Getters
Now, this advice doesn't seem to consistent as the stdlib itself violates this multiple times.
As you can see in above screenshot, there are multiple methods which use GetX naming convention which is advised against in the effective go guide.
So the question is is the advice given in guide wrong or these methods are named wrongly & would be fixed in future versions?
These names are not consistent with Go naming by design. Rob Pike, one of the Go creators, says this about the names in the OS package:
There are inconsistencies but this is the key point. It should be Stdout not StdOut, because that name is coming from the underlying system. Similarly it's Fprintf not FPrintf or FPrintF because that is a very familiar name. These names are coming into Go, not being created there, and the initial cap is the admission fee.
The names will not be changed in a future version of Go.
[go-nuts] FunctionName caseinconsistencies
A lot of the all lowercase names were chosen before we had really
figured out what the naming conventions should be. The rule we
adopted, which might be worth revisiting later, was that entry points
in package os or syscall, which are named after equivalents in C, just
had a single capital at the beginning, to avoid needing to decide
where the internal capitalizations are in abbreviations like geteuid
or getwd or chdir. Names like Readdirnames, which are actual words,
might be worth revisiting at some point.
Russ
os: inconsistent casing in names #1187
Is there any sort of rule about the casing of functions used in the
"os" package? Looking through, it doesn't sound like it's very easy
to recall whether a given function should be called LikeThat or
Likethat.
For instance:
Mkdir
MkdirAll
TempDir
Getenv
ForkExec
Readlink
ReadAt
Readdir
It feels very ad-hoc, and hard to recall.
It's a known issue. It's unplanned.
The term "getters" refers to methods on structs that allow you to read values of (often unexported) fields on that struct. The functions you're pointing to are top-level functions which allow you to read values from the OS. That idiomatic rule is not relevant to this case.

How to name factory like methods?

I guess that most factory-like methods start with create. But why are they called "create"? Why not "make", "produce", "build", "generate" or something else? Is it only a matter of taste? A convention? Or is there a special meaning in "create"?
createURI(...)
makeURI(...)
produceURI(...)
buildURI(...)
generateURI(...)
Which one would you choose in general and why?
Some random thoughts:
'Create' fits the feature better than most other words. The next best word I can think of off the top of my head is 'Construct'. In the past, 'Alloc' (allocate) might have been used in similar situations, reflecting the greater emphasis on blocks of data than objects in languages like C.
'Create' is a short, simple word that has a clear intuitive meaning. In most cases people probably just pick it as the first, most obvious word that comes to mind when they wish to create something. It's a common naming convention, and "object creation" is a common way of describing the process of... creating objects.
'Construct' is close, but it is usually used to describe a specific stage in the process of creating an object (allocate/new, construct, initialise...)
'Build' and 'Make' are common terms for processes relating to compiling code, so have different connotations to programmers, implying a process that comprises many steps and possibly a lot of disk activity. However, the idea of a Factory "building" something is a sensible idea - especially in cases where a complex data-structure is built, or many separate pieces of information are combined in some way.
'Generate' to me implies a calculation which is used to produce a value from an input, such as generating a hash code or a random number.
'Produce', 'Generate', 'Construct' are longer to type/read than 'Create'. Historically programmers have favoured short names to reduce typing/reading.
Joshua Bloch in "Effective Java" suggests the following naming conventions
valueOf — Returns an instance that has, loosely speaking, the same value
as its parameters. Such static factories are effectively
type-conversion methods.
of — A concise alternative to valueOf, popularized by EnumSet (Item 32).
getInstance — Returns an instance that is described by the parameters
but cannot be said to have the same value. In the case of a singleton,
getInstance takes no parameters and returns the sole instance.
newInstance — Like getInstance, except that newInstance guarantees that
each instance returned is distinct from all others.
getType — Like getInstance, but used when the factory method is in a
different class. Type indicates the type of object returned by the
factory method.
newType — Like newInstance, but used when the factory method is in a
different class. Type indicates the type of object returned by the
factory method.
Wanted to add a couple of points I don't see in other answers.
Although traditionally 'Factory' means 'creates objects', I like to think of it more broadly as 'returns me an object that behaves as I expect'. I shouldn't always have to know whether it's a brand new object, in fact I might not care. So in suitable cases you might avoid a 'Create...' name, even if that's how you're implementing it right now.
Guava is a good repository of factory naming ideas. It is popularising a nice DSL style. examples:
Lists.newArrayListWithCapacity(100);
ImmutableList.of("Hello", "World");
"Create" and "make" are short, reasonably evocative, and not tied to other patterns in naming that I can think of. I've also seen both quite frequently and suspect they may be "de facto standards". I'd choose one and use it consistently at least within a project. (Looking at my own current project, I seem to use "make". I hope I'm consistent...)
Avoid "build" because it fits better with the Builder pattern and avoid "produce" because it evokes Producer/Consumer.
To really continue the metaphor of the "Factory" name for the pattern, I'd be tempted by "manufacture", but that's too long a word.
I think it stems from “to create an object”. However, in English, the word “create” is associated with the notion “to cause to come into being, as something unique that would not naturally evolve or that is not made by ordinary processes,” and “to evolve from one's own thought or imagination, as a work of art or an invention.” So it seems as “create” is not the proper word to use. “Make,” on the other hand, means “to bring into existence by shaping or changing material, combining parts, etc.” For example, you don’t create a dress, you make a dress (object). So, in my opinion, “make” by meaning “to produce; cause to exist or happen; bring about” is a far better word for factory methods.
Partly convention, partly semantics.
Factory methods (signalled by the traditional create) should invoke appropriate constructors. If I saw buildURI, I would assume that it involved some computation, or assembly from parts (and I would not think there was a factory involved). The first thing that I thought when I saw generateURI is making something random, like a new personalized download link. They are not all the same, different words evoke different meanings; but most of them are not conventionalised.
I'd call it UriFactory.Create()
Where,
UriFactory is the name of the class type which is provides method(s) that create Uri instances.
and Create() method is overloaded for as many as variations you have in your specs.
public static class UriFactory
{
//Default Creator
public static UriType Create()
{
}
//An overload for Create()
public static UriType Create(someArgs)
{
}
}
I like new. To me
var foo = newFoo();
reads better than
var foo = createFoo();
Translated to english we have foo is a new foo or foo is create foo. While I'm not a grammer expert I'm pretty sure the latter is grammatically incorrect.
I'd point out that I've seen all of the verbs but produce in use in some library or other, so I wouldn't call create being an universal convention.
Now, create does sound better to me, evokes the precise meaning of the action.
So yes, it is a matter of (literary) taste.
Personally I like instantiate and instantiateWith, but that's just because of my Unity and Objective C experiences. Naming conventions inside the Unity engine seem to revolve around the word instantiate to create an instance via a factory method, and Objective C seems to like with to indicate what the parameter/s are. This only really works well if the method is in the class that is going to be instantiated though (and in languages that allow constructor overloading, this isn't so much of a 'thing').
Just plain old Objective C's initWith is also a good'un!

Guide to Win32 API Data Type Naming Conventions

I'm new to programming with the Win32 API, and I'm still getting used to the prefix / suffix data type naming conventions. While Google and a little common sense will normally explain what the prefix is referring to, it would be nice if there was one (relatively) concise guide to explain them. Does anyone know of a resource like this?
And on a related note, what does the '_' (underscore) prefix mean with a variable? Does that underscore have a name, other than "underscore"?
The naming convention is called Hungarian Notation, as mentioned by others. Since you're not familiar with it, and are probably going to start using it, it is worth mentioning there are two main flavors of Hungarian:
prefix the variable with its type code
prefix the variable with its usage code
The difference is visible when, for instance, an int is used to describe the number of bytes in a certain strings. On the former, nLen will be used, meaning the variable is an int. On the later, cbLen will be used, meaning the variable counts bytes (as opposed to cchLen, which counts characters). Give this article a look, should give you a better explanation.
As for the underscores in front of a variable or function - this is a naming convention reserved for the compiler and its standard library. Some people use it for other purposes, but they really shouldn't. The purpose of the convention is to provide the compiler a naming standard that will prevent collisions with names given by the user.
Win32 API follows Hungarian Notation
It's called a hungarian notation, Wikipedia has some information about it, and there's something on MSDN.

Should a method parameter name specify its unit in its name?

Of the following two options for method parameter names that have a unit as well as a value, which do you prefer and why? (I've used Java syntax, but my question would apply to most languages.)
public void move(int length)
or
public void move(int lengthInMetres)
Option (1) would seem to be sufficient, but I find that when I'm coding/typing, my IDE can indicate to me I need a length value, but I typically have to break stride and look up the method's doco to determine the units, so that I pass in the correct value (and not kilometres instead of metres for example). This can be an annoying interruption to a thought process. Option (2) alleviates this problem, but can be verbose, particularly if your unit is metresPerSecondSquared or some such. Which do you think is the best?
I would recommend making your parameter (and method) names as clear as possible, even if they become wordy. You'll be glad when you look at or use the code in 6 months time, or when someone else has to look at your code.
If you think the names are becoming too long, consider rewording them. In your example you could use parameter name int Metres that would probably be clear enough. Consider changing the method name, eg public void moveMetres(int length).
In Visual Studio, the XML comments generated when you enter 3 comment symbols above a method definition will appear in Intellisense hints when you use the method in other locations. Other IDEs may have similar functionality.
Abbreviations should be used sparingly. If absolutely necessary only use commonly known and/or relevant industry-standard abbreviations and be consistent, ie use the same abbreviation everywhere.
Take a step back. Write the code then move on to something else. Come back the next day and check to see if the names are still clear.
Peer reviews can help too. Ask someone who knows the programming language (or just thinks logically), but not the specific functionality, if your naming scheme is clear enough or to help brainstorm alternatives. They might be the poor sap who has to maintain your code in the future!
I would prefer the second approach (i.e. lengthInMeters) as it describes the input needed for the method accurately. The fact that you find it confusing to figure out the units when you are just writing the code would imply it would be much more confusing when you (or some one) looks at the same piece of code later. As regard to issue of the variable name being longer you can find ways to abbreviate it (say "mtrsPerSecondSquared").
Also in defence second approach, the book Code Complete mentions a research that indicates, effort required to debug a program was minimized when variables had names averaged to 10 to 16 characters.

Do you use articles in your variable names?

Edit: There appears to be at least two valid reasons why Smalltalkers do this (readability during message chaining and scoping issues) but perhaps the question can remain open longer to address general usage.
Original: For reasons I've long forgotten, I never use articles in my variable names. For instance:
aPerson, theCar, anObject
I guess I feel like articles dirty up the names with meaningless information. When I'd see a coworker's code using this convention, my blood pressure would tick up oh-so-slightly.
Recently I've started learning Smalltalk, mostly because I want to learn the language that Martin Fowler, Kent Beck, and so many other greats grew up on and loved.
I noticed, however, that Smalltalkers appear to widely use indefinite articles (a, an) in their variable names. A good example would be in the following Setter method:
name: aName address: anAddress.
self name: aName.
self address: anAddress
This has caused me to reconsider my position. If a community as greatly respected and influential as Smalltalkers has widely adopted articles in variable naming, maybe there's a good reason for it.
Do you use it? Why or why not?
This naming convention is one of the patterns in Kent Beck's book Smalltalk Best Practice Patterns. IMHO this book is a must-have even for non-smalltalkers, as it really helps naming things and writing self-documenting code. Plus it's probably one of the few pattern langages to exhibit Alexander's quality without a name.
Another good book on code patterns is Smalltalk with Style, which is available as a free PDF.
Generally, the convention is that instance variables and accessors use the bare noun, and parameters use the indefinite article plus either a role or a type, or a combination. Temporary variables can use bare nouns because they rarely duplicate the instance variable; alternatively, it's quite frequent to name them with more precision than just an indefinite article, in order to indicate their role in the control flow: eachFoo, nextFoo, randomChild...
It is in common use in Smalltalk as a typeless language because it hints the type of an argument in method call. The article itself signals that you are dealing with an instance of some object of specified class.
But remember that in Smalltalk the methods look differently, we use so called keyword messages and it this case the articles actually help the readability:
anAddressBook add: aPerson fromTownNamed: aString
I think I just found an answer. As Konrad Rudolph said, they use this convention because of a technical reason:
...this means it [method variable] cannot duplicate the name of an instance variable, a temporary variable defined in the interface, or another temporary variable.
-IBM Smalltalk Tutorial
Basically a local method variable cannot be named the same as an object/class variable. Coming from Java, I assumed a method's variables would be locally scoped, and you'd access the instance variables using something like:
self address
I still need to learn more about the method/local scoping in Smalltalk, but it appears they have no other choice; they must use a different variable name than the instance one, so anAddress is probably the simplest approach. Using just address results in:
Name is already defined ->address
if you have an instance variable address defined already...
I always felt the articles dirtied up the names with meaningless information.
Exactly. And this is all the reason necessary to drop articles: they clutter the code needlessly and provide no extra information.
I don’t know Smalltalk and can't talk about the reasons for “their” conventions but everywhere else, the above holds. There might be a simple technical reason behind the Smalltalk convention (such as ALL_CAPS in Ruby, which is a constant not only by convention but because of the language semantics).
I wobble back and forth on using this. I think that it depends on the ratio of C++ to Objective C in my projects at any given time. As for the basis and reasoning, Smalltalk popularized the notion of objects being "things". I think that it was Yourdon and Coad that strongly pushed describing classes in the first person. In Python it would be something like the following snippet. I really wish that I could remember enough SmallTalk to put together a "proper" example.
class Rectangle:
"""I am a rectangle. In other words, I am a polygon
of four sides and 90 degree vertices."""
def __init__(self, aPoint, anotherPoint):
"""Call me to create a new rectangle with the opposite
vertices defined by aPoint and anotherPoint."""
self.myFirstCorner = aPoint
self.myOtherCorner = anotherPoint
Overall, it is a conversational approach to program readability. Using articles in variable names was just one portion of the entire idiom. There was also an idiom surrounding the naming of parameters and message selectors IIRC. Something like:
aRect <- [Rectangle createFromPoint: startPoint
toPoint: otherPoint]
It was just another passing fad that still pops up every so often. Lately I have been noticing that member names like myHostName are popping up in C++ code as an alternative to m_hostName. I'm becoming more enamored with this usage which I think hearkens back to SmallTalk's idioms a little.
Never used, maybe because in my main language there are not any articles :P
Anyway i think that as long as variable's name is meaningful it's not important if there are articles or not, it's up to the coder's own preference.
Nope. I feel it is waste of characters space and erodes the readability of your code. I might use variations of the noun, for example Person vs People depending on the context. For example
ArrayList People = new ArrayList();
Person newPerson = new Person();
People.add(newPerson);
No I do not. I don't feel like it adds anything to the readability or maintainability of my code base and it does not distinguish the variable for me in any way.
The other downside is if you encourage articles in variable names, it's just a matter of time before someone does this in your code base.
var person = new Person();
var aPerson = GetSomeOtherPerson();
Where I work, the standard is to prefix all instance fields with "the-", local variables with "my-" and method parameters with "a-". I believe this came about because many developers were using text editors like vi instead of IDE's that can display different colors per scope.
In Java, I'd have to say I prefer it over writing setters where you dereference this.
Compare
public void setName(String name) {
this.name = name;
}
versus
public void setName(String aName) {
theName = aName;
}
The most important thing is to have a standard and for everyone to adhere to it.

Resources