Sign in to follow this  
Elehisie

[java] when is it the time for separating a single .java into packages and interfaces?

Recommended Posts

this may sound odd for some... (but as im natively a pascal coder...) yeah thats right, my very first language was pascal, followed by delphi, c, c++, java. i took a look into C#, but never went into it. in pascal, youd want to create "unit" files when your code was longer than 3000lines. (the compiler was unable to compile more than 3000 lines at a time). in delphi, it would automatically put every form source in a different file, and even if you wanted, you couldnt have it in the same one. and you would create .dll files when you have different projects running the same routines. in C in general from what ive seen, it really depends on the programmer... ive encountered a few whod split everything, and some whod always make huge single files... now that you know my backgrounds, re-read the title: when is it the right time to split a single .java into packages and interfaces? what i mean is: how better for performance would it be? (not thinking about team related stuff, as im the only coder in my team haha) my only real reason to go thru the trouble of splitting the code: - its a damn long file right now, where i tried to follow a logical sequence for ordering variables, objects, swing components, classes and methods, but as it does a lot of nearly-unrelated tasks atm... IE: accessing files in disk, communicating with a server, warning pop-ups for the users, generating parts of the GUI from users responses in real time, not to mention a complex GUI, with a few different JFrames, and many different "states" of the main JFrame, according to what task the user may be executing... and a HUGE "import" part... importing many many many many packages... you have to admit that to have all that in the same file is ugly-coding... and... well its becoming hard to manage. as in: when i have to scroll up to this *specific* part of the code, finding variables, blah blah... but i do have some static methods, and i use a single "action performed" method to manage all gazillions of buttons, and this is managed by a "command list"... now, having them in packages: - will performance be the same? - will i need to add all package files into the "instalation" dir (like needing to have a few .jar files in the same dir as the main executable) - is there any REAL advantage of having a few different packages rather than a single file? (the organizing part wont count as advantage, ok? cuz despite it being hard to manage, its not impossible to have an organized code in a huge file) -would it be faster to have the fired actions for the buttons run from different packages rather than iterating thru a list using a switch?

Share this post


Link to post
Share on other sites
Hmm, sounds to me like your not too familiar with the whole point of OO programming.

(Very) Basically, your program should be designed such that each class fulfills a specific role. For example, one class would work on server communication, another on rendering the GUI, another on reading input from the GUI, etc.

There is no performance hit at all from putting files in different packages. The point of packages is to logically group related classes, e.g. all your GUI classes might go in one package. Packages in Java pretty much means just having different classes in different folders, they're not the same as C++ namespaces.

Quote:
will i need to add all package files into the "instalation" dir (like needing to have a few .jar files in the same dir as the main executable)

You can either wrap each package into a different JAR, or wrap the entire application into the one. It makes little difference to your program, the only reason you might want to wrap packages in different JARs might be if you want to use those packages in different applications at a later date.

Share this post


Link to post
Share on other sites
Quote:
Hmm, sounds to me like your not too familiar with the whole point of OO programming.


I have good knowledge of OO programming... but as i said, my OO backgrounds come from Delphi. the bad part is the "lybrary building" part in delphi is very automated, as it automatically picks which part goes in which file, and you dont have a lot of freedom when building, and this "lack of freedom" from delphi killed my ability to "design well" in Java, when i have to define those things on my own, and i have enough freedom to design as I want. besides, im an electronics engineer. i didnt have good programming skills subjects at university, as it wasnt oriented in software building... so all my programming knowledge, or at least 95% of it comes from teaching myself. the result is that even if i have good knowlegde of OO design, I dont use any "academic approach" when designing. (which i recognize as very bad, and am trying to change). but most of time, if it compiles, im satisfied with it. i dont build code for any company atm... i code for my own fun, more likely, and i have fun building games :P whenever a "professional programmer" sees my codes s/he will act like: "ewwwwww does that sh*t even compile??" :P

Quote:
I'm afraid to ask, but...

How many classes do you have? And of them, how many are nested classes?


hmm i wont show the code here,ok? this app is more or less some "experiment" for my mmorpg. like: ive come up with code that works in the manner i want it to work, but it recently looks ugly, is disorganized, and its really not presentable in the programming community. but after all, it runs, and it has shown good performance so far. but when i go for a final version, i want to look "properly"

I currently have: 4 classes, 2 of them have no more than 4 nested classes, and the nested classes have no nested classes. in those 4 classes i have at least 8 methods in each, plus 3 or 4 methods that arent in any class, as they are "common" to 2 classes. I have 3 GUI-generating methods that return JComponents,and display on the same JForm, due to run-time changes in the GUI. all of them implement "ActionListener" and theres is only one "ActionPerformed" method thats common for everything that implements "ActionListener". the same goes to the other listeners I have: "focusGained", "focusLost", "valueChanged" and "propertyChange" listeners.

