Continue Discussion 45 replies
August 2005

matt122

So if a language had a library that contained a single function such as:

public void ReadFileAndWriteToConsole(string fileName)

Then it would be considered to be a much better language than any other based on line count? Hmmm… there is still something wrong with your metrics (and obviously your example).

Your point about the fact that “the main work loop, if considered alone, is almost identical in every language” is a good one. However, it seems to point to the fact that newer languages have more robust libraries than just the original C language had. Not that the languages themselves are that much better. So where do you draw the line between comparing “languages” and “librarys”?

August 2005

codinghorror

The first one yields 5 lines, and the second yields 4. If LOC is ever used to measure productivity or efficiency, breaking to the next line should not be awarded/penalized for the programmer’s coding style

I realized after I posted this that the counting methods used in Des’ post ignore “do nothing” lines, so the C# curly positions don’t matter and I shouldn’t have bothered.

This also means the ending clauses in VB aren’t counted. In “If… End If”, only the If line is counted.

Your point about the fact that “the main work loop, if considered alone, is almost identical in every language” is a good one

In every MODERN language eg not C or C++. I assume Java will soon add, if they haven’t already, a File.ReadAllLines() method.

So, like you were saying, we have a lot of libraries. Does the language glue matter that much any more?

August 2005

Josh

I’ve never really understood this whole flap. If Perl or Python does something with fewer lines of code, then it’s because there’s a library somewhere that wraps up a bunch of primitive operations into one function call. You could write this in whatever language you’re using and then you’d have the same productivity. The thing that makes C painful is the memory issues, but you can even make a lot of this go away with good libraries…or smart pointers.

Assuming equivalent libraries, I honestly think the thing that contributes the most to productivity is familiarity with the language and libraries, and things like Intellisense so you can know what everything does even if you’re not that familiar, or you’ve forgotten.

August 2005

codinghorror

“Priest of BOB” posted this to a different topic but it belongs here:

open FILENAME, $filename = 'short_perl.pl' or die 'foo';
print (@bob = );

TMTOWTDI.

if you’re worried about an exception while reading, then throw an eval around the print.

Cheers.

August 2005

codinghorror

So, Josh, if I understand you correctly, you’re saying that the IDE is more important than the language?

I agree..

August 2005

Des_Traynor

Hi Jeff,
Thanks for the trackback. I’ll try to answer/defend some of what I said.

To Marty, Yes I would never count a bracket as a line of code (unless I was being paid per line of code of course)

To Matt, obviously as I pointed out, this was not a rigorous scientific analysis of languages. The IEEE paper has that if you want it. I agree that the work loop is very similar in all languages, its the amount of Object creation/initialisation sit-ups that you have to do that weight down the OO languages.

To Josh: I agree, but I would say that perl/python provides libraries written by hackers for hackers, and as a result they tend to handle many things in a far more concise manner.

Just for reference, I am a PhD student researching Computer Science Education. Many questions I regularily deal with are along the lines of “How many languages should we teach”, “what is the best language to teach first”,
“what is the one language all students should now”
“Should we teach the libraries or just the language”.

Many of these are cut and dry issues (for me at least), but I must say I find the notion that the IDE is more important than the language very interesting. Something I will think more about.

I must confess I only starting reading this blog today, but I will stick to it. It is very interesting stuff.

August 2005

StevenC

In defense of the OO languages, their strength is their ability to handle complexity, not their brevity.

August 2005

OleE

Given - “the abandonment of C/C++ for mainstream programming”.

Really?

Name any OS which isn’t coded in C/C++. I mean, a real one.

Name any Office package which isn’t coded in C/C++. I mean, one with measuable market share.

Name any database which isn’t coded in C/C++.

Name any X which isn’t coded in C/C++. Where X = webserver, application server, financial application, image analysis package, etc.

I think your definition of “mainstream” must be different from mine, because from my point of view EVERY mainstream program is written in C/C++, and nothing is even close.

Someday this may change - when pigs fly, maybe, or when hardware is SO FAST that performance doesn’t matter - but that day is not today.

Ole

August 2005

thedisciple

