If you use eclipse, try:
Window > Prefferences > Java > Editor > Save Actions
Check "perform the selected actions on save", "Additional Actions" and click "Configure".
Using eclipse's Save Actions can be really useful in real life coding, but you will probably learn some neat java tricks going through the Save Actions wizard.
Java is an Object Oriented language. You need to take advantage of that fact.
Use classes to separate your code into different logical / structural components. Learn how to use OOP. Follow SOLID design and use design patterns.
Another important thing is to know your language. Start by reading basic classes javadocs and relevant sections of the java spec. I would begin with deeply understanding the different types of java (class, interface, enum and inner / nested / anonymous types) and the different modifiers (private, public, protected, static, abstract, final, default).
Some other eclipse's short cuts:
CTRL-A, CTRL-I ("indentation") will fix your code indentation.
CTRL-SHIFT-O ("organize imports") will omit redundant imports.Are there best practices for (Java) package organization? - Stack Overflow
recommendation for java code organization
Use interfaces for everything you can and avoid abstract base classes. Then, when you come across an issue where it feels like it may be easier to use ABCs, first consider if your design is right or whether it can be organised differently. If you conclude that it still makes sense, then and only then use abstract base classes.
Interface-based development forces you to keep implementation detail out of your contracts much more than ABCs, and supports multiple inheritance. ABCs are far less flexible, do not work as nicely for composition and delegation, and can result in more messy code down the line if you don't get it right.
ABCs are much more tightly coupled to your implementation than interfaces are. Interfaces also have the benefits of multiple inheritance as already stated in the previous paragraph, and can be used as functional interface types in some cases. They can also be used with enums, records, and other interfaces as a superinterface. Much easier to test too, as your unit tests don't have to argue with implementation details you inherit as much (this would be a code smell, but far easier to avoid if you avoid them in the first place).
Remember your code should define what it does as part of the API for other components to use, not how it does it.
More on reddit.comjava - What is the best way to organize object oriented code? - Stack Overflow
java - How to keep code clean and organized? - Stack Overflow
Videos
If you use eclipse, try:
Window > Prefferences > Java > Editor > Save Actions
Check "perform the selected actions on save", "Additional Actions" and click "Configure".
Using eclipse's Save Actions can be really useful in real life coding, but you will probably learn some neat java tricks going through the Save Actions wizard.
Java is an Object Oriented language. You need to take advantage of that fact.
Use classes to separate your code into different logical / structural components. Learn how to use OOP. Follow SOLID design and use design patterns.
Another important thing is to know your language. Start by reading basic classes javadocs and relevant sections of the java spec. I would begin with deeply understanding the different types of java (class, interface, enum and inner / nested / anonymous types) and the different modifiers (private, public, protected, static, abstract, final, default).
Some other eclipse's short cuts:
CTRL-A, CTRL-I ("indentation") will fix your code indentation.
CTRL-SHIFT-O ("organize imports") will omit redundant imports.You might consider taking a look at Code Complete, which deals with the issues that you're concerned with here, and otherwise is just a classic in our field that every serious developer should read.
In general, when you're organizing code you should do so with a few things in mind: readability and atomicity. These two factors apply to code on every level of an application, from variable naming, routines, methods, classes, packages, and so on.
Readability is a simple idea: can a human being read this code and understand it? To gauge the readability of the code all you have to do is read it! Do variable names help the reader understand what something is? Are routines and classes properly formatted and not needlessly complex? Have you removed all code that isn't being used? Is your code written in a logical progression?
Atomicity is the idea that everything should have one purpose. A function or method should (usually) do one thing and one thing only. A class should usually be a logical grouping of related methods and fields serving some type of unique purpose, and NOT a mish-mash of unrelated stuff. A package should also contain a set of related files. Same with a project, and so on.
The main benefit of atomicity is that once you get into more involved applications it's actually much easier to debug and isolate issues in your code because you know where stuff is. For instance: I have a database access error! Good thing I have a package that's specifically defined for my database access objects.
I know when I was just getting started in the field this was something that threw me off too. It might not be until you do a lot of coding within more significant apps that you really start to understand best practices and why people build stuff a certain way.
I organize packages by feature, not by patterns or implementation roles. I think packages like:
beansfactoriescollections
are wrong.
I prefer, for example:
ordersstorereports
so I can hide implementation details through package visibility. Factory of orders should be in the orders package so details about how to create an order are hidden.
Package organization or package structuring is usually a heated discussion. Below are some simple guidelines for package naming and structuring:
- Follow Java package naming conventions
- Structure your packages according to their functional role as well as their business role
- Break down your packages according to their functionality or modules. e.g.
com.company.product.modulea - Further break down could be based on layers in your software. But don't go overboard if you have only few classes in the package, then it makes sense to have everything in the package. e.g.
com.company.product.module.weborcom.company.product.module.utiletc. - Avoid going overboard with structuring, IMO avoid separate packaging for exceptions, factories, etc. unless there's a pressing need.
- Break down your packages according to their functionality or modules. e.g.
- If your project is small, keep it simple with few packages. e.g.
com.company.product.modelandcom.company.product.util, etc. - Take a look at some of the popular open source projects out there on Apache projects. See how they use structuring, for various sized projects.
- Also consider build and distribution when naming (allowing you to distribute your API or SDK in a different package, see the servlet API)
After a few experiments and trials, you should be able to come up with a structuring that you are comfortable with. Don't be fixated on one convention, be open to changes.
Hi everyone! I am new to java and have some questions about code organization. My learning process is going smoothly so far as the syntax goes, but i have hard time grasping organizational stuff, such as where would i use interfaces vs abstract classes, especially when interfaces have default methods. I have found a lot of theory about this, but less practical examples. I would also like to get good at architectural patterns in practice. What would the best approach to do that? When I am coding, I notice that the codebase is going out of control really fast. thanks for any input and suggestions.
Use interfaces for everything you can and avoid abstract base classes. Then, when you come across an issue where it feels like it may be easier to use ABCs, first consider if your design is right or whether it can be organised differently. If you conclude that it still makes sense, then and only then use abstract base classes.
Interface-based development forces you to keep implementation detail out of your contracts much more than ABCs, and supports multiple inheritance. ABCs are far less flexible, do not work as nicely for composition and delegation, and can result in more messy code down the line if you don't get it right.
ABCs are much more tightly coupled to your implementation than interfaces are. Interfaces also have the benefits of multiple inheritance as already stated in the previous paragraph, and can be used as functional interface types in some cases. They can also be used with enums, records, and other interfaces as a superinterface. Much easier to test too, as your unit tests don't have to argue with implementation details you inherit as much (this would be a code smell, but far easier to avoid if you avoid them in the first place).
Remember your code should define what it does as part of the API for other components to use, not how it does it.
where would i use interfaces vs abstract classes
When you need state, as in instance fields, use abstract classes. Otherwise use interfaces.
Take a look at the SOLID principles.
EDIT (some more pointers):
You need a SOLID GRASP of some design principles.
To start small, take a look at these first:
- Single Resposibility Principle (pdf) (the S in SOLID)
- Neil Ford gives some excellent advice in this presentation, including:
- Single Level of Abstraction Principle
- Composed Method
When writing code, high maintainability should be your ultimate goal, and it's all about assigning responsibilities and separation of concerns.
First of all, never just lump everything together. Try to identify the objects first. Build a class for each object your program will work with. If you're building an application for truck drivers, you will need a class for the driver, the truck, the load he's hauling, there's really no limit to how far you can break these bigger objects down. As for the methods, a method handles an action for the object. Truck.Start() would start the truck. Drive() would start it driving, etc... Maybe the Drive method takes a Route object for an argument which contains the roads to drive on. In short, create a method when an object needs to do something and create a class when you want to deal with another type of object.
Where to start
I'm pretty sure you don't apply all best practices if you have many difficult to understand fragments similar to:
ifinsideifinsidefor
A very good place to start with clean code is reading a book related to the topic. Although books are sometimes criticized, it allows to cover many aspects at once and make the knowledge possessed on tutorials, blog notes, SO more systematic. Personally, I can recommend Clean Code by Robert C. Martin.
If you are familiar with a theory, practice a lot. Write a code and improve it. Again and again. It is also useful to find somebody, who is more experienced and ask him about more difficult cases.
I suggested below three points that are very important from my point of view.
Self-documenting code
First of all, I would reduce the amount of comments to minimum, avoid dashed lines, "editor-folds" and so one. If you need to split your code with separators - the class is probably too long. Please, read more about good comments and self-documenting code here.
Unconditional programming
Many times it is a good idea to replace if-else and switch instructions with some OOP principles. This answer contains a couple of useful links.
Package/Class/Method size
Reorganize all of the routines, that are too big to easily understand. Split long methods into smaller, redesign God classes using OOP paradigms. The rule applies also to projects - you can split it into modules or subprojects and reuse. Single responsibility principle might be helpful - some examples.
A good code is pretty much its own documentation.
Java documentation provides lots of details on how to write code in a better way.
My suggestions are:
Use proper naming conventions:
In your code i can see some code smells, the variables test and test2 can be the big cause of trouble for other programmers.
Try making modules:
Making modules can also make code easy to understand. For example creating possible methods out of long code and naming them properly. My teacher once told me: "if you cannot name a method or think of any appropriate name for your method it means you are doing it wrong"
Comments are thought to be important but my opinion is good written code do not rely on comments. You can add them to explain what is complex.
Proper Indentation is also important.