Search code examples
javajavabeansgetterstruts-1

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. For example let's say I have a bean class like below: Website 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:

        <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. Do we see any issues in this or its perfectly fine to use like this ?

edit: changed return type to string of getUrl()


Solution

  • It's perfectly OK to have the getUrl() method.

    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. Bean properties are not at all restricted to just pass a field value.

    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().