[英]Best practice to avoid function's parameter manipulation
我有以下抽象代碼片段:
// definitions
MyClass1 mc1 = new MyClass1();
MyClass2 mc2 = new MyClass2();
List<String> elements = new ArrayList<>();
// some black magic...
// setters based on condition 0
mc2.setElements(elements);
String id = saveMyClass2(mc2)
mc1.setMc1Id(id);
// Some other business black magic
// setters based on condition 1
mc2.setElements(elements);
String id = saveMyClass2(mc2)
mc1.setMc1Id(id);
// Some other business black magic
// setters based on condition 2
mc2.setElements(elements);
String id = saveMyClass2(mc2)
mc1.setMc1Id(id);
我在代碼的多個部分使用了 setter 流程。 我想通過這樣的包裝函數來詳細說明:
void doSettings(MyClass1 mc1, MyClass2 mc2, List<String> elements) {
mc2.setElements(elements);
String id = saveMyClass2(mc2)
mc1.setMc1Id(id);
}
但是我正在這個函數中進行參數操作,我想避免。 克隆類也不是一種選擇,它們有 3 層深,創建深拷貝需要花費太多精力。
那么,您是否知道有助於避免代碼重復的任何最佳實踐或編碼模式?
一個真正好的方法是使用Immutable
裝飾器。 Immutable
模式是主要對象的包裝器,可防止對基礎數據進行更改。 這些使用Unmodifable
概念的Collections
開箱即用:
String[] array = ... ;
List<String[]> list = List.<String[]>of(array);
或copyOf()
在另一個集合的情況下:
List<String> mylist = ...;
List<String> unmodifableList = List.copyOf(mylist);
對於您正在定義的其他對象,您可能希望創建一個子類,在調用更改器時拋出UnsupportedOperationException
。
class UnmodifiableMyClass1 extends MyClass1 {
UnmodifiableMyClass1( MyClass1 copy) {
// do copy constructor stuff here
// (probably just referencing the primary object)
}
@override void setMc1Id( int id ) {
throw new UnsupportedOperationException("nope");
}
}
MyClass1 mc1 = new MyClass1();
UnmodifiableMyClass1 umc1 = new UnmodifiableMyClass1(mc1);
當然,如果您可以在接口而不是實現上執行此操作,那是最好的,因為維護對象狀態的需求較少,但是您必須使用現有的東西,並且您沒有提到擁有MyClass{1,2}
的接口.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.