return this

To implement proprietary communication protocol, I needed to create message builders as well as parsers.
Usually, we put 90% of time to implement parsing algorithm using some tools like lex/yacc (or java/cup).
Yes, builder is much easier than a parser but there's even better way to implement builders which is reusable and easy to read.
Look at following code, first.

SegBuilder seg=new SegBuilder("Command");

This is straightforward code but what if you can do like following?

SegBuilder seg=new SegBuilder("Command")

Doesn't this look like a natural language?
The secret of this usage is returning self.

class SegBuilder
  private StringBuilder segment;
  private String delimiter="*";

  public SegBuilder(String header) { segment=new StringBuilder(header); }

  public SegBuilder add(String param)
    return this;

  public SegBuilder AddDelim()
    return this;

  public SegBuilder AddLF()
    return this;

  public String toString()
    return segment.toString();

This reduced lots of my code lines and easier to explain codes to others.
Actually, it's not just for the communication but a good tip for most of object oriented programming.
Thanks David for this tip!

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License