188 points · by nkurz · 15y ago · 109 comments
I see this argument a lot, and they strike me as people complaining because they don't use tools their language provides.
Typedefs are the answer to excessive name length, and they're nearly everywhere. Just create a couple typedef files, and import them as needed - future programmers get the full names easily, while you can program in your pseudo-K version of C for maximum keyboard efficiency. I have a handful of such files, they're endlessly useful - why write `Pop_froM_lIsT_WhIch_COntaiNs_speCiFik_type_X`, doing battle with naming-scheme-X that only employee-Y uses (and their associated spelling errors) when you can do so once, and write `pop` from then on, unambiguously?
The upside of typedefs for this comparison is that they're precisely what we do with spoken language - nobody knew what a "taxi cab" was until someone told them it the shorter version of "taximeter cabriolet", or until the full phrase was well enough known that it could be inferred accurately by the average person.
HashMap<String, Integer> foo = Maps.newHashMap();
The return type of newHashMap is determined by the type of foo, so you don't need to repeat the generic types in angle brackets. public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
http://google-collections.googlecode.com/svn/trunk/javadoc/i...(I'm not a fan of Java myself, but there are some tricky ways to cut down on its verbosity)
Also it's rarely important that you know the actual type of Map you're using (the interface is what's important), so you can just call
Map<String, Integer> foo = Maps.newHashMap();
The closest you can get in Java is to wrap it in a private, internal class. Which also lets you rename some verbose or frequently-combined operations, say:
foo.someoneCouldntComeUpWithAShorterName() -> wrapped.succinct()
-- or --
foo.store(val);
foo.store(val);
foo.store(val); // I hate void functions...
-> wrapped.store(val,val,val);
But yes, it's a pain. Java's largely a pain. NSString *thing = [NSString stringWithFormat:@"Result: %@", [foo someoneCouldntComeUpWithAShorterNameWithZipcode:08205 name:@"larry" parcels:5]];
NSDictionary *request = [NSDictionary dictionaryWithObjectsAndKeys:@"iphoneapp/0.1", @"User-Agent", @"news.ycombinator.com", @"Host", nil];
This isn't to kick off pet language wars, by the way, just to point out that my OCD tic to wrap to 80 characters has absolutely zero place in Xcode. Or Java.The great thing about ConcurrentHashMap<Long,String> isn't writing it, it's reading it. Even if you're not a Java programmer you know exactly what that is (and FWIW it's world-class on implementation). We could do with some syntactical sugar to make that constructor line a little simpler, but declaring the type and calling a specific constructor, not masking either with personal shorthand are both Good Things if someone's going to have to read that code later.
var foo = new Dictionary<string, int>();
and foo's type is infered as Dictionary<string, int> foo = {}C really shines for low-level programming: while something like Linux Kernel is extremely complex, it has relatively simple needs as far as interface goes. The public interface is very small (defined by system calls - I don't know the count, but suffice to say the most trivial python libraries will often have more functions). Same thing can be said for other applications where C has been very successfull for.
But something as fundamental as a lack of any namespace in C really hurts when you need to handle very large applications which cannot be easily split in very well defined components with small interfaces. Complex GUI and browsers come to mind, which is exactly the kind of things where C++ is a well accepted choice.
There is a degree of namespacing in C. Each compilation unit introduces own, anonymous (cannot be addressed/indicated directly) namespace. Symbols defined `static' (``having static linkage'', actually) reside only in it, and are not visible outside of that namespace. Symbols with external linkage are the API of the namespace. It may sound strange, but it's perfectly OK to have symbols with same name in several namespaces, as long as they are static (residing only in it); no conflict because they are not addressible from outside. In a way, a C's compilation unit is similar to C++'s class -- static (C) / private (C++) elements are visible only from this compilation unit (C) / class (C++).
So yes, you can easily split any C application into well defined components with small APIs, without risk of collision between names of private symbols. You only need to ensure unique naming among the `public' API symbols.
Linker use and linkage is a lost art those days, eh ;-(
This is especially excruciating once you need to use various libraries outside your control.
"Lumping together function pointers that operate on the same data structure is essentially object-oriented programming" is unbelievably contentious regardless of which of the various definitions of OOP you follow.
Some of the more exotic features of what people call "OOP", like polymorphism, take a bit more care and feeding to pull off in straight C. They are most certainly possible, that being said.
Unwind "OOP" to "working with objects that contain data and methods together," and structs with function pointers fit the bill. I've had people stand in my face and practically shout that C++ is object-oriented and C isn't, and one refused to believe or admit that C++ basically compiles down to C in the end.
C++ 'basically compiles down to C' for some constructs more than others (exceptions, RTTI, multiple inheritance goop) but if the C it compiles to is dark, arcane, unreadable crap, then this is no more illuminating than the truism that C++ basically compiles down to assembly language.
Neither is object-oriented, except C++ allows you to easily work with objects unlike C, where you have to reinvent them.
It is easy for me not to pick C if I need more abstraction than a struct with pointers to functions can provide.
And thus the discussion devolves into a pissing contest over whose programming language is the most object oriented...
Look, one can reasonable agree to disagree on the definition of 'object-oriented', but I don't see how you can seriously state that C++ is not object-oriented. According to the most broadly accepted superset of what constitutes 'object-oriented', C++ is object-oriented (or rather, can be used in such a way).
But what's the difference between foo->doshit() and doshit(&foo)? Those people still don't get stuff like data orientation, etc. but are shouting out loud how evil OO is and how they killed that dragon ;)
I have serious concerns, however, especially with the first page and the first few chapters.
- They support the biases of the myopic programmer who believes that now he or she knows C, they know everything one must know about programming. I know that isn't the entire point, but you can get that from the article and I have met such programmers. You don't want to work with them, even on projects written in C.
- The "C Craft" section largely describes hacks to work around shortcomings in the syntax or semantics of C.
- The languages used for "vs" comparison are: FORTRAN, C++, Java. Fish in a barrel, anyone? Haskell, APL & J are presented as curios. Python is only mentioned in passing, as an inferior choice to Haskell for rapid prototyping of mathematically-oriented code.
- Go is presented as the "better C", which is encouraging but I'd feel more encouraged if the author showed they were properly familiar with some additional modern programming languages and the cases in which one might use them.
- The assertion that "you can write object-oriented code in C" is accurate, although I think a better point to stress is "you can write mostly-well-modularised code in C, and that's what you want a lot of the time."
- The author also ignores the reality that object-oriented C really only scales up to a certain amount of object-orientatedness, and then it becomes very unwieldly if you are not very careful. Unwieldy at a scale where using a small subset of C++ (ie "C with classes") would remove the overhead, improve the code's signal-to-noise ratio, and still not bring in most of the "bad C++" that the author is talking about.
- The author seems to have chosen to define certain terms as they see fit. For instance, simplicity is defined in terms of brevity & terseness but the example used to prove the point is that Eiffel requires "character" and "integer" whereas C only requires "char" and "int".
For an alternative point of view on what constitutes "brevity" and "simplicity", see the common C idioms for filtering or mapping any variable sized data structure. The only time it becomes less brief is if you rewrite it in C++ w/ STL or Boost. ;)
- It's also telling that in Chapter 2 the Fibonacci counterpoint to Java is in Haskell, not C. That's because a full C program would look pretty similar to the Java program quoted, albeit without the sore-thumb of wrapping it all in a class .
Anyhow, I should quit ranting but IMHO (a) you should know C, (b) you should respect C but (c) you should know some other languages and use C only when you actually need to.
(c) may not apply if you're a super-whizz genius C programmer, some of those people seem like they can carry off ridiculous use cases without making horrible messes. Most of us are not those people. ;)
I disagree that C is superior to C++ for most projects.
First of all, C++ offers higher-level semantics which leads to an increase in productivity. According to [1], the ratio of C++ to C LOC is 1 to 1-2.5, but I'd be interested to read other studies or articles. My experience and [1] also contradicts your statement that rewriting code with STL/Boost will lead to increased code size. It's almost impossible for C++ to be more verbose than C - consider that you can write C-like code directly in C++.
Second of all, for a developer that has good knowledge of both C and C++, writing quality C is harder. C is very prone to programmer errors, much more so than C++ where you can choose to use libraries/language features that completely eliminate some of these errors. e.g: scope-based destruction, the STL data structures, string classes, etc.
Third of all, when discussing C++ many try to make C++ look as a frightening monster ("full-blown C++"?) where you have template meta-programming interacting with automatic conversions and operator overloading and all the other features in the worst possible way. This is not much different to claiming C is bad because you can use macros and void* for everything. The languages should be compared by real-world use patterns, not dreamed up criteria.
[1] Estimating Software Costs (Jones 1998) and Software Cost Estimation with Cocomo II (Boehm 2000)
"[...]that object-oriented programming is no panacea[...]"
While it is true that some have argued for OOP as panacea, this is mostly a strawman. OOP is one possible solution that works most of the time.
Strongly disagree. The full C++ spec, templates and all is pretty complicated. I am sure you can squeeze out less LOC out of it, but then why not just use APL.
> Second of all, for a developer that has good knowledge of both C and C++.
I think there are very few people who know C++ well. And by know I mean they know all of its aspects equally well. Now there are plenty of people who _think_ they know C++, but don't or just know just some parts of it well. I can easier trust someone who says they 'know C', because it is a fairly short spec, not so with C++.
If you imagine a team of developers. If all of them are true C++, experts, then everything is fine. But I have never seen that. So one developer likes templates, another likes some other part of C++, and they start using that and eventually they all write C++ but they can't all necessarily read and understand each others' code. And here is where another 50 pages of C++ style guide comes in to help. But if a language needs 50 pages of custrom style guides to be useful, there is probably something wrong with that language.
> It's almost impossible for C++ to be more verbose than C - consider that you can write C-like code directly in C++.
I think it is a false dichotomy. I know the original article compared both head to head, your point picked it up, but in general it should'be be between C and C++ only. It should be C++ vs C+Python or C vs Go and so on. In other words comparing lines of code by presenting a somewhat artificial constraint is not that representative of the real world.
Then we've used templates to stream arbitrary data-types into an IPC socket.
Finally, we've also used templates to create a generic repository class and to create a specialized compare function for multiple types of containers.
All of these resulted in lesser lines of code without complicating the code base. This kind of template code is nothing fancy and brings real benefits. Now it's your turn to tell me how templates have complicated your projects. Please use real-world examples.
By the way, we're not all true C++ experts in the team and yes, some of us prefer different coding styles. You know what we did? At the beginning we created a coding guidelines/standards document that outlines what is acceptable to use in the project. Problem solved. What you describe - "can't all necessarily read and understand each others' code" - is a dysfunctional team and a management failure.
"it should'be be between C and C++ only"
Ok, we can compare Python + C++ with Python + C, but C++ wins there too. e.g: PyQt/PySide.
* reading and trying to understand source code
* maintaining source code
* typing and programming-related injuries
The dynamic-typed camp argues that even declaring a variable is a pain. Conciseness is one of the favourite features of JS/Ruby/Python developers and prolixity is universaly loathed in Java.
Please expand on your assertion that subtle programming errors are caused by templates. I'm interested especially in errors as a consequence of using templates from the STL or to build generic code. i.e: not metaprogramming
Please indicate how so. I cannot think of ways that make templates more prone to programmer error than, let's say, str_xxx functions for which the programmer needs to allocate extra room for a \0 (or not, depending on which function you use...). Those types of C idiosyncrasies cause much more mistakes than any inadvertent template overload ever could.
Like I said also, I agree with a lot of the premises. I just think the essay is overly positioned as "C is the best hammer" when a better essay might be "Use the right tool, C is a powerful tool. Here is how to use C like a craftsman, here are some good ways to use C you might not have thought of."
It's definitely not a piece for beginners
Who is it for? (I mean this in the most respectful way possible, I'm actually not sure.)
Couldn't disagree more. C++ has a much better type system than C. For many C++ programmers (myself among them) C++ was less about OO and more about giving C programmers the ability to create new types that have the powers of the built in types. I can have strings with proper string schematics instead of an array of chars that is null terminated by convention (i.e. can't be type enforced).
But I find other features/interactions in C++ are unnecessary and even harmful (inheritance and virtuals, typedef of references, C++'s useless implementation of checked exceptions). Templates are implemented pretty badly (Haskell's type-classes a.k.a the discarded "Concepts" could have been used to reduce the auto-generated code duplication). The "rule of three" (Copy constructors, assignment, destructors) is not enforced by the compiler and is a great error-prone hole.
C++ exceptions are problematic, and I actually prefer C's lack of mechanism, where it is completely clear (as long as nobody uses "longjmp") what the control flow is, from simple static analysis or code review. In C++, you have to keep all of the code exception-safe, but due to interaction with external libraries, it can be tough and even error-prone. Cleanup order is sometimes very important and also implicit when using exceptions, making review of its correctness much harder.
I also disagree about exceptions. It does make control flow trickier to follow, but the problem with C is that to really have all failure cases covered you have to put every single function in an if statement. Anything and everything can fail.
I agree that for Torvalds work it is the only sane choice. But I'm not writing kernels.
So if you had to choose one programming language to do all of your work in, which language would it be?
One programming language? As I recall DI Disks let one pick 10 pieces of music, and threw in the Bible, all of Shakespeare, and a luxury of your choosing. But I suppose that if one were not distracted by King James, King Lear, or a luxury, the sensible thing would be to follow in steps of Wall, Ousterhout, Van Rossum, and Matz: use C and create an extensible scripting language.
(edit: spelling)
- What has the verbosity of java vs python have to do with the validity of object oriented programming?
"New languages like Erlang and Go have become popular despite not being object-oriented. In fact, Joe Armstrong, inventor of Erlang, explains why OO sucks."
- Actually later Joe Armstrong came back and said the following:
"Actually it’s a kind of 180 degree turn because I wrote a blog article that said "Why object-oriented programming is silly" or "Why it sucks". I wrote that years ago and I sort of believed that for years. Then, my thesis supervisor, Seif Haridi, stopped me one day and he said "You’re wrong! Erlang is object oriented!" and I said "No, it’s not!" and he said "Yes, it is! It’s more object-oriented than any other programming language." And I thought "Why is he saying that?" He said "What’s object oriented?" Well, we have to have encapsulation, so Erlang has got strong isolation or it tries to have strong isolation, tries to isolate computations and to me that’s the most important thing. If we’re not isolated, I can write a crack program and your program can crash my program, so it doesn’t matter.
You have to protect people from each other. You need strong isolation and you need polymorphism, you need polymorphic messages because otherwise you can’t program. Everybody’s got to have a "print myself" method or something like that. That makes programming easy. The rest, the classes and the methods, just how you organize your program, that’s abstract data type and things. In case that the big thing about object-oriented programming is the messaging, it’s not about the objects, it’s not about the classes and he said "Unfortunately people picked up on the minor things, which is the objects and classes and made a religion of it and they forgot all about the messaging."
"In my Eiffel days, I was encouraged to write "integer", not "int", "character", not "char", and so on. I believe Java encourages this practice too."
1. No Java uses char, int, and so on.
2. No, C is absolutely not concise even compared to Java. At least how I write Java code.
Look at this Java method:
String strangeConcat(String str1, String str2) { return str1.substring(0, str1.length() - 1) + str2.substring(1, str2.length()); }
Is it really more concise in C? How do you tell the caller to free the memory of the returned string?
And if you compare C to Ruby, Python, Scala, Clojure etc... then it is no question that C is not a concise language for most tasks.
int i = 4;
i.toString(); //Exception - int isn't a class, so i isn't an object, so you can't call its methods.
Integer j = 4;
j.toString(); //Returns "4" as a string, because Integer is a class.
Java would 'encourage' the latter practice at times because its useful to be able to call methods off of characters and integers and such, but there is a difference.Instead you might see:
logger.fatal( String.format("Program crashed on index %d: %s", i, message) );
I think C has a similar construct, not quite as verbose, that would save 7 characters out of the line...Is he being funny or serious?