Is Java is a bad language for beginners?

Please compose all posts in Emacs.

Moderators: phlip, Moderators General, Prelates

User avatar
aldimond
Otter-duck
Posts: 2665
Joined: Fri Nov 03, 2006 8:52 am UTC
Location: Uptown, Chicago
Contact:

Is Java is a bad language for beginners?

Postby aldimond » Wed Oct 24, 2007 1:49 am UTC

I got into a bit of an argument in another thread because I think Java's way of referring to data is inconsistent and lots of people disagree.

If Java's system of references and the way that strings are assigned and passed as parameters wasn't a horrible mess, then this forum would not be filled with people asking questions about these topics. Thread titles like "Java question about references (I think)". Having not put a lot of study into it, I bet immutable strings (this was something I was initially confused by, not knowing much Java) significantly reduce the number of string copies made in most programs, compared to the number of copies that wind up being made in most other languages. But that's not something any beginning programmer should worry about. It's unintuitive. It makes them think about the language rather than about their programs. When I was in high school the AP CS test was in C++, so of course the advanced programming courses were taught in C++... and C++ has that same problem as Java... I spent so much of my time overcoming the language that I never wrote anything cool in it. On the other hand, I wrote lots of really cool stuff in toy languages like TrueBASIC and for my graphing calculator.

Furthermore, the whole idea of object-oriented programming, to me, has no business in introductory programming courses. Save it for college. People think that if kids get non-OO thinking in their squishy brains they'll be doomed to write code like this their whole lives:

Code: Select all

main(i){char*f,a[99],b,*c;while(gets(a)){b=*(strchr(a,32)+4)-'d';i=strtoul (a,&f,b?10:16);for(f-=c=a;f;i>>=8,f=b?i:f-2,c+=2)sprintf(c,"%02hhx\n",i);printf(b?a:"%u\n",strtol(a,0,16));}}


In reality, the only reason I truly understand why writing code like that is usually undesirable (usually = unless you're coding for the lulz) is because I've done it. Abstraction and encapsulation are good things to keep in mind when writing medium-to-large programs that you'll want to reuse, and OOP is a good tool to enforce abstraction and encapsulation (that's all it is... well, it also helps you model reality sometimes... and there may be other practical things it's good for... the point is that OOP is not a means unto itself). But when you're a beginner writing small programs you should use a language that lets you get at the code, and get at the data. A language where it's easy to explore, easy to think of and design your own cool programs. Even if your design totally sucks; it's important to write badly-designed programs... how else will you ever find out why bad design is bad?!?! Java requires you to think about objects -- you can't write "Hello, World!" without writing a class. You already have to learn how to program, which is one problem... someone says, "use classes!" Now you have two problems. Frankly, the culture surrounding Java doesn't help. There's no Joie de Java, no, "and this is how you hack around with port IO and simple graphics" (QBASIC on DOS) or "smashing the stack for fun and profit" (C/asm) , but a lot of, "YOUR DESIGN PATTERNS ARE ALL WRONG". In one of the Java threads on this board a beginning programmer was advised to use inheritance to factor out code duplication, and to FUCKING CAPITALIZE THE NAMES OF HIS CLASSES! A programmer will learn inheritance from teachers, and about the perils of code duplication from co-workers. A programmer will absorb naming conventions just like people absorb social conventions. A young programmer should explore. Should Do Cool Stuff. Shouldn't be abstracted from the hardware. Shouldn't have code and data encapsulated away where they can't be seen.

QBASIC on 386s running DOS is a *great* first platform. I knew a guy in high school that wrote stuff in QBASIC to interface with electronics projects and model train systems that he built; I'd have to look through lots of manpages to do that in a "real language", even with my advanced education. I knew a guy in college that still prototyped everything he wrote in QBASIC; he knew no language that got in his way less, that made simple programs as absolutely trivial as QBASIC. It's truly a classic. Graduate them to C on Linux or something. Commit gross, dirty hacks. Maybe learn some assembler. Learn how those confounded boxes actually work. Or, alternately, start with something that's clean and high-level but actually abstracted *well* (some might say lisp? I'm not really knowledgeable about any languages that fall in this category), something that makes beautiful algorithms look and feel beautiful... and then let them fall down to languages burdened by pragmatic considerations, the ones that have won the marketplace (C++, Java, .NET, etc.) when they've already grown old and lost their will to live.
Last edited by Hammer on Thu Nov 01, 2007 5:41 pm UTC, edited 1 time in total.
Reason: Changed topic title
One of these days my desk is going to collapse in the middle and all its weight will come down on my knee and tear my new fake ACL. It could be tomorrow. This is my concern.

photosinensis
Posts: 163
Joined: Wed Aug 22, 2007 6:17 am UTC

Re: Why Java is a bad language for beginners

Postby photosinensis » Wed Oct 24, 2007 4:46 am UTC

QBASIC might be a bit out of reach for most kids. That said, I agree that a dialect of BASIC (NOT Visual Basic, which has absolutely nothing to do with Basic in the first place) is a good starting point. I first coded on a TI-83 in its dialect of BASIC. Sure, it's a terrible language for abstraction, what with its heavy dependence on GOTO--and we won't even speak about the inability to pass arguments to functions or return values--but it did teach me about menu systems, loops, and modeling math in computer code.

That said, I was talking to one of my professors today after helping teach a class of intro students (with two other upperclassmen). We're a C++ school, and a good number of them were lost in that abstraction level. It wasn't a complex program, but simple array structure and simple command line I/O was not something they understood. They're not even fine with the difference between memory and disk space. She (my prof) was lamenting that they weren't using the best tools we have (and admittedly, they weren't), but at the same time, I don't think they're ready for such things. They need an understanding of the basic tools first--and we don't have that.

I've said it before, and I'll say it again. The moment I get my own classroom (I intend to do some time teaching), I'm ripping any kind of GUI system out of the computer labs and dropping them onto command-line only Linux thin clients, giving them GCC, vim, and bash, and getting them to be comfortable with those tools first. Of course, they won't code at all for the first semester. They'll go through a basics of computers class, in which they actually get to know what everything is inside their box and what it does. And even then, the first language they see should not be Java, but a language that supports more than one coding paradigm. Object-oriented programming is good for many things, but it isn't the only way--nor is it often the best way. I don't want to know what the one-off prime finder I wrote today in C would have looked like in a strictly OO language.

Also, console I/O in Java is a bitch. All in all, it's a bad choice for a teaching language. That said, it can't be beaten for networking or system-end database stuff.
While I clicked my fav'rite bookmark, suddenly there came a warning,
And my heart was filled with mournng, mourning for my dear amour.
"'Tis not possible!" I uttered, "Give me back my free hardcore!"
Quoth the server: 404.

User avatar
Geekthras
3) What if it's delicious?
Posts: 529
Joined: Wed Oct 03, 2007 4:23 am UTC
Location: Around Boston, MA