as i know that Swing has issues around "thread safety" and I do run at least 2 threads at a time, i run mostly everything thru the event dispatching thread. but only one of the threads displays a GUI (made of swing components), the others are server conenctions listeners/parsers, and display the stuff they need on a JTextArea, when needed be.

well... i know this will be scary for you guys, but my "import" section goes like:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import java.awt.print.*;

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;

import java.util.*;
import java.text.*;

import java.util.AbstractList;


and yeah, i do know its getting too big!

Share this post


Link to post
Share on other sites
The accepted "Best Practice" is to have one class or interface per source file, and that source file has the same name as the class/interface. Now, if I'm being lazy I might let a very small interface slip into a file that already has a class, but only if I'm being VERY lazy.

I highly suggest you stick to the one-file-one-class rule.

Get rid of the nested classes, move them to their own files as full classes. Just really bad design. Nested classes and anonymous classes cause problems when debugging. ESPECIALLY anonymous classes. If I could find the person that thought it a good idea to include anonymous classes, I would beat them into jelly.

you also seem to be using the words pacakge and file interchangeably. They are most assuredly not the same thing. While the Java package structure is tied to the file system, a package should be thought of as merely a set of related classes and should not be thought of as files residing in the same directory.

Your imnport list is fairly typical of a java application. Don't worry about it. I let eclipse organize my packages automatically.

Share this post


Link to post
Share on other sites
ive been thru a lot of the tuts in java.sun.com, and they are all very basic (and i mean too very basic) or really not deep enough (imo).

---> well im gonna search for some good designing resources later :)
(when im not at paying job) for now, i really appreciate the attention, guys!

(and that "best practice" thing really explains why some code ive been running into looks so incomplete)

Share this post


Link to post
Share on other sites
Quote:
Original post by Kevinator
Uhhh... I thought you could only have one public class per file, and it had to be the name of the file. What am I missing?

I think you miss nothing. The Java compiler (Java 1.5 from Sun and also those I've used before) complains if you violate the mentioned rules. (However, you could have inner classes as much as you want, of course, but that wasn't the question.) So, even if some other compiler accepts such stuff, it will not be portable.

EDIT: An excerpt from the man page of javac:
Quote:
man javac
Source code file names must have .java suffixes, class file names must have .class suffixes, and both source and class files must have root names that identify the class.



[Edited by - haegarr on December 5, 2005 11:57:36 AM]

Share this post


Link to post
Share on other sites
Hi dude!

I suggest you buy a book to learn OOP and Java. Delphi is a RAD tool, so it has several disadvantages compared to OOP with Java or C++

I like the Deitel brothers book, as well as some of the O'Reilly ones.

Engaging in a Java community is also a good move - here in Brazil we have several JUGs, take a look at www.guj.com.br and ask the friendly people there!

Cya

Son Of Cain

PS: BTW, if you can't afford buying a book right now, there's the "Thinking in Java"series - pretty good ones, and free.

Share this post


Link to post
Share on other sites
Quote:
Original post by haegarr
Quote:
Original post by Kevinator
Uhhh... I thought you could only have one public class per file, and it had to be the name of the file. What am I missing?

I think you miss nothing. The Java compiler (Java 1.5 from Sun and also those I've used before) complains if you violate the mentioned rules. (However, you could have inner classes as much as you want, of course, but that wasn't the question.) So, even if some other compiler accepts such stuff, it will not be portable.

EDIT: An excerpt from the man page of javac:
Quote:
man javac
Source code file names must have .java suffixes, class file names must have .class suffixes, and both source and class files must have root names that identify the class.


your source file can also contain non-public classes that are not nested in other classes (default to protected).

Share this post


Link to post
Share on other sites
[quote]your source file can also contain non-public classes that are not nested in other classes (default to protected).
[\quote] exactly.... i have loads of "protected static" things

Son of Cain: I have the Deitel book... Didnt like it very much actually. Ive found out that the docs in java.sun.com are better in some points. Deitel pretty much explains what he likes to use, in the way he likes to use...

Quote:
Delphi is a RAD tool, so it has several disadvantages compared to OOP with Java or C++
dont call me "dude" :P Im a girl!! GIRL!! but yeah... ive always beens a Delphi freak... cuz their IDE is so.... "lemme do everything for you".... but one day I went for Java ... never got really serious in C... but when i went for Java, I divorced from Delphi :P I saw the light :P ive always missed a few things from the borland-like IDE... (deugging can be awfull when youre usin notepad to type your java files... try counting lines up to 55 to find where the error came from....) tried JCreator (java tool from borland) and it stinks.... then I found out about Eclipse, and it was love at first sight! LOL :)

Share this post


