Skip to main content

Command Palette

Search for a command to run...

Refactoring 036 - Replace String Concatenations with Text Blocks

Replace messy string concatenation with clean, readable text blocks

Updated
β€’4 min read
Refactoring 036 - Replace String Concatenations with Text Blocks

TL;DR: You can eliminate verbose string concatenation and escape sequences by using text blocks for multi-line content.

Problems Addressed πŸ˜”

  • Poor code readability
  • Excessive escape sequences
  • String concatenation complexity
  • Maintenance difficulties
  • Code verbosity
  • Translation Problems
  • Indentation issues
  • Complex formatting
  • No, Speed is seldom a real problem unless you are a premature optimizator

Related Code Smells πŸ’¨

Steps πŸ‘£

  1. Identify multi-line string concatenations or strings with excessive escape sequences
  2. Replace opening quote and concatenation operators with triple quotes (""")
  3. Remove escape sequences for quotes and newlines
  4. Adjust indentation to match your code style
  5. Add .strip() for single-line regex patterns or when trailing newlines cause issues

Sample Code πŸ’»

Before 🚨

public class QueryBuilder {
    public String buildEmployeeQuery() {
        String sql = "SELECT emp.employee_id, " +
                     "emp.first_name, emp.last_name, " +
                     "       dept.department_name, " +
                     "emp.salary " +
                     "FROM employees emp " +
                     "JOIN departments dept ON " +
                     "emp.department_id = " +
                     "dept.department_id " +
                     "WHERE emp.salary > ? " +
                     "  AND dept.location = ? " +
                     "ORDER BY emp.salary DESC";
        return sql;
    }

    public String buildJsonPayload(String name, int age) {
        String json = "{\n" +
                      "  \"name\": \"" + name + "\",\n" +
                      "  \"age\": " + age + ",\n" +
                      "  \"address\": {\n" +
                      "    \"street\": " +
                      "\"123 Main St\",\n" +
                      "    \"city\": \"New York\"\n" +
                      "  }\n" +
                      "}";
        return json;
    }
}

After πŸ‘‰

public class QueryBuilder {
    public String buildEmployeeQuery() {
        // 1. Identified multi-line string concatenation
        // 2. Replaced quotes and + operators with """
        // 3. Removed \n escape sequences
        // 4. Adjusted indentation
        String sql = """
            SELECT emp.employee_id, emp.first_name, 
                   emp.last_name,
                   dept.department_name, emp.salary
            FROM employees emp
            JOIN departments dept ON 
                 emp.department_id = dept.department_id
            WHERE emp.salary > ?
              AND dept.location = ?
            ORDER BY emp.salary DESC
            """;
        return sql;
    }

    public String buildJsonPayload(String name, int age) {
        // 1. Identified concatenation with escape sequences
        // 2. Replaced with text block using """
        // 3. Removed \" and \n escapes
        // 4. Preserved natural indentation
        // 5. No .strip() needed here
        String json = """
            {
              "name": "%s",
              "age": %d,
              "address": {
                "street": "123 Main St",
                "city": "New York"
              }
            }
            """.formatted(name, age);
        return json;
    }
}

Type πŸ“

[X] Semi-Automatic

Safety πŸ›‘οΈ

This refactoring is safe.

It does not change the runtime behavior of strings; it only cleans up syntax and formatting.

You follow compilation rules carefully to avoid errors.

Why is the Code Better? ✨

You reduce code noise caused by concatenations and escape sequences.

The multi-line strings become easier to read and maintain. Indentation and formatting are preserved without manual adjustments, making your code more natural and less error-prone.

How Does it Improve the Bijection? πŸ—ΊοΈ

You make the code closer to the real-world representation of the string content, preserving layout and format as seen by the developer.

This enhances the one-to-one mapping between intent and code, minimizing translation errors from concept to implementation.

Limitations ⚠️

Some languages still lack multi-line string mechanisms.

Some languages with full support examples:

LanguageFeatureSyntaxDocs
JavaText Blocks"""https://openjdk.org/jeps/378
KotlinRaw Strings"""https://kotlinlang.org/docs/strings.html
PythonTriple-Quoted Strings""" / '''https://docs.python.org/3/reference/lexical_analysis.html
JavaScriptTemplate Literals` ` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
GoRaw Strings` ` https://go.dev/ref/spec#String_literals
SwiftMultiline Strings"""https://docs.swift.org/swift-book/documentation/the-swift-programming-language/stringsandcharacters
C#Raw String Literals"""https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#raw-string-literals
RubyHeredocs<<EOFhttps://ruby-doc.org/core/doc/syntax/literals_rdoc.html
PHPHeredoc / Nowdoc<<<https://www.php.net/manual/en/language.types.string.php
ScalaMultiline Strings"""https://docs.scala-lang.org/scala3/reference/changed-features/multiline-strings.html

Refactor with AI πŸ€–

Suggested Prompt: 1. Identify multi-line string concatenations or strings with excessive escape sequences2. Replace opening quote and concatenation operators with triple quotes (""")3. Remove escape sequences for quotes and newlines4. Adjust indentation to match your code style5. Add .strip() for single-line regex patterns or when trailing newlines cause issues

Tags 🏷️

  • Standards

Level πŸ”‹

[X] Beginner

Related Refactorings πŸ”„

See also πŸ“š


This article is part of the Refactoring Series.