Source:10 best practices in Java | Medium
Oh, this author's chart is really interesting.
This blog post will discuss some of the most common Java best practices, and explain why they are important. use your best judgement when deciding what is right for your codebase.
this blog will only present you the overall idea for each practice, but it will not go in depth, if you know to know more about any of these best practices…cough cough… Google is your friend!
Motto?
When you begin your career as a programmer, following a standard set of rules is likely appropriate. But as you progress, your skills become stronger, and you start to develop something which is lacking in the beginner — a sense of taste. This sense of taste, this wisdom which you’ve acquired through real experience, is what really guides a mature programmer. In essence, wisdom transcends rules.
1. Your Code Is Like A Story(More Important)
No matter how elegantly written, how efficient or how complex your code is, a piece of code is not going to make any sense unless it is well-organized and easy to follow.
- That’s why the best code tells a clear, concise story that can be easily understood by anyone who reads it
- In other words, your code should be like a good children’s book: each line should be expressive and contribute to the overall narrative.
- the best code is often creative and expressive
- If you can’t explain it simply, you don’t understand it well enough.
- But above all, it should be easy to read and understand
2. Use Design Patterns
Design patterns can save you a lot of time and effort when it comes to coding.
But that’s not all they’re good for. Design patterns can also make your code more readable and maintainable.
So if you’re not using design patterns, you should definitely consider doing so. They could just be the thing that takes your code to the next level.
I personally recommend that you focus on reading about the more popular and commonly used design patterns and understand the reasoning behind them.
3. Follow SOLID Principles
SOLID acronym stands for:
- Single Responsibility Principle (SRP)
- Open Closed Principle (OCP)
- Liskov Substitution Principle (LSP)
- Interface Segregation Principle (ISP)
- Dependency Inversion Principle (DIP)
Here is a website where you can get into details about them:
What are the SOLID principles in Java? (educative.io)
If you don't have time to read, here are some simple code examples as a reference:
Single Responsibility Principle (SRP)
By applying SRP, we can separate the above class into three classes with separate responsibilities.
public class Vehicle {
public void printDetails() {}
public double calculateValue() {}
public void addVehicleToDB() {}
}
Open Closed Principle (OCP)
Please read the following code;
public double calculateValue(Vehicle v) {
if (v instanceof Car) {
return v.getValue() * 0.8;
if (v instanceof Bike) {
return v.getValue() * 0.5;
}
}
}
We would have to modify the above class by adding another if statement, which goes against the Open-Closed Principle.
So, we tried to remodel
public class Vehicle {
public double calculateValue() {...}
}
public class Car extends Vehicle {
public double calculateValue() {
return this.getValue() * 0.8;
}
}
public class Truck extends Vehicle {
public double calculateValue() {
return this.getValue() * 0.9;
}
}
Liskov Substitution Principle (LSP)
The Liskov Substitution Principle (LSP) applies to inheritance hierarchies such that derived classes must be completely substitutable for their base classes.
public class Rectangle {
private double height;
private double width;
public void setHeight(double h) { height = h; }
public void setWidht(double w) { width = w; }
...
}
public class Square extends Rectangle {
public void setHeight(double h) {
super.setHeight(h);
super.setWidth(h);
}
public void setWidth(double w) {
super.setHeight(w);
super.setWidth(w);
}
}
Interface segregation principle
The Interface Segregation Principle (ISP) states that clients should not be forced to depend upon interface members they do not use.
Here is a counter example
public interface Vehicle {
public void drive();
public void stop();
public void refuel();
public void openDoors();
}
public class Bike implements Vehicle {
// Can be implemented
public void drive() {...}
public void stop() {...}
public void refuel() {...}
// Can not be implemented
public void openDoors() {...}
}
The bike obviously shouldn't have doors.
ISP proposes that the interfaces be broken down into multiple, small cohesive interfaces so that no class is forced to implement any interface, and therefore methods, that it does not need.
Dependency inversion principle
The Dependency Inversion Principle (DIP) states that we should depend on abstractions (interfaces and abstract classes) instead of concrete implementations (classes).
Instead of Car depending directly on Engine, let’s add an interface:
...
public interface Engine {
public void start();
}
...
public class Car {
private Engine engine;
public Car(Engine e) {
engine = e;
}
public void start() {
engine.start();
}
}
public class PetrolEngine implements Engine {
public void start() {...}
}
public class DieselEngine implements Engine {
public void start() {...}
}
4. DRY& KISS
- DRY = Don’t Repeat Yourself
- KISS = Keep It Simple Stupid
DRY:The DRY principle is stated as, “Every piece of knowledge or logic must have a single, unambiguous representation within a system.”.Divide your code and logic into smaller reusable units and use that code by calling it where you want.
Key Points:Don’t write lengthy methods.
KISS:Wherever possible, complexity should be avoided in a system. KISS is a design principle which states that designs and/or systems should be as simple as possible.
If you have a lot of conditions in the method, break these out into smaller methods. It will not only be easier to read and maintain, but it can help find bugs a lot faster.
Key Points:smaller methods.
5. Stop Hardcoding Stuff
First of all, it can make your code more difficult to read and understand.
Secondly, it can make your code less reusable.
Finally, it can lead to errors if the values you hardcode into your code happen to change (for example, if the current year changes).
if you ever need to use the same piece of code with different values, you’ll have to go in and manually change the hardcoded values
Hard coding is junk code, It’s usually better to use variables instead.
6. Comment Your Code
Comment Your Code or you have a one clear design, which of course is very difficult.
When you come back to a piece of code that you wrote six months ago, chances are you won’t remember what it does or how it works. But if you take the time to leave a clear and concise comment, you’ll save yourself a lot of headaches later on.
In addition, commenting your code makes it easier for others to understand and work with. So next time you’re programming, remember to take a few minutes to comment your code.
7. Declare Class Members Private Wherever Possible
Rule of thumb is to try to hide information as much as possible, sharing it only when absolutely necessary.
So, as to when you should make things private: I’d say make everything private by default, and then expose only those parts that have to be public. The more you can make private, the better.
8. Use StringBuilder/Buffer For String Manipulation
9. Learn To Check for Nulls
Generally, null variables, references and collections are tricky to handle in Java code. They are not only hard to identify but also complex to deal with.
There are many ways in which you can check for nulls and actually avoid or take care of them. There is a similar article in the previous personal study notes:
[[Checking for Nulls in Java Minimize Using If Else]]
Some of the methods she is mentioning are:
- java.util.Optional
- Utility classes of apache.commons
- Objects::nonNull in Streams
- requireNonNull methods of java.util.Objects
- Lombok’s Builder.Default
- NotNull, NotEmpty, NotBlank Annotations
10. Use Proper Naming Conventions
In java, it is good practice to name class, variables, and methods as what they are actually supposed to do instead of naming them randomly.
Java uses CamelCase as a practice for writing names of methods, variables, classes, packages, and constants.
These naming conventions must be followed while developing software in java for good maintenance and readability of code.
You can view the following article to understand more details of the name specification, the subsequent personal will also read this article and organize notes:
Finally
It’s important to realize that the coding techniques you learn should not be applied blindly, without thinking.
Rules are blind, in the sense that they often don’t deal with the full context of a problem, or the complete picture.
You shouldn’t be afraid to consider breaking the rules, if you have thought about the problem, and when you feel it’s an appropriate thing to do.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。