Re: Why Java is a bad language for beginners

Postby Geekthras » Wed Oct 24, 2007 5:42 am UTC

My progression went
TruBasic (TI)
QBasic
Java
Common Lisp
Wait. With a SPOON?!

User avatar
TomBot
Posts: 228
Joined: Sun Jul 29, 2007 1:17 am UTC
Location: Illinois (UIUC)
Contact:

Re: Why Java is a bad language for beginners

Postby TomBot » Wed Oct 24, 2007 6:03 am UTC

I think I agree with this. Beginners should learn C. Then maybe mips assembly for about a week. Then they should try to write an abstract data type in C, thus naturally progressing to C++. Then Java, if they need it for something.

Why C? At college I sat in on CS125 (Intro to programming, taught in Java), and watched the professor explaining references, and just getting blank stares. If you haven't thought about what's actually happening in the computer, it doesn't make any sense why "objects" would live in this ephemeral cloud called the "heap", pointed to by arrows called "variables", which live on the "stack", which is like a bunch of notecards with function arguments written on them. It's just way to abstract, and you don't even see the reason for the distinction between a variable and an object.

C can teach you the basic syntax of most languages, if you stick to native types. Once you look at a bit of assembly, you'll understand how recursive functions work perfectly. You'll also learn why it's inefficient to pass big structs or arrays directly. And most importantly, you'll understand pointers.

Then when you learn C++ in the context of trying to make, say, an array class, object orientation will just make sense, because you can clearly see the motivation. Let's move array_sort() into struct array, and we'll call it as a.sort() instead of array_sort(&a).

Frankly, a knowledge of these low-level things even helps with totally different languages like OCaml. Looking at OCaml from a Java perspective, it seems strange to keep passing the tail of the list as a recursive argument, and the immutability of basically everything seems like nothing but a hindrance. But from a C perspective, you see that really you're just dangling linked lists in very elegant ways, and the immutability means you never ever have to copy anything. Plus you see that a tail-call is really just a goto to save stack space.

Sadly I learned QBasic first, entirely from the help files. I say sadly because it was probably a few months before I saw subroutines and functions. The editor hid them from you in all the example code. It was cool in that it had a graphics library that let you write cool screen-savers with palette cycling. Also, looking back, now I finally understand what VARPTR was.

User avatar
Geekthras
3) What if it's delicious?
Posts: 529
Joined: Wed Oct 03, 2007 4:23 am UTC
Location: Around Boston, MA

Re: Why Java is a bad language for beginners

Postby Geekthras » Wed Oct 24, 2007 6:06 am UTC

Same here on QBasicness
However, I found Java really simple and obvious to learn. I learned from the "help" files also.
Wait. With a SPOON?!

Notch
Posts: 318
Joined: Tue Dec 12, 2006 5:52 pm UTC
Location: Stockholm, Sweden
Contact:

Re: Why Java is a bad language for beginners

Postby Notch » Wed Oct 24, 2007 8:49 am UTC

My first experience with programming was copying basic programs from magazines onto my Commodore 128, then trying to change some of the numbers to see if I had correctly guessed what they did. Often I was right.

From there, I went to STOS on atari (horrible, I know), QBasic on PC, then Pascal (Turbo Pascal, I believe). TP was nice, as it was easy to inline assembler into it, and at first I just copied assembler blocks I had found in programming tutorials just to get the extra speed, but after not too long, I started changing the numbers to see if I had correctly guessed what they did. I had to reboot my computer a lot. ;)

Then I went directly to java, skipping C/C++ (well, i tried them briefly), and it took me a very long time to understand OO. A VERY long time.

Moral of the story: If you get stuck just playing around for too long, you might develop bad habits.

