#92 HVal validation

Matthew Lohbihler Wed 5 Jun 2013

I'm not sure it's entirely efficient to have validation of HVals in the toZinc method. For example, if the unit attribute of an HNum is invalid, an IllegalArgumentException is throws in the toZinc/toString call. I think a better way to do this is to validate the unit in the constructor. An even better way would be to have a validate method that could be called at the client code's convenience.

I would be willing to make these changes if there is agreement...

Brian Frank Thu 6 Jun 2013

I agree in principle that state validation should be in constructor. But looking at the code, I'm not sure I see where HNum unit throws IllegalArgumentException - its really just tokenizing specific chars and then passes raw string to HNum constructor?

Matthew Lohbihler Fri 7 Jun 2013

This is the toZinc method currently in the repo:

public String toZinc()
{
  StringBuffer s = new StringBuffer();
  if (val == Double.POSITIVE_INFINITY) s.append("INF");
  else if (val == Double.NEGATIVE_INFINITY) s.append("-INF");
  else if (Double.isNaN(val)) s.append("NaN");
  else
  {
    // don't let fractions
    double abs = val; if (abs < 0) abs = -abs;
    if (abs > 1.0)
      s.append(new DecimalFormat("#0.####").format(val));
    else
      s.append(val);

    if (unit != null)
    {
      for (int i=0; i<unit.length(); ++i)
      {
        int c = unit.charAt(i);
        if (c < 128 && !unitChars[c]) throw new IllegalArgumentException("Invalid unit name '" + unit + "', char='" + (char)c + "'");
        s.append((char)c);
      }
    }
  }
  return s.toString();
}

Note how characters in the unit attribute are validated, with an IllegalArgumentException if something bad is found.

This code illustrates the issue:

HNum.make(123, "#").toZinc();

Brian Frank Fri 7 Jun 2013

Oh - I was looking at reader. Yeah, I agree with that change - if you want to fix, please email me a patch to [email protected], that would be great

Matthew Lohbihler Fri 7 Jun 2013

How wedded are you to code formatting? My eclipse automatically formats code using the Eclipse built-in, which is very different than current Haystack code.

Brian Frank Fri 7 Jun 2013

How wedded are you to code formatting?

Very :-)

Matthew Lohbihler Fri 7 Jun 2013

What about Java 1.4? Generics are pretty useful.

Brian Frank Fri 7 Jun 2013

What about Java 1.4? Generics are pretty useful.

I wrote it all to be run on Java J2ME which does not support generics, and unless we did some major rewrite, that is the way I would like to keep it (at least for few more years)

Matthew Lohbihler Fri 7 Jun 2013

I created a bitbucket fork of the project, made my changes, and then created a pull request. Please have a look. And happy birthday.

Login or Signup to reply.