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
Sedro
Dec 31, 2008
It's important to follow Java naming conventions whether you like them or not. Beyond that, follow the convention used by the project. Java convention says not to prefix variables, so you're right - you'll have to use this.

Curious, how do you guys differentiate interfaces vs implementations?
code:
interface Foo;
class FooImpl implements Foo;

Adbot
ADBOT LOVES YOU

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."

Mustach posted:

Same goes for the horrifying convention of prefixing member variables with m_.

I don't think programmers will ever stop reinventing Hungarian notation. It's a tenaciously bad idea.

zeekner
Jul 14, 2007

Internet Janitor posted:

I don't think programmers will ever stop reinventing Hungarian notation. It's a tenaciously bad idea.

pH'nglui mGlw'nafh mHungarian r'Lyeh wGah'nagl fHtagn.

Milotic
Mar 4, 2009

9CL apologist
Slippery Tilde

Sedro posted:

It's important to follow Java naming conventions whether you like them or not. Beyond that, follow the convention used by the project. Java convention says not to prefix variables, so you're right - you'll have to use this.

Curious, how do you guys differentiate interfaces vs implementations?
code:
interface Foo;
class FooImpl implements Foo;

You call it IFoo, and try to avoid anything like IInternet, as it looks dumb. :colbert:

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
I've never been a fan of the "I" prefix for interfaces. I prefer to make my interface names adjectives, which is the convention the standard APIs seem to use- Serializable, Comparable, Readable, Cloneable, etc.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
I use the "I" prefix for interfaces, which leaves the base word free for an abstract class if necessary. It's better than calling your abstract class a FooAdapter or something like that.

Since I haven't seen an IDE that syntax-colours interfaces differently from classes, it's nice to be able to distinguish them at a glance.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Jabor posted:

I use the "I" prefix for interfaces, which leaves the base word free for an abstract class if necessary. It's better than calling your abstract class a FooAdapter or something like that.

Since I haven't seen an IDE that syntax-colours interfaces differently from classes, it's nice to be able to distinguish them at a glance.
Why do you need interfaces to be different colors?

1337JiveTurkey
Feb 17, 2005

To take a somewhat fundamentalist position, the only place that you should really be referring to the implementation class outside of its implementation should be the constructor. If that's the case, then the interface shouldn't have its name mangled.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Aleksei Vasiliev posted:

Why do you need interfaces to be different colors?

The same reason you want keywords to be coloured differently to class names.

That is; you don't. But it's a nice-to-have.

Milotic
Mar 4, 2009

9CL apologist
Slippery Tilde

1337JiveTurkey posted:

To take a somewhat fundamentalist position, the only place that you should really be referring to the implementation class outside of its implementation should be the constructor. If that's the case, then the interface shouldn't have its name mangled.

You create an interface for every class you produce? Don't you find it slightly tedious, and often doesn't add much/any value?

Internet Janitor posted:

I've never been a fan of the "I" prefix for interfaces. I prefer to make my interface names adjectives, which is the convention the standard APIs seem to use- Serializable, Comparable, Readable, Cloneable, etc.

Not everything is best expressed as an adjective though. Many objects are best expressed as nouns - INode, ICustomer, IConnection, IWannaKnowWhatLoveIs. Back in the day, Eclipse (or maybe it was Netbeans), would always moan at you for using an interface not prefixed with the letter I. And all the .NET libraries use "I" as a prefix. It's a good signal so you don't waste 3s trying to type
code:
x = new Serializable()

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Milotic posted:

You create an interface for every class you produce? Don't you find it slightly tedious, and often doesn't add much/any value?
If you're using an interface, then you shouldn't be referring to the implementing class outside of construction.

Milotic
Mar 4, 2009

9CL apologist
Slippery Tilde

Aleksei Vasiliev posted:

If you're using an interface, then you shouldn't be referring to the implementing class outside of construction.

