Should a Variable's Type Come After Its Name? (benhoyt.com) 321
Canonical engineering manager Ben Hoyt believes that a variable's name is more important than its type, so "the name should be more prominent and come first in declarations."
In many popular programming languages, including C, C++, Java, and C#, when you define a field or variable, you write the type before the name. For example (in C++):
// Struct definition
struct person {
std::string name;
std::string email;
int age;
};
In other languages, including Go, Rust, TypeScript, and Python (with type hints), you write the name before the type. For example (in Go):
// Struct definition
type Person struct {
Name string
Email string
Age int
}
There's a nice answer in the Go FAQ about why Go chose this order: "Why are declarations backwards?". It starts with "they're only backwards if you're used to C", which is a good point — name-before-type has a long history in languages like Pascal. In fact, Go's type declaration syntax (and packages) were directly inspired by Pascal.
The FAQ goes on to point out that parsing is simpler with name-before-type, and declaring multiple variables is less error-prone than in C. In C, the following declares x to be a pointer, but (surprisingly at first!) y to be a normal integer:
int* x, y;
Whereas the equivalent in Go does what you'd expect, declaring both to be pointers:
var x, y *int
The Go blog even has an in-depth article by Rob Pike on Go's Declaration Syntax, which describes more of the advantages of Go's syntax over C's, particularly with arrays and function pointers.
Oddly, the article only hints at what I think is the more important reason to prefer name-before-type for everyday programming: it's clearer.
Hoyt argues a variable's name has more meaning (semantically) — pointing out dynamically-typed languages like Python and Ruby don't even need types, and that languages like Java, Go, C++ and C# now include type inference.
"I think the takeaway is this: we can't change the past, but if you're creating a new language, please put names before types!"
// Struct definition
struct person {
std::string name;
std::string email;
int age;
};
In other languages, including Go, Rust, TypeScript, and Python (with type hints), you write the name before the type. For example (in Go):
// Struct definition
type Person struct {
Name string
Email string
Age int
}
There's a nice answer in the Go FAQ about why Go chose this order: "Why are declarations backwards?". It starts with "they're only backwards if you're used to C", which is a good point — name-before-type has a long history in languages like Pascal. In fact, Go's type declaration syntax (and packages) were directly inspired by Pascal.
The FAQ goes on to point out that parsing is simpler with name-before-type, and declaring multiple variables is less error-prone than in C. In C, the following declares x to be a pointer, but (surprisingly at first!) y to be a normal integer:
int* x, y;
Whereas the equivalent in Go does what you'd expect, declaring both to be pointers:
var x, y *int
The Go blog even has an in-depth article by Rob Pike on Go's Declaration Syntax, which describes more of the advantages of Go's syntax over C's, particularly with arrays and function pointers.
Oddly, the article only hints at what I think is the more important reason to prefer name-before-type for everyday programming: it's clearer.
Hoyt argues a variable's name has more meaning (semantically) — pointing out dynamically-typed languages like Python and Ruby don't even need types, and that languages like Java, Go, C++ and C# now include type inference.
"I think the takeaway is this: we can't change the past, but if you're creating a new language, please put names before types!"
I can see a heated debate coming (Score:5, Insightful)
Re: (Score:3)
Everyone knows SVO order is much more understandable than SOV. Just ask anyone from Germany.
Re: (Score:2)
45% of languages use SOV ... only 42% use SVO ... ...
German uses a mix of both
Re:I can see a heated debate coming (Score:4, Insightful)
And we all know SOV is better. RPN FTW!
Re: (Score:2)
Cool. Let the variables be any type they want, instead of forcing a role onto them. And type cast is just violence.
Re:I can see a heated debate coming (Score:4, Funny)
Explicit type casting only means you cannot accept variables as what they are, you narrow minded person!
Re: (Score:2)
you narrow minded person
Only if you're, say, casting an int32 to a char. If you're casting to a double or int64 you're a wide mined person.
Re: (Score:3)
preview blahhhhh
wide MINDED
Re: (Score:2)
Most languages use a mix of more than two (there's at least 6), just some are more dominant in certain cases. Watch NativLang [youtube.com]'s most recent two videos. They address this head-on.
Re: (Score:2)
for large OO projects I've been using a three letter suffix to distinguish things like types, classes, enumerations, etc from instances. I usually name the variable capitalizing first letters of words, and have the suffix all caps
StoreFruitENU for the enumerator for store fruits for example. StoreFruitTYP for the type class, StoreFruitINT for the class interface, and so forth. That way I'm not having to essentially create alternate names for the same thing due to type differences. Really becomes importa
Re: (Score:2)
Non sense IMHO but whatever fits you I guess. My variable would be fruit and the enum would be fruits. I always personally hated what you suggest and it's against my projects guidelines. The clutter is useless and we're not in 1960 anymore anyway, any IDE will tell you the variable type with a mouse over!
Re: (Score:2)
My variable would be fruit and the enum would be fruits.
While there are no perfect naming schemes, as it's always a balance between utility and convenience, I also eventually gravitated towards using type indicators in my variable names. I resisted it for years, but found it far too useful to ignore at some point in the early 1990's. I use prefixes rather than suffixes, as I was loosely inspired by Hungarian Notation and Java standards.
My enum would be "FruitType", a variable would be "fruit" (or a generic "item" if used in a short, independent, transient code b
Re: (Score:2)
A type suffix used to be considered a type wart.
I propose a compromise. (Score:5, Funny)
The type should be given in the middle of the variable's name:
myC(int)ount;
single-letter variables will no longer be allowed, which is good because such names are too short to be descriptive anyway.
Ok, problem solved. Next!
Re:I can see a heated debate coming (Score:5, Informative)
German (like Dutch) uses a verbial frame, which could be noted as x(V1)x(V2). A verb is usually split into a conjugated and a non conjugated part. In the main clause, the conjugated part comes at second position. The non conjugated part gets last position, framing most of the sentence. One non-verbial part has to come first, but this is not necessarily the subject. It is the most important part of the sentence, whatever it is in the context. It could be an adverbial phrase describing the mode or the time (like "luckily" or "suddenly"), or it could be one of the objects in the sentence. If the verbial frame gets very long (Mark Twain makes fun of this feature in his essay "About the German language"), German allows for taking out some parts out and putting it at the end behind the non conjugated part of the verb. In the Dutch language, this is frowned upon, albeit it is possible.
In subordinate clauses, the conjugated part of the verb comes last, and the non conjugated part of the verb is second last. Again, the other parts can be sorted at will, the most important part usually comes first.
Questions in Germany either start with an interrogative, and then the conjugated part of the verb is in second position (like main clauses), or they start with the conjugated part of the verb (creating something like Vxx). Again, other parts of the sentence can be freely mixed.
Only a few very simple clauses in German fit a word order which could be described as SVO or SOV, and even those could be OVS or OSV instead, depending on context. Every adverbial modifier destroys this word order. The whole word order scheme was probably invented by linguists who don't know Dutch or German, because in those two languages, the conjugated part of the verb acts as a pivot point for the whole clause, and its position is fixed, while everything else is depending on context.
An easy example (for German magnitudes of "easy"):
"Ich sitze am Tisch" (I sit at the table). This is SVO with S = Ich, V = sitze, and O = am Tisch. But "Am Tisch sitze ich" would be correct too (if for instance, someone asks me where I am, and "am Tisch" is the most important information in my answer). If I add an adverbial phrase like "heute" (today), the whole SVO scheme breaks down, as the correct German clause is now "Heute sitze ich am Tisch". The word order in this case is (a)VSO (with (a) being an adverbial phrase of time), and the verb "sitze" has to move before everything else. "Ich sitze heute am Tisch" would be fine too, and even "Am Tisch sitze ich heute" or "Am Tisch sitze heute ich". All that matters is that "sitze" has to come second.
Re:I can see a heated debate coming (Score:5, Funny)
Everyone knows the most understandable thing is what you grew up learning. In other news Fahrenheit is stupid and senseless. Why? Because I learnt Celsius so everything else is strange.
Re: (Score:2)
I learned all three major ones in childhood (C, F, K). Objectively, I prefer K, followed by C and F.
Also objectively, F is more arbitrary than C, while K is the most scientific (doh).
Re: (Score:2)
K is just as arbitrary. It's still based around water at an arbitrary pressure, which is just a measurement of the pressure at Earth's surface. So the divisions aren't based on anything more than the freeze/boil points, and saying "It's 100 between these!" But if you alter the pressure even a little bit, then the division would change. Yes all of Metric is based on "this is a kilogram, now work out the rest" for a lot of it, but temperature isn't. Still arbitrary to the "average" pressure of Earth's su
Re: (Score:3)
K has the advantage that one can meaningfully compare temperatures by ratios or percentages, e.g.: "Where I live, it's typically 7% warmer in July than in January."
And ratios of temperatures are useful. For instance, around here in the summer, the daily highs (5 pm) are 5% higher than the daily lows (7 am). This means that if I measure tire pressure at 5 pm, and then find it's 5% lower at 7 am, the loss of pressure is exactly what is expected (assuming volume change is negligible) and hence not indicative o
Re: (Score:2, Interesting)
How is F more arbitrary than C? The goal of F was that 0 is when human blood froze and 100 is the normal body temperature of a healthy adult human. While it easy to say that humans are too variable to be a good measurement baseline, use of a brine rather than human blood for the measurements was sloppy, etc. None of that is bad science, even if it is bad engineering. It certainly isn't more arbitrary that using water at Earth's sea level, which varies by atmospheric conditions so STP ends up being a bit ar
Re: (Score:3)
How is F more arbitrary than C? The goal of F was that 0 is when human blood froze and 100 is the normal body temperature of a healthy adult human.
What's more arbitrary than a temperature scale reliant on biology? There is no "normal body temperature of a healthy adult human". Healthy adult humans have a wide range of "normal" temperatures. https://www.health.harvard.edu... [harvard.edu]
Water purity and air pressure, however, are very controllable and repeatable, and is governed by physics only. That makes it perfect to standardize on.
Furthermore, it makes for an easy science demonstration for students - look at what happens to the temperature when you boil w
Re: (Score:3)
No, 0F was defined simply as the coldest temperature Fahrenheit could reach with contemporary tools - basically the coldest temperature he could get with a brine solution and the cooling technology of the time. Brine because they could get well below the freezing point of water.
96F was then chosen to be the average body temperature. Not 100F. This was because 96 had many, many more factors in it
Fahrenheit is objectively worse for general use (Score:2)
Fahrenheit is objectively worse for general use, it's not me saying it, Fahrenheit himself did not design it for that purpose.
There are logical people who can recognise something is better/worse regardless of what they grew up with. E.g. I grew up in a country where cars have right of way going into a roundabout. It took me just a couple of days of driving in the UK (right of way for cars already in the roundabout) to realize we've been doing it wrong!
But I was fortunate to grow up in a metric country. When
Re:Fahrenheit is objectively worse for general use (Score:4, Interesting)
Some testing I did for a high school science fair project suggests most people can detect a half-degree difference in Fahrenheit scale when the temp is between ~70 deg F and ~85 deg F. Hotter or colder than that, no. Lots of caveats around that -- it was high school with some really poor data samples -- but that was my conclusion.
Re: (Score:2)
Re: (Score:2)
Essentiality shouldn't be an issue. Declarations exist solely to name the datatype of things - the thing does not exist before its declaration, and the declaration is to say what the thing is and give a name.
In sequence the name doesn't mean anything before its declaration. There's are reasons PASCAL is not that popular anymore. Playing with the ordering convention but still copying the "name (space) name" format in new languages is just annoying and creates confusion.
When a pregnant mother deliver
Re: (Score:2)
There are also reasons why Windows is popular. Doesn't mean they are good reasons.
Re: (Score:2)
Over the most non-essential thing in programming. What is it, type before name or spaces vs tabs?
This article is the basis of a bikeshedding argument.
Re: (Score:2)
Particularly because almost everyone uses syntax highlighting now, so it's extremely clear which is the type and which is the variable name.
Re: (Score:3)
Re: (Score:2)
M/D/Y, Y/M/D, or D/M/Y?
Re: (Score:3)
M/D/Y, Y/M/D, or D/M/Y?
Let's start by cutting the chaff.
Y/M/D, or D/M/Y?
Re: (Score:2)
In day-to-day, D/M/Y, because "today" superseeds "this year".
In computing, Y/M/D, because filenames using this format are nicely sorted alphabetically, as well as chronologically.
Re:I can see a heated debate coming (Score:4, Informative)
There is no excuse for using dates in any order other than ISO8601 order. YYYYMMDD. Add dashes, slashes, dots, hyphens, whatever you want, just put them in that order. Everything else is wrong, and has been for ~35 years.
Re: I can see a heated debate coming (Score:2)
Re:I can see a heated debate coming (Score:4)
COBOL:
01 group-field.
03 numeric-field pic 9(4) display.
03 numeric-bin pic 9(4) binary.
03 num-array.
05 num-element pic 9 binary occurs 32.
03 an-field pic x(32).
and so on.
C is just the first letter of COBOL.
As for Fortran, the type comes first - as in "integer numvar (10)"
Re: (Score:2)
I remember having to work on a COBOL program where the variables had names such as i1-v1, i1-s1, i1-s2, i2-s1 and garbage like that. In the end I refused to touch it unless I could make global changes to the variable names. He (the programmer, he was no longer with the company) had also had paragraphs with similar names, and some of them would just contain "perform l2-p1" so I had to go somewhere else in the coding to see what it actually did (and often it was just another "perform i2-p3"). This was back
Re: (Score:3)
but will you shit shit or shit shit?
Re: (Score:3)
It starts with "they're only backwards if you're used to C"
You're used to C, or Java, C#, Or just about every other widely-used modern programming language.
They're also inconsistent. Go has "func abc() int { return 1 }" instead of "main() func int { return 1 }".
long history in languages like Pascal.
I see... so Go was developed by language historians trying to put a new twist around failed languages that rapidly fell out of favor amongst developers for reasons.
The notation they're using is not like
Re: (Score:2)
Far more helpful than worrying about the order would be to enforce some simple rules for naming stuff. Calling their type "person" is just confusing. Call it "person_t" or even better "PERSON_t".
Then it doesn't matter what order you use, it's still clear which is the type and which is the variable name. Same applies to function names.
Re: (Score:2)
type Person struct {
WTF? Person is not the type, its the name
You're creating a Type named Person. At least that part case kind of makes sense; Like in the C programming language you would write
struct Person {
char *(names_v[5]);
int age;
};
When using the C typedef; it kind of works backwards there
typedef struct { int a; } Foo;
Re: (Score:2)
Both is a matter of preference and can be rationalized:
int x,y,z;
"I want to create variables of type int, the variable names should be x, y and z"
var x,y,z: int;
"I want to create three variables - x, y, z, they all should be of of type int"
type Person struct {
"I want to define a type called 'Person' and it should be struct"
Re: (Score:2)
Exactly this. It comes down to, I guess, what each person started learning on and what they got used to.
"tomato, tomato".
The One True Way (tm)! (Score:2)
I'm sure it's all quite settled now.
Re: (Score:3, Informative)
Exploit potential.... (Score:2)
It might make it easier to extract the value and type from memory since the asociation will be stronger. As a result apps and their services will find the data easier to handle.
This assumes similar languages ... (Score:2)
...some languages don't declare types, some don't have types, some don't have variables!
Thought this was about naming - Hungarian IS good (Score:4, Insightful)
People threw out good Hungarian with the bad Hungarian bathwater.
Hungarian used properly makes programs much more literate, easy to read and understand.
It is a great way to name variables.
Re: (Score:2)
Re: (Score:2)
its barely a good thing
Re:Thought this was about naming - Hungarian IS go (Score:4, Informative)
First, your suggested names aren't Hungarian. Hungarian notation prefixes names with an identifier of the variable type, like str for string or f for floating point. "pounds", "euros," and "rate" are not variable types. https://en.wikipedia.org/wiki/... [wikipedia.org]
Second, it's unnecessary in today's development systems to use name prefixes, because the IDE will very easily tell you what the type is, typically by hovering over the name. The need to "decorate" the name is no longer important.
Third, cardinality. A name or value should mean one and only one thing. By adding a type name prefix, you are combining two meanings into one name: the variable type, and the purpose.
Re: (Score:3)
It's simply camelCase naming, with meaningful names. If you read the Wikipedia article I linked to, it explains that the prefix pertains to the variable type as specified in the language. It was originally conceived because BCPL didn't have any kind of typing, other than "word."
Re:Thought this was about naming - Hungarian IS go (Score:4, Funny)
I'm glad we're in agreement. Now all we have to do is agree on which are the "good" parts and which are the "bad" parts. But I'm sure that's completely obvious and won't cause any friction whatsoever.
He needs more work on his plate (Score:2)
completely irrelevant (Score:2)
I, for one, (Score:3, Funny)
think the letters of the name and the type should be interleaved.
But there's room to argue which gets the first letter.
Natural language (Score:5, Insightful)
Let's have a look how this is done in plain english:
* I know that guy called John
* This is my friend Jack
* A fish called Wanda
* King Henry VIII
* There Was a Farmer Had a Dog and Bingo was it's name-o
Type first, then name.
The counter example would be three-word-sentences for beginner (This is Spot. Spot is a dog.) and when the type becomes part of the name ("Vlad the Impaler")
And in programming, it's the type that matters. Names are arbitrary.
I could live with both, as long as there ARE enforced types.. But if asked for a preference, I'd go with the C#-style (that's C without the pointer nonsense)
Re: (Score:2)
* John is a tall man.
* 'Egyptian' is what you call a person from Egypt.
etc
Also, names don't even require types:
* Damn you John Brown!
etc
Or for that matter, types don't require names:
* That person is stupid.
etc
And of course, English isn't the model for everything.
Re: (Score:2)
I realize that as it isn't my first language. But as most programming languages are more or less based on English, we probably can ignore that.
If you are looking for some fun activity about programming in plain English, have a look at inform7: https://en.wikibooks.org/wiki/... [wikibooks.org]
Re: (Score:2)
Also, names don't even require types:
* Damn you John Brown!
Compile error: Who the fuck is John Brown?
Re:Natural language (Score:4, Funny)
Re: (Score:2)
By the same token, why do so many languages assign gender to inanimate objects? Just imagine what a nightmare programming would be if variables needed a gender.
Re: (Score:2)
Nice....
Re: (Score:2)
In 2023... Really? (Score:3)
Next hot issue: snake case, camel case or Pascal case.
When you're done with this particularly novel discussion, I also recommend the fascinating VI vs. Emacs debate.
Re: (Score:2)
Indeed! Why not simply both?
In this day and age compilers can be dynamically updated every other week to please both name-type and type-name camps.
With obvious exceptions on Christmas and Ramadan when everything will be reset to name-type, or type-name depending on the geolocation and in which sphere (North, South, East or West) one is located, while Buddhists, Hindus and everyone else get to be prompted on those days to make a choice.
Every 60 minutes. Or thereabout.
There's no need to be a slave to ancient
Type Confusion CVE's (Score:3)
struct foo {
int_cost float;
};
Re: (Score:2)
We should learn from GO!?!?? (Score:2)
Go is a badly-named language. Who picks an unsearchable name for something you're going to need help on? If you don't know to look for 'golang' you're hosed, and who knows how much useful info isn't findable by that?
Go is a restrictive language not by syntax but by the libraries -- what system allows you to spawn many subtasks but doesn't let you COUNT them?
Go has no standard commandline parsing system except for a completely inept one implemented to replace the even more inept one, which lead to many rep
Re: (Score:2)
C isn't any better..
Searching for Java is going to get you pages about Indonesia and/or coffee.
BASIC?
The search engine needs to understand context in order for a search to be of any use, especially when you are using languages with unambiguous names.
Objective C (Score:2)
I've worked with managers like this (Score:3)
You know the type; utterly forgettable, and they know it, so they look for any way to make some fundamental change. Now, they typically aren't smart enough to find something truly meaningful, so they latch on to something frustrating, yet meaningless, instead to "Make their Mark".
9 times out of 10 they're gone before it's even implemented, and you're left behind having to explain that bit of technical debt to the noobs. It grows from "we had a manager" to "it's stupid, don't ask" to "that's how we've always done it", ripe yet again for the next empty headed manager to change.
I don't even see the variable names. (Score:5, Funny)
Old languages vs new languages (Score:5, Insightful)
"I think the takeaway is this: we can't change the past, but if you're creating a new language, please put names before types!"
Or, how about "don't confuse problems you had due to unfamiliarity with a language as being the same as problems with the language".
Python, C++, Javascript, Lisp, Ada blahblahblah once you get proficient enough at any language, bikeshedding like this doesn't matter. No language, once it gets popular enough, will not have developed analysis tools outside of the definition of the language that makes bullshit nonsense like this worth talking about.
Nerds needs to learn to have some self-reflection and think "was it the language I have a problem with, or was I just unfamiliar with it?"
HINT: Most of the time, it's the latter. Most of the time, it's just noobs being frustrated. So catering to noobs will be a losing proposition because, regardless of language, if someone sticks with programming long enough, they will not be a noob and will find all the "noob friendly" stuff to be more of a hindrance than helpful.
Why is type inference important? (Score:2)
I know nothing about language design so be gentleâ¦
At the end of the summary it says that type last works better when you consider type inference, in which case the type is missing.
But why is this a thing? Iâ(TM)m missing the use case.
I find it difficult to believe that typing âoeintâ is so tiring that we needed compiler tech to eliminate it, and having seen the super slow compiles that result when the system tries to figure out the type, Iâ(TM)m clearly not seeing the upside.
I
Don't know about one being better, but... (Score:2)
The example cited isn't really about "should type be first or next". The problem is the association of the '*' during a type declariation.
int* x, y;
This is confusing because the * is associated solely with the x variable, not because it comes before the variable names, but because of the scope. It's confusing because it breaks down to:
int* x;
int y;
If go had similar scoping rules, then:
var x, y *int
Would also be confusing if the scoping were such that broke down as:
var x int;
var y *int;
* was designed as a u
Re: (Score:2)
> This is confusing because the * is associated solely with the x variable
Uh ? No, it's not. * is part of the type. A pointer to int. That's the type. So the following x, y are both pointers to an int.
int* x, y;
reads the same as :
int x, y;
The 2 variables of a given type. You're not confused about y being an int in the second statement, why are you confused if y is an int* in the first ?
Re:Don't know about one being better, but... (Score:4, Informative)
Uh ? No, it's not. * is part of the type. A pointer to int. That's the type. So the following x, y are both pointers to an int.
That was literally the subject material, that in C the * applies to x but not to y. So conceptually it's better to perceive it as denoted as int *x, y; The difference between golang and C that is critical in the example is *not* that the type comes later, but the association of the '*' during a type declaration makes it associated with the type rather than the individual variable. The ordering of the words still allows for similar 'natural grammar' ambiguity, as the '*' is still between base type and variable name.
In C, he syntactic choice to put the '*' next to int is because the compiler doesn't care if the operator is denoted as 'int* x' or 'int * x' or 'int *x'. This matches how the '*' operator works for dereferencing a pointer to get value (though only an insane person would put a space between '*' and the variable name in that context, it is permitted). Many folks think '*' logically should be with the type, because the base behavior of the unqualified variable changes, so they put it next to the type. However the C language design considers it a unary operator on the variable, making only the single variable 'pointerify'.
In C, * is always a unary operator that modifies the singular variable it precedes, no matter what the context, declaring or in use. This is confusing during declaration, as people conceptualize it as being associated with the 'type' rather than the 'variable' in a statement what contains multiple variables. Golang chooses the more "intuitive" choice of the '*' operator modifying the type rather than the nearest variable.
When C was being decided, "intuitive" was not necessarily known and with the benefit of decades of programmers coming through, the intuitive expectation is clearly counter to C choices. However, that's nothing to do with whether it comes before or after the variable, particular with Go's choice to have the * precede the type.
Golang choice is:
var x, y *int;
Which, from a grammer perspective, could be ambiguous enough to have plausibly meant (like C):
var x int
var y *int.
They *didn't* make the choice, but having the '*' after the variable instead of before the variable did not make the '*' grammatically more obviously one way versus another.
Now if the syntax had been:
var x, y int*
That would have made it unambiguously obvious that '*' is modifying the type (too far from a variable). By the same token, if C had the 'intuitive' behavior instead, they could have done:
*int x, y;
To also clearly indicate the type is being modified, not a single variable. The key is the pointer operator needed to be well away from the variable to unambiguously indicate the type as the thing being modified. However neither C or Go does it this way, so the grammar is technically ambiguous to a human reader who doesn't remember the association by rote.
Re: (Score:2)
int[] x;
int x[];
x int[];
x[] int;
Meta languages (Score:2)
Most programming languages are supposed to be used as a meta language.
Aka you define yourself everything you need, besides if and while which is given by the compiler.
This example below, is simply a wrong example:
In C, the following declares x to be a pointer, but (surprisingly at first!) y to be a normal integer:
int* x, y;
First "int* x" is written wrong. Seriously, you put the type indication to the variable, as in "int *x". Yes, a very minour change but is important in the long run.
Secondly, the a
Light the blue touch paper... (Score:3)
Implied (Score:3)
Implied (yet strong) typing solves this another way (TypeScript, Scala, many others):
const processingComplete = true
This order makes no sense to me (Score:3)
I always considered declarations to essentially be the function to create the integer variable with the name that follows. It is not logically consistent to me to put the variable name first.
It is far more common in English to say "My name is Bob" rather than "Bob is my name", so it is more linguistically consistent as well.
Assigning a value upon creation of the variable is more understandable written as "int i = 0" rather than "i int = 0".
Another anecdote (Score:2)
The past 5 years I've written a lot of code in Java, TypeScript, JavaScript and Clojure (and incidentally some SQL). I would say it is more important to have a type than the position it is written in (It is quite useful to provide extra information when the oh-so-well-chosen variable name still leaves you wondering. Position is just a matter of what you are used to.) But, one can get away without types if you really need to and are prepared to spend the extra time tracking down bugs ( : any has become a pet
Whatever Floats Your Boat (Score:2)
I think you should do it however you feel like doing it. Unless you're part of an organization and that org has standards. Then you follow your org's standards.
editor syntax highlighter (Score:2)
Shouldn't the editor be able to toggle this on and off based on the user preference ?
If the editor's syntax highlighter can't figure out the type of a variable it seems like that would be another useful red flag.
Even K+R admit they messed up types in C (Score:2)
To decipher a type in C you often have to read it backwards starting from the name. E.g.:
int const * const x[10];
x is an array of 10 elements of constant pointers to constant integers.
The point being, C is probably one of the last languages to which you should look for guidance on typing variables.
Hello UML (Score:2)
Sure, and that's what we see in UML, for example.
It seems like the mental design process is more (a) describe the data we need here, then (b) decide on what type it should be (as a college CS instructor I'm keenly aware of this).
Related and more importantly, return types should be at the end of a function declaration; that seems like kind of a no-brainer (following the same mental design process).
One makes skimming far simpler (Score:2)
At least on principle, I couldn't care less about which goes first. I cut my teeth on both approaches.
But one benefit of type-first is that types are uniformly named. And int is always called "int", and so on. As such, if you have a series of variables that you're declaring, all of which happen to be ints in, say, a calculation engine, you can easily scan down the list to read the variable names or spot the one that isn't an int. Swapping the order means having to read much more slowly and carefully because
Re: (Score:2)
Right handed bigotry! (Score:2)
Why does the author assume the leftmost thing comes first and is most important. What an insensitive clod!
TypeScript (Score:2)
Worth noting TypeScript doesn't have much of a choice as it wants to be compatible with JS syntax, including allowing defining variables without types.
I'd say it doesn't really matter as long as the type is made clear on the declaration line SOMEWHERE.
Worth noting C# allows for an "auto" keyword in place of the type name if the type can be inferred from usage. For example: auto x = new Widget(); I personally prefer the type name first though: Widget x = new(); // Inferred type works in constructors too!
Re: (Score:2)
It's C++ that uses "auto". In C#, it's "var".
Ease of parsing (Score:4, Informative)
The FAQ goes on to point out that parsing is simpler with name-before-type
I would argue in all cases it is easier to parse if the type is first. Since variable types are predefined keywords, your parsing template is always:
var type [indefinite list of arbitrary identifiers]
Which is easier to parse and validate than:
var [indefinite list of arbitrary identifiers] type
Since data types are reserved keywords, your keywords always come first as a couplet that developers would be used to seeing "var int WHATEVER" So just like with reading, where we are used to see specific combinations of words together, the var and types form phrases that go together, followed by whatever mess the developer chose for their names (long names, short names, camel case, whatever is arbitrary).
Validation is easier with the type first. Following var you always require a known type, and then afterwards no reserved words can be used. Simple. With the type at the end you end up with more complex ways for developers to screw up and break syntax. For example, "var foo int bar". What is bar? Was it intended to be part of the type? Or did they accidentally list more variable names afterwards? Is the fix to just move int to the end then? If the type comes first then you simply consume all known keywords / type definitions until there is no more, and that is your type. Then the arbitrary stuff comes after. It's more explicit which is want you want in defining a language.
Finally, I also argue that editing / entering is easier as well. Since your arbitrary list of things come last, it is easier to append additional variable names. It's just the end of the line, instead of having to insert between reserved words.
The only reason parsing variables is easier in Go has nothing to do with whether the type comes first or second, but because it is a more verbose language requiring variable declarations to begin with var. With C the declaration is implicit - if there is a type then arbitrary label and no function parameters then it is a variable declaration, otherwise it is a function declaration. In the original C standard, to make things easier on the parsers, all local variables had to be defined at the beginning of the function before anything else. They could have alleviated parsing headaches with an explicit declaration keyword, but one of the main motivations of the C language (besides being compiler friendly) was brevity.
int *x, y; ?! NEVER! (Score:5, Insightful)
Re: (Score:3)
Dim sName As String (Score:3)
Re: (Score:2)
Why is a carrot more orange than an orange?
because of its molecular structure
Is it better to be smart or happy?
Happy, trust me.
Why does Pamela Ewing have such vivid dreams?
Because she wished she married JR instead of Bobby
What is the sound of one hand clapping in a forest when there is no one there to hear it?
It's like "whoosh!"
Glad to be of service. Don't think I have all the answers. This timeless question, first asked in a quiz with DeLaSoul, still puzzles me:
What does ‘tush-et-le-le-pu’ mean?
Re: Pointer non-problem (Score:2)
Yep. The arguments for "int*" have never made sense to me.
Re:Pointer non-problem (Score:4, Insightful)
The pointer "problem" with int* x, y; goes away if you always place the asterisk with the name instead of the type.
The reason it's not intuitive is that the "*" is part of the type declaration, not of the variable name. It's counter-intuitive that it associates with the variable name instead of the type.
Most think they are declaring a "pointer to int" named "x", not an "int" named "pointer x".