I want to print a description of a warrior to the console that will include the warrior's strength and the warrior's weapon in the form This <description> warrior uses a <weapon> For example: This strong warrior uses a butter knife.
Edit for clarity: I want to do this without asking objects for data by using getters or any other method (like toString) which reveals the internal implementation of an object. I also want to do this without hard coding my current UI (a console) into the objects themselves.
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;
}
}
I can avoid 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);
}
I can avoid a 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 so in the above example?
Note: In response to some initial answers, a getter is not a method that follows the naming convention getSomeFieldName. Therefore, renaming getSomeFieldName to aMethodThatIsNotPrefixedByGet is not a solution. A getter is a method that passes private data from an object to the scope which called it.
To be completely clear, the issue I am trying to deal with here is to do with data encapsulation (as this question is tagged). How can I prevent passing data to objects which do not need to know that data and still avoid hard coding the UI?
Additionally, based on these questions, I don't think toString should be used in the way that it has been suggested by the many of the answers. toString seems to be for generating a text representation of an object for debugging and so forth, not for returning arbitrary output and especially not for returning application dependent output.
Yes go for 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 + '!';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With