I’ve tried python for hobby code while using C/C++/C# at work. There are pros and cons to using a scripting language such as python.

Pros: It is indeed much faster to code and test most practical apps in python. It’s not just LOC. Perhaps it’s the lack of the compile step, just code, run and test, repeat until done, a very significant productivity gain. Or maybe it’s because the libraries are much more varied, there’s always a python lib out there that supplies functions for what you want to do. It could also be the little stuff. For example, to return a set of x,y coordinates in python, you just do it:

def func1():
  x = 1
  y = 1
  return (x+2, y+3)

(a,b) = func1()

In C++ or C#, I would need to declare a struct or class in order to return the coords. In general, there’s less anxiety while coding due to the loose typing and such.

Cons: There are significant negatives which are enough to make me shift back to C++ or C#. The main problem with python is the lack of documentation and a good GUI lib (wxWidgets doesn’t cut it). Sometimes when developing apps you want to put that extra 10%, whether it’s extra UI trimmings or perf improvement, or something. And I found myself stuck with not knowing how to do it in python due to the lack of docs. In C++/Win32 or C#/.NET, there’s always a documented way to get that extra 10% which makes all the difference.

So I would say, for quick programming jobs, consulting tasks, etc. a scripting language such as python would do the job well. This would probably be the majority of all practical apps. But if you’re developing your own shareware or shrinkwrap products, better do it in a well-established environment such as C++, C#, or VB.

August 2005

ChristianM

Complexity measures like Function Points are probably more relevant here.

Perl

$a = "2";
$b = $a + 3;

is less complex/has fewer FPs than the equivalent C

char* pA = "2";
int b = atoi(pA) + 3;

especially if you count the type declaration as a FP…

Scripting wins by making the environment smarter, at the expense of predictability.

$a = "abc";
$b = $a * 3;
# returns "abcabcabc" 
$x = "69";
$y = $x * 3;
# y = "696969" or 207 ?
August 2005

JamesA

To respond to Jeff, the equivilent entire perl “script” would be:

#! /usr/bin/perl -p

…which I’m not sure if you’d count as zero lines of code (perl is infinitely better?;), but in general I’d agree with Ole probably 99% of applications I work with are in C or C++[1] … the last 1% are some form of quick automation script, and a very few are desktop apps. that are in C#/Java/Python … and with an average developer class workstation I can often still spot which are in the later category by their startup time, not to mention that something always goes wrong with them everytime their runtime changes (with Java being the worst, and python being the best … but there isn’t much in it).

[1] This is different if you talk about webapps. … but IME these are often written by morons who should be required to write them in ASM as revenge.

August 2005

Josh

Exactly! If you’re talking about productivity (and not, say, extracting the last microseconds of performance for some space probe), then I think the biggest bang for the buck is in the IDE, not the syntax.

Ironically, I read something by VB god Matt Curland that said that in this respect VB is better than C/C++/C#, because the verboseness of the syntax made it much easier for them to create Intellisense for. Can’t find the link just now.

August 2005

JohanL

Mogensen said
"Scripting wins by making the environment smarter, at the expense of predictability."

That thing with lack of predictability doesn’t fly, at least not with your example which rather displays a lack of Perl knowledge :slight_smile:

The first example does not result in string concatenation (should have used the “x” operator, not the “*” operator for that), but a numeric operation (so $b contains 0). That’s basic to how the Perl type system works. So in this case it’s predictable if you know the language :slight_smile:

August 2005

RonnyD

Enjoy,

August 2005

Jerry

by the way - what tools do you use to count LOC for the different languages ?

August 2005

codinghorror

Yes, but… all other things being equal, less LOC is generally better. That’s fewer lines of code to debug, to understand, etcetera.

It’s just a general guideline, of course, not a strict rule.

August 2005

Jim_Cooper

I can’t help but think that all this LOC stuff is just a load of bollocks. For productivity to be affected by the amount of typing you do, you have to be typing an awful lot. All the studies I’ve ever seen suggest that the average programmer’s number of correct lines of code produced per day is in the order of 20 (lines that actually do something, not counting autogenerated lines, eg by IDE form designers, or extra syntactic fluff).

20 lines. Per day. But you spend all day typing, right? No you don’t. And when you are typing, you aren’t always writing new code, are you? No.

If conciseness was the ultimate measure of productivity we’d all be using Forth or APL.

Scripting languages may be all very well for trivial applications, but most applications are huge. It is far more important that our code be readable (by others as well as ourselves). Code that is easy to understand is much more productive in the end, no matter what the language. OO languages tend to score better when it comes to features supporting programing in the large.

Examples like the one given here lead only to pointless arguments over people’s favourite language/syntax/code layout/naming conventions. It is completely irrelevant to a discussion of productivity.

September 2005

grumpy1

Name any OS which isn’t coded in C/C++. I mean, a real one.

the web. the web has basic i/o, file storage, apis etc. it is an os, it abstracts complex systems. it is coded mostly in perl, python, php, etc

Name any Office package which isn’t coded in C/C++. I mean, one with measuable market share.

no one cares, its not 1992 anymore

Name any database which isn’t coded in C/C++.

google

September 2005

WillF

Here’s how I would code the example in Common Lisp:

(with-open-file (s "rl.lisp" :direction :input)
  (do ((line (read-line s nil :eof) (read-line s nil :eof)))
      ((eq line :eof) (values))
    (format t "~A~%" line)))
September 2005

maries

Quote “the studies I’ve ever seen suggest that the average programmer’s number of correct lines of code produced per day is in the order of 20…”

Actually 20 lines of code per day typically also includes documentation

September 2005

Binny_V_A

open FILENAME, $filename = 'short_perl.pl' or die 'foo';
 print (@bob = );

Come on - it can be done in one line…

print join('',IN) if open(IN,"file.txt") or die("$!");

Don’t complain about not being able to read the code. :wink:

September 2005

bored1

The python one-liner is:

print open("file.txt", 'r').read()

No need to iterate through the lines if you’re going to read them all in at once with .readlines() anyway. Add two or more lines for a try/except clause if you like.

October 2005

mohammad1

plze i want ask you about to help me to make this program in java
write a program to count (in LOC) the
• total program size
• total size of each of the program’s parts (classes, functions, or procedures)
• the number of items (or methods) in each part

Produce and print
• a single count for the entire program
• size and item counts for each part together with the part name
.
plze answer me in short time.

October 2005

nikolausk

for completeness, a one line ruby solution:

puts IO.readlines("test.file").join rescue puts "oops..."
November 2005

programmer4

I like perl and all, but c# inside visual studio.net is the best development platform of all time. It is just so fucking sick, nothing can compare. As much as some people hate microsoft, they sure make programming pleasant.

spreading code out onto multiple lines just makes it easier to read, easier to comment, easier to maintain, and easier to get the project done closer to the deadline. scripting languages are a waste of time if you are trying to do anything important such as hundreds to thousands of pageview per second server farms, or complicated windows applications.

I’m talking applications with over 100,000 lines of source code developed by four to five developers.

November 2005

the1

I think scripting languages are a great tool for sysadmins though, and programs that munge data and do spidering of web content and things like that.

November 2005

the2

no, scripting languages are only useful for sysadmins. what else are they good for?

November 2005

the3

Yes, but… all other things being equal, less LOC is generally better. That’s fewer lines of code to debug, to understand, etcetera.

If you have too few lines of code it becomes harder to understand. Why do some coding standards of good development teams outlaw tertiary syntax? Because it is a pain in the ass to look at.

PLEASE PLEASE PEOPLE DO NOT EVER USE TERTIARY SYNTAX. THAT SHIT IS SO FUCKING ANNOYING TO MAINTAIN.

December 2005

Bob_Aman

@previous commenter

There’s nothing wrong with tertiary syntax, you just have to know how to write it clearly. For example, placing it within an if statement or within another tertiary statement would be an example of being unclear. But on a relatively short line, especially one that simply does an assignment operation, there’s nothing unclear about it at all, unless you’ve never seen a tertiary statement before.

December 2005

codinghorror

