Importance of Good Programming Style and Proper Documentation
Good programming style and appropriate documentation make reading and understanding programs easier, reducing errors and improving overall efficiency. Even though a poorly formatted program might compile correctly, it would become difficult to comprehend and maintain.
Both coding style and documentation play crucial roles alongside actual implementation. Well-documented and stylishly written code helps reduce bugs and makes collaboration smoother among teams.
Writing Effective Comments
At the beginning of any significant piece of code, include a summary describing the purpose, key features, and unique technical aspects of the program. For long programs, place additional comments before important steps or sections that could otherwise be hard to follow.
Make sure comments are concise enough not to overwhelm readers yet informative enough to clarify complexities. Avoid cluttering the code unnecessarily.
Comment Styles in Java
Besides regular single-line comments starting with // and multiline comments surrounded by /*...*/, Java also supports special comments known as Javadocs. Javadocs begin with /** and end with */.
Javadoc comments should precede either whole classes or individual methods and serve to generate HTML-based documentation using the javadoc tool included in the Java Development Kit (JDK).
Syntax Highlighting Example
/**
* Display welcome message
*/
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Consistent Indentation Practices
Indentation improves readability by visually representing hierarchical relationships between different elements of the code. Although Java compilers ignore whitespace, well-indented code makes debugging and maintenance much simpler.
For instance, add two spaces for each level of indentation:
public class MyClass {
public static void main(String[] args) {
System.out.println("Hello from main!");
}
}
Styles for Curly Braces and Blocks
There are two common styles for placing curly braces: Next-Line Style and End-of-Line Style.
Next-Line Style
public class Test
{
public static void main(String[] args)
{
System.out.println("Block styles");
}
}
End-of-Line Style
public class Test {
public static void main(String[] args) {
System.out.println("Block styles");
}
}
Both styles are acceptable, depending on personal preference or company standards. Consistency across projects is essential—mixing styles is discouraged.
Task L0t1. Practice Reformatting Code
Reformat the given program according to recommended best practices regarding style and documentation. Use the End-of-Line style for placement of curly braces.
How to Run Java files
- Save the file as L01t1.java.
- Compile:
bash (terminal):
javac L0t1.java
- Run:
bash (terminal):
java L0t1
public class L0t1
{// main method
public static void main(String[] args) {
/** Output message */
System.out.println("Welcome to Java!");
}}
