0

I have implemented a utility class called FormatUtils (final with static methods) that converts data from Employee objects into a usable format (e.g. stripping '$' signs off strings and parsing them as doubles, reformatting names into first and last names). Now, somewhere in my code, I need a method that formats lots of Employee data fields for output as a single string (sent later to stdout). Does it make sense to put it in this utility class when it is probably only going to be needed for use with Employee objects, rather than having general purpose?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
false_azure
  • 1,333
  • 4
  • 25
  • 46
  • Sounds like you should move it to `Employee#toString()`. – Keppil Apr 09 '13 at 20:23
  • sounds like a `employee.toString()` method – Kent Apr 09 '13 at 20:24
  • Sounds like a plan! Thanks – false_azure Apr 09 '13 at 20:25
  • Maybe is just me, but I don't think is a good idea that your entity package depends on utility package. An option may be having `Employee#toString` (as stated by 2 people) but maybe (just maybe) you have another class that could receive the `Employee` object and return a `String` from it. – Luiggi Mendoza Apr 09 '13 at 20:26

2 Answers2

2

I'd probably move the methods to format a single Employee into the Employee class itself. If there's different/additional formatting that needs to be done for a list of employees (like row & column headings, for example), I might put that in a utility method (or class, if it needs to be reused).

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
1

Don't use Employee#toString() to format it for human readers; use that method for debugging only. Otherwise, you might not be able to use anything in the class to show its status in the debugger. I know the primitive wrappers and enums use toString() for that, but that's mostly for using them with string concatenation.

What does "stripping '$' signs off strings and parsing them as doubles" mean? Are you storing the employee's salary as a String? Don't do that. By and large, currency values should be BigDecimal or BigInteger objects. You put the dollar signs in when formatting using NumberFormat.getCurrencyInstance(). It makes database work easier too.

If you are busy splitting names into first and last names, you really need a Name class, and you should provide formatters for that. For JPA work, you can make the Name instance variable@Embeddable.

You can give the Employee class format methods, or you can have your class implement java.util.Formattable, possibly accepting the alternative formatting flag. You could even use 'getless programming' and give Employee methods like:

public void writeToFormally(final Appendable a) {...}
public void writeToSimply(final Appendable a) {...}
Eric Jablow
  • 7,874
  • 2
  • 22
  • 29