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");
seg.add("param1");
seg.addDelim();
seg.add("param2");
seg.addLF();

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

SegBuilder seg=new SegBuilder("Command")
                .add("param1").addDelim().add("param2").addLF();

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)
  {
    segment.append(param);
    return this;
  }

  public SegBuilder AddDelim()
  {
    segment.append(delimeter);
    return this;
  }

  public SegBuilder AddLF()
  {
    segment.append("\n");
    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