Program Tip

내 getter 메서드가 저장된 값을 변경하도록하는 것이 나쁜 습관입니까?

programtip 2020. 11. 9. 20:32
반응형

내 getter 메서드가 저장된 값을 변경하도록하는 것이 나쁜 습관입니까?


내 수업에서 버전 2와 같은 getter 메서드를 변경하는 것이 나쁜 습관입니까?

버전 1 :

 public String getMyValue(){
     return this.myValue
 }

버전 2 :

 public String getMyValue(){

    if(this.myValue == null || this.myValue.isEmpty()){
       this.myValue = "N/A";
    }

    return this.myValue;
 }

getter 메서드가 개체의 내부 상태를 변경하는 것은 실제로 매우 나쁜 습관이라고 생각 합니다.

같은를 달성하기 위해 난 그냥 제안 반환"N/A".

  • 일반적으로이 내부 필드는 getter 메서드를 사용할 필요가없는 다른 장소 (내부적으로)에서 사용될 수 있습니다. 따라서 결국에 대한 호출 foo.getMyValue()은 실제로의 동작을 변경할 수 있습니다 foo.

또는에서 nullto 로의 변환 "N/A"setter 에서 수행 될 수 있습니다 . 즉, 내부 값이 "N/A"if null가 전달됨 으로 설정 될 수 있습니다 .


일반적인 설명 : 일부 API 또는 코드에 의존하는 다른 인스턴스에서 예상되는
상태와 같은 상태 만 추가 "N/A"합니다. 그렇지 않은 경우 프로그래밍 언어에서 사용할 수있는 표준 null 유형을 사용해야합니다.


내 생각에, 당신이하고 있지 않는 한 (당신이 lazy-loading그런 경우가 아닌) 게터는 값을 변경해서는 안됩니다. 따라서 다음 중 하나를 수행합니다.

setter에 변경 사항을 넣으십시오.

public void setMyValue(String value) {
    if(value == null || value.isEmpty()){
        this.myValue = "N/A";
    } else {
        this.myValue = value;
    }
}

또는 값이 제대로 설정되지 않은 경우 getter가 기본값을 반환하도록합니다.

public String getMyValue() {
    if(this.myvalue == null || this.myvalue.isEmpty()){
        return "N/A";
    }    
    return this.myValue;
}

게터에서 멤버를 변경하는 것이 좋다고 말하는 지연 로딩의 경우 다음과 같이 할 수 있습니다.

public String getMyValue() {
    if (this.myvalue == null) {
        this.myvalue = loadMyValue();
    }    
    return this.myValue;
}

아뇨. 여기서 두 가지를하고 있습니다. 얻기 및 설정.


예. 그것은 나쁜 습관입니다.

왜?

값이 설정되면 (생성자 또는 setter 메서드에서) getter 메서드가 호출 될 때가 아니라 유효성을 검사해야합니다. 이를위한 private validate*방법을 만드는 것도 좋은 생각입니다.

private boolean validateThisValue(String a) {
     return this.myValue != null && !this.myValue.isEmpty();
}

public void setThisValue(String a) {
    if (validateThisValue(a)) {
        this.myValue = a;
    } 
    else {
        // do something else
        // in this example will be
        this.myValue = "N/A";
    }
}

그리고 getter 메소드에서는 절대로 객체의 상태를 변경하지 마십시오. 나는 몇몇 프로젝트에서 일했고, getter는 종종 만들어 져야한다 const: "이 방법은 내부 상태를 바꿀 수 없다".

적어도 일을 복잡하게하고 싶지 않다면 getter 메소드에서 내부 상태를 변경하는 대신 리턴 하고로 설정 해야 합니다."N/A"myValue"N/A"


나는 일반적으로 특정 getter.

원본을 변경하지 마십시오 getter.

 public String getMyValue(){
     return this.myValue
 }

그리고 특정 생성 getter:

public String getMyValueFormatted(){

    if(this.myvalue == null || this.myvalue.isEmpty()){
       return "N/A";
    }else{
       return this.myValue;
    }
 }

I think it's better to initialize this.myValue = "N/A". And subsequent calls to setMyValue should modify the this.myValue according to your business conditions.
The getMyValue shouldn't modify in any way this.myValue. If your needs are to return a certain value, you should return that value (like "N/A") and not alter this.myValue . Getters must not modify member's value.


I would change better the setter method so, if the value is null or empty, the N/A is assigned to the attribute. So, if you use the attribute in other methods inside the class (v.g. toString()) you will have the intended value there.

Alternatively, change the setter method to launch an exception when the value being set is not right, so the programmer is forced to improve its handling prior to setting the value.

Other than that, it is ok.


I do feel this is a bad practice unless and until you explain the reason why it is so necessary for you modify the object inside the getter method instead of doing it inside the setter method.
Do you feel this cannot be done for some reason? Could you please elaborate?


Do what ever you like. After all getters and setters are just another public methods. You could use any other names.

But if you use frameworks like Spring, you are bound to use those standard names and you should never put your custom codes inside them.


A setter could modify as part of validation, but a getter should return the value and let the validation be done by the caller. If you do validate, then how should be documented.


This actually highly depends on the contract you want to enforce with your get()-method. According to design-by-contract conventions the caller has to make sure that the preconditions are met (which means doing a validation in a setter method often is actually bad design) and the callee (I do not know if that's the correct english term for that, i.e., the called one) makes sure that the post conditions are met.

If you define your contract so that the get()-method is not allowed to change the object then you are breaking your own contract. Think about implementing a method like

public isValid() {
    return (this.myvalue == null || this.myvalue.isEmpty());
}

Advantage of this approach is that you do not have to check wether the return of your get() is "N/A" or something else. This also can be called before calling set() to validate that you do not insert illegal values into your object.

If you want to set a default value you should do that during initialization.


absolutely yes, it's a bad pratice.

Imagine you communicate accross network with a third party (remoting, COM, ...), this will increase the round-trip and then hit application performance.


State changes in getters should be a hanging offence. It means that client code must be careful about the order in which it accesses getters and setters and to do this it must have knowledge of the implementation. You should be able to call the getters in any order and still get the same results. A related problem occurs when the setter modifies the incoming value depending on the current state of the object.


You can use some value holder for this purpose. Like Optional class in guava library.

참고URL : https://stackoverflow.com/questions/13876066/is-it-bad-practice-to-have-my-getter-method-change-the-stored-value

반응형