Programming Search⌘K

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.

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 the this modifier lets code call it as text.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 that string itself has no WordCount method.
  • Rust uses an extension trait. The crate defines the trait WordCount and implements it for str. 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 a String too, because a String dereferences to str, 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 string and puts WordCount on it. A conversion Text(s) costs nothing, but a Text is a different type from string.
  • 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 uses Object.defineProperty, because "properties added using Object.defineProperty() are not writable, not enumerable, and not configurable"4 by default; the code sets writable and configurable to true, and keeps the method out of for...in loops like the built-in methods. It also refuses to replace a wordCount that 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 str does not accept new attributes, so str.word_count = ... fails with a TypeError. A subclass Text(str) adds the method and keeps all the methods of str. Only values made as Text have the method.
  • Java uses a static method. Java has no extension methods, and String is declared as public 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 a std::string_view, which accepts a std::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 Text does. 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 the empty case.
  • 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 wordCount with 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 existing wordCount first.
  • An enumerable property shows in loops. An assignment such as String.prototype.wordCount = function () {...} makes an enumerable property, so for (const k in s) lists it next to the indexes. Object.defineProperty with enumerable: false does 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());
Output
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 Text is not a string, and a Python Text loses its type after most str methods: Text("a").upper() returns a plain str.

Code

The build runs the native tests of each language in a pinned toolchain.

words.pyI0RawGitHub
# 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
words.cppI0RawGitHub
// 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;
}
Words.javaI0RawGitHub
// 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()));
  }
}
words.cI0RawGitHub
// 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;
}
StringExtensions.csI0RawGitHub
// 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"));
    }
}
words.jsI0RawGitHub
// 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);
});
words.tsI0RawGitHub
// 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);
});
words.goI0RawGitHub
// 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")
	}
}
words.rsI0RawGitHub
// 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

  1. Extension members, C# programming guide, Introduction; Binding extension members at compile time
  2. Defining Shared Behavior with Traits, The Rust Programming Language, Implementing a Trait on a Type
  3. The Go Programming Language Specification, Method declarations
  4. Object.defineProperty(), JavaScript reference, MDN, Description
  5. Declaration Merging, TypeScript Handbook, Global augmentation
  6. String (Java SE 21 & JDK 21), API documentation, Class String, declaration
  7. Extensions, Kotlin documentation, Introduction; Nullable receivers
  8. 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source