Java – how to avoid using getters and hard coding the UI?

I want to print a description of a soldier on the console, including the strength of the soldier and the weapon of the soldier. The form is < description > the soldier uses < weapon > for example, this powerful soldier uses a butter knife

Edit for clarity: I want to query the data object without doing so by using getters or any other method implemented inside the display object, such as toString I also want to do this without hard coding the current UI (console) to the object itself

public class Warrior
{
  private String description;
  private Weapon weapon;

  public Room(String description,Weapon weapon)
  {
    this.description = description;
    this.weapon = weapon
  }
}

public class Weapon
{
  private String name;

  public Weapon(String name)
  {
    this.name = name;
  }
}

Avoid inhaling

I can avoid using getters by hard coding the UI:

//Warrior class
public void display() 
{
  String.out.println("This " + description + " warrior uses a ");
  weapon.display();
}

//Weapon class
public void display() 
{
  String.out.print(name);
}

Avoid hard coded UI

I can avoid using hard coded UI by using getters:

//Warrior class
public String getDescription() 
{
  return "This " + description + " warrior uses a " + weapon.getName();
}

//Weapon class
public String getName() 
{
  return name;
}

Is it possible to avoid both? How can I do this in the above example?

Note: in response to some initial answers, getter does not follow the naming convention getsomefieldname Therefore, renaming getsomefieldname to a methodthatisnotprefixedbyget is not a solution Getter is a method that passes private data from an object to the scope that calls it

To be completely clear, the problem I want to solve here is data encapsulation (because this problem is marked) How to prevent data from being passed to objects that do not need to know the data but are still difficult to hard code the UI?

In addition, based on on these questions, I don't think toString should be used in the way suggested by many answers ToString seems to be used to generate text representations of objects for debugging, etc., rather than to return arbitrary output, especially not application dependent output

Solution

Yes, go I18N,

messages.properties
displayMessage = This {0} warrior uses a {1}

messages.properties_en_US
displayMessage = This {0} warrior uses a {1}

and

public static String getString(String key,Object... params  ) {
        try {
            return messageformat.format(RESOURCE_BUNDLE.getString(key),params);
        } catch (MissingResourceException e) {
            return '!' + key + '!';
        }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>