Link to post
Share on other sites
[quote]Original post by capn_midnight
If I could find the person that thought it a good idea to include anonymous classes, I would beat them into jelly.
[/quoto]
So............ do you write all your listeners in seperate files?
[begin file]
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ExitButtonListener implements ActionListener
{
public void ActionPerformed(ActionEvent e)
{
System.out.exit(0);
}
}
[end file]

I never had any debug problems with anonymous classes. I always write every commnad in a seperate line, so when I get an exception, I can see if it's inside an anonymous class.

Anonymous classes can be your best friends. The best thing about them is that they can access the final variables of the function creating them. No need to transfer values to the constructor and store them in variables. All is automated
for you.

Quote:
Original post by Elehisie
Ive found out that the docs in java.sun.com are better in some points.

The javadocs are good for learning the different feautures of JAVA. If you want to learn it from the begining, get a book, a tutorial, or a course.

Quote:
Original post by Elehisie
deugging can be awfull when youre usin notepad to type your java files... try counting lines up to 55 to find where the error came from....)

Check "Status Bar" under the "View" menu. No more lines counting. It helped me alot when I was hand-writing VRML files.

Share this post


Link to post
Share on other sites
Quote:
Original post by Elehisie
dont call me "dude" :P Im a girl!! GIRL!!


Sorry, I couldn't guess. You know how rare women are in the field of programming, so I'm glad at this little surprise.

About Deitel's books, I learned C++ at college through one of them. Since I was a total noob, I liked their approach. I never read their Java books, so I assumed they had the same grasp.

The Java Tutorial is a nice paper, but they focus on the language, teaching OOP as you go on; to learn OOP in a proper manner, and using Java, I keep advice on this book.

Cya

Son Of Cain

Share this post


Link to post
Share on other sites
Quote:
Original post by someboddy
Quote:
Original post by capn_midnight
If I could find the person that thought it a good idea to include anonymous classes, I would beat them into jelly.

So............ do you write all your listeners in seperate files?
[begin file]
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ExitButtonListener implements ActionListener
{
public void ActionPerformed(ActionEvent e)
{
System.out.exit(0);
}
}
[end file]

No, I have my main class that extends the JFrame class implement any appropriate listeners. Anonymous classes are just sloppy.
Quote:

I never had any debug problems with anonymous classes. I always write every commnad in a seperate line, so when I get an exception, I can see if it's inside an anonymous class.

perhaps they fixed it for 1.5, I haven't gotten to use it that much, but I know in 1.4 it could not figure out the source line properly if the error occured in an anonymous class. I learned this on a project that involved finishing someone's end-of-year software engineering assignment because the CS department thought the idea was sound and wanted to actually use it. Too bad the student never actually got around to coding any of the functionallity, and what they did have was precisely equivalent to garbage served for dinner. Every single button listener was implemented with an anonymous class.
Quote:

Anonymous classes can be your best friends. The best thing about them is that they can access the final variables of the function creating them. No need to transfer values to the constructor and store them in variables. All is automated
for you.

I've only ever seen this used in such a way that developers have tagged parameters as final when they should not have been final. That's just bad design. One typical use of anonymous classes is for the callback method on a thread. Being able to access those final properties introduces major syncrhonization concerns, especially for collections and streams. And if the property is a constant, primitive value (and therefore read-only), then it should be static as well and therefore is accesible through the fully qualified name of the property (ParentClassName.PropertyName). Just not necessary to introduce such cludge.

Share this post


Link to post
Share on other sites
Quote:
Original post by capn_midnight
Being able to access those final properties introduces major syncrhonization concerns, especially for collections and streams.


Ohh Nohh, my exit button will be unsyncrhonized....

Anonymous classes are meant for fast implementation of short code. Personally, I like to put my exit button code in the same place I create the exit button.

Take a look at the following code:

private Button createButton(String caption,final int index)
{
Button ret=new Button(caption);
ret.addActionListener({
public void actionPerformed(ActionEvent e)
{
StuffDoer.doSomething(index);
}
});
return ret;
}


public Panel createThePanel(int nob)
{
Panel ret=new Panel();
ret.setLayout(new FlowLayout);
for(int i=1;i<=nob;++i)
ret.add(CreateButton("do action"+i,i));
return ret;
}



"index" is a final primitive. Should it be declared static?

Share this post


Link to post
Share on other sites
ever heard of setActionCommand("command") method?

instead of doing that, you can have a single actionPerformed handle handle all of the buttons in a JFrame. trust me... i have over 90 buttons for a quizz thingy and all of those need to do the same thing: parse a string to a certain var. so i just set the same action command for all of them :P

and the same actionperformed handle handles my exiter button, and all other buttons...

all i have to do is to search the command in a list object, get its index and use the index in a switch statement. sweet.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this