在 get 中使用 set 是一种不好的做法吗?
Is it a bad practice to use a set inside get?
您好,我在 android 项目中使用 MVVM 模式,对于 ViewModel,代码如下:
public class LoginViewModel extends ViewModel {
public MutableLiveData<User> user = new MutableLiveData<>();
public MutableLiveData<String> email = new MutableLiveData<>();
public MutableLiveData<String> password = new MutableLiveData<>();
public MutableLiveData<Boolean> emailError = new MutableLiveData<>();
public MutableLiveData<Boolean> register = new MutableLiveData<>();
private LoginRespository loginRespository = new LoginRespository();
private MutableLiveData<Boolean> enable = new MutableLiveData<>();
public LoginViewModel() {
}
public void login() {
...
}
public void startRegister() {
...
}
private String getEmailValue() {
if (email.getValue() == null) {
email.setValue("");
}
return email.getValue();
}
....
}
在办公室,我们讨论过在 get 中使用 set 是一种不好的做法,但我认为这不是一个坏做法,因为 java 允许空值,我不想这样做调用 getEmailValue() 时得到一个空值 我认为封装的概念就是针对这些情况的。
问题是这是否真的是一种不好的做法?
谢谢
是的,这是不好的做法;你的 getters 不应该修改任何状态(他们自己或通过调用 setters),只是检查并公开它。
您的特定问题的解决方案是执行以下两项操作之一:
让你的getterreturn一个空字符串而不是null
,不修改存储值.
private String getEmailValue() {
String emailValue = email.getValue();
return emailValue != null ? emailValue : "";
}
让您的 setter 将传入的 null
值替换为空字符串。
private String setEmailValue(String email) {
email.setValue(email != null ? email : "");
}
这样,您可以确定当您调用 getEmailValue()
时,您将始终得到一个非空的 String
,但您永远不会修改 setter 中的对象。
您好,我在 android 项目中使用 MVVM 模式,对于 ViewModel,代码如下:
public class LoginViewModel extends ViewModel {
public MutableLiveData<User> user = new MutableLiveData<>();
public MutableLiveData<String> email = new MutableLiveData<>();
public MutableLiveData<String> password = new MutableLiveData<>();
public MutableLiveData<Boolean> emailError = new MutableLiveData<>();
public MutableLiveData<Boolean> register = new MutableLiveData<>();
private LoginRespository loginRespository = new LoginRespository();
private MutableLiveData<Boolean> enable = new MutableLiveData<>();
public LoginViewModel() {
}
public void login() {
...
}
public void startRegister() {
...
}
private String getEmailValue() {
if (email.getValue() == null) {
email.setValue("");
}
return email.getValue();
}
....
}
在办公室,我们讨论过在 get 中使用 set 是一种不好的做法,但我认为这不是一个坏做法,因为 java 允许空值,我不想这样做调用 getEmailValue() 时得到一个空值 我认为封装的概念就是针对这些情况的。
问题是这是否真的是一种不好的做法?
谢谢
是的,这是不好的做法;你的 getters 不应该修改任何状态(他们自己或通过调用 setters),只是检查并公开它。
您的特定问题的解决方案是执行以下两项操作之一:
让你的getterreturn一个空字符串而不是
null
,不修改存储值.private String getEmailValue() { String emailValue = email.getValue(); return emailValue != null ? emailValue : ""; }
让您的 setter 将传入的
null
值替换为空字符串。private String setEmailValue(String email) { email.setValue(email != null ? email : ""); }
这样,您可以确定当您调用 getEmailValue()
时,您将始终得到一个非空的 String
,但您永远不会修改 setter 中的对象。