Ah right, gotcha. Definitely agree for 99% of all cases. Sometimes there's a 1% edge case where you just have to do an instanceof check.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
I'm not much of a fan of "BlahImpl" because it carries the implication that you're only ever going to use that class to implement the interface anyhow and have probably gone overboard with OO. "DefaultBlah" is a tiny bit better because it implies someone might actually want to do something differently and make another implementation, but it still feels icky.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I kind of like using the interface name in the implementation class name. i.e. I made an interface called ComponentCommunicator, and it defines the type of messages you can send to Component. Then the implementations are called things like RestfulComponentCommunicator, SoapComponentCommunicator, ProtobufComponentCommunicator.

Max Facetime
Apr 18, 2009

1337JiveTurkey posted:

To take a somewhat fundamentalist position, the only place that you should really be referring to the implementation class outside of its implementation should be the constructor. If that's the case, then the interface shouldn't have its name mangled.

The collection classes are a good example of this in action.

There are interfaces (Map, List), which have short and easy names.

There are implementing classes (HashMap, TreeMap, ArrayList, LinkedList). These summarize their gimmick in their names.

There are base classes to help with new implementations (AbstractMap, AbstractList). Their names are long and ugly, but that's OK because they should never be mentioned outside classes that extend them.

Code should be written against the interfaces as much as possible. By giving the shortest, easiest to type names to interfaces the naming convention encourages best practices.

JingleBells
Jan 7, 2007

Oh what fun it is to see the Harriers win away!

I'm having some trouble with various JAXP implementations and some XML I've got.
I'm using JWebUnit with HTMLUnit to test a webpage which is using AJAX to retrieve some XML from the server, the XML has empty CDATA sections in it, like so:
code:
<xml>
   <node1><![CDATA[Text]]></node1>
   <node2><![CDATA[]]></node2>
</xml>
When good old Internet Explorer receives the XML it leaves it in a DOM as above, with empty CDATA section, the javascript code then refers to the text inside this section using a hard coded path (e.g. dom.getElementsByTagName("node2")[0].childNodes[0].nodeValue -treating the CDATA node as being an actual node).

JWebUnit mimics a web-browser, including down to handling XML via AJAX - however it uses a JAXP DocumentBuilderFactory implementation to get the String into an XML object.

The XML becomes as follows:
code:
<xml>
   <node1><![CDATA[Text]]></node1>
   <node2/>
</xml>
and our tests fail as the javascript breaks

I've tried the following JAXP implementations:
Built in Java 1.6
Xerces 2.9 & 2.11
Oracle XDK
Crimson
Saxon 9.2 & 9.3 (Interestingly 9.3 has deprecated the DocumentBuilderFactorImpl and suggests using Xerces)

All of them remove the empty CDATA node.

I know the problem is actually due to the way Microsoft parse XML in Internet Explorer, but I can't change the web application code, nor can I change from JWebUnit + HTMLUnit - are there any other JAXP providers I've missed? The only resources I've found referring to this seem very out of date.

Otherwise I'm going to have to break the HTMLUnit code and manually try and add empty CDATA nodes once the String has been parsed into a Document, which won't be pretty

JingleBells fucked around with this message at 00:19 on Sep 5, 2011

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."

I am in posted:

The collection classes are a good example of this in action.
...

I agree with everything in this post. In general the Java Collections API is one of the best designed corners of the standard library and well worth imitating.

JingleBells
Jan 7, 2007

Oh what fun it is to see the Harriers win away!

If anyone cares I've managed to find a workaround for my XML parsing issues - I found that someone had submitted a patch to Xerces for this, but it's never been implemented.

So I built myself a copy of Xerces with the patch, and then had to fix a bug in HTMLUnit where if it's mimicing Internet Explorer it treats empty DOM Text nodes as empty nodes and uses the short form XML, and CData nodes are subclasses of DOM Text nodes - so they also get shortened.

Not sure whether to submit the bug to the HTML Unit team seeing as it only appears when using a hacked XML parser

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
I'm taking my introduction to Java programming class this fall, and I'd like to get some practice using the language before classes begin. Right now though it seems that most of the resources available on the internet are for version 6 instead of 7. Will I be fine studying off of the version 6 materials for the basic foundational programming aspects of Java?

For reference, I've been going over The New Boston's introductory java programming videos, and there don't seem to be any problems despite the fact that he's using version 6 and I'm using 7.

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
Java doesn't change anything between versions, too much. All the major changes from 6 to 7 are either under the hood or advanced features you will probably never encounter.

Hidden Under a Hat
May 21, 2003
I'm curious, what are people's opinions on using multi-dimensional arrays? I found myself using a four dimensional array recently and thought to myself that it was going a bit too far and was making it difficult to read, even though I could follow it.

epswing
Nov 4, 2003

Soiled Meat
For your particular situation what would have been your alternative?

crazyfish
Sep 19, 2002

I've found myself doing the equivalent using collections, doing things like creating a Map<String, Map<Integer, String>> or something like that. It can get verbose as hell, as you might anticipate.

bitreaper
Jan 1, 2007

I'm a C++ developer most of the time, playing with writing games for my phone so I'm in Java land for the immediate future. I'm trying to figure out best practices, canonical Java ways of doing things. I'm having this one recurring issue and I'd really appreciate it if someone could point me in the right direction.

In C++ I use RAII for memory/resource management. All the time, for everything. I know that I can't use RAII in Java because it lacks deterministic destruction; I have to wrap every resource-managing object in a try/finally block if I want my program to be deterministic (read: correct). This is maddening and ugly and I would like to not have to do it. How do you get around this? There has to be a solution here.

1337JiveTurkey
Feb 17, 2005

bitreaper posted:

I'm a C++ developer most of the time, playing with writing games for my phone so I'm in Java land for the immediate future. I'm trying to figure out best practices, canonical Java ways of doing things. I'm having this one recurring issue and I'd really appreciate it if someone could point me in the right direction.

In C++ I use RAII for memory/resource management. All the time, for everything. I know that I can't use RAII in Java because it lacks deterministic destruction; I have to wrap every resource-managing object in a try/finally block if I want my program to be deterministic (read: correct). This is maddening and ugly and I would like to not have to do it. How do you get around this? There has to be a solution here.

Java 7 has automatic resource management blocks for anything which implements Autocloseable I think. To use them, you write (I'm still working on a Java 6 product so this is from memory):

code:
try (BufferedReader br = new BufferedReader(new FileReader(someFile))) {
    // Reference br as normal, close() is called when you leave scope
}
catch (IOException e) {
    // This also covers any exceptions that are thrown in close()
}
A couple of related notes:

First, Java finalize methods get brought up a lot in this context by people who want destructor-like behavior but they're generally to be avoided. Among other reasons, they're not always run if the VM is abnormally terminated in certain circumstances. There's also a significant performance penalty due to how compacting garbage collectors operate and how finalizers mess up any assumptions about what's really absolutely unreachable ever again.

Second, relatively small (64 bytes IIRC) objects which don't escape the local scope are stack allocated in later versions of Java 6 and Java 7. This means that they do have deterministic deallocation in that case. Unfortunately finalizers also break escape analysis for similar reasons so objects with them are still always heap allocated.

TheReverend
Jun 21, 2005

Regarding Java and XML:

There is like 4 or 5 different XML parsers and they all seem unnecessarily complicated compared to how I deal with XML in .NET.

Anyways, I have a simple table like this:

code:
<Doc>
   <Item>
      <Name>Cat</Name>
      <Color>Black</Color>
   </Item>
   <Item>
      <Name>Dog</Name>
      <Color>White</Color>
   </Item>
</Doc>
All I want to do is read in the XML file, add a row, and write the modified file back to disk. What's the simplest way of doing this? Is it through the SAX parser?

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
I use JDOM, and it's really, really easy. When you read in the file, it forms a tree of Elements, which have all the relevant things associated with them.

epswing
Nov 4, 2003

Soiled Meat
Yep. JDOM!

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!
I find XOM 1000 times easier than JDOM.

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
I didn't know it could get even easier than JDOM.

TheReverend
Jun 21, 2005

Sweet, thanks to all!

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
Why doesn't Iterator implement Iterable?

I'm dealing with some code to process a data set with some attributes and instances, and I want to iterate over the attributes. I add this to DataSet.java:

code:
public Iterator<Attribute> getAttributes() {
    return Collections.unmodifiableList(attributes).iterator();
}
and try to do this elsewhere:
code:
for (Attribute attribute : dataset.getAttributes()) {
    // ...
}
What do I see? "foreach not applicable to type 'java.util.Iterator<data.Attribute>'." :saddowns:

BE MORE LIKE PYTHON DAMNIT

Lysidas fucked around with this message at 22:15 on Sep 12, 2011

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Why don't you make Dataset Iterable?

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
I already did; it implements Iterable<Instance>. This is what I get for bolting my own API onto someone else's data set processing code without really thinking through what I'm doing.

The easy solution here is just to do
code:
public List<Attribute> getAttributes() {
    return Collections.unmodifiableList(attributes);
}
and then my other loop works unmodified.

The list is already in memory, so returning an iterator doesn't save any resources. It's just a reflex since I've been writing so much Python 3 lately. The realization that Iterator doesn't implement Iterable was a good :wtc: moment nonetheless.

Max Facetime
Apr 18, 2009

Iterators are really limiting if used like that. You can't create a copy of the Iterator and you can only iterate once with each Iterator.

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
I really don't get your confusion. If something is Iterable, it can provide an Iterator. Each Iterator represents an individual cursor over the data structure- you can have as many walking the same data structure as you like. It doesn't make any sense for Iterators to themselves produce new Iterators unless you're explicitly trying to make a copy or something, so it doesn't make sense for them to implement Iterable.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Internet Janitor posted:

I really don't get your confusion. If something is Iterable, it can provide an Iterator. Each Iterator represents an individual cursor over the data structure- you can have as many walking the same data structure as you like. It doesn't make any sense for Iterators to themselves produce new Iterators unless you're explicitly trying to make a copy or something, so it doesn't make sense for them to implement Iterable.

I never said or implied that an Iterator should produce new Iterators. I would expect the implementation of Iterator.iterator() to just return this; so that I can use it in an enhanced for loop.

Like I said, I've been writing a lot of Python lately.

http://docs.python.org/library/stdtypes.html posted:

iterator.__iter__()
Return the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements. This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API.

Lysidas fucked around with this message at 01:36 on Sep 13, 2011

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Lysidas posted:


Like I said, I've been writing a lot of Python lately.

Yes this is a problem. I've been writing a lot of Python for the past couple years and then 6 months ago started writing Android apps. I still get tripped up by differences like this.

Hidden Under a Hat
May 21, 2003
I'm trying to get a parent component to initiate an action when something is altered in a child component. Basically, I have a JTabbedPane, which has a JPanel inside it, which has another JPanel inside of that, which instantiates a JDialog that becomes visible when a button is pressed in the panel. When a certain button is pressed in the JDialog, I want a change to occur in the JTabbedPane (namely the tab title). The only two ways I know how to do this are not elegant.

The first involves passing an invisible JButton through each object instantiation. The JTabbedPane has the action listener for the button that invokes a method to implement a change, and as each subsequent JPanel/JDialog is instatiated, the JButton is passed to it in the constructor. In the final component, when the actual physical button is pressed, I simply invole the doClick() method of the invisible JButton.

The other way would be to make a reference to the parent component by doing JTabbedPane parent = (JTabbedPane) this.getParent().getParent().getParent(); This is also messy.

Does anyone know of another way to do what I'm trying to do? Let me know if I need to clarify what I'm trying to do.

Adbot
ADBOT LOVES YOU

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Hidden Under a Hat posted:

The first involves passing an invisible JButton through each object instantiation. The JTabbedPane has the action listener for the button that invokes a method to implement a change, and as each subsequent JPanel/JDialog is instatiated, the JButton is passed to it in the constructor. In the final component, when the actual physical button is pressed, I simply invole the doClick() method of the invisible JButton.

Why does this need to be a full JButton again?

Fundamentally, you're basically trying to attach an actionListener from the JTabbedPane to a deeply-nested JButton - so wouldn't it make more sense to just pass down the actionListener and have the bottom JPanel attach it for you?

Now, whether that's the best design or not is up for debate. There's basically two ways of doing this:

1. The JTabbedPane manages everywhere that could change its title. In this case, doing it as above makes sense.
2. The JTabbedPane exposes a means to change its title, and doesn't care about it otherwise.

In the second case, you probably want each JPanel to grab the "change the title" method and expose it to its direct child, so you're not overdependent on the exact level-of-nesting that you have going on.

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