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?
toStringmethod inside classAddress(I personally don’t like this approach, as ‘toString’ is not directly related to an Address)- class
ReadableAddressFormatterReadableAddressFormatter(AddressaddressToFormat)- public
String getFormatted()
- Previous class but
getFormmatedwould be static, receiving theAddressinstance and returning the string - Other? Suggestions please.
I’m looking for a good design, focusing also in Clean Code, Decoupling and Maintainability.
All of these methods have been used, and there’s no way to offer a “context independent” best practice. The best answer in Software Engineering is usually “it depends.” That’s said, let’s analyze each:
Hope this helps, and kudos for thinking about Clean Code, Decoupling, and Maintainability from the beginning.
For an example of principle #2 in action–using the Strategy Pattern, adhering to the Single Responsibility Principle, the Open/Closed Principle and allowing for Inversion of Control via Dependency Injection— compare the following approach (graciously provided by @SteveJ):
With this one (in “mostly correct” Groovy):
As @SteveJ has observed: