[英]Should we have java getter for bean without actual property behind it?
Is it a good practice to have getter method for a property for which actual property in not defined inside a bean. 对没有在bean内部定义实际属性的属性使用getter方法是一种好习惯吗? For example let's say I have a bean class like below: Website Bean: 例如,假设我有一个如下所示的Bean类:网站Bean:
public class Website
{
private string name;
public string getName() {
return name;
}
public string getUrl() {
return "http://" + name + "-env.organization.com";
}
}
And lets say if I am working on struts the using this class as follows : Index.jsp: 并说如果我正在使用以下类使用struts:Index.jsp:
<logic:present name="Website" property="url">
<li><a href="<bean:write name="Website" property="url"/>" class="webAdress" target="_blank"><bean:write name="exhibitor" property="url"/></a></li>
</logic:present>
So my question is: Is is a good practice to use url like this in jsp file while we don't have any property binding behind it. 所以我的问题是:在jsp文件中使用像这样的url是一种好习惯,而我们背后没有任何属性绑定。 Do we see any issues in this or its perfectly fine to use like this ? 我们是否看到任何问题,或者使用这种方法完全正常?
edit: changed return type to string of getUrl() 编辑:将返回类型更改为getUrl()的字符串
It's perfectly OK to have the getUrl()
method. 拥有getUrl()
方法是完全可以的。
To the outside world, your Website class has a property named url
, no matter how the class answers questions for this property - that's private internals of your class. 对于外界,您的Website类具有一个名为url
的属性,无论该类如何回答有关此属性的问题-这都是您的类的私有内部。 Bean properties are not at all restricted to just pass a field value. Bean属性完全不限于仅传递字段值。
Things might become a little more complex if you were to implement a setUrl()
method, as your callers expect the getUrl()
method to return the value they stored with setUrl()
. 如果要实现setUrl()
方法,事情可能会变得有些复杂,因为调用者希望getUrl()
方法返回他们使用setUrl()
存储的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.