Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Chairman Steve
Mar 9, 2007
Whiter than sour cream

Flobbster posted:

This is what wildcards are for. If you want a method that takes a List of anything, do this:

Anyone using wildcard generics should also be familiar with the PECS rule:

http://groups.google.com/group/juglugano/browse_thread/thread/c11531309ed37646?pli=1

If you don't understand the proper usage of super and extends, you'll be missing out on a significant bit of the power of Java's wildcard generics.

Adbot
ADBOT LOVES YOU

Chairman Steve
Mar 9, 2007
Whiter than sour cream

UberJumper posted:

Does such a thing exist? Also any suggestions to turn this from a monster into something not as ugly.

An IDE should help "suggest" good coding principles. Eclipse (and I don't imagine this is restricted to just Eclipse) has a shortcut key combination of Ctrl + Shift + F to format your code nicely.

Chairman Steve
Mar 9, 2007
Whiter than sour cream

UberJumper posted:

1. Is it bad practice to fully write out the namespace (or package) of uncommon types?

Not necessarily. However, IDEs like Eclipse have visual cues (and provide Javadoc when you hover over the reference) to let you know which one it is. The problem with verbosity in your code is that it can become cluttered pretty easily (especially with longer package names, such as org.springframework.instrument.classloading.weblogic. Unless I have references to two different classes by the same name, I don't use their canonical names.

quote:

2. Is there anyway i can get a POD datastructure?

I'm not sure exactly how you're transforming an object to packets, but if you're dealing with streams, I might recommend a combination of ByteArrayInputStream and IOUtils, combined with your own implementation of OutputStream to convert the byte array into an object.

If you're disgruntled with getters and setters, be aware that accessing objects' fields directly is generally a bad idea. You can't enforce any kind of business rules on your objects, and, if there's any kind of logic you want to perform whenever someone accesses or sets your fields, you're SOL.

Additionally, if you're not aware of the exact length of the byte array that you're going to build, I'd recommend creating a Collection<Byte>, adding each of the sets of bytes as you go, and use the [url=http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/java/util/Collection.html#toArray(T[])]toArray(T[])[/url] method to convert it to a byte array.

quote:

Does anyone have any good recommendations for links about threading for java?

I don't (I know that's not helpful, but I didn't want you to think I had missed this question).

If you're seriously interested in learning Java, then pick up the Java Bible:

http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/ref=sr_1_1?ie=UTF8&s=books&qid=1278636056&sr=8-1

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Shavnir posted:

Are there really any other major "must have" books for bookshelves of Java programmers or is Effective Java it?

I've never read Ritual's book, so I can't endorse it (nor will I discourage reading it, of course :)), but, beyond these books, I've heard good things about POJOs in Action. Really, there's only so much you can read about Java syntax - beyond that, reading is more applicable to specific frameworks or platforms, such as J2EE, Hibernate, Spring, JUnit, Eclipse RCP, OSGi bundling...

Of course, all reading really does is prepare you for your work - it's the actual experience that will make you a better programmer. Reading just lays down the foundations.

[ Edit: I should note that Effective Java doesn't introduce revolutionary concepts that will rock the foundation of your perception of object-oriented programming. What it contains are a bunch of concepts where you'll read it and go, "Huh. That makes sense." It's all stuff that you would have figured out after years of trial-and-error and general work experience. It just saves you the time of having to learn those lessons yourself and supporting the code you wrote when you hadn't yet learned those lessons. ]

Chairman Steve fucked around with this message at 02:32 on Jul 10, 2010

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Notorious H.P.B. posted:

I hope this makes sense.

What zootm posted works sufficiently for testing (though I would always use Reflections as a last resort, in testing or production code). However, in future designs, getter/setter methods are good idea. If I want to maintain the immutability of an object's fields (i.e., no public getter/setters and no protected getter/setters to be used by a subclass of the given class), I make the setter method package-private - that way, the method is only exposed to classes within the same package (which includes the JUnit tests). Some might argue that it's still exposure because a programmer can make their package the same as your class' package, but the immutability of a class is still vulnerable as long as the Reflections API is allowed via security permission (which, if you're using Spring, I imagine it is).

Chairman Steve
Mar 9, 2007
Whiter than sour cream

zootm posted:

For what it's worth I find getters/setters a bad paradigm as they make it impractical or impossible to use the language's built-in features for enforcing some degree of immutability, but constructor injection is definitely worthwhile.

Definitely. I like constructor injection because it ensures that all dependencies are accounted for (assuming proper constructor...er...construction). My personal preference is to write an interface with only getters (no setters) and implement it with an object that has setters - effectively, the consumer has no idea about the setters and sees only the interface, but I'm still able to override and inject for testing. I probably should have mentioned that in my original post.

Oh, interfaces. :allears:

Chairman Steve
Mar 9, 2007
Whiter than sour cream

TRex EaterofCars posted:

Do you name everything IFoo and/or FooImpl? That's the part of that paradigm that I hate.

I go the route of naming the interface the noun or adjective it represents ("Car" or "Driveable"), which satisfies the "is/isa" kind of relationship that an interface is supposed to be in Java. I used to do the *Impl pattern, but I've moved to the following:

  • For a default implementation that's to be used in lieu of an implementation provided via IoC, I use Default*.
  • Otherwise, I name it depending on what backs the implementation - JdbcCar, XmlCar, HibernateCar, JpaCar, etc. It describes what the object is and how it's implemented.

[ Edit: I hate the ICar naming convention. It violates the nature of interfaces, in my opinion - you don't go around naming your classes "CCar" or "CDriveable", do you? ]

Chairman Steve
Mar 9, 2007
Whiter than sour cream

RitualConfuser posted:

If you're the former I'd say that there are reasons why you should learn a lower level language like C first before moving to a language like Java. There are also arguments for learning a language like Java or Python first. This seems to be widely debated, so take that with a grain of salt.

This. I'd rather claw my eyes out with a spork than write C for a living (I write Java at the moment), but taking a semester on C in college gave me such a better understanding of memory and pointer management than I ever got in the two Java classes I had taught before it. There's sometimes value in learning where you've come from.

Chairman Steve
Mar 9, 2007
Whiter than sour cream
^^ Agreed.

Honestly, I'd like into using something that's IDE-agnostic, such as Maven, to build your project. It has an Eclipse plugin that can be used to generate Eclipse project artifacts by reading the project's POM.

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Parantumaton posted:

This sentence started with such great potential... (I don't mean that Maven wouldn't be IDE-agnostic, it's more like reality agnostic).

Eh? Care to elaborate?

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Is it in any way possible that it has something to do with Java's caching of DNS resolution[1]?

http://myhowto.org/java/42-understanding-host-name-resolution-and-dns-behavior-in-java/

Chairman Steve
Mar 9, 2007
Whiter than sour cream

omlette-a-gogo posted:

In fact I do this so often I wrote a helper class that I am always reusing:

http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html#closeQuietly(java.io.InputStream)

Learn to love Apache commons! :eng101:

Or for some Java 6 goodiness: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Closeables.html#closeQuietly(java.io.Closeable)

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Or use the file-read methods of FileUtils[1] or Files[2].

1. http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#readLines(java.io.File)
2. http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Files.html#readLines(java.io.File, java.nio.charset.Charset)

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Yeah, Guava and Apache Commons are pretty useful. I like to use Guava when I get to use Java 6 (we frequently do Java 5 at work) because it uses generics, where as Commons does not, either by lack of maintenance or intentional support of Java 4.

Chairman Steve
Mar 9, 2007
Whiter than sour cream

fart factory posted:

This closes the frame fine, but although the owner frame is no longer displayed, the thread continues to run. I wanted to use System.exit(0) on the owner frame, but don't know if this is possible.

System.exit(0) is very, very rarely a workable solution. I try to avoid it whenever possible.

That said, would this:

http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation(int)

...plus this:

http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html#EXIT_ON_CLOSE

...do the trick?

Chairman Steve
Mar 9, 2007
Whiter than sour cream
If you're worried about overflow, you might as well just accept two longs and return a long, unless you're worried about memory consumption.

Chairman Steve
Mar 9, 2007
Whiter than sour cream

mister_gosh posted:

What is the answer here? Is making this serializable the easy answer? Would I be required to store that connection data to a stream? Or is this a deeper issue or some other easy solution?

Why not use connection pooling? You can potentially take a page from the JDBC API - they have a DataSource object which may (or may not) be used to represent a connection pool from which Connection[2] objects are either checked out or created (as needed). When a consumer invokes the close method on the Connection object, it's not physically closed - it's checked back into the connection pool, where it waits to either be checked out by another consumer or physically closed by the connection pool per whatever eviction policy it follows.

1. http://download.oracle.com/javase/6/docs/api/javax/sql/DataSource.html
2. http://download.oracle.com/javase/6/docs/api/java/sql/Connection.html

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Chinapwns posted:

Why do people use arrays? This might sound stupid but it seems to me that ArrayLists are better in pretty much every way.

You'll see char arrays used to store passwords (rather than String objects) because it's always passed by reference and is mutable (Strings are not the latter). This allows the password to be zeroed out when it's no longer needed, which prevents the password from being potentially dumped out as part of a heap dump. But, yeah, starting with Java 5, there's rarely a good reason to use an array over a List implementation.

For what it's worth, I hope nothing you write is explicitly returning an ArrayList. You should always return a List reference, as that gives you the freedom to use whatever implementation of the List interface that you want without having to worry about passivity issues.

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Alternatively, you could use Reflections to modify the underlying character array within a String object. :downs:

Chairman Steve
Mar 9, 2007
Whiter than sour cream
If you ever need to do anything beyond a simple URL (POST parameters, and possibly even for a URL with a query string), Apache's HttpClient library is pretty durn nice: http://hc.apache.org/httpclient-3.x/

Chairman Steve
Mar 9, 2007
Whiter than sour cream
While that's odd, alternatively:

code:
C:\>java -version
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) 64-Bit Server VM (build 17.0-b17, mixed mode)

Chairman Steve
Mar 9, 2007
Whiter than sour cream

MariusMcG posted:

I'm building a project in Eclipse that uses some third-party libraries. I've placed those libraries in my GlassFish domain/lib directory so that they're getting auto-loaded when the server starts. Is there a way to configure my Eclipse project so that it will expect to use the libraries on the server instead of bundling the libraries inside of the WAR file?

I find it generally a good idea to have WARs "isolated" with all of their dependencies within the WAR itself, except in the case of licensing issues that would prevent shipping them with your project (such as MySQL JDBC drivers). That way, you never ever have to worry about the wrong version of code into a web app. For example, say you're dependent on v1.2 of com.foo.Bar with method fooBar(); however, that method doesn't exist in v1.1. However, some other app needs v1.1 of com.foo.Bar - consequently, the app that needs version 1.2 will fail with a NoSuchMethod exception.

Even if it's a licensing issue, try to include everything you need for the app that can be packaged into it and then resort to common lib directories for those that you can't package in the WAR.

Chairman Steve fucked around with this message at 03:42 on Oct 11, 2010

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Baby steps. Let's get Java 7 out the door first.

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Set the body of the e-mail as the HTML and the context type to text/html?

Chairman Steve
Mar 9, 2007
Whiter than sour cream
I do. I used to use JDeveloper (*shudder*) to do Swing editing using a GUI-based designer, and it...wasn't the best.

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Step 1 would be to not use a text editor and use an IDE. There are so many different objects you'll use in GUI programming that it'll be more of a headache than it's worth to manage your imports, not to mention other benefits of using an IDE. Trust me - when I studied Java in college, my TAs and professor were adamantly opposed to using IDEs, and I hate them every day for it.

This article[1] seems to have a good intro to Swing.

As for IDEs, I use Eclipse. I can't speak to other IDEs, but Eclipse does what I need to do and it does it well enough, from what I can tell. You mentioned that diving into an IDE can be overwhelming; that's true of Eclipse. The first thing you do when you start up Eclipse is to close the drat welcome screen, because that thing's useless. This PDF[2] speaks to an old version of the IDE, but it looks like most of the workflows are still applicable. If you're feeling adventurous, I'd recommend also looking into Maven[3].

If anyone tells you to bypass Swing and use something like RCP, politely tell them that you're just starting to learn how to program in Java and that trying to wrap your head around OSGI, classloaders, fragments, and bundling would just be a total mindrape.

1. http://www.javabeginner.com/java-swing/java-swing-tutorial
2. http://cs.armstrong.edu/liang/intro5e/SupplementJEclipse.pdf
3. http://maven.apache.org/

Chairman Steve
Mar 9, 2007
Whiter than sour cream
You can't use a while() { } loop because it's going to run on the same thread as the display, so it's going to block any ability for the Swing code to do anything until the while() { } loop breaks (inclusively, it will block your ability to interact with the JFrame).

You may want to look into implementing a TimerTask[1] object that closes the JFrame and kick it off using Timer[2]. When the user clicks the button, just use the TimerTask object's cancel() method.

I'd recommend using a class-level boolean to indicate whether or not the TimerTask has been cancelled. cancel() sets the boolean to true and the run() method will check that boolean before trying to execute. Because it's a multi-threaded application, I would recommend synchronizing around a lock object. If you're on Java 5 or greater, you can probably use a ReentrantLock object[3], or just declare a class-level Object and use it in a synchronized() { } object.

1. http://download.oracle.com/javase/1.4.2/docs/api/java/util/TimerTask.html
2. http://download.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html#schedule(java.util.TimerTask, long)
3. http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Or just use this method: http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly(java.io.Closeable)

Chairman Steve
Mar 9, 2007
Whiter than sour cream
My work uses RESTful URLs. Our requests are fairly simple, so I would think that, if you have extremely complex requests (which can only be simplified otherwise by maintaining state on the server), you might want to go with SOAP. My general sentiment is that, more times than not, most anything that is currently accomplished in SOAP can be done with RESTful URLs, and those are typically very much easier to consume.

Chairman Steve
Mar 9, 2007
Whiter than sour cream

MariusMcG posted:

Based on the learning I've done thus far on this subject, I think I'd agree with you. Even for web services where I'll be using XSDs, RESTful services should do the job nicely, and more intuitively to boot. Then again, I haven't yet researched the advantages of SOAP in regards to security, which is where I'd really have an uphill battle at work...

I'd say keep authentication and authorization separate from the API's language. Use something like OpenID to authenticate (which opens you up to allowing people to log in using things like their GMail account) and OAuth to authorize users. Otherwise, you'll have to deal with things like sharing of keys to encrypt the SOAP request, which would probably contain your username and password, when it's sent from the client to the server.

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Be aware of the waitFor() method and the destroy() methods. Otherwise, you might end up with InterruptedExceptions and the like.

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Your constructors for "Student" and "GradStudent" have the "void" keyword in them. Constructors don't have the return type semantic.

Chairman Steve
Mar 9, 2007
Whiter than sour cream
Oh, God, please capitalize the l in Loader and the m in Midlet.

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Rohaq posted:

Well jeez, sorry. I've just started in Java, and I've never seen a programming language where its users/maintainers actually attempt to enforce a particular formatting standard for names...

Are you using any kind of IDE? If not, I realize it adds a little bit to the learning curve at the beginning, but it's a bigger pay-off in the end: for example, in Eclipse, it would have given you warnings about the casing of your class name.

One of Java's biggest strengths are things like Javadoc, which are hooks built into the specification that facilitate documentation of code and conveyance of that documentation. Thusly, consistency in styling lends itself toward improved documentation, which results in better understanding by others. I don't mean to jump down your throat (and apologize if it came off that way) - styling habits can be difficult to change later in development, and establishing good habits earlier makes it easier for you to later maintain the code you write now.

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Rohaq posted:

Oh Goddamnit, I've got an enumerator in my code too. Back I go!

Just to make sure it's clear: the proper declaration of an enum is a mix of camel case and all caps:

code:
public enum ThisIsAnEnum {
OPTION_ONE,
OPTION_TWO;
}

Chairman Steve
Mar 9, 2007
Whiter than sour cream
They're a God-send when you're using multiple third-party libraries - without them, a deployer would have to configure JDK logging, Log4j logging, and Commons Logging for a single application.

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Aleksei Vasiliev posted:

Using it on a field throws an error to let you know you're...

Not in this case. If you look at the Javadoc[1], the annotation's only targeted to methods. While it's definitely used to let you know that you're not overriding a method when you think you are, the reason it throws an error when used on a field is because it's a compilation error (rather than a "you're not overriding anything" error).

1. http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Override.html

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Thermopyle posted:

edit: Or the meta-question is, "what's the best way to convert txt to total seconds?"

Would something like Joda-Time[1] fit your needs?

1. http://joda-time.sourceforge.net/

Chairman Steve
Mar 9, 2007
Whiter than sour cream
You should read Sun's documentation on serialization[1]. I suspect your list isn't getting serialized. Also, for the benefit of anyone who has to read your code, learn about Java's variable naming conventions[2].

1. http://java.sun.com/developer/technicalArticles/Programming/serialization/
2. http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html

Adbot
ADBOT LOVES YOU

Chairman Steve
Mar 9, 2007
Whiter than sour cream

Contra Duck posted:

...you might as well go with ArrayList which is far more common and provides better performance.

Unless random access is of dire importance, isn't a LinkedList the best to use, since you don't have to deal with array resizing?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply