Một kỹ thuật tôi đã sử dụng trong C# (và chỉ được chuyển đến Java - xin lỗi nếu tôi đã mắc lỗi, tôi mới sử dụng Java) là tạo các lớp StringlyTyped, ví dụ:một lớp cơ sở
public abstract class StringlyTyped {
private String value;
public StringlyTyped (String value){
if (value == null){
throw new IllegalArgumentException("value must not be null");
}
this.value = value;
}
public String getValue() { return value; }
@Override
public boolean equals(Object other){
if (other == this) {
return true;
}
if (other == null || !this.getClass().equals(other.getClass())){
return false;
}
StringlyTyped o = (StringlyTyped)other;
return o.getValue().equals(this.getValue());
}
@Override
public int hashCode(){ return this.getValue().hashCode(); }
@Override
public String toString() { return this.getValue(); }
}
Sau đó, có nguồn gốc lớp
public class ProviderName extends StringlyTyped {
public ProviderName(String value) {
super(value);
}
}
Và sử dụng
public void Foo(ProviderName provider) {
}
Nó có ý nghĩa khi bạn có phương pháp với nhiều parametrers String, ví dụ bạn có thể tránh
public void Foo(String username, String password, String db, String table, String constraint)
và thay vào đó có mã số đó là mạnh mẽ gõ như thế này:
public void Foo(UserName username, Password password, DatabasePath db, TableName table...)
vv ...
Nguồn
2016-04-24 10:14:49
không lưu trữ đường dẫn cơ sở dữ liệu trong các biến hoặc tạo ra một lớp học để đại diện cho một databasae với hoạt động được xác định trong phương pháp, âm thanh tốt. – NimChimpsky