OO Design Advice - toString

2020-02-26 09:07发布

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?

  1. toString method inside class Address (I personally don't like this approach, as 'toString' is not directly related to an Address)
  2. class ReadableAddressFormatter
    • ReadableAddressFormatter(Address addressToFormat)
    • public String getFormatted()
  3. Previous class but getFormmated would be static, receiving the Address instance and returning the string
  4. Other? Suggestions please.

I'm looking for a good design, focusing also in Clean Code, Decoupling and Maintainability.

7条回答
男人必须洒脱
2楼-- · 2020-02-26 10:10

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.

public class TestClass {

    class City{};

    class State{};

    class Country{};

    class Address {
        private String streetAddress;
        private int number;
        private String postalCode;
        private City city;
        private State state;
        private Country country;

        public String toLongFormat(){
            return null; // stitch together your long format
        }

        public String toShortFormat(){
            return null; // stitch together your short format
        }

        public String toMailingLabelFormat(){
            return null; // stitch together your mailing label format
        }

        @Override
        public String toString(){
            return toShortFormat(); // your default format
        }
    }

}
查看更多
登录 后发表回答