Taskcore
Add a method to an existing type
Also called add a method to a built-in type, extend a type, extend String, extension method, extension trait, add a method to a class you do not own, retroactive method.
Give the string type of the language a word_count method that it does not have, with an extension method, an extension trait, a prototype property, a subclass, a new type or a free function.
- Evidence
- Code in 9 languages
Task
Add a method word_count to the string type of the language, so that code can write text.word_count() for any string text. The method returns the number of words, where a word is a run of one or more characters that are not whitespace. The string type comes from the language or its standard library, so the code cannot change its source.
Then use it. The function word_count(text) returns the count, through the method when the language allows one. For example, word_count("the quick fox") is 3, and word_count(" two\twords\r\nand three ") is 4. The input has 0 to 100,000 characters, and its only whitespace characters are space, tab, newline and carriage return. The tests also check that the method does not break other code that uses strings.
Languages give very different answers. Some add a method that is only a static function with a receiver, some change the type for the whole program, and some do not allow either. Each solution uses the nearest form that its language allows.
Solutions
| Language | Form | Does the type change? | Called as |
|---|---|---|---|
| Python | a subclass Text(str) |
no; only Text values have the method |
Text(s).word_count() |
| JavaScript | a property on String.prototype |
yes, for all code in the realm | s.wordCount() |
| TypeScript | declare global plus the prototype property |
yes, for all code in the realm | s.wordCount() |
| Java | a static method in the utility class Words |
no | Words.wordCount(s) |
| C# | an extension method | no | s.WordCount() |
| Go | a new type Text with string as its underlying type |
no | Text(s).WordCount() |
| Rust | an extension trait WordCount implemented for str |
no | s.word_count() |
| C | a function | no | word_count(s) |
| C++ | a free function in the namespace words |
no | words::word_count(s) |
- C# uses an extension method.
WordCount(this string text)is a static method, and thethismodifier lets code call it astext.WordCount(). The guide says that extension members add methods "without creating a new derived type, recompiling, or otherwise modifying the original type."1 The test checks thatstringitself has noWordCountmethod. - Rust uses an extension trait. The crate defines the trait
WordCountand implements it forstr. The orphan rule allows this, because "we can implement a trait on a type only if either the trait or the type, or both, are local to our crate."2 Here the trait is local. The method works on aStringtoo, because aStringdereferences tostr, and only code that imports the trait can call it. - Go uses a new type. A method needs a receiver type that is declared in the same package: "A receiver base type cannot be a pointer or interface type and it must be declared in the same package as the method."3 So the package declares
type Text stringand putsWordCounton it. A conversionText(s)costs nothing, but aTextis a different type fromstring. - JavaScript changes the prototype. Every string gets its methods from
String.prototype, so a function on it is a method of every string in the program. The code usesObject.defineProperty, because "properties added using Object.defineProperty() are not writable, not enumerable, and not configurable"4 by default; the code setswritableandconfigurableto true, and keeps the method out offor...inloops like the built-in methods. It also refuses to replace awordCountthat is already there. - TypeScript adds a type declaration. The run-time code is the JavaScript code.
declare global { interface String { wordCount(): number } }tells the compiler about the method, because interface declarations merge, and "You can also add declarations to the global scope from inside a module".5 - Python uses a subclass. A built-in type such as
strdoes not accept new attributes, sostr.word_count = ...fails with aTypeError. A subclassText(str)adds the method and keeps all the methods ofstr. Only values made asTexthave the method. - Java uses a static method. Java has no extension methods, and
Stringis declared aspublic final class String,6 so a subclass is not possible either.Words.wordCount(text)takes the string as its first parameter. - C and C++ use a function. C has no methods. C++ cannot add a member function to
std::string, so a free function in a namespace takes astd::string_view, which accepts astd::string, a string literal and a part of a string.
Alternatives
- Kotlin extension functions.
fun String.wordCount() = ...adds a function that code calls as a method. Kotlin says that "extensions don't modify the classes or interfaces they extend",7 in the same way as C#. - Monkey patching a user-defined class. In Python, Ruby and JavaScript, code can assign a function to an attribute of a class that it did not write, and every instance gets the method. See open classes and monkey patching for the risks.
- A wrapper or decorator type. A class that holds a string and adds methods works in every language with classes, as Go's
Textdoes. It is the safest form, but code must wrap and unwrap the values. - A free function. The plain function
word_count(text)is the answer in C, and it is a good answer in every language. A method form is only shorter to call.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: the empty string has no words, so the result is 0.blank: a string of only whitespace also has no words. A count of the separators, plus one, gives a wrong answer here and in theemptycase.mixed-whitespace: tabs, newlines, a carriage return and runs of more than one space separate words, and the string starts and ends with spaces. A split on a single space gives empty words.non-ascii:naïve café 東京has 3 words. The counts are of runs, so it does not matter whether a language reads bytes, UTF-16 code units or code points.
Pitfalls
- A changed prototype is global. The JavaScript method is on every string in the realm, for every library. Two libraries that add
wordCountwith different rules break each other. Wikipedia lists this risk: "If the same method is patched multiple times, then only the last one is used; the other patches have no effect".8 A new version of the language can also add a method with the same name. The solution checks for an existingwordCountfirst. - An enumerable property shows in loops. An assignment such as
String.prototype.wordCount = function () {...}makes an enumerable property, sofor (const k in s)lists it next to the indexes.Object.definePropertywithenumerable: falsedoes not.
String.prototype.shout = function () { return this.toUpperCase() + "!"; };
Object.defineProperty(String.prototype, "whisper", {
value: function () { return this.toLowerCase() + "..."; },
writable: true,
configurable: true,
});
const keys = [];
for (const k in "hi") keys.push(k);
console.log(keys.join(" "));
console.log("Hi".shout(), "Hi".whisper());
0 1 shout
HI! hi...
- A member wins over an extension. A C# extension method or a Kotlin extension function with the same signature as a member is never called. If a later version of the type adds
WordCount, the code calls the new member, which can count words in a different way. - Extensions use the declared type. A C# extension method is chosen at compile time from the declared type of the expression, so it does not act like a virtual method. A Rust trait method works only where the trait is imported.
- A new type does not mix with the old type. A Go
Textis not astring, and a PythonTextloses its type after moststrmethods:Text("a").upper()returns a plainstr.
Related tasks
- Define a method on a type defines a method on a type that the code owns.
- Extension methods explains how extension methods work and how the compiler picks them.
- Open classes and monkey patching explains how dynamic languages change a class at run time.
- Partial classes splits one type that the code owns into parts.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
class Text(str):
"""A str with one more method. A built-in type such as str cannot get new
attributes, so a subclass adds the method, and a Text is still a str."""
__slots__ = ()
def word_count(self):
"""Returns the number of runs of characters that are not whitespace."""
return len(self.split())
def word_count(text):
return Text(text).word_count()
test_words.py 36 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
import pytest
from words import Text, word_count
CASES = {
"three-words": ("the quick fox", 3),
"one-word": ("hello", 1),
"punctuation": ("Hello, world! How are you?", 5),
"empty": ("", 0),
"blank": (" \t\n ", 0),
"mixed-whitespace": (" two\twords\r\nand three ", 4),
"non-ascii": ("naïve café 東京", 3),
}
@pytest.mark.parametrize("name", CASES)
def test_word_count(name):
text, want = CASES[name]
assert word_count(text) == want
def test_text_is_still_a_str():
t = Text("one two")
assert isinstance(t, str)
assert t == "one two"
assert t.upper() == "ONE TWO"
assert t.word_count() == 2
def test_str_itself_does_not_change():
assert not hasattr("one two", "word_count")
with pytest.raises(TypeError):
str.word_count = Text.word_count
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
#include "words.hpp"
namespace words {
int word_count(std::string_view text) {
int count = 0;
bool in_word = false;
for (char c : text) {
const bool space = c == ' ' || c == '\t' || c == '\n' || c == '\r';
if (!space && !in_word) {
count++;
}
in_word = !space;
}
return count;
}
} // namespace words
words.hpp 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
#ifndef WORDS_HPP
#define WORDS_HPP
#include <string_view>
// C++ cannot add a member function to std::string. A free function in the
// namespace of the code takes the string as a parameter instead.
namespace words {
// word_count returns the number of runs of characters in text that are not
// space, tab, newline or carriage return.
int word_count(std::string_view text);
} // namespace words
#endif
test_words.cpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
#include "words.hpp"
#include <iostream>
#include <string>
#include <string_view>
static int failures = 0;
static void check(std::string_view name, std::string_view text, int want) {
if (words::word_count(text) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("three-words", "the quick fox", 3);
check("one-word", "hello", 1);
check("punctuation", "Hello, world! How are you?", 5);
check("empty", "", 0);
check("blank", " \t\n ", 0);
check("mixed-whitespace", " two\twords\r\nand three ", 4);
check("non-ascii", "na\xc3\xafve caf\xc3\xa9 \xe6\x9d\xb1\xe4\xba\xac", 3);
const std::string s = "one two"; // a std::string converts to std::string_view
if (words::word_count(s) != 2) {
std::cerr << "case std-string failed\n";
failures++;
}
if (failures == 0) {
std::cout << "all cases passed\n";
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
/**
* Java cannot add a method to String: the class is final, and the language has no extension
* methods. A static method in a utility class takes the string as its first parameter instead.
*/
public final class Words {
private Words() {}
/** Returns the number of runs of characters that are not space, tab, newline or return. */
public static int wordCount(String text) {
int count = 0;
boolean inWord = false;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
boolean space = c == ' ' || c == '\t' || c == '\n' || c == '\r';
if (!space && !inWord) {
count++;
}
inWord = !space;
}
return count;
}
}
WordsTest.java 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.lang.reflect.Modifier;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class WordsTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("three-words", "the quick fox", 3),
Arguments.of("one-word", "hello", 1),
Arguments.of("punctuation", "Hello, world! How are you?", 5),
Arguments.of("empty", "", 0),
Arguments.of("blank", " \t\n ", 0),
Arguments.of("mixed-whitespace", " two\twords\r\nand three ", 4),
Arguments.of("non-ascii", "naïve café 東京", 3));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void wordCount(String name, String text, int want) {
assertEquals(want, Words.wordCount(text), name);
}
@Test
void stringIsFinal() {
assertTrue(Modifier.isFinal(String.class.getModifiers()));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
#include "words.h"
#include <stdbool.h>
static bool is_space(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r';
}
int word_count(const char *text) {
int count = 0;
bool in_word = false;
for (const char *p = text; *p != '\0'; p++) {
bool space = is_space(*p);
if (!space && !in_word) {
count++;
}
in_word = !space;
}
return count;
}
words.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
#ifndef WORDS_H
#define WORDS_H
// C has no methods, and its strings are arrays of char, so nothing can be
// added to the type. A function that takes the string as its first parameter
// does the job.
// word_count returns the number of runs of characters in the NUL-terminated
// string text that are not space, tab, newline or carriage return.
int word_count(const char *text);
#endif
test_words.c 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
#include "words.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *name, const char *text, int want) {
int got = word_count(text);
if (got != want) {
fprintf(stderr, "case %s failed: got %d, want %d\n", name, got, want);
failures++;
}
}
int main(void) {
check("three-words", "the quick fox", 3);
check("one-word", "hello", 1);
check("punctuation", "Hello, world! How are you?", 5);
check("empty", "", 0);
check("blank", " \t\n ", 0);
check("mixed-whitespace", " two\twords\r\nand three ", 4);
check("non-ascii", "na\xc3\xafve caf\xc3\xa9 \xe6\x9d\xb1\xe4\xba\xac", 3);
if (failures == 0) {
printf("all cases passed\n");
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
using System;
/// <summary>
/// Adds WordCount to string. An extension method is a static method whose first
/// parameter has the this modifier, so code can call it as text.WordCount().
/// </summary>
public static class StringExtensions
{
private static readonly char[] Whitespace = [' ', '\t', '\n', '\r'];
/// <summary>Returns the number of runs of characters that are not whitespace.</summary>
public static int WordCount(this string text) =>
text.Split(Whitespace, StringSplitOptions.RemoveEmptyEntries).Length;
}
StringExtensionsTests.cs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
using Xunit;
public sealed class StringExtensionsTests
{
public static TheoryData<string, string, int> Cases => new()
{
{ "three-words", "the quick fox", 3 },
{ "one-word", "hello", 1 },
{ "punctuation", "Hello, world! How are you?", 5 },
{ "empty", "", 0 },
{ "blank", " \t\n ", 0 },
{ "mixed-whitespace", " two\twords\r\nand three ", 4 },
{ "non-ascii", "naïve café 東京", 3 },
};
[Theory]
[MemberData(nameof(Cases))]
public void WordCount(string name, string text, int want)
{
Assert.NotNull(name);
Assert.Equal(want, text.WordCount());
}
[Fact]
public void ExtensionIsAStaticCall()
{
Assert.Equal(2, StringExtensions.WordCount("one two"));
Assert.Null(typeof(string).GetMethod("WordCount"));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
// Add wordCount to String.prototype, so that every string has it. The
// property is not enumerable, like the built-in methods, and the code refuses
// to replace a method that is already there.
if ("wordCount" in String.prototype) {
throw new Error("String.prototype.wordCount is already defined");
}
Object.defineProperty(String.prototype, "wordCount", {
value: function wordCount() {
return this.split(/[ \t\n\r]+/).filter((w) => w !== "").length;
},
writable: true,
configurable: true,
enumerable: false,
});
export function wordCount(text) {
return text.wordCount();
}
words.test.js 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { wordCount } from "./words.js";
const cases = [
["three-words", "the quick fox", 3],
["one-word", "hello", 1],
["punctuation", "Hello, world! How are you?", 5],
["empty", "", 0],
["blank", " \t\n ", 0],
["mixed-whitespace", " two\twords\r\nand three ", 4],
["non-ascii", "naïve café 東京", 3],
];
for (const [name, text, want] of cases) {
test(name, () => {
assert.equal(wordCount(text), want);
});
}
test("every string has the method", () => {
assert.equal("one two".wordCount(), 2);
assert.equal(String("a b c").wordCount(), 3);
});
test("the method is not enumerable", () => {
const keys = [];
for (const k in "ab") {
keys.push(k);
}
assert.deepEqual(keys, ["0", "1"]);
assert.equal(Object.keys(String.prototype).includes("wordCount"), false);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
// Tell the compiler that every string has wordCount. Interface declarations
// merge, so this adds a member to the global String interface.
declare global {
interface String {
wordCount(): number;
}
}
// Then add the method at run time, as in JavaScript.
if ("wordCount" in String.prototype) {
throw new Error("String.prototype.wordCount is already defined");
}
Object.defineProperty(String.prototype, "wordCount", {
value: function wordCount(this: string): number {
return this.split(/[ \t\n\r]+/).filter((w) => w !== "").length;
},
writable: true,
configurable: true,
enumerable: false,
});
export function wordCount(text: string): number {
return text.wordCount();
}
words.test.ts 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { wordCount } from "./words.ts";
const cases: [string, string, number][] = [
["three-words", "the quick fox", 3],
["one-word", "hello", 1],
["punctuation", "Hello, world! How are you?", 5],
["empty", "", 0],
["blank", " \t\n ", 0],
["mixed-whitespace", " two\twords\r\nand three ", 4],
["non-ascii", "naïve café 東京", 3],
];
for (const [name, text, want] of cases) {
test(name, () => {
assert.equal(wordCount(text), want);
});
}
test("every string has the method", () => {
assert.equal("one two".wordCount(), 2);
assert.equal(Object.keys(String.prototype).includes("wordCount"), false);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
// Package words adds a method to a string type. Go allows a method only on a
// type declared in the same package, so the package declares Text, a new type
// whose underlying type is string, and puts the method on it.
package words
import "strings"
// Text is a string with methods. Convert with Text(s) and string(t).
type Text string
// WordCount returns the number of runs of characters that are not whitespace.
func (t Text) WordCount() int {
return len(strings.Fields(string(t)))
}
// WordCount counts the words of a plain string through Text.
func WordCount(text string) int {
return Text(text).WordCount()
}
words_test.go 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
package words
import "testing"
var cases = []struct {
name string
text string
want int
}{
{"three-words", "the quick fox", 3},
{"one-word", "hello", 1},
{"punctuation", "Hello, world! How are you?", 5},
{"empty", "", 0},
{"blank", " \t\n ", 0},
{"mixed-whitespace", " two\twords\r\nand three ", 4},
{"non-ascii", "naïve café 東京", 3},
}
func TestWordCount(t *testing.T) {
for _, c := range cases {
if got := WordCount(c.text); got != c.want {
t.Errorf("%s: got %d, want %d", c.name, got, c.want)
}
}
}
func TestTextIsAString(t *testing.T) {
var x Text = "one two"
if x.WordCount() != 2 || string(x)+"!" != "one two!" || len(x) != 7 {
t.Fatal("Text does not behave like a string")
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
/// An extension trait. The trait is local to this crate, so the crate can
/// implement it for `str`, a type of the standard library. Code that imports
/// the trait can call `text.word_count()` on any string slice.
pub trait WordCount {
/// Returns the number of runs of characters that are not whitespace.
fn word_count(&self) -> usize;
}
impl WordCount for str {
fn word_count(&self) -> usize {
self.split_whitespace().count()
}
}
pub fn word_count(text: &str) -> usize {
text.word_count()
}
tests/words_test.rs 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/add-a-method-to-an-existing-type/.
use algo_add_a_method_to_an_existing_type::{word_count, WordCount};
#[test]
fn cases() {
let cases: Vec<(&str, &str, usize)> = vec![
("three-words", "the quick fox", 3),
("one-word", "hello", 1),
("punctuation", "Hello, world! How are you?", 5),
("empty", "", 0),
("blank", " \t\n ", 0),
("mixed-whitespace", " two\twords\r\nand three ", 4),
("non-ascii", "naïve café 東京", 3),
];
for (name, text, want) in cases {
assert_eq!(word_count(text), want, "{name}");
}
}
#[test]
fn method_works_on_str_and_string() {
assert_eq!("one two".word_count(), 2);
assert_eq!(String::from("a b c").word_count(), 3);
}
References
- Extension members, C# programming guide, Introduction; Binding extension members at compile time
- Defining Shared Behavior with Traits, The Rust Programming Language, Implementing a Trait on a Type
- The Go Programming Language Specification, Method declarations
- Object.defineProperty(), JavaScript reference, MDN, Description
- Declaration Merging, TypeScript Handbook, Global augmentation
- String (Java SE 21 & JDK 21), API documentation, Class String, declaration
- Extensions, Kotlin documentation, Introduction; Nullable receivers
- Monkey patch, Wikipedia, Introduction; Pitfalls
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 089KSM Edit this page History Report an error Markdown