2 ms·
Circle can inherit from Ellipse if objects of both classes are immutable. The "stretch" method should return a new Ellipse. The implementation of "stretch" gets
by cousin_it 16y ago
Circle can inherit from Ellipse if objects of both classes are immutable. The "stretch" method should return a new Ellipse. The implementation of "stretch" gets inherited into class Cicrle, so stretching a Circle yields a new Ellipse as the method signature says.
That example may look impractical. Here's a better one: define SanitizedString as a subclass of String (if your language allows that). Methods that output HTML to the client can take SanitizedStrings as input, so the type checker ensures the absence of XSS attacks. The constructor of SanitizedString could take an ordinary String and sanitize it, and that's the whole implementation of SanitizedString, because all other methods are already provided by String and none of them can break the sanitization because String is immutable. So using immutable objects allows you to write less code and get more compile-time guarantees.
- pornel 16y agoSince there is no universally safe string, it would be better to call it HTMLString (different context such as SQL, e-mail headers, CLI require different types of sanitisation). string.convertToHTML() would escape special characters as HTML entities, preserving the fact that it's just a benign text.