Java中的访问器和Mutator [英] Accessor and Mutator in Java

查看:138
本文介绍了Java中的访问器和Mutator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如在主要方法中,我有setFirstName()并调用 Contact 类来执行此操作. 在联系人类中,我知道我应该使用:public String getName() 然后public void setFirstName(String name)

我知道这是正确的方法. 但是相反,我发现如果我这样做:

public String setFirstName(String name)
{
    return this.name=name;
}

这也将起作用,我不需要使用getName()方法.

有人可以帮我这是为什么吗?我的访问器/更改器方法正确吗?

解决方案

这是访问器的基本概念,它仅读取但不进行修改.这是一个有用的约定,因为如果一致地进行操作,将使您对某些代码的推理变得不那么容易.通常,您不必从名为getX()的东西中得到怪异的副作用.进行一些延迟初始化可能是可以的,但是更清楚的是,是否将此类延迟获取器"命名为getOrCreateX()或类似名称,以便向用户暗示首次使用可能会花费更长的时间/并涉及一些昂贵的操作.

返回某些内容的增变器可能会很有用,但是如果您以某种暗示其返回内容的方式对其进行命名,它将对类的用户有所帮助.是错误代码还是先前的值?人们不期望来自名为setX()的东西的返回值,因此他们会惊讶地看到这样的签名,而不得不查看类的文档以了解它的作用.

摘要:始终编写代码,好像别人随时都需要接管您的代码一样-不要做令人惊讶的事情.即使您从未将代码交给其他任何人,您未来的自我也会感谢您选择能够解释该方法功能的名称.

注意:您对setter的实现不是很有用,因为它总是返回您刚刚传入的新值.

For instance in main method I havesetFirstName() and call the Contact class to do this. In the contact class I know I should use:public String getName() and then public void setFirstName(String name)

I know this is the right way to do that. But instead, I find that if i do:

public String setFirstName(String name)
{
    return this.name=name;
}

this will also work and I don't need to use getName()method.

Can anyone please help me out why is that? Is my accessor/mutator method correct?

解决方案

It is the very idea of an accessor that it only reads but does not modify. That is a useful convention, because if done consistently it makes reasoning about some code you don't know a lot easier. Normally, you shouldn't have to expect weird side effects from something named getX(). It may be ok to do some lazy initialization, but it is clearer if such "lazy getters" are named getOrCreateX() or similar to give the user a hint that the first use might take a bit longer/involve some expensive operation.

A mutator that returns something may be useful, but it will help users of your class if you name it in a way that gives a hint about what it returns. Is it an error code or the previous value? People don't expect return values from something named setX(), so they will be surprised to see such a signature and have to look at the documentation of your class to see what it does.

Summary: Always code as if someone else will have to take over your code any moment - don't do things that would be surprising. Even if you never hand your code to anyone else, your future self will thank you for picking names that explain what the method does.

Note: Your implementation of the setter is not very useful, as it always returns the new value you just passed in.

这篇关于Java中的访问器和Mutator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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