Good programming practices

StructuredInfo – objects instead of plain String

December 29th, 2011

Common method toString is a simple way to display inner values of an object. But when you get a String want to present it in other format it can be difficult or unsafe to parse it. So better way is to pass a structured object witch can be next serialized to desired format. So I created a project in Scala 2.9.1 for gathering and serializing information in an application.

Sample code using these classes:

  1. object InfoMain {
  2. def main(args: Array[String]): Unit = {
  3. println("Info example")
  4.  
  5. val info = new OrderedInfo("Top").addComment(new Date).
  6. addProperty("top1", "value1").
  7. addInfo(new OrderedInfo("Level1").addProperty("valueL1", 1).
  8. addInfo(new OrderedInfo("Level2").addComment("next comment").
  9. addProperty("valueL2", 1)).
  10. addComment("many\nlines\nhere"))
  11.  
  12. println("Ini file:")
  13. println(new IniFormatter(info).toString)
  14. }
  15. }

Output of the above code:

  1. Info example
  2. Ini file:
  3. [Top]
  4. ; Thu Dec 29 09:56:01 CET 2011
  5. top.top1 = value1
  6. [Top.Level1]
  7. top.level1.valueL1 = 1
  8. [Top.Level1.Level2]
  9. ; next comment
  10. top.level1.level2.valueL2 = 1
  11. ; many
  12. ; lines
  13. ; here

Full source code of the StructuredInfo project is available at github.org. License ISC.

Leave a Response