如果按代碼量算工資,也許應(yīng)該這樣寫!
你知道的越多,不知道的就越多,業(yè)余的像一棵小草!
你來,我們一起精進!你不來,我和你的競爭對手一起精進!
編輯:業(yè)余草
來源:juejin.cn/post/7263760831052906552
推薦:https://t.zsxq.com/12i139nQc
自律才能自由
如果按代碼量算工資,也許應(yīng)該這樣寫!
前言
假如有一天我們要按代碼量來算工資,那怎樣才能寫出一手漂亮的代碼,同時兼顧代碼行數(shù)和實際意義呢?
要在增加代碼量的同時提高代碼質(zhì)量和可維護性,能否做到呢?
答案當然是可以,這可難不倒我們這種摸魚高手。
耐心看完,你一定有所收獲。
正文
實現(xiàn)更多的接口
給每一個方法都實現(xiàn)各種“無關(guān)痛癢”的接口,比如Serializable、Cloneable等,真正做到不影響使用的同時增加了相當數(shù)量的代碼。
為了這些代碼量,其中帶來的性能損耗當然是可以忽略的。
public class ExampleClass implements Serializable, Comparable<ExampleClass>, Cloneable, AutoCloseable {
@Override
public int compareTo(ExampleClass other) {
// 比較邏輯
return 0;
}
// 實現(xiàn) Serializable 接口的方法
private void writeObject(ObjectOutputStream out) throws IOException {
// 序列化邏輯
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
// 反序列化邏輯
}
// 實現(xiàn) Cloneable 接口的方法
@Override
public ExampleClass clone() throws CloneNotSupportedException {
// 復(fù)制對象邏輯
return (ExampleClass) super.clone();
}
// 實現(xiàn) AutoCloseable 接口的方法
@Override
public void close() throws Exception {
// 關(guān)閉資源邏輯
}
}
除了示例中的Serializable、 Comparable、 Cloneable、 AutoCloseable,還有Iterable
重寫 equals 和 hashcode 方法
重寫 equals 和 hashCode 方法絕對是上上策,不僅增加了代碼量,還為了讓對象在相等性判斷和散列存儲時能更完美的工作,確保代碼在處理對象相等性時更準確、更符合業(yè)務(wù)邏輯。
public class ExampleClass {
private String name;
private int age;
// 重寫 equals 方法
@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 && Objects.equals(this.name, other.name);
}
// 重寫 hashCode 方法
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
增加配置項和參數(shù)
不要管能不能用上,梭哈就完了,問就是為了健壯性和拓展性。
public class AppConfig {
private int maxConnections;
private String serverUrl;
private boolean enableFeatureX;
// 新增配置項
private String emailTemplate;
private int maxRetries;
private boolean enableFeatureY;
// 寫上構(gòu)造函數(shù)和getter/setter
}
增加監(jiān)聽回調(diào)
給業(yè)務(wù)代碼增加監(jiān)聽回調(diào),比如執(zhí)行前、執(zhí)行中、執(zhí)行后等各種Event,這里舉個完整的例子。
比如創(chuàng)建個 EventListener ,負責(zé)監(jiān)聽特定類型的事件,事件源則是產(chǎn)生事件的對象。通過EventListener 在代碼中增加執(zhí)行前、執(zhí)行中和執(zhí)行后的事件。
首先,我們定義一個簡單的事件類 Event:
public class Event {
private String name;
public Event(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
然后,我們定義一個監(jiān)聽器接口 EventListener:
public interface EventListener {
void onEventStart(Event event);
void onEventInProgress(Event event);
void onEventEnd(Event event);
}
接下來,我們定義一個事件源類 EventSource,在執(zhí)行某個業(yè)務(wù)方法時,觸發(fā)事件通知:
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");
// 通知監(jiān)聽器:執(zhí)行前事件
for (EventListener listener : listeners) {
listener.onEventStart(event);
}
// 模擬執(zhí)行業(yè)務(wù)邏輯
System.out.println("Executing business method...");
// 通知監(jiān)聽器:執(zhí)行中事件
for (EventListener listener : listeners) {
listener.onEventInProgress(event);
}
// 模擬執(zhí)行業(yè)務(wù)邏輯
System.out.println("Continuing business method...");
// 通知監(jiān)聽器:執(zhí)行后事件
for (EventListener listener : listeners) {
listener.onEventEnd(event);
}
}
}
現(xiàn)在,我們可以實現(xiàn)具體的監(jiān)聽器類,比如 BusinessEventListener,并在其中定義事件處理邏輯:
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());
}
}
最后,我們寫個main函數(shù)來演示監(jiān)聽事件:
public class Main {
public static void main(String[] args) {
EventSource eventSource = new EventSource();
eventSource.addEventListener(new BusinessEventListener());
// 執(zhí)行業(yè)務(wù)代碼,并觸發(fā)事件通知
eventSource.businessMethod();
// 移除監(jiān)聽器
eventSource.removeEventListener(businessEventListener);
}
}
如此這般那般,代碼量猛增,還順帶實現(xiàn)了業(yè)務(wù)代碼的流程監(jiān)聽。當然這只是最簡陋的實現(xiàn),真實環(huán)境肯定要比這個復(fù)雜的多。
構(gòu)建通用工具類
同樣的,甭管用不用的上,定義更多的方法,都是為了健壯性。
比如下面這個StringUtils,可以從ApacheCommons、SpringBoot的StringUtil或HuTool的StrUtil中拷貝更多的代碼過來,美其名曰內(nèi)部工具類。
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();
}
// 新增方法:將字符串反轉(zhuǎn)
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
// 新增方法:判斷字符串是否為整數(shù)
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
添加新的異常類型
添加更多異常類型,對不同的業(yè)務(wù)拋出不同的異常,每種異常都要單獨去處理
public class CustomException extends RuntimeException {
// 構(gòu)造函數(shù)
public CustomException(String message) {
super(message);
}
// 新增異常類型
public static class NotFoundException extends CustomException {
public NotFoundException(String message) {
super(message);
}
}
public static class ValidationException extends CustomException {
public ValidationException(String message) {
super(message);
}
}
}
// 示例:添加不同類型的異常處理
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 {
// 正常處理邏輯
}
} catch (IllegalArgumentException e) {
// 異常處理邏輯
} catch (ArithmeticException e) {
// 異常處理邏輯
}
}
}
實現(xiàn)更多設(shè)計模式
在項目中運用更多設(shè)計模式,也不失為一種合理的方式,比如單例模式、工廠模式、策略模式、適配器模式等各種常用的設(shè)計模式。
比如下面這個單例,大大節(jié)省了內(nèi)存空間,雖然它存在線程不安全等問題。
public class SingletonPattern {
// 單例模式
private static SingletonPattern instance;
private SingletonPattern() {
// 私有構(gòu)造函數(shù)
}
public static SingletonPattern getInstance() {
if (instance == null) {
instance = new SingletonPattern();
}
return instance;
}
}
還有下面這個策略模式,能避免過多的if-else條件判斷,降低代碼的耦合性,代碼的擴展和維護也變得更加容易。
// 策略接口
interface Strategy {
void doOperation(int num1, int num2);
}
// 具體策略實現(xiàn)類
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);
}
}
// 上下文類
class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy(int num1, int num2) {
strategy.doOperation(num1, num2);
}
}
// 測試類
public class StrategyPattern {
public static void main(String[] args) {
int num1 = 10;
int num2 = 5;
// 使用加法策略
Context context = new Context(new AdditionStrategy());
context.executeStrategy(num1, num2);
// 使用減法策略
context = new Context(new SubtractionStrategy());
context.executeStrategy(num1, num2);
}
}
對比下面這段條件判斷,高下立判。
public class Calculator {
public static void main(String[] args) {
int num1 = 10;
int num2 = 5;
String operation = "addition"; // 可以根據(jù)業(yè)務(wù)需求動態(tài)設(shè)置運算方式
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");
}
}
}
擴展注釋和文檔
如果要增加代碼量,寫更多更全面的注釋也不失為一種方式。
/**
* 這是一個示例類,用于展示增加代碼數(shù)量的技巧和示例。
* 該類包含一個示例變量 value 和示例構(gòu)造函數(shù) ExampleClass(int value)。
* 通過示例方法 getValue() 和 setValue(int newValue),可以獲取和設(shè)置 value 的值。
* 這些方法用于展示如何增加代碼數(shù)量,但實際上并未實現(xiàn)實際的業(yè)務(wù)邏輯。
*/
public class ExampleClass {
// 示例變量
private int value;
/**
* 構(gòu)造函數(shù)
*/
public ExampleClass(int value) {
this.value = value;
}
/**
* 獲取示例變量 value 的值。
* @return 示范變量 value 的值
*/
public int getValue() {
return value;
}
/**
* 設(shè)置示例變量 value 的值。
* @param newValue 新的值,用于設(shè)置 value 的值。
*/
public void setValue(int newValue) {
this.value = newValue;
}
}
結(jié)語
哪怕是以代碼量算工資,咱也得寫出高質(zhì)量的代碼,合理合法合情的賺票子。

代碼有兩個基本要求,一是完成了它該有的功能,二是結(jié)構(gòu)清晰明了,方便后期維護。為 KPI 而瘋狂“湊字數(shù)”,增加代碼行數(shù)只會讓代碼不好讀,不好用。
拿代碼量算工資?既毀了程序員,也早晚會毀了公司!
