views:

216

answers:

4

I code in Python a lot, and I frequently create classes. Now, I'm not sure if this is good Python form, but I just declare a class in the same file as my main().

class foo {
...
}

I'm wondering if it's good form in Java to do the same?

For example,

class foo {
    public static int name;
    public static int numPoints;
    public static int[] points;
}

public class bar {

    public static void main(String[] args) {
    ...
    }
}

Does not throw errors in Eclipse, so it must be allowed. But is it okay to do? Would it be better to just declare this class in a separate file..?

Edit: I just want to emphasize that my new class literally is just a container to hold the same type of data multiple times, and literally will only have like 3 values. So it's total about 5 lines of code. The question is - does this merit a new file?

A: 

From a maintenance point of view it is always easier if each class is declared in its own file (with the filename the same as the classname).

I do not consider what you are proposing as good form, no.

Ries
+5  A: 

Depends on what you want the class to do. If it's only used by the class with main method, there's little loss in declaring it in the same file, although I'd prefer to declare it as a private static inner class then, for clarity and less namespace clutter:

class Program {
    public static void main(String[] args){ ... }
    private static class Foo {
        public int name;
        public int numPoints;
        public int[] points;
    }
}

If >1 other class use your class, it is generally considered good form to have it in a file of its own. If it's declared as a public class, it must be in a separate file with the same name as the class. (Unless its an inner class, of course. :)

gustafc
it's definitely a throwaway class that only the main() in this file will ever use.
hatorade
Then I'd declare it as a `private static` inner class to the main class to avoid namespace clutter.
gustafc
A: 

If You write a "use-once-and-forget" program it is Ok, but it is technically impossible for real applications.

Classes should be declared in their own files, because each file has to correspond to one public class (that is the idea of Java Developers). There can be only one public class per file, so if You need to use foo class in other class (outside this file), You have to split them into separate files.

Dejw
+2  A: 

Edit: I just want to emphasize that my new class literally is just a container to hold the same type of data multiple times, and literally will only have like 3 values. So it's total about 5 lines of code. The question is - does this merit a new file?

I think, code size should not be a criteria to use a separate file.

penguru