Last active
November 23, 2023 18:43
-
-
Save fercomunello/b36a9bd730461b9bae8eb438e437f2c3 to your computer and use it in GitHub Desktop.
An OOP Text implementation (not nullable & always "trimmed")
This file contains hidden or 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
@Test | |
@DisplayName("Any nullable text should always produce an empty value") | |
void testTextDefaultValue() { | |
assertEquals("", new Text(null).toString()); | |
} |
This file contains hidden or 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
import java.util.Objects; | |
public class Text implements CharSequence { | |
protected final CharSequence origin; | |
public Text(final String origin) { | |
this.origin = origin == null ? "" : origin.trim(); | |
} | |
public Text(final Object origin) { | |
this.origin = origin == null ? "" : origin.toString().trim(); | |
} | |
public Text(final CharSequence origin) { | |
this.origin = origin instanceof String str ? str.trim() : ""; | |
} | |
public boolean isBlank() { | |
return this.origin instanceof String str && str.isBlank(); | |
} | |
@Override | |
public String toString() { | |
return this.origin.toString(); | |
} | |
@Override | |
public int length() { | |
return this.origin.length(); | |
} | |
@Override | |
public char charAt(final int index) { | |
if (index < 0 || index >= length()) { | |
throw new StringIndexOutOfBoundsException(index); | |
} | |
return this.origin.charAt(index); | |
} | |
@Override | |
public CharSequence subSequence(final int start, final int end) { | |
final int length = length(); | |
if (start < 0 || start > end || end > length) { | |
throw new StringIndexOutOfBoundsException( | |
"begin " + start + ", end " + end + ", length " + length); | |
} | |
return this.origin.subSequence(start, end); | |
} | |
@Override | |
public boolean equals(final Object o) { | |
if (this == o) return true; | |
if (!(o instanceof Text)) return false; | |
return Objects.equals(this.origin, ((Text) o).origin); | |
} | |
@Override | |
public int hashCode() { | |
return Objects.hash(this.origin); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment