So I got the Address
class:
class Address
{
private String streetAddress;
private int number;
private String postalCode;
private City city;
private State state;
private Country country;
}
And I want to get its readable version to, lets say, show in a grid column.
Whats the best and concise way to implement this?
toString
method inside classAddress
(I personally don't like this approach, as 'toString' is not directly related to an Address)- class
ReadableAddressFormatter
ReadableAddressFormatter
(Address
addressToFormat
)- public
String getFormatted()
- Previous class but
getFormmated
would be static, receiving theAddress
instance and returning the string - Other? Suggestions please.
I'm looking for a good design, focusing also in Clean Code, Decoupling and Maintainability.
toString() is the most flexible and convenient, being implicitly called when you combine an object of the Address class with a String, as in System.out.println("My address is " + objectOfAddressClass).
The only reason I can think of to not override toString() is if you need to alter the formatting. Then you would need different methods (as in toMailingString() and toShortFormString() and so on) or a parameterized method (as in toMailingString(boolean useShortForm) or whatever), but either way, toString() won't cut it.
Of course, you can (and should) do both. Have toString() as your default, probably calling one of your specific format methods, and then have your other helper methods for alternate formats.