Because the official account has changed the push rules, please click “Looking” and add “star” to get exciting technology sharing as soon as possible
Click to follow the #InternetArchitect official account and get the full set of architect information here
0,2T architect learning materials dry content
Previous article: Sharing of useful learning materials for 2T architects
Hi everyone, I am an Internet Architect!
Foreword
If one day we have to calculate wages based on the amount of code, how can we write beautiful code while taking into account the number of lines of code and its practical significance?
Is it possible to improve code quality and maintainability while increasing the amount of code?
The answer is of course yes, which is not difficult for fish masters like us.
If you read it patiently, you will definitely gain something.
Text
Implement more interfaces
Implement various “insignificant” interfaces for each method, such as Serializable
, Cloneable
, etc., which truly does not affect the use and adds a considerable amount of code.
For this amount of code, the performance loss is certainly negligible.
public class ExampleClass implements Serializable, Comparable<ExampleClass>, Cloneable, AutoCloseable { @Override public int compareTo(ExampleClass other) { // comparison logic return 0; } //Methods that implement the Serializable interface private void writeObject(ObjectOutputStream out) throws IOException { // Serialization logic } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { //Deserialization logic } //Methods that implement the Cloneable interface @Override public ExampleClass clone() throws CloneNotSupportedException { //Copy object logic return (ExampleClass) super.clone(); } // Method to implement the AutoCloseable interface @Override public void close() throws Exception { //Close resource logic } }
In addition to Serializable
, Comparable
, Cloneable
, AutoCloseable
in the example, there is also Iterable
Override equals and hashcode methods
Rewriting the equals
and hashCode
methods is definitely the best idea. It not only increases the amount of code, but also allows the object to work more perfectly during equality judgment and hash storage. Ensure your code is more accurate and consistent with business logic when handling object equality.
public class ExampleClass { private String name; private int age; // Override equals method @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } ExampleClass other = (ExampleClass) obj; return this.age == other.age & amp; & Objects.equals(this.name, other.name); } // Override hashCode method @Override public int hashCode() { return Objects.hash(name, age); } }
Add configuration items and parameters
Don’t worry about whether it can be used or not. Stud is over. The reason for asking is for robustness and scalability.
public class AppConfig { private int maxConnections; private String serverUrl; private boolean enableFeatureX; //Add configuration item private String emailTemplate; private int maxRetries; private boolean enableFeatureY; //Write constructor and getter/setter }
Add listening callback
Add listening callbacks to the business code, such as various events before execution, during execution, and after execution. Here is a complete example.
For example, create an EventListener
that is responsible for listening to specific types of events. The event source is the object that generates the event. Use EventListener
to add pre-execution, execution and post-execution events in the code.
First, we define a simple event class Event
:
public class Event { private String name; public Event(String name) { this.name = name; } public String getName() { return name; } }
Then, we define a listener interface EventListener
:
public interface EventListener { void onEventStart(Event event); void onEventInProgress(Event event); void onEventEnd(Event event); }
Next, we define an event source class EventSource
to trigger event notification when a certain business method is executed:
public class EventSource { private List<EventListener> listeners = new ArrayList<>(); public void addEventListener(EventListener listener) { listeners.add(listener); } public void removeEventListener(EventListener listener) { listeners.remove(listener); } public void businessMethod() { Event event = new Event("BusinessEvent"); //Notification listener: pre-execution event for (EventListener listener : listeners) { listener.onEventStart(event); } // Simulate execution of business logic System.out.println("Executing business method..."); //Notification listener: executing event for (EventListener listener : listeners) { listener.onEventInProgress(event); } // Simulate execution of business logic System.out.println("Continuing business method..."); //Notification listener: post-execution event for (EventListener listener : listeners) { listener.onEventEnd(event); } } }
Now, we can implement a specific listener class, such as BusinessEventListener
, and define event processing logic in it:
public class BusinessEventListener implements EventListener { @Override public void onEventStart(Event event) { System.out.println("Event Start: " + event.getName()); } @Override public void onEventInProgress(Event event) { System.out.println("Event In Progress: " + event.getName()); } @Override public void onEventEnd(Event event) { System.out.println("Event End: " + event.getName()); } }
Finally, we write a main function to demonstrate listening events:
public class Main { public static void main(String[] args) { EventSource eventSource = new EventSource(); eventSource.addEventListener(new BusinessEventListener()); // Execute business code and trigger event notification eventSource.businessMethod(); //Remove listener eventSource.removeEventListener(businessEventListener); } }
In this way, the amount of code increased sharply, and process monitoring of business code was also implemented. Of course, this is just the crudest implementation, and the real environment must be much more complicated than this.
Build a common tool class
Similarly, regardless of whether they are used or not, defining more methods is all for the sake of robustness.
For example, for the following StringUtils, you can copy more code from Apache Commons, SpringBoot’s StringUtil or HuTool’s StrUtil, and euphemistically call it an internal tool class.
public class StringUtils { public static boolean isEmpty(String str) { return str == null || str.trim().isEmpty(); } public static boolean isBlank(String str) { return str == null || str.trim().isEmpty(); } // New method: reverse the string public static String reverse(String str) { if (str == null) { return null; } return new StringBuilder(str).reverse().toString(); } // New method: determine whether a string is an integer public static boolean isInteger(String str) { try { Integer.parseInt(str); return true; } catch (NumberFormatException e) { return false; } } }
Add new exception type
Add more exception types and throw different exceptions for different businesses. Each exception must be handled separately.
public class CustomException extends RuntimeException { // Constructor public CustomException(String message) { super(message); } //Add exception type public static class NotFoundException extends CustomException { public NotFoundException(String message) { super(message); } } public static class ValidationException extends CustomException { public ValidationException(String message) { super(message); } } }
//Example: Add different types of exception handling public class ExceptionHandling { public void process(int value) { try { if (value < 0) { throw new IllegalArgumentException("Value cannot be negative"); } else if (value == 0) { throw new ArithmeticException("Value cannot be zero"); } else { //Normal processing logic } } catch (IllegalArgumentException e) { //Exception handling logic } catch (ArithmeticException e) { //Exception handling logic } } }
Implement more design patterns
It is also a reasonable way to use more design patterns in the project, such as singleton pattern, factory pattern, strategy pattern, adapter pattern and other commonly used design patterns.
For example, the following singleton greatly saves memory space, although it has problems such as thread insecurity.
public class SingletonPattern { // singleton mode private static SingletonPattern instance; private SingletonPattern() { // private constructor } public static SingletonPattern getInstance() { if (instance == null) { instance = new SingletonPattern(); } return instance; } }
There is also the following strategy pattern, which can avoid excessive if-else conditional judgments, reduce the coupling of the code, and make the expansion and maintenance of the code easier.
//Strategy interface interface Strategy { void doOperation(int num1, int num2); } //Specific strategy implementation class class AdditionStrategy implements Strategy { @Override public void doOperation(int num1, int num2) { int result = num1 + num2; System.out.println("Addition result: " + result); } } class SubtractionStrategy implements Strategy { @Override public void doOperation(int num1, int num2) { int result = num1 - num2; System.out.println("Subtraction result: " + result); } } //Context class class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void executeStrategy(int num1, int num2) { strategy.doOperation(num1, num2); } } // test class public class StrategyPattern { public static void main(String[] args) { int num1 = 10; int num2 = 5; // Use addition strategy Context context = new Context(new AdditionStrategy()); context.executeStrategy(num1, num2); // Use subtraction strategy context = new Context(new SubtractionStrategy()); context.executeStrategy(num1, num2); } }
Compare the following conditional judgment and make a judgment.
public class Calculator { public static void main(String[] args) { int num1 = 10; int num2 = 5; String operation = "addition"; // The operation method can be dynamically set according to business needs if (operation.equals("addition")) { int result = num1 + num2; System.out.println("Addition result: " + result); } else if (operation.equals("subtraction")) { int result = num1 - num2; System.out.println("Subtraction result: " + result); } else if (operation.equals("multiplication")) { int result = num1 * num2; System.out.println("Multiplication result: " + result); } else if (operation.equals("division")) { int result = num1 / num2; System.out.println("Division result: " + result); } else { System.out.println("Invalid operation"); } } }
Extended comments and documentation
If you want to increase the amount of code, writing more and more comprehensive comments is also a way to do it.
/** * This is a sample class to demonstrate techniques and examples for increasing the amount of code. * This class contains an example variable value and an example constructor ExampleClass(int value). * Through the example methods getValue() and setValue(int newValue), the value of value can be obtained and set. * These methods are used to show how to increase the amount of code, but do not actually implement the actual business logic. */ public class ExampleClass { // example variables private int value; /** * Constructor */ public ExampleClass(int value) { this.value = value; } /** * Get the value of the example variable value. * @return the value of the demonstration variable value */ public int getValue() { return value; } /** * Set the value of the example variable value. * @param newValue The new value, used to set the value of value. */ public void setValue(int newValue) { this.value = newValue; } }
Conclusion
Even if the salary is calculated based on the amount of code, we still have to write high-quality code and earn money in a reasonable, legal and reasonable way.
The code has two basic requirements. One is to complete its functions, and the other is to have a clear structure to facilitate later maintenance. Crazy “cracking up the word count” for KPIs and increasing the number of lines of code will only make the code difficult to read and use.
Do you calculate your salary based on code volume? It will not only destroy the programmers, but it will also destroy the company sooner or later!
1.2TSharing of useful learning materials for architects
2.10000 + TB resources, Alibaba cloud disk, awesome! !
3. Basically covers the summary of all core knowledge points of Spring
· END ·
Finally, follow the public account Internet Architect and reply in the background: 2T, you can get the Java series interview questions and answers I compiled, which is very complete.
If this article is helpful or inspiring to you, please scan the QR code above to pay attention. Your support is my biggest motivation to keep writing.
Please like, retweet and watch three times in one click