Ex10 - why should "indent" call "newline"?

L4_
BASIC-Programmierer
BASIC-Programmierer
Beiträge: 104
Registriert: 24. Apr 2012 15:44

Ex10 - why should "indent" call "newline"?

Beitrag von L4_ »

Hello,

the SourceCodeBuilder contains the following code:

Code: Alles auswählen

  def indent() {
    ind += 1
    if (buf.last != '\n') newline()
  }
If the last line is not '\n', the builder will be returned (by "newline()").
Otherwise, we do not return the builder.
What is the point of that?
Shouldn't "indent" only increase the level without side effects?

Furthermore, if buf.isEmpty == true, buf.last will throw a nullpointer exception.
Shouldn't we check that before?

Kind regards

imaier
Mausschubser
Mausschubser
Beiträge: 61
Registriert: 21. Okt 2013 21:27

Re: Ex10 - why should "indent" call "newline"?

Beitrag von imaier »

In the code template, the indent method will also automatically add a newline, yes. This makes sense for the given use case. Moreover, your SourceCodeBuilder doesn't have to be bullet proof, and you are of course open to change the implementation slightly. It is meant to be an internal support class used by the other builders. In an actual implementation, it would make sense to catch errors early, e.g., throw a sensible exception if indent is called before anything else, or alternatively make indent safe, but that also depends a bit on the level of abstraction this builder represents.

The important part for this exercise is that it correctly maintains indentation, that the other builder use it correctly and that it gives you a feel for a somewhat low-level builder.

Cheers,
Ingo

Antworten

Zurück zu „Archiv“