Java - 我应该在方法中使用 getter 吗?

问题描述 投票:0回答:2

我有两种可行的解决方案,但我应该使用哪一种?哪个解决方案是正确的?

解决方案1:

List<Client> myClient = new ArrayList<>();
public class Client {
    private final String firstName;
    private final String lastName;
    protected String cID;
    protected boolean subscription = false;
}
public int getNumberOfSubsrtipion(){
    int count = 0;

    for( Client myCustomer: myClient ){
        if( myCustomer.subscription ){
            count += 1;
        }
    }

    return count;
}

解决方案2:

List<Client> myClient = new ArrayList<>();
public class Client {
    private final String firstName;
    private final String lastName;
    protected String cID;
    private boolean subscription = false;

    protected boolean getSubscription(){
        return this.subscription;
    }
}
public int getNumberOfSubsrtipion(){
    int count = 0;

    for( Client myCustomer: myClient ){
        if( myCustomer.getSubscription() ){
            count += 1;
        }
    }

    return count;
}

解决方案仅在 IF 条件函数的内容上有所不同。

java getter-setter
2个回答
0
投票

两个都很好。在第一种情况下,如果其他功能需要,您可以使用 getter。


0
投票

如果这是一门私人课程,那么在我看来,您使用哪一个并不重要。如果您要发布该类,我将使用

getters
setters
,以便您可以隐藏字段存储方式的实现细节。后者还允许您更改它们的存储方式,而不影响用户的应用程序。

© www.soinside.com 2019 - 2024. All rights reserved.