Re: Prize and Milestone as mutable state idioms
"Tyler Close" <[email protected]>
| Newsgroups | gmane.comp.lang.e.general |
|---|---|
| Message-ID | <[email protected]> |
On Tue, Jul 1, 2008 at 11:26 AM, Monty Zukowski <monty-aaXZSQuah4Ac3H1WRXY/HAC/[email protected]> wrote: > I really like those idioms of Milestone and Prize, however in the code > for ValueWriter, I'm not clear on why Prize is important to > understanding the code. ... > > In general I'm having trouble understanding the expected flow through > the code, and after 15 minutes of studying it I'm giving up. The goal of the ValueWriter is to ensure that its client can only output a syntactically correct JSON value. The ValueWriter provides an API for generating all the different kinds of JSON values and the client gets to choose which one to use, but it can only choose one! The Prize class is used to ensure that once the client starts creating a particular kind of JSON value, it sticks to that decision; otherwise, the output stream would be corrupted. Each of the writeXXX() methods starts by claiming the prize, the output stream, and then writes to it. If the prize has already been claimed, an exception is thrown. A correctly coded client will never encounter this exception, only a buggy or malicious one. > I also don't understand: > > 116 protected ValueWriter > 117 startMember(final String name) throws IOException { > 118 if (!member.isWritten()) { throw new NullPointerException(); } > 119 > 120 member = new ValueWriter(inset, out); // prevent > calls until after The "member" variable acts almost like a Prize, but not quite. A JSON object can contain an arbitrary number of members. Once a client has started creating a member, it must finish it, but once it's done, a new member can be started. Line 120 above is like claiming a newly created Prize, where the prize is the ability to output a new member. The check on line 118 ensures that the previously created member is complete before allowing this new prize to be created and claimed. > I was going to comment that the below code will throw a > NullPointerException if called twice, but then I noticed > NullPointerExceptions being thrown on purpose elsewhere for > essentially the same reason. Oh, maybe that's why you use Prize, to > force that NPE instead of possibly writing the output twice? > > 81 protected ObjectWriter > 82 startObject() throws IOException { > 83 final Writer out = output.claim(); > 84 out.write('{'); Yes, that's it exactly. So it looks like you understood the concept of a Prize, and eventually understood why the output stream was being treated as one. Is that right? How could this be made clearer? A comment at the Prize construction site? Thanks, --Tyler