(Java's still my favorite language, it's so pure and clean, and the style guide actually makes it pretty to look at (except that {'s should be on their own lines, damnit))

User avatar
yy2bggggs
Posts: 1261
Joined: Tue Oct 17, 2006 6:42 am UTC

Re: Why Java is a bad language for beginners

Postby yy2bggggs » Wed Oct 24, 2007 1:39 pm UTC

aldimond wrote:I got into a bit of an argument in another thread because I think Java's way of referring to data is inconsistent and lots of people disagree.

Uhm... references are easy. Maybe they have a bad name... an alternative name for them is "aliases".

Pass by reference (alias), and you get to change the value of what you are referencing (aliasing). Pass by value, and all you're doing is giving the value to some function.

If that's difficult to understand for a beginning, I have no hope for the beginner. I can understand how it would be difficult if it just plain weren't simply explained.


Furthermore, the whole idea of object-oriented programming, to me, has no business in introductory programming courses. Save it for college.

That sounds fine to me, depending on what you mean by introductory programming course. If it's purpose is to help you at some point in the future to program, teaching OO isn't that valuable, and you should be learning procedural programming (like I did originally, in BASIC on a VIC20, using a vague notion of ranges of lines and gosub/return).

On the other hand, although OO programming is very nice for certain domains, it's not the silver bullet the OOP weenies preach it to be. Even for medium to large, complex programs, a lot of what you are doing just plain isn't OO code. The religious OOP crowd is to blame for most of the convolution here. (It's worthy to note that programming using classes is not equivalent to using OOP).

C++ shouldn't be that bad of a language to learn. It's usually taught wrong, but the really nice thing about C++ is that it supports a lot of different paradigms for programming. Why in the hell someone would claim that C is easier to start in than C++ is beyond me, though. C++ has a lot of easier ways (easier to use, less error prone, etc) to do things than C. There's a subset of C++ that's very easy to learn, MUCH easier than figuring out the nightmare that is the char terminated string, that pointers can be treated as but aren't the same as arrays (and precisely what the difference is), that you have to allocate buffers and use silly named libraries like strcpy, etc to copy strings. Sure, you can do template metaprogramming, multiple inheritance, and a number of complicated, advanced things in C++, but C++ is very happy to oblige you with a simple subset.

But I have no objections to people starting in BASIC on a VIC-20.
Image

mrkite
Posts: 336
Joined: Tue Sep 04, 2007 8:48 pm UTC

Re: Why Java is a bad language for beginners

Postby mrkite » Wed Oct 24, 2007 4:10 pm UTC

Mine went:

BASIC
Logo
6502 Assembly
x86 Assembly
C
C++
Java
Perl
PHP
C#

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

Re: Why Java is a bad language

Postby Pesto » Wed Oct 24, 2007 6:08 pm UTC

^^ Subject fix'd

User avatar
Shrewtality
Posts: 41
Joined: Wed Oct 17, 2007 4:15 am UTC
Location: Somewhere between 4 and 5

Re: Why Java is a bad language for beginners

Postby Shrewtality » Wed Oct 24, 2007 6:11 pm UTC

Well I'm lucky for you guys. I'm at the forefront of learning Java as a beginning language. I can tell you how my experience has been thus far.

Really good. Would be the short answer.

Understanding Java has not been an issue for me at all and I think it's because it is the first language that I'm learning. Java has it's own structure as to how it works.

What I've perceived is that the people who are knowledged in C and C++ are having a harder time then people who are learning Java as a first programming language, in most cases.

I personally don't see Java's references to be a problem, anything I've done has been over come by a bit of brute force. And I've done cool side projects on my own. Refer to my "picture imperfect" thread. After about 4 hours I was able to solve my problem- and it's even beyond the scope of my beginning classes and is still very cool in it's concept (which relates vaguely to the idea of fractals).

Anyone who truly has problems with Java probably isn't putting in the amount of effort expected by the class itself.

Strings are immutable- big deal.

Code: Select all

String s1 = "Hello";
String s2 = "World";
String s1 = s1.concat(s2);
s2 = s2.toLowerCase();  //It's not that hard to remember to say s2 = s2.*some change on itself*

I can overcome it easily - perhaps it's inefficient in memory and speed, but why should a beginner be worrying about efficiency?

As far as OOP- I find I like it, and the concept really isn't that hard to grasp. Anybody who should really be studying computer science should not have a hard time with these concepts in the first place.

Of course take this all with perhaps a tablespoon of salt, as I'm the "over-acheiver" of my class- as I'm also auditing a graduate level class on reflective and meta programming. AspectOP and MetaOOP.
Image
I approach infinity around 5, that way i can get through with it sooner.
me: I wouldnt know where to begin to respond to that... perhaps after the last digit of pi...

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Why Java is a bad language for beginners

Postby Berengal » Wed Oct 24, 2007 11:32 pm UTC

Java was the first real programming language I learned. I've briefly looked upon c, c++ and python before, as well as learning NWScript (which is really easy, but looks like c, making c easier to understand (but not learn)). Now I know Java (pretty much) and Python (for a given value of "know") and I'm teaching myself Haskell, c and d.
The inner workings of Java never bothered me any at all during any of my programs, both related to my class and my personal projects. The reason I created the "Help with Java references (I think)" thread was because we were querried about the inner workings explicitly by our professor and I wasn't completely sure about the answer. I had an idea (something to do with references (which I hadn't encountered anywhere previously in my limited programming experience) thus the "references" in the title), which turned out to be right, but I wanted to make sure first (thus the "(I think)" in the title). The point here is that I too believe that those who migrate from mid-level languages like c and c++ to Java might despair about how it treats it's variables in a to them unintuitive way, but really, it's pretty intuitive if you haven't encountered anything like it before. It's also very easy to write Clean Code, of which I'm a big fan. Python is arguably more readable, but I still hold that Java is the cleanest of the two.

(Less on topic beoynd this point)

I've only got a few irkings about Java, mostly brought by the easiness of Python:
-The inability to "return string, int, myType" instead forcing one to "return new Object[] {[VERBOSITY]}" and subsequent unpacking.
-Python's "file = open ("filename")" contrasts heavily to Java's "try { file = new BufferedStream(new FileStream(new StreamOfBlood(new SatanicRitual(new BlackGoat("Lucifer's billygoat"))))) } catch (Throwable e) {System.bugger.all()}"

Of course, Python has it's annoyances as well, but both these languages (and other languages) have their differences and their different uses; each one's better at something. I'd love a language with Java's strict type checking AND python's dynamic types, but that's pretty much impossible. Can't have it all.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

mrkite
Posts: 336
Joined: Tue Sep 04, 2007 8:48 pm UTC

Re: Why Java is a bad language for beginners

Postby mrkite » Thu Oct 25, 2007 1:39 am UTC

Shrewtality wrote:perhaps it's inefficient in memory and speed, but why should a beginner be worrying about efficiency?


I may be wrong (it's been over a decade since I was in college), but usually the first course after CS101 is a Data Structures course which delves into BigO notation and efficiency.

The bad habits you learn early on will carry with you for quite some time.

User avatar
Shrewtality
Posts: 41
Joined: Wed Oct 17, 2007 4:15 am UTC
Location: Somewhere between 4 and 5

Re: Why Java is a bad language for beginners

Postby Shrewtality » Thu Oct 25, 2007 1:44 am UTC

mrkite wrote:
Shrewtality wrote:perhaps it's inefficient in memory and speed, but why should a beginner be worrying about efficiency?


I may be wrong (it's been over a decade since I was in college), but usually the first course after CS101 is a Data Structures course which delves into BigO notation and efficiency.

The bad habits you learn early on will carry with you for quite some time.


Well next semester I'll worry about it then ^^. I already know some bits and pieces about BigO notation. Which measures the max(?) time it takes an algorithm to run based on input size. Usually derived from nested loops or something. Like how bubblesort is O(N2) because of the two for loops required to run the algorithm.

But either way, in Java.. theres no more efficient way I could write that code itself- that I know of.
Image
I approach infinity around 5, that way i can get through with it sooner.
me: I wouldnt know where to begin to respond to that... perhaps after the last digit of pi...

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Why Java is a bad language for beginners

Postby EvanED » Thu Oct 25, 2007 2:03 am UTC

Shrewtality wrote:Well next semester I'll worry about it then ^^. I already know some bits and pieces about BigO notation. Which measures the max(?) time it takes an algorithm to run based on input size.

You're about right in terms of the idea... I just thought I would clarify the "max(?)" bit.

You'll often see talk of both the average case time and the worst case time -- both can be measured in big-O notation. For instance, take quick sort: this is an algorithm that (in almost all presentations) takes O(n * log n) time on average, but can take O(n2) in the worst case.

(What's typically meant by average is a uniformly distributed input; in the case of sorting, this basically means you choose one of the n! permutations of the array uniformly at random. For a given application, which will almost always constrain the inputs further and change their distribution, the average case of an algorithm may change.)

User avatar
Hexadecimator
Posts: 177
Joined: Thu Jul 26, 2007 10:48 pm UTC
Location: WA, USA, Earth, ZZ9 Plural Z Alpha

Re: Why Java is a bad language for beginners

Postby Hexadecimator » Thu Oct 25, 2007 2:54 am UTC

My progression went all over the place:
Age 10: Rudimentary C/C++ (cin, cout, and functions. summer camp)
11: VB (briefly, it was painful even then)
11: BASIC
13: C#
13: Whatever is on the TI-83
14: C++ (easy class)
16: Ruby (3 weeks ago, and so far it's awesome)

Except C++, all my knowledge is self-taught and from the internet. I've also dabbled in various other languages including asm. I picked it all up with no problems, and I can code circles around the kids in AP Java who 'learned' how to use the built-in classes to read images, draw sprites, and useless junk like that. Instead, I taught myself valuable programming skills and concepts, including the ability to locate and read the documentation for an image processing library should I ever need one.

Students should start learning to program with a text editor and the command line. No GUI builder. The focus should be on programming concepts, not learning to use language-specific standard libraries.
In that respect, I would start with a lower-level language like C/C++ or BASIC.
"In the beginning, the universe was created. This made a lot of people very angry and was widely regarded as a bad move." -Douglas Adams

User avatar
aldimond
Otter-duck
Posts: 2665
Joined: Fri Nov 03, 2006 8:52 am UTC
Location: Uptown, Chicago
Contact:

Re: Why Java is a bad language for beginners

Postby aldimond » Thu Oct 25, 2007 3:25 am UTC

yy2bggggs wrote:
aldimond wrote:I got into a bit of an argument in another thread because I think Java's way of referring to data is inconsistent and lots of people disagree.

Uhm... references are easy. Maybe they have a bad name... an alternative name for them is "aliases".

Pass by reference (alias), and you get to change the value of what you are referencing (aliasing). Pass by value, and all you're doing is giving the value to some function.


This isn't just about passing things. But I'll talk about passing things. I have no problem with passing by reference and value, when those things work consistently. But in Java they really don't. In Java if you have an identifier it names either a primitive number or a reference to an object. For example, a string. And if you pass by reference you can change the value inside the function, right? Like this?

Code: Select all

class helloworldawd
{
        public static void main(String args[])
        {
                String a = "Hello, World!";
                barring(a);
                System.out.println("Hello, World!");
        }

        public static void barring(String foo)
        {
                foo = "Barring foo, foo shall be barred!";
        }
}


Heh, not so much. To actually understand why this outputs "Hello, World!" you have to understand what a reference is, and understand what the assignment operator is really doing. It's doing something totally different than what it does for integer primitives, on the surface at least. I suppose if you had a Java object that could be edited in ways other than the assignment operator its value could change if you passed it by reference, but your definition of what pass-by-reference means doesn't actually apply in Java at all. And I bet you've written at least a thousand times more Java than I have (I've only written about 10 lines of it).

The problem isn't fundamentally about passing things. The problem fundamentally is that in most programming you use with approximately equal frequency integer, strings, and everything else. Operating on all of them requires totally different syntax. For integers you might say, if (everybody != to_the_limit) everybody <<= come_on_fhqwgdzz;. For strings, if (sketch_status.IsEquals("run its course")) sketch_status = "and now for something completely different"; (that might not be the right function to call for equality, like I said, I have written all of 10 lines of Java). For other objects, given support for this type of thing, you might say, if (jude.hasLetUnderSkin(her)) jude.begin(MAKE_IT_BETTER);. Now, this is also true in C. But at least in C you declare declare a pointer to a struct differently than you declare an integer literal. struct pasta *vermicelli; vs. int o_thin_air;. They're clearly different things. You declare a pointer, you act on the pointer. And a pointer is something very concrete; you can even printf(%x, vermicelli);, just as easily as you can printf(%d, vermicelli->diameter);... and I think that's important, especially for people starting out. In java it's int everybody;, String sketch_status;, and SongProtagonist jude;. Always type name. And you can't get your metaphorical hands on what precisely changes when you do sketch_status = "tuesday is not good for the eradicator";.

The real, real, real problem is that the problems that Java is solving are software engineering problems. Enforcing class structure, data hiding and abstraction... in the case of Java's string model, eliminating unnecessary string copies (I don't have hard numbers on it, but I'd guess the performance-to-effort ratio it yields is much higher than C++ STL strings (which have to be copied byte-by-byte every time there's assignment or copy construction) or C-style char arrays (which can yield great performance but cost lots of effort and time, and often result in inflexible, error-prone and insecure code), but they're also a bit unintuitive and work quite differently from other data types. Not a good trade-off for people writing throw-away code for educational purposes. At any rate, using a language designed with an eye towards writing accounting reporting software Is Not Much Fun. Using a language designed with an eye towards system coding, and letting you at the OS, or one designed with an eye towards elegant expression of algorithms, has a much better chance of developing enthusiasm and love for programming.

For all that the AP curriculum tried to drill OOP into my head when I took it, I never really grokked it until I'd worked in a huge C codebase. Until I'd actually done the work necessary to deal with maintaining duplicated code as a big part of my job. I suspect the same is true of lots of people... they'll ape their professors on the talking points of OOP, of encapsulation and abstraction, and not have any feel for why it's useful. They'll design programs (and I've seen this) trying to fit them into some mold that they've been taught, rather than understanding the real problems that they'll encounter if they design poorly. Or design programs in OO languages that really don't take advantage of object orientation at all... they don't even know that, because they don't have a true feel for the problems that OOP tries to solve. So, I say, keep the OOP at arm's length while teaching. AP exam be damned. Have some college courses on it. At the end of those courses, say, "You'll understand this all when you have a real job."
One of these days my desk is going to collapse in the middle and all its weight will come down on my knee and tear my new fake ACL. It could be tomorrow. This is my concern.

User avatar
TomBot
Posts: 228
Joined: Sun Jul 29, 2007 1:17 am UTC
Location: Illinois (UIUC)
Contact:

Re: Why Java is a bad language for beginners

Postby TomBot » Thu Oct 25, 2007 7:14 am UTC

yy2bggggs wrote:C++ shouldn't be that bad of a language to learn. It's usually taught wrong, but the really nice thing about C++ is that it supports a lot of different paradigms for programming. Why in the hell someone would claim that C is easier to start in than C++ is beyond me, though. C++ has a lot of easier ways (easier to use, less error prone, etc) to do things than C. There's a subset of C++ that's very easy to learn, MUCH easier than figuring out the nightmare that is the char terminated string, that pointers can be treated as but aren't the same as arrays (and precisely what the difference is), that you have to allocate buffers and use silly named libraries like strcpy, etc to copy strings. Sure, you can do template metaprogramming, multiple inheritance, and a number of complicated, advanced things in C++, but C++ is very happy to oblige you with a simple subset.


I'm not saying C is the easy way to start, I'm saying it's the right way. I am assuming we're talking about students who have not programmed much before, but plan to study CS or program a lot in the future.

Yes, string handling is difficult in C. That's because you actually have to think hard about exactly how big this block of memory is, who will delete it when its not needed, etc. Also, with both string handling and printf, it's easy to get programs that compile fine but crash. This is a very good thing! The "write a bunch of code without thinking, fix typos until it compiles, and you're done" habit holds a lot of beginners back, because it works okay for small programs, but doesn't scale at all. It's also a good thing to learn first because it puts memory and pointers right there in front of you, instead of being some big scary advanced topic as in C++, or completely abstracted away as in Java.

I'm not saying you talk about this on the first day, or dwell on it for longer than a week or so. Basically you would start with doing mathematical functions on ints, maybe printf(), maybe scanf(). You should really only be doing pure C for like two weeks anyway, there's just not that much to learn.

The other reason for starting with C is that it provides the perfect motivation for moving to C++. Objects aren't some mysterious abstraction that the gods of CS have given to us, they're a very logical solution to the annoyances of procedural languages. I think people learn better when they see the motivation behind what they're learning. So get them good and tired of C's sucky string manipulation, then have them write a struct and some functions to make it easier. Then turn them into a class. Then do operator overloading. Then tell them about STL, and how they shouldn't reinvent the wheel outside of an educational setting.

It can be hard for us to see the advantages of starting simple and close to the metal, because we presumably understand this stuff. If you already know 17 programming languages, Java looks beautiful and simple and clean. But I've seen people for whom it just doesn't make any sense. That's why I don't think it's best to start at such a high level of abstraction.

Aii
Posts: 5
Joined: Thu Oct 25, 2007 7:18 am UTC
Contact:

Re: Why Java is a bad language for beginners

Postby Aii » Thu Oct 25, 2007 7:27 am UTC

My college's Intro CS course (CS 5) had been taught in C++, switched to Java for exactly 1 year, and then moved to Python, which it is currently taught in.

The follow up course (CS 60) includes segments taught in different languages, to help cover different programming paradigms. These included rex, an in-house functional language, as well as the more common Prolog and others. Recently, they started using Scheme for a decent portion of it, and dropped rex from the lineup (mostly because it was getting old, and the rex interpreter wouldn't run on the new CS dept. servers anymore! too much of a hassle to port the source code over).
See also: Aaeriele

brodieboy255
Posts: 58
Joined: Thu Aug 30, 2007 10:40 am UTC

Re: Why Java is a bad language for beginners

Postby brodieboy255 » Thu Oct 25, 2007 9:28 am UTC

Java is a Horrible language for beginners. Look at:

Code: Select all

class Name {
    public static void main(String args[])
        {
            KeyboardReader kb = new KeyboardReader();
            System.out.println("Enter your name: ");
            String name = kb.getInput(String);
            System.out.println("Hello " + name);
        }
}


Compared to Python's

Code: Select all

print "Enter your name: "
name = raw_input()
print "Hello " + name


Python is cool :D

User avatar
Geekthras
3) What if it's delicious?
Posts: 529
Joined: Wed Oct 03, 2007 4:23 am UTC
Location: Around Boston, MA

Re: Why Java is a bad language for beginners

Postby Geekthras » Thu Oct 25, 2007 11:55 am UTC

Totally do Lisp 8)
(print 'sup)
Wait. With a SPOON?!

User avatar
hotaru
Posts: 1045
Joined: Fri Apr 13, 2007 6:54 pm UTC

Re: Why Java is a bad language for beginners

Postby hotaru » Thu Oct 25, 2007 2:11 pm UTC

aldimond wrote:

Code: Select all

class helloworldawd
{
        public static void main(String args[])
        {
                String a = "Hello, World!";
                barring(a);
                System.out.println("Hello, World!");
        }

        public static void barring(String foo)
        {
                foo = "Barring foo, foo shall be barred!";
        }
}


Heh, not so much. To actually understand why this outputs "Hello, World!" you have to understand what a reference is, and understand what the assignment operator is really doing.


i'd think System.out.println("Hello, World!"); would always output "Hello, World!"...

Code: Select all

factorial product enumFromTo 1
isPrime n 
factorial (1) `mod== 1

mrkite
Posts: 336
Joined: Tue Sep 04, 2007 8:48 pm UTC

Re: Why Java is a bad language for beginners

Postby mrkite » Thu Oct 25, 2007 4:22 pm UTC

Geekthras wrote:Totally do Lisp 8)
(print 'sup)


My CS101 class taught Scheme.... but I hear it's all java now.

User avatar
Pesto
Posts: 737
Joined: Wed Sep 05, 2007 5:33 pm UTC
Location: Berkeley, CA

Re: Why Java is a bad language for beginners

Postby Pesto » Thu Oct 25, 2007 5:03 pm UTC

Shrewtality wrote:What I've perceived is that the people who are knowledged in C and C++ are having a harder time then people who are learning Java as a first programming language, in most cases.

I don't think they have a hard time understanding it. They just don't like it.

I personally don't like it because you have to type five times as much to do basically the same thing. Also, I'm not a fan of such strict adherence to OOP. Being forced to create an object as a container for you main function seems like pounding a round peg into a square hole.
Last edited by Pesto on Thu Oct 25, 2007 5:21 pm UTC, edited 1 time in total.

User avatar
Torn Apart By Dingos
Posts: 817
Joined: Thu Aug 03, 2006 2:27 am UTC

Re: Why Java is a bad language for beginners

Postby Torn Apart By Dingos » Thu Oct 25, 2007 5:15 pm UTC

Java and C/C++, among others, are bad in general because you spend more time fighting the language than writing program logic.

Rysto
Posts: 1460
Joined: Wed Mar 21, 2007 4:07 am UTC

Re: Why Java is a bad language for beginners

Postby Rysto » Thu Oct 25, 2007 6:45 pm UTC

Torn Apart By Dingos wrote:Java and C/C++, among others, are bad in general because you spend more time fighting the language than writing program logic.

I hear this a lot, and as far as I'm concerned, the people who say these things really just don't understand how to program the language they're talking about. I program C for a living and I never have to fight with the language. Most of my school projects and basically all of my personal side projects are in Java and I'm rarely fighting with that language, either. C++ I do have to fight on occasion but that's a consequence of me being a C programmer more than anything.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Why Java is a bad language for beginners

Postby EvanED » Thu Oct 25, 2007 7:40 pm UTC

Rysto wrote:I hear this a lot, and as far as I'm concerned, the people who say these things really just don't understand how to program the language they're talking about.

Yes, but then you have a chicken-egg problem. By definition, someone new doesn't understand how to program the language they are talking about, so so will do a lot of struggling. Have a memory leak in C? I would consider that fighting against the language, at least to some extent. And who doesn't have a few of those when starting out?

This is one reason why I think starting with a "simple" language like Scheme is a good idea: to a large extent, it decouples learning how to program from learning the language, because the latter can be done very quickly.

Once someone learns some techniques for decomposing and formalizing problems, then you can start throwing in things like syntactically more complicated languages, memory allocation, etc.

User avatar
aldimond
Otter-duck
Posts: 2665
Joined: Fri Nov 03, 2006 8:52 am UTC
Location: Uptown, Chicago
Contact:

Re: Why Java is a bad language for beginners

Postby aldimond » Thu Oct 25, 2007 11:54 pm UTC

hotaru wrote:
aldimond wrote:Heh, not so much. To actually understand why this outputs "Hello, World!" you have to understand what a reference is, and understand what the assignment operator is really doing.


i'd think System.out.println("Hello, World!"); would always output "Hello, World!"...


:shock:

I LOL'd.

I could do what many writers of crap programs do and explain the process by which the code came to be that way, and why it's really not as stupid as it looks if you understand the history of the program's development (there are such books about Windows, about C++... and probably shit-tons of them about Unix). But... no.

EDIT: not only can I not code, I can't even get BBcode right.
One of these days my desk is going to collapse in the middle and all its weight will come down on my knee and tear my new fake ACL. It could be tomorrow. This is my concern.

immute
Posts: 20
Joined: Sun May 27, 2007 10:29 pm UTC

Re: Why Java is a bad language for beginners

Postby immute » Fri Oct 26, 2007 1:56 am UTC

photosinensis wrote:The moment I get my own classroom (I intend to do some time teaching), I'm ripping any kind of GUI system out of the computer labs and dropping them onto command-line only Linux thin clients, giving them GCC, vim, and bash, and getting them to be comfortable with those tools first. Of course, they won't code at all for the first semester. They'll go through a basics of computers class, in which they actually get to know what everything is inside their box and what it does. And even then, the first language they see should not be Java, but a language that supports more than one coding paradigm. Object-oriented programming is good for many things, but it isn't the only way--nor is it often the best way. I don't want to know what the one-off prime finder I wrote today in C would have looked like in a strictly OO language.

Yes, that is exactly how it should be taught. Maybe even use Perl, since it (like C++) lets you use the very advanced things to get advanced problems solved, or use just the bare minimum to get something done. And above all, it gives you enough rope to kill your entire family if you aren't careful (or write a ton of line noise).

User avatar
aldimond
Otter-duck
Posts: 2665
Joined: Fri Nov 03, 2006 8:52 am UTC
Location: Uptown, Chicago
Contact:

Re: Why Java is a bad language for beginners

Postby aldimond » Fri Oct 26, 2007 3:33 am UTC

I'm not so sure about perl. Perl gives up a lot of legibility in favor of terseness, and it is very light on compiler errors/warnings, which are usually more useful than just getting broken output.

Python or Ruby might be better, or they might not be; I haven't used either very much.

I wouldn't necessarily dismiss GUIs entirely. If you want to write graphical programs a GUI can help you a lot in designing interfaces. stdin and stdout are just as much abstractions as a GUI layer is. They're just an older and more stable abstraction. If you want to write certain kinds of graphical programs, often the cleanest way to do that is with graphical tools. And event-driven programming is an interesting contrast to the model of most command-line programs, where your code runs from int main(int argc, char** argv) { to return EXIT_SUCCESS; } (or return EXIT_FAILURE; }). It may be that there's no point in introducing GUIs early on, but there might be good uses for them.

I mean, in the end, what gets executed isn't a bunch of text that you write. It's machine code. Whether you generate that machine code by typing "make" or clicking "compile", it's still taking your text and making the machine code. Just a different kind of program is doing it. If you're writing a console app you're writing for a fake VT100. Whether it's the same fake VT100 your editor ran in or not is pretty irrelevant. IMHO.
One of these days my desk is going to collapse in the middle and all its weight will come down on my knee and tear my new fake ACL. It could be tomorrow. This is my concern.

User avatar
Torn Apart By Dingos
Posts: 817
Joined: Thu Aug 03, 2006 2:27 am UTC

Re: Why Java is a bad language for beginners

Postby Torn Apart By Dingos » Fri Oct 26, 2007 9:54 am UTC

Rysto wrote:
Torn Apart By Dingos wrote:Java and C/C++, among others, are bad in general because you spend more time fighting the language than writing program logic.

I hear this a lot, and as far as I'm concerned, the people who say these things really just don't understand how to program the language they're talking about. I program C for a living and I never have to fight with the language. Most of my school projects and basically all of my personal side projects are in Java and I'm rarely fighting with that language, either. C++ I do have to fight on occasion but that's a consequence of me being a C programmer more than anything.

C++ was my first real programming language and I was quite a fan of it back then. But once I learned Haskell and Python I can't stand it. I meant "fighting with the language" in a broader sense of having to focus too much on the language when coding. You have to write too much boilerplate code.

A simple loop shouldn't require me to write all of

Code: Select all

for (int i = 0; i < 10; i++)
{

}
or the even more horrid

Code: Select all

for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
}

mrkite
Posts: 336
Joined: Tue Sep 04, 2007 8:48 pm UTC

Re: Why Java is a bad language for beginners

Postby mrkite » Sat Oct 27, 2007 1:54 am UTC

Here is a good article that demonstrates the pain-in-the-ass-i-tude of Java.

_W_
Posts: 8
Joined: Tue Oct 23, 2007 10:31 am UTC

Re: Why Java is a bad language for beginners

Postby _W_ » Tue Oct 30, 2007 10:58 pm UTC

I don't remember who it was but I believe it was one of the first guys working on Java*, back when it was called Oak, that when asked what single thing he would have done different with the Java language in retrospect, answered "classes" (later explaining he wanted class inheritance gone).

* I don't think it was Gosling, and a quick googling don't turn up any quote like that by his name.
mrkite wrote:Here is a good article that demonstrates the pain-in-the-ass-i-tude of Java.

This problem, and many many many others involving equals, hashCode, etc., comes from allowing class inheritance. Java's OO model is really based upon interface inheritance and explicit delegation. But this is simple to fix; just make every class you write final, and never have an argument or return value of a method that is a direct class, rather than an interface (or a generic). This way, if you want some way to compare instances of your Cat class and your Dog class, you have to use a class implementing Comparator<Animal>, or some other common interface. Dogs should never know about cats, and vice versa. Comparing different animals is not something that belongs in any one animal class either.

Yes, this will often involve creating a lot of interfaces, and possibly extra classes. Worst case, you have an interface for every single class. But no one ever claimed Java's strength lied in not being verbose.


I've coded this way for some years now, and I have to say it avoids a whole god damn lot of issues entirely, with the cost of at worst doubling the time actually spent typing code (which we all know is like 5% of the time spent creating an application), and it turns out much cleaner, more self-explanatory, and better thought through code to boot.




As for what language is best for beginners I never claimed that was Java, but at the same time I don't see what's so bad about it. To become a good programmer, you need exposure to different and diverse programming languages, and I don't think where you start matters all that much. I managed fine learning first C64 BASIC, then 6510 machine code, then assembler mnemonics for said machine code. Java is as good place as any to learn about interfaces vs implementations, static type checking, scope, and almost all of the ideas behind object oriented programming, and the compiler is really good at teaching good practices.

User avatar
e946
Posts: 621
Joined: Wed Jul 11, 2007 6:32 am UTC

Re: Why Java is a bad language for beginners

Postby e946 » Wed Oct 31, 2007 6:22 am UTC

photosinensis wrote:The moment I get my own classroom (I intend to do some time teaching), I'm ripping any kind of GUI system out of the computer labs and dropping them onto command-line only Linux thin clients, giving them GCC, vim, and bash, and getting them to be comfortable with those tools first. Of course, they won't code at all for the first semester. They'll go through a basics of computers class, in which they actually get to know what everything is inside their box and what it does.


While you get started on that, I'll remind all the people who aren't retarded at computers to not waste their time on your class.

User avatar
OOPMan
Posts: 314
Joined: Mon Oct 15, 2007 10:20 am UTC
Location: Cape Town, South Africa

Re: Why Java is a bad language for beginners

Postby OOPMan » Wed Oct 31, 2007 7:36 am UTC

Rysto wrote:
Torn Apart By Dingos wrote:Java and C/C++, among others, are bad in general because you spend more time fighting the language than writing program logic.

I hear this a lot, and as far as I'm concerned, the people who say these things really just don't understand how to program the language they're talking about. I program C for a living and I never have to fight with the language. Most of my school projects and basically all of my personal side projects are in Java and I'm rarely fighting with that language, either. C++ I do have to fight on occasion but that's a consequence of me being a C programmer more than anything.


You make a good point. Many times I've heard people say they're "fighting with the language" it's more often than not due to them using the wrong language.

Simply put, no language is universally good at everything. C and C++ have their place and it's a different place from Java, despite what some may think. Languages like Python and Ruby are in a different place of their own as well, separate from all three of the preceeding langs.
Image

Image

User avatar
blob
Posts: 350
Joined: Thu Apr 05, 2007 8:19 pm UTC

Re: Why Java is a bad language for beginners

Postby blob » Wed Oct 31, 2007 8:35 am UTC

Berengal wrote:I'd love a language with Java's strict type checking AND python's dynamic types, but that's pretty much impossible. Can't have it all.

Haskell and *ML have type inference. It's like static typing, but the compiler declares the variables for you! I'm not sure why it hasn't caught on elsewhere.

Torn Apart By Dingos wrote:C++ was my first real programming language and I was quite a fan of it back then. But once I learned Haskell and Python I can't stand it. I meant "fighting with the language" in a broader sense of having to focus too much on the language when coding. You have to write too much boilerplate code.

A simple loop shouldn't require me to write all of

Code: Select all

for (int i = 0; i < 10; i++)
{

}
or the even more horrid

Code: Select all

for (std::vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
}

It's amazing what C++ templates+macros can do, though. The people over at Boost have an entire functional programming library. There's also Boost.Foreach:

Code: Select all

#define foreach BOOST_FOREACH
short array_short[] = {1,2,3};
foreach(int i, array_short)
{
    // The short was implicitly converted to an int
}
Avatar yoinked from Inverloch.

"Unless ... unless they kill us, then animate our corpses as dead zombies to fight for them. Then I suppose they've taken our lives, AND our freedom."
- Elan, OOTS 421.

User avatar
Citizen K
Posts: 103
Joined: Fri Sep 21, 2007 11:42 am UTC
Location: Maryland

Re: Why Java is a bad language for beginners

Postby Citizen K » Wed Oct 31, 2007 7:55 pm UTC

Berengal wrote:-The inability to "return string, int, myType" instead forcing one to "return new Object[] {[VERBOSITY]}" and subsequent unpacking.

Out of curiosity, can you give a concrete example of what you were doing that required a multi-return ability? (Java is hardly the only language that only allows a single return value)
I've always been sort of on the fence about whether a multi-value return would be a good and useful thing to have in a language. I do like the cleanliness of passing arguments in the top and getting returns off the bottom (and no modifying pass-by-reference things). But it's easy enough to work around and it seems fairly uncommon to have more than one return value that have no business being packaged together in a single object.

I remember doing a lot of pass by reference to get multiple returns back in my Pascal days. But in OOP-land, needing a return value that's more than just a single object or success/error code seems more the exception than the rule.

And to the main thread topic, I absolutely agree that throwing students into OOP without a solid grounding in a nice flat procedural language (Pascal's what we used for years in high school) is a horrible idea. The concepts in the former are entirely built upon those in the latter, and trying to learn both at once is a recipe for trouble.
Beware the cows! Not all milk is enriched.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Why Java is a bad language for beginners

Postby EvanED » Wed Oct 31, 2007 9:10 pm UTC

Citizen K wrote:
Berengal wrote:-The inability to "return string, int, myType" instead forcing one to "return new Object[] {[VERBOSITY]}" and subsequent unpacking.

Out of curiosity, can you give a concrete example of what you were doing that required a multi-return ability? (Java is hardly the only language that only allows a single return value)


I'll give plenty. ;-)

In Java, I have sort of an artificial one, which is that we had a refactoring assignment in a class I was taking. One of the requirements was to keep functions below I think around 65 lines. I was given a function that was about 200 that did lexing. Which meant that it was a giant switch statement with multiple cases. Each case could be made into a function, but the problem was that there were several local variables which each case needed to access and modify. This meant that they needed to be passed into then out of these functions. In general, there were a few solutions I came up with: (1) make them class-level variables, (2) pass-by-reference, but this is unavailable in Java, (3) make a mutable arithmetic wrapper and use those, (4) return a class with several, largely unrelated values. I went with the fourth option.

In general, there are a lot of places where you want to do something, then say whether that something was done. Several instances of this:

I would say a majority of the Windows driver API follow a scheme where the return value is always an error code, then the actual result is put in a pass-by-pointer parameter.

In the C++ STL, the set and map insert() functions return a pair of values: a boolean indication of whether it was inserted (false if the element was already present) and an iterator to to the value if it was inserted.

One that I encountered recently was in the Intel Thread Building Blocks library. There is a place in there where you have to write a function that produces more work: it returns an object of a type "task" or something like that. But it also needs to return an indication of whether there is more work. Hence the task is stored in a pass-by-reference parameter, and a boolean return value indicates whether there actually was more work to do.

In a homework assignment, we had to write (well, modify) a concurrent tree that presented a transactional interface: so you could say tree.InitiateTransaction(); then do some tree.TransactionalSet() and tree.TransactionalLookup() calls and such that would provide atomicity and isolation guarantees. If the guarantees can't be satisfied, the transaction must be aborted, and the calling code notified. If a TransactionalSet or TransactionalLookup call cannot complete, it needs to notify the calling code of this. TransactionalSet isn't an issue, but TransactionalLookup needs to return both the requested item and this indication. Again, the return value indicates whether the call succeeded, and the result goes into a pass-by-reference parameter.

pthread_create() puts the thread ID of the newly created thread in a pass-by-pointer parameter, and returns an error code.

I could go on and on... this idiom is extremely common.

User avatar
Berengal
Superabacus Mystic of the First Rank
Posts: 2707
Joined: Thu May 24, 2007 5:51 am UTC
Location: Bergen, Norway
Contact:

Re: Why Java is a bad language for beginners

Postby Berengal » Wed Oct 31, 2007 10:45 pm UTC

I'll give another example:
As part of a cs class assignement, I made a method finding the root of a mathematical function using one of several different methods. It had to return the root (if it found one), the root, and the number of iterations used to find it.
It is practically impossible to teach good programming to students who are motivated by money: As potential programmers they are mentally mutilated beyond hope of regeneration.

User avatar
Citizen K
Posts: 103
Joined: Fri Sep 21, 2007 11:42 am UTC
Location: Maryland

Re: Why Java is a bad language for beginners

Postby Citizen K » Thu Nov 01, 2007 1:42 pm UTC

EvanED wrote:I could go on and on... this idiom is extremely common.

Which doesn't necessarily make it right, of course :)

My intuition (which may be faulty) is that if you find yourself needing to do this in an OOPL, nine times out of ten a little refactoring will get around it, and leave you with a design that is at least as legible as where you started.

For example:
Berengal wrote:As part of a cs class assignement, I made a method finding the root of a mathematical function using one of several different methods. It had to return the root (if it found one), the root, and the number of iterations used to find it.

A prime candidate for refactoring. Create a RootFinder abstract class, with methods like:
void setFunction( Function f )
abstract int findRoots() //just processing, return an error/success code
float[] getRoots() //return any real roots found by the processing
ImaginaryNumber[] getImaginaryRoots() //return any imaginary roots found by the processing
...and so on. Then create a set of subclasses for your different root-finding methods that just implement the findRoots() method.
Another advantage of this sort of design is that it makes it easy to push the heavy lifting work off into another thread to process (passing around your RootFinder once its been initialized with a function), then collect the results once it's finished.

EvanED wrote:One of the requirements was to keep functions below I think around 65 lines. I was given a function that was about 200 that did lexing.

You're right, that is a pretty artificial example. It is possible, especially in a situation like that, to have a function that's well-written, legible, and also pretty long. Breaking up a big switch statement just to get line counts down seems silly unless it has some other benefit.

In the C++ STL, the set and map insert() functions return a pair of values: a boolean indication of whether it was inserted (false if the element was already present) and an iterator to to the value if it was inserted.

That design seems redundant. If the caller cares whether the item is already in the set, wouldn't a set.contains() call suffice? If the value that gets inserted isn't necessarily the one passed in, just return the one that got inserted or was found already in the set (or null if there was some sort of problem).

One that I encountered recently was in the Intel Thread Building Blocks library. There is a place in there where you have to write a function that produces more work: it returns an object of a type "task" or something like that. But it also needs to return an indication of whether there is more work.

See my first example. "Give me the next chunk of work" and "Are there any more chunks after the current one?" are two separate questions and should be two separate methods for you to implement.

In a homework assignment, we had to write (well, modify) a concurrent tree...

Okay, this one's a bit stickier. I start thinking about database APIs here. The usual approach might be to have something throw a checked exception if your transaction suddenly becomes invalid (since you really have no idea when that may happen, as it may be caused by another thread's operations). Though I also never like the idea of using exceptions as a lame excuse for returning normal error codes. Seems like it would be nicer if this design had some sort of Transaction object which holds a sequence of commands, and can be easily committed, rolled back, etc.

pthread_create() puts the thread ID of the newly created thread in a pass-by-pointer parameter, and returns an error code.

I don't know, seems like having a sort of factory setup here would be just as nice, then the factory could keep track of any error for perusal at your convenience. Though this may be an instance where a checked exception would be more appropriate -- isn't it usually seriously bad news if you can't get a new thread created? (As in, really hard to keep doing what you were trying to do until it works, and good odds of it failing again if you just keep trying.)
Beware the cows! Not all milk is enriched.

EvanED
Posts: 4331
Joined: Mon Aug 07, 2006 6:28 am UTC
Location: Madison, WI
Contact:

Re: Why Java is a bad language for beginners

Postby EvanED » Thu Nov 01, 2007 3:19 pm UTC

Citizen K wrote:
EvanED wrote:One of the requirements was to keep functions below I think around 65 lines. I was given a function that was about 200 that did lexing.

You're right, that is a pretty artificial example. It is possible, especially in a situation like that, to have a function that's well-written, legible, and also pretty long. Breaking up a big switch statement just to get line counts down seems silly unless it has some other benefit.

True. Though this function in particular was both poorly written and extremely long. ;-)

In the C++ STL, the set and map insert() functions return a pair of values: a boolean indication of whether it was inserted (false if the element was already present) and an iterator to to the value if it was inserted.

That design seems redundant. If the caller cares whether the item is already in the set, wouldn't a set.contains() call suffice? If the value that gets inserted isn't necessarily the one passed in, just return the one that got inserted or was found already in the set (or null if there was some sort of problem).

True, there may be other ways to do it. Doing set.find(key) then set.insert(key) is not great though: you have two traversals through the tree. The STL set can help you though, because there's a form of insert that takes an iterator as a hint and reduces insert time from O(log n) to O(1). I think the final code is:

Code: Select all

set<T>::iterator iter = myset.lower_bound(search_key);
if(*iter != search_key) {
    iter = myset.insert(search_key, iter);
}

There is at least one issue with this, which is that if you have a locked tree structure, "insert this item and tell me if it was there" is an atomic operation that doesn't require external locking if it uses the STL interface, and it is not if it needs two separate calls. (Of course, if you then want to *use* the iterator you get back, you need external locking anyway, so this is probably a pretty poor argument.) In this case you still have the option of returning an invalid iterator for the "not present" case, but then you're not returning the position of the existing value if there is one.

Citizen K wrote:
In a homework assignment, we had to write (well, modify) a concurrent tree...

Okay, this one's a bit stickier. I start thinking about database APIs here. The usual approach might be to have something throw a checked exception if your transaction suddenly becomes invalid (since you really have no idea when that may happen, as it may be caused by another thread's operations). Though I also never like the idea of using exceptions as a lame excuse for returning normal error codes. Seems like it would be nicer if this design had some sort of Transaction object which holds a sequence of commands, and can be easily committed, rolled back, etc.

I think the use of an exception wouldn't be too bad in this case.

I *don't* like the idea of a separate transaction object though, because if you're thinking what I'm thinking, you wouldn't be able to make decisions based on lookups in the transaction unless you built in potentially arbitrarily-complex evaluation (or had callbacks). For instance, if your transaction object is just a straight list of operations, you wouldn't be able to say "remove an item with this key if the value is 0".

I think an exception is the best approach here.

Though this may be an instance where a checked exception would be more appropriate -- isn't it usually seriously bad news if you can't get a new thread created?

Probably, though I guess not necessarily. Though remember, pthread_create() is an interface that should work in C. Hence you have to find an error reporting mechanism other than exceptions.
Last edited by EvanED on Thu Nov 01, 2007 3:44 pm UTC, edited 3 times in total.


Return to “Religious Wars”

Who is online

Users browsing this forum: No registered users and 5 guests