在类方法中使用吸气剂 [英] Using getters within class methods

查看:63
本文介绍了在类方法中使用吸气剂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您的类具有一些简单的get/set属性,那么是否有任何理由在类方法中使用getter,还是应该仅使用私有成员变量?我认为可能会有更多关于setter的争论(验证逻辑?),但我想知道有关getter的问题.

If you have a class with some plain get/set properties, is there any reason to use the getters within the class methods, or should you just use the private member variables? I think there could be more of an argument over setters (validation logic?), but I'm wondering just about getters.

例如(在Java中)-是否有任何理由使用选项2?:

For example (in Java) - is there any reason to use option 2?:

public class Something
{
    private int messageId;
    public int getMessageId() { return this.messageId; }
    public void setMessage(int messageId) { this.messageId = messageId; }

    public void doSomething()
    {
        // Option 1:
        doSomethingWithMessageId(messageId);

        // Option 2:
        doSomethingWithMessageId(getMessageId());
    }
}

推荐答案

通常,Java程序员在使用getter方法方面往往非常一致.我编写了多种语言,但我不太一致;)

Java programmers in general tend to be very consistent about using getter methods. I program multiple languages and I'm not that consistent about it ;)

我想说的是,只要您不要吸气,就可以使用raw变量-用于 private 变量.当您做吸气剂时,您应该只使用它.当我为私有字段创建getter时,我的IDE建议当我引入getter时它会自动为我替换原始字段访问.切换到使用吸气剂仅几步之遥(并且没有机会引入错误),因此我倾向于将其推迟到需要时为止.

I'd say as long as you don't make a getter it's ok to use the raw variable - for private variables. When you make a getter, you should be using only that. When I make a getter for a private field, my IDE suggests that it replace raw field accesses for me automatically when I introduce a getter. Switching to using a getter is only a few keystrokes away (and without any chance of introducing errors), so I tend to delay it until I need it.

当然,如果您想使用getter-injection之类的东西,某些类型的代理和子类化的framworks(例如休眠),则必须使用getters!

Of course, if you want to stuff like getter-injection, some types of proxying and subclassing framworks like hibernate, you have to user getters!

这篇关于在类方法中使用吸气剂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