It’s actually “ternary”, guys. See the comments here:

January 2006

bebadoh

If you have a group of coders, how can you really measure their productivity across the group, in order to get a sense of who is lagging behind and encourage improvement? LOC just doesn’t sound like a good measure, because it has nothing to do with the relative usefulness or quality of the code in the end.

How have you all been measured in ways that you thought were fair and useful? Bugs after submission, rework after design, number of features implemented, accuracy of estimated time to implement, etc.?

April 2006

Max

I think the are other issues, like how easy or fast you can find the module (or example) you are looking for.
I know CPAN is great for fast search of lots of modules, and it is there from the day one , but where do you look for C++ or C# etc?

If the was a C++ CPAN then the story might be diffrent.

September 2006

remi1

neat comparison. i love python and ruby, but i also use c# for scripting. when i saw your 13 lines of c#, i created a new c# script on my desktop …

string filename = "readAFile.cs";
try {
	Console.WriteLine(System.IO.File.ReadAllText(filename));
} catch {
	Console.WriteLine("Problem with {0}", filename);
}

there’s no reason to over-complicate things. out-of-the-box, i would need class and namespace declarations (+4 more lines). here, i’m using a classless c# file (using c# script).

i code ASP.NET pages, so my c# is typically sharper than any of my other languages … so, when i want to script something, i throw a new .cs on my desktop and code it up and use a scripting engine to run the scripts.

the difference here is really the TOOLS. sure, visual studio always requires namespaces and class declarations, but not all c# tools do. c# is a powerful language and can, when well written, have a simple and easy to read syntax.

dunno. i LOVE ruby and i’ve been using python more and more, but i’m paid to be a c# coder, so that’s what i use most.

October 2006

ChristopherS

Counting 15 lines for Java is really unfair. Using similar tricks as in your C# example (avoid imports, don’t put opening braces on a new line), a Java version can be quite short:

public class ReadAFile {
  public static void main( String[] args ) throws java.io.IOException {
    java.io.BufferedReader in = new java.io.BufferedReader(new java.io.FileReader("ReadAFile.java"));
    String line;
    while ((line = in.readLine()) != null) 
      System.out.println(line);
  }
}

