Bernardo Sulzbach
Bernardo Sulzbach

Reputation: 1581

Should toString be used for a complex operation?

I have a class named CommandHelp. It stores some strings that (obviously) describe what a command does, what are its aliases, the arguments it requires and whatever else I need to register about the command.

CommandHelp.toString() is a "complex" method as it does not return the command name or anything short such as "COMMAND: GOTO", instead it returns (usually) a 200+ character long String object.

The class also has a toOneLineString() method.

Question is:

Should toString - as a method's name - be avoided? Would it be considered a good practice (or a better practice) to use toFullString or toFullCommandDescription as that method's name?

EDIT: toString() was overriden. I was just asking if the method I implemented there should be refactored under another method name.

Upvotes: 1

Views: 83

Answers (1)

Bohemian
Bohemian

Reputation: 425003

The wisdom is that toString() should only be used for humans to read and developers should be free to change the implementation at will without impacting the program's behaviour.

Methods that produce a String that is relied on by other code to have a particular format should not involve toString() in any way.

Your idea of special methods seems on the right track. Consider using method names like getDescription().

Upvotes: 4

Related Questions