Last active
March 31, 2016 15:45
-
-
Save ccdschool/67a9534ceb3ac2f8fbeaa916cc607113 to your computer and use it in GitHub Desktop.
Quellcode zum Artikel über die Refaktorisierung
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using NUnit.Framework; | |
using System.Collections.Generic; | |
using System.Linq; | |
[TestFixture] | |
public class WordWrap | |
{ | |
[Test] | |
public void testErzeugeZeilen() { | |
var worte = new[]{ "1", "22", "333", "55555"}; | |
var lineLength = 5; | |
var result = WordWrap.Erzeuge_Zeilen(worte, lineLength); | |
Assert.AreEqual(new String[]{"1 22", "333", "55555"}, result); | |
} | |
[Test] | |
public void testErzeugeZeilenMitZuLangemWort() { | |
var worte = new[]{ "1", "22", "666666", "55555"}; | |
var lineLength = 5; | |
var result = WordWrap.Erzeuge_Zeilen(worte, lineLength); | |
Assert.AreEqual(new String[]{"1 22", "66666", "6", "55555"}, result); | |
} | |
static string[] Erzeuge_Zeilen(string[] worte, int maxLineLength) { | |
return worte.Aggregate (new Ergebnistext (maxLineLength), | |
(text, wort) => text.Erweitern (wort)) | |
.Zeilen; | |
} | |
class Ergebnistext { | |
List<string> zeilen = new List<string>(); | |
string aktuelleZeile = ""; | |
int maxLineLength; | |
public Ergebnistext(int maxLineLength) { | |
this.maxLineLength = maxLineLength; | |
} | |
public Ergebnistext Erweitern(string wort) { | |
Versuche_Wort_noch_in_Zeile_aufzunehmen (wort, | |
() => Versuche_zu_langes_Wort_umzubrechen (wort, | |
() => Neue_Zeile_mit_Wort_beginnen (wort)) | |
); | |
return this; | |
} | |
void Versuche_Wort_noch_in_Zeile_aufzunehmen(string wort, Action wortPasstDochNichtInZeile) { | |
int futureLength = this.aktuelleZeile.Length + wort.Length + (this.aktuelleZeile.Length > 0 ? 1 : 0); | |
if (futureLength <= this.maxLineLength) { | |
this.aktuelleZeile += (this.aktuelleZeile.Length > 0 ? " " : "") + wort; | |
} else | |
wortPasstDochNichtInZeile(); | |
} | |
void Versuche_zu_langes_Wort_umzubrechen(string wort, Action wortDochNichtZuLang) { | |
if (string.IsNullOrEmpty (this.aktuelleZeile) && wort.Length > this.maxLineLength) { | |
this.zeilen.Add (wort.Substring (0, this.maxLineLength)); | |
Erweitern (wort.Substring (this.maxLineLength)); | |
} else | |
wortDochNichtZuLang (); | |
} | |
void Neue_Zeile_mit_Wort_beginnen(string wort) { | |
this.zeilen.Add(this.aktuelleZeile); | |
this.aktuelleZeile = ""; | |
Erweitern (wort); | |
} | |
public string[] Zeilen { | |
get { | |
if (string.IsNullOrEmpty (this.aktuelleZeile)) | |
return this.zeilen.ToArray (); | |
else | |
return this.zeilen.Concat (new[]{ this.aktuelleZeile }).ToArray (); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment