I am new to Java programming, i created one class with name as Demo and saved as sample.java while compile this java program it giving compilation error as below
public class Demo {
public static void main(String[] args) {
System.out.println("This is year");
}
}
sample.java:3: class Demo is public, should be declared in a file named Demo .java
why do we declare public classes in individual files......
Thanks
Mukthyar
Because that's what the Java specification requires (or at least, it allows implementations to require this; see Jon's comment below).
As to "why", I can only hypothesise. But it's evident that the designers of Java were very keen on clear coding conventions, etc. One public class per source file means there's no ambiguity about where to find something.
(If there's a technical reason, I'm not aware of it.)
#Oli Charlesworth is right: this is required by Java language specification. You can probably ask why do they require this? The possible answer is to make things clear. Class is atomic unit by definition. You can replace class by its other version and if the public interface was not changed everything will continue working.
So, Java language designers decided to force us to store each classes in separate files.
They just did some exception for non-public classes. Several non-public classes can be saved in one file. I think that the reason is that non-public class is a kind of gory details of the implementation that can be changed at any time by author. Since class is non-public these changes should not affect any API user.
But I strongly recommend you to save every class (even if it is not public) in separate file. This improves code readability and in the end of the day its quality.
TL;DR : To reduce the conceptual complexity of the software.
If you have many public classes hidden in files that have unrelated names makes it much more harder to see the conceptual structure of the programm just by looking at the package structure.
#because the java spec says so - I think the real question is the reasoning behind the spec
It's to stop people cluttering up files with hundreds of classes in non orthogonally named files. The namespacepart/namespacepart/namespacepart/classname structure is there to provide a standard and sustainable structure.
Related
It's been told me (and I have seen this statement in a few other places) that it's not recommended to store your constants in a separate class in Java, in order to use them in the other classes. But I haven't seen anywhere WHY is it so. What is the reason I should not store them in their own interface/class?
I came from C to Java and in C i would just make a .h file where i defined constants with #define
Constants in a dedicated file are frowned upon for stylistic reasons. Having a class dedicated to constants can encourage developers to add increasing numbers of unrelated (undocumented?) constants to a file that slowly bloats out of control.
By contrast, having constants associated with the classes they are related to is a more scalable and readable design.
So you can be an engineer and measure constants and their locations as a technical choice. This is great and fine when you work on performance critical systems or on cool small snippets. Once your application tends to grow however, it becomes harder and harder to grasp the business requirements and end-user needs reflected in the code.
So instead of thinking about style -- separate class, properties file or nested inside a class -- I tend to follow domain driven design -- if the set of constants exclusively belong to a specific class (entity), nest the constants; if the concept touches more than one of the entities in your domain model, feel free to make it a separate entity.
And please do remember, that since Java 5, you do have enums at your disposal.
A separate constants class is not object-oriented design. In OO, a class (or interface) represents a contract, and a class which only contains constants does not define any contract.
Another object-oriented consideration is that a separate constants class encourages misuse of inheritance. Inheritance is supposed to indicate that a class fully adheres to the contract defined by another class or interface. Inheritance should not be used just to share functionality or constants; that's what public methods and fields are for. Thus, this code is incorrect:
class SomeApplicationClass
implements ScrollPaneConstants // Incorrect, import ScrollPaneConstants instead
Issue is that they should be living outside of your source code entirely. You should be using something like Apache Commons Config, or at least loading from a .properties file.
I will also note that I'm interpreting "single" with respect to a reasonable scope. For instance, there should not be one Config file for all Java developers used stored on Google's servers with a request form for modifying. There probably should not be done for your entire code base; however, per UOR or package is a reasonable scope, and is the one I use in practice.
We have a huge projects based on an old jdk 1.4. We have migrated the web app to JDK 1.6 but still lot of inefficient practices and bad design exist in the code.
On of the major pain point huge java classes 2500+ lines of code in single java file. So many files like these.
In an attempt to refactor the classes I had started off by removing constants and putting constants in different Constants.java file. but since there are so many constants through-out the application, the constants file has the risk of growing to humongous proportions.
I would appreciate feedback on what strategy are developers adopting to keep code clean and maintainable.
Keep your constants in the class they are related to, don't feel obligated to extract them. It may clean up the code of the class, but mixing unrelated constants in a file is not an improvement.
Keep things related together.
And also you can convert them to Enums when possible/useful (but that can require some refactoring).
Putting all the Constants in a single file is a terrible idea! Especially the uber-Constant anti-pattern where all the Constants are in an Interface that every class has to implement. 10 ways to Sunday terrible! This was a bad idea when people started doing it back in the early 1990's before Java! It is definitely a bad idea in 2012!
It means you are mingling lots of un-related information and creating un-needed dependencies everytime you import this uber-Constants file. Things that go together should be together in an Enum or at least in the Class that uses them as arguments to its methods so that when they are changed you know how to do an impact analysis easily.
Imagine Color constants mixed in with DaysOfTheWeek constants mixed in with other business domain constants and there will be hundreds if not thousands of these things in a single file. How can that ever be considered a good idea? In every non-contrived case, an Enum that is a public inner member of a Class is a better solution.
It also means you have a single flat namespace to try and create names that don't conflict, then they aren't obvious what they belong to and how they should be used. This is never a positive exercise.
When designing and refactoring you should always:
Strive for high cohesion, this means keep related things as close together as possible.
Strive for loose coupling this means don't let un-related things leak into other un-related scopes.
Strive for self-documenting maintainable code, dozens or hundreds of private static final String/int declarations all mixed together doesn't fit this definition by anyone's standard!
In 2012 C-style constants are a poor solution when you now have Enum as a tool, you should be focused on converting as many of these groups of Constants to Enum wherever possible. Enum is type safe and can have other attributes and properties and behaviors attached to it to make them intelligent. That is the path to go down.
Just putting constants in a Constant.java file doesn't make sens in my opinion (it just move the problem away). But sometimes I use to regroup them to clear the things and use several files to regroup them : DatabaseConstants.java, GraphicConstants.java and so on...
and of course, using enums can be useful too (and best practice).
edit : to be precise, I actually work with Java ME application, so it's just a way to "mimic" the enums I can't have, with a "controlled vocabulary" in abstract classes (I miss all the Java EE features...)
For someone who is visiting this page.
If you don't want to maintain multiple constant files, below is the better way to organize.
public interface Constants {
public static final String CREATE_USER = "createUser";
// Nested Interface.
public interface ProjectConstants {
public static final String CREATE_PROJECT = "createProject";
public static final String INVALID_SESSION = "Invalid Session";
// As you know they are implicity public static final.
}
}// Accessed as:
Constants.ProjectConstants.CREATE_PROJECT
Updates:
As a best practice, its better to use Class.(See comments. . Thanks keplerian.)
public final class Constants {
private Constants() {
// restrict instantiation
}
public static final double PI = 3.14159;
public static final double PLANCK_CONSTANT = 6.62606896e-34;
}
import static Constants.PLANCK_CONSTANT;
import static Constants.PI;
public class Calculations {
public double getReducedPlanckConstant() {
return PLANCK_CONSTANT / (2 * PI);
}
}
I'd like to share a design pattern for constants i've seen a few years ago that maybe can help.
Start by creating a BaseConstant file. This will hold all your global constants that all packages could use.
Now in each subpackage of your app create a Constants file that will only be related to the subpackage . So if you had . a subpackage called Login only put constants related to login there. But the key is to extend off of BaseConstants. this way you get to see all the global constants in the IDE chooser but when you open the file you only see your package constants. that being said i think constant files can get really heavy and duplicate values and hard to read.
Here is what i mean ..
public class BaseConstants{
public static final String GLOBAL1= "GLOBAL string";
public static final String GLOBAL2= "another GLOBAL string";
}
Now in all your other packages create a files like this:
class MyPackageConstants extends BaseConstants{
public static final String LOCAL1 = "local String"
public static final String LOCAL2= "ANOTHER LOCAL string";
}
in your IDE when you type "MyPackageConstants." you should see all the constants for the entire application.
I've never heard of putting all of the constants to a single java file. The best way is to put the constants accossiated with the classes in themselves, but name them with capital letter and underscores like this one: EXAMPLE_CONSTANT
Have you tried using Enums for all of your constants? I've been told it is the preferred way since Java 1.5.
http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html
I think that if you have multiple java files over 2500 LOCs, the decision where to put the constants should be the least of your problems. You should form a clear picture of how the restructured system will look like.
This is probably much harder then deciding where to stick the constants and other syntactic considerations but needs to be done first nevertheless.
As everyone knows - public java classes must be placed in their own file named [ClassName].java
( When java class X required to be placed into a file named X.java? )
However, we are auto-generating 50+ java classes, and I'd like to put them all in the same file for our convenience. This would make it substantially easier to generate the file(s), and copy them around when we need to.
Is there any way I can get around this restriction? It seems like more of a stylistic concern - and something I might be able to disable with a compiler flag.
If not, what would you recommend?
Can you put wrapper class around your classes? Something like:
public class Wrapper {
public static class A {...}
public static class B {...}
....
}
Then you can access them via Wrapper.A, Wrapper.B.
At the .class level, this is a requirement per the Java spec. Even the inner classes get broken out into their own class file in the from Outer$Inner.class. I believe the same is true at the language level.
Your best bet is to generate the files and make your copy script smart. Perhaps generate them and zip them up. Usually, if you have to move these files around then either everyone has the same generator script OR you distribute them as a JAR.
Is there any way I can get around this restriction?
You can change your generated source code to make it acceptable; e.g. by using nested classes, by putting the generated classes into their own package.
It seems like more of a stylistic concern - and something I might be able to disable with a compiler flag.
It is not just a stylistic concern:
The one file per class rule is allowed by the Java Language Specification.
It is implemented by all mainstream Java compilers.
It is implemented by all mainstream JVMs in the form of the default classloader behavior.
It is assumed by 3rd party Java tools; e.g. IDEs, style checkers, bug checkers, code generation frameworks, etc.
In short, while it would theoretically be legal to implement a Java ecosystem that didn't have this restriction, it is impractical. No such compiler switch exists, and implementing one would be impractical for the reasons above.
The nested class solution is a good one. Another alternative would be to put the generated classes into a separate package (but with separate file) to make them easier to manage.
Is it a bad practice to have a package with only one class in it? Would it make more sense just to move the single class to a util package that would contain other random useful classes?
Is it a bad practice to have a package with only one class in it?
Not necessarily. It could be a sign of somebody getting obsessed with classifying things. On the other hand, it could just be a logical consequence of a sensible general classification scheme applied in an unusual case.
An example of the latter might be where you have a general API, and multiple implementations of that API, where each of the implementations consists of multiple classes. But one of those implementations (lets call it the Null implementation) consists of just one class.
The real test is whether the package structure is serving its purpose(s):
Is it making it easier to find library classes?
Do the packages organize the application classes along the lines of the application's logical module structure?
Does the structure allow you to effectively make use of "package private" visibility?
Would it make more sense just to move the single class to a util package that would contain other random useful classes?
Not necessarily. If the class is just another "randomly useful" leaf class, then there is a good case for moving it. On the other hand, if it has a specific function and is not intended to be used generally, then it may be better to leave it where it is.
It is best not to get too obsessed with creating elegant package hierarchies, or with rejigging them when they turn out to be not as elegant (or useful) as you first thought. There are usually more important things to do, like implementing functionality, writing tests, writing documentation and so on.
No
Package is used to put similar classes together,
In your system if there is no similar class then obviously you can put it .
Is it a bad practice to have a package with only one class in it?
Not necessarily. Packages are using to group together logically related entities. It doesn't prevent you from having just one such entity in a package.
Would it make more sense just to move the single class to a util package that would contain other random useful classes?
Not to me, for two reasons:
Util has a specific meaning. Moving an arbitrary entity to util for reasons of loneliness would be a borderline case of util-abuse.
This is premature organization. With Java the IDE support is rich enough to reorganize easily and effectively using a few clicks. Wait a while to see how your project evolves and then take a call.
There are different stategies for static util classes. I use this one :
if your util class is generic (String utils, DB utils, etc.), I put it in a "util" package, that is used in all the application.
if the util class is specific to a domain, I call it "DomainHelper" by convention, and put it in the domain package, at the same level as domain classes.
Yes, it's a definite code smell.
This doesn't mean it's necessarily wrong, but there should be a really good reason for a lone class in a package.
Most instances of a package with a single class that I've seen have been erroneous.
Packages should implement features. It's rare that a feature is implemented using only a single class.
Its not 'bad' to have a single class in a package, Create a new package to group more than one related classes and in case if you expect more related classes to your present single logically unrelated class in future to avoid refactoring. Moving all the random utility type classes to a single package is a common practice seen in many places.Its a matter of choice really.
I guess it depends. It is quite rare in to have a package with one class in it because in addition to the answers listed above, packages also serve the purpose of creating a layered system. A package with only one class in it indicates that the decomposition of the system has not surfaced some objects in the system. So, yes, I would take a closer look at this package and question what the purpose is.
It is better not to stick random stuff in an Util package precisely because of the reason mentioned above. You should ask yourself whether you would think to look in Util for your class in the future before putting it there. When Util grows large it starts to get difficult finding the Utility one is looking for.
This is language agnostic, but I'm working with Java currently.
I have a class Odp that does stuff. It has two private helper methods, one of which determines the max value in an int[][], and the other returns the occurrences of a character in a String.
These aren't directly related to the task at hand, and seem like they could be reused in future projects. Where is the best place to put this code?
Make it public -- bad, because Odp's functionality is not directly related, and these private methods are an implementation detail that don't need to be in the public interface.
Move them to a different class -- but what would this class be called? MiscFunctionsWithNoOtherHome? There's no unifying theme to them.
Leave it private and copy/paste into other classes if necessary -- BAD
What else could I do?
Here's one solution:
Move the method that determines te max value in a two-dimensional int array to a public class called IntUtils and put the class to a util package.
Put the method that returns the occurrences of a character in a String to a puclic class called StringUtils and put the class to a util package.
There's nothing particularly bad about writing static helper classes in Java. But make sure that you don't reinvent the wheel; the methods that you just described might already be in some OS library, like Jakarta Commons.
Wait until you need it!
Your classes wil be better for it, as you have no idea for now how your exact future needs will be.
When you are ready, in Eclipse "Extract Method".
EDIT: I have found that test driven development give code that is easier to reuse because you think of the API up front.
A lot of people create a Utility class with a lot of such methods declared as static. Some people don't like this approach but I think it strikes a balance between design, code reuse, and practicality.
If it were me, I'd either:
create one or more Helper classes that contained the methods as static publics, naming them as precisely as possible, or
if these methods are all going to be used by classes of basically the same type, I'd create an abstract base class that includes these as protected methods.
Most of the time I end up going with 1, although the helper methods I write are usually a little more specific than the ones you've mentioned, so it's easier to come up with a class name.
I not know what the other languages do but I have the voice of experience in Java on this: Just move to the end-brace of your class and write what you need ( or nested class if you prefer as that is accepted canonical convention in Java )
Move the file scope class ( default access class right there in the file ) to it's own compilation unit ( public class in it's own file ) when the compiler moans about it.
See other's comments about nested classes of same name if differing classes have the same functionality in nested class of same name. What will happen on larger code bases is the two will diverge over time and create maintainability issues that yield to Java's Name of class as type of class typing convention that forces you to resolve the issue somehow.
What else could I do?
Be careful not to yield to beginner impulses on this. Your 1-2 punch nails it, resist temptation.
In my experience, most large projects will have some files for "general" functions, which are usually all sorts of helper functions like this one which don't have any builtin language library.
In your case, I'd create a new folder (new package for Java) called "General", then create a file to group together functions (for Java, this will just be a class with lots of static members).
For example, in your case, I'd have something like: General/ArrayUtils.java, and in that I'd throw your function and any other function you need.
Don't worry that for now this is making a new class (and package) for only one function. Like you said in the question, this will be something you'll use for the next project, and the next. Over time, this "General" package will start to grow all sorts of really great helper classes, like MathUtils, StringUtils, etc. which you can easily copy to every project you work on.
You should avoid helper classes if you can, since it creates redundant dependencies. Instead, if the classes using the helper methods are of the same type (as kbrasee wrote), create an abstract superclass containing the methods.
If you do choose to make a separate class do consider making it package local, or at least the methods, since it may not make sense for smaller projects. If your helper methods are something you will use between projects, then a library-like approach is the nicest to code in, as mentioned by Edan Maor.
You could make a separate project called utils or something, where you add the classes needed, and attach them as a library to the project you are working on. Then you can easily make inter-project library updates/fixes by one modification. You could make a package for these tools, even though they may not be that unified (java.util anyone?).
Option 2 is probably your best bet in Java, despite being unsatisfying. Java is unsatisfying, so no surprise there.
Another option might be to use the C Preprocessor as a part of your build process. You could put some private static functions into file with no class, and then include that file somewhere inside a class you want to use it in. This may have an effect on the size of your class files if you go overboard with it, of course.