That’s six lines if we don’t count closing braces (as for C# and VB above).

March 2007

gtpunch

A brace can sometimes be a line of code. Take this code snippet, where the ResourceHungryClass instance is in scope for the duration of DoSomethingTimeConsuming().

auto_ptrResourceHungryClass pFoo = new ResourceHungryClass;
pFoo-Bar();
DoSomethingTimeConsuming();

This situation can be resolved by adding braces, and making a change to the lifetiime of ResourceHungryClass:

{
    auto_ptrResourceHungryClass pFoo = new ResourceHungryClass;
    pFoo-Bar();
}
DoSomethingTimeConsuming();

Not saying that this is good practice, just that the closing brace is as much a line of code as pFoo.release() would be, except the version with braces doesn’t leave the variable in scope (which is arguably safer).

August 2007

keppla

i think, to decide whether brackets count as LOC or not, it is important to look, why we are counting the lines: to get an approximation to the complexity of the code.
LOC may be a good way if you look at big projects, but are hard to interpret if you look at single functions.

For example: what is more complex, a full line of regular expression, or three lines of simple search/replace commands?

September 2007

ThomasW

A google search on ‘programmers lines of code’ brought me here, and in way has answered my question.

I was looking for a gateway into a discussion of true programmer productivity. Essentially, all the wrong measures are still being used and the idiosyncracies of the language syntax being debated here validate my view. Whether five lines in Ruby or 15 in C++, an experienced programmer in the particular language will knock those out very quickly.

Today’s programs are not built on 5 or 15 or 20 lines of code, but on 40 to 400 to 4000 objects. That is the fundamental block. Having programmed since the late '70’s across most platforms from real-time embedded to client / server applications to today’s web solutions, the logic block has moved from counting lines of code and execution time in microseconds, from designing structures and implementing in ‘lines of code’, to objects and inter-object relations and frameworks.

Spaghetti code does not exist, but rather Spaghetti objects are today’s bane.

So I will put forth a simple definition and a number, as a gut call, and see who bites :

Clean object with a good interface, minimal ties to other objects to prevent support hell, typical programmer documentation on the methods with a simple sample of using the object in the target environment. This is the base for the ‘object’.

How many of these per week?

Let’s start with 1 as my guestimate, with a degree of experience if 'not else, as how many per week.

Journey far and fare well!

November 2007

99999999

Languages and lines of code comparisons are nice. However the only real thing that matters, is how debuggable the language is, and whether or not there is a good means of debugging (i.e. a good debugger.)

Most anything can be done from any of the languages out there, but if you can’t actually debug the code, what does it matter?

November 2008

Bob_Farrell

Unfortunately the Python code shown is a little crappy. File objects are their own iterator (i.e. for line in f:) and doing a try: …; except: … without a raise is very bad form - MemoryError and KeyboardInterrupt, for example, will both be caught as a problem with the file. Catch explicitly (IOError) instead. Pedantry aside, if the code doesn’t do what it’s actually supposed to do or if it does it particularly badly (reading a whole file into memory before outputting, incorrectly catching exceptions) then how short the code is is insignificant. Moreover it is a disservice (although I’m sure unintentional) to the language to publish examples of it being used badly.

February 2010

MartyT

Every LOC counting method I’ve seen for C and C-style languages does not count lines that only contain a brace.

For example, a coder could write an if block two possible ways:

if(condition)
{
    DoSomething();
    DoSomethingElse();
}

or…

if(condition) {
    DoSomething();
    DoSomethingElse();
}

The first one yields 5 lines, and the second yields 4. If LOC is ever used to measure productivity or efficiency, breaking to the next line should not be awarded/penalized for the programmer’s coding style. As VB does not use the brace in this fashion, the only lines that shouldn’t be considered are whitespace.

On another note, I think people that put the opening brace on a conditional/loop/other construct are evil. :stuck_out_tongue:

February 2010

MartyT

Last line should have read:

On another note, I think people that put the opening brace on the same line as a conditional/loop/other construct are evil. :stuck_out_tongue:

February 2010

BrandonR

Think about it a good moment.

A closing bracket IS a line of code, because it DOES do something. (At least in C++). What happens on the closing bracket in C++, might you ask? Deconstructors for all objects that were declared in that set of brackets are executed when the ending bracket is reached. That can be a lot of processing done at that ending bracket that wouldn’t be counted otherwise!

February 2010

MartyT

“I agree with Brandon that a line with a bracket is a LineOfCode, except for python ;-)”

There’s no reason a line containing only a bracket should be counted as a line of code. As an example, say you’re using LOC counts as efficiency, so a lower LOC reflects a more efficient programmer. If you’re counting “brace lines”, then a programmer may change his style to show a greater efficiency.

Example:
if(condition)
{
DoSomething();
DoSomethingElse();
}

Counting brace lines, that snippet contains five LOC. Assuming indentation(which I don’t know how to force in these comments :P), this code is very readable.

Now, we can reduce that snippet to three LOC, just by keeping braces on the same line, like so:

if(condition){
DoSomething();
DoSomethingElse(); }

You lose readability by doing this(IMO), but reduce your total LOC. However, the main point is that they do the same thing, despite where you place the braces. Since they do the same exact thing, why should a programmer be punished(or rewarded in some cases) for making more readable code.

Of course, all of this can be resolved by implementing and enforcing coding standards at your company, but this is about as rare as code reviews.

April 2010

VladimirH

PHP should be added to the list.

<?php
$filename = "readAFile.php"
@readfile ($filename);
?>

Or with “checks”

<?php
$filename = "readAFile.php"
if (file_exists ($filename) && is_readable($filename))
     readfile ($filename);
else
    echo "Error reading file, or file not found."
?>

https://php.net/manual/en/function.readfile.php
https://www.php.net/manual/en/function.file-exists.php

February 2011

keno

Visual Fox in just 2 lines of code:

ON ERROR wait window "Error reading file, or file not found."
?FILETOSTR("filename.txt")