DEV Community

Pasindu Balasooriya
Pasindu Balasooriya

Posted on Originally published at Medium

The Operator’s Identity Crisis: Polymorphism of the plus (+) Operator

A few months ago, as a beginner in programming, it always made me wonder how the + operator behaves with such functional versatility across various use cases in Python, which is my first programming language. Having deliberated this dynamic, a few clicks on google made me realise that this concept exists and that it’s called a polymorphic behaviour. In this article, I will walk you through a library of codes that I came across later when I started working with different programming languages which solidified my understanding of this theory.

Polymorphism is a significant concept in object-oriented programming which enables a single and otherwise exclusive function to behave differently based on context. While polymorphism is often coupled with functions, operators such as the plus (+) operator exhibit this behavior just as well. This article explores how the plus operator demonstrates polymorphism across various programming languages. From numeric addition of the unary + to string concatenation, the + operator shows different masks depending on the data type being interacted with.

Simply put, polymorphism accommodates a single interface to represent different underlying formats or forms. In programming, polymorphism is generally associated with functions or operators when and where their performance and by extension, behavior changes according to the data type. The most typical and commonplace example is the instance of how a method behaves differently when it is called depending on the class of the object on which it is called. Beyond this, polymorphism also applies to operators.

In languages that support operator overloading(This refers to the ability to redefine or customise the behaviour of operators like +,-,*,/, with user defined data types like classes. Programming languages like C++ allows operator overloading. While java does not natively support this, the sole exception is the + operator.) ,or implicit type coercion (the automatic conversion of a value from one data type to another, without explicit manipulation from the programmer), the + operator can perform a varied list of tasks. Understanding the polymorphism of the + operator is important to mastering the subtleties of different programming languages and concepts.

The plus operator serves multiple roles depending on the context in which they are being used. Now let’s have a look at some code snippets that I happened across during studies, where you can compare and contrast to get a concrete understanding.

The + operator is used most commonly to perform arithmetic addition which is the standard behaviour in all the programming languages I have worked with so far.

Python:

a = 5
b = 3
result = a + b  # Output: 8
Enter fullscreen mode Exit fullscreen mode

Java:

class Main {
  public static void main(String[] args) {
    int a = 5;
    int b = 3;
    int result = a + b; // Output: 8
    System.out.println(result);
  }
}
Enter fullscreen mode Exit fullscreen mode

C#:

class Main {
  public static void main(String[] args) {
    int a = 5;
    int b = 3;
    int result = a + b; // Output: 8
    System.out.println(result);
  }
}
Enter fullscreen mode Exit fullscreen mode

JavaScript:

let a = 5;
let b = 3;
let result = a + b; // result is 8
console.log(result);
Enter fullscreen mode Exit fullscreen mode

In many programming languages, the + plus operator also functions as the key binding element in string concatenation.

JavaScript:

let greeting = "Hello, " + "World!";
console.log(greeting);  // Output: "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

Java:

class Main {
  public static void main(String[] args) {
    String greeting = "Hello, " + "World!";
    System.out.println(greeting); // Output: "Hello, World!"
  }
}
Enter fullscreen mode Exit fullscreen mode

C#:

using System;

class Program {
  static void Main() {
    string greeting = "Hello, " + "World!";
    Console.WriteLine(greeting); // Output: "Hello, World!"
  }
}
Enter fullscreen mode Exit fullscreen mode

Python:

greeting = "Hello, " + "World!"
print(greeting)  # Output: "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

In some languages like Python, the + operator can also be used to concatenate(join) lists or arrays instead of the extend() method.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2  # Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

In Java, the language not having accommodated operator overloading, attempting to do this would result in a compiler error. C# and JavaScript do not allow this action to be performed on their respective platforms as well.

Type coercion or type casting refers to the process of converting a value from one data type to another.

JavaScript is famous for its implicit type coercion. When the + operator is used with a number and a string, it converts the number to a string and concatenates them.

let result = "Score: " + 10;
console.log(result); // Output: "Score: 10"

let anotherResult = 5 + "1";
console.log(anotherResult); // Output: "51"
Enter fullscreen mode Exit fullscreen mode

Java also performs automatic type coercion when a String is one of the operands. The other operand (e.g., an int) is converted to its string representation.

class Main {
    public static void main(String[] args) {
        String result = "Agent " + 7;
        System.out.println(result); // Output: "Agent 7"

        // The integer 42 is coerced into the string "42"
        String anotherResult = 42 + " is the answer.";
        System.out.println(anotherResult); // Output: "42 is the answer."
    }
}
Enter fullscreen mode Exit fullscreen mode

C# behaves very similarly to Java. The + operator triggers string concatenation if at least one operand is a string, converting the other types.

using System;

class Program {
    static void Main() {
        string result = "Level " + 99;
        Console.WriteLine(result); // Output: "Level 99"

        // The integer 3 is coerced into the string "3"
        string anotherResult = 3 + " lives remaining";
        Console.WriteLine(anotherResult); // Output: "3 lives remaining"
    }
}
Enter fullscreen mode Exit fullscreen mode

Python is more strict. It does not perform automatic type coercion between strings and numbers with the + operator. Trying to do so will raise a TypeError. You must explicitly convert the types when and where necessary.

While polymorphism of the + operator can help simplify coding, it can also lead to confusion and errors if not properly understood in a platform dependent way.

One of the main challenges is implicit type casting in JavaScript which can lead to unexpected results when numbers and strings are combined, or when non-compatible data types are used.

  • In JavaScript, adding null or undefined values to a string can lead to unexpected behaviour.

  • Python will raise a TypeError should you attempt to concatenate incompatible types. (eg: A string and a number).

*Performance overhead (the additional resources such as time and memory that a process may consume beyond what is necessary to achieve a set goal) in JavaScript can arise due to type coercion ,especially when large datasets are considered.

In order to avoid confusion and ensure smooth usage of the + operator, I recommend following these best practices.

1. Be explicit

In dynamically typed languages like JavaScript, always make sure that your operands are of the same type before using + operator.

*2. Use type checking
*

In languages like Python, consider performing type checks using functions such as type() before using the + operator to avoid runtime errors.

3. Know your programming language

Understand how + operator works in the language that you are working with, by referring to and reviewing documentation to see how it handles data types and coercion.

The polymorphism of the + operator highlights the flexibility and the complexity inherent in many a programming language. Streching from numeric addition to string concatenation and more complex operations like list merging, the polymorphism of the + can be both helpful and challenging simultaneously. By understanding the behavior dynamics of the operator, we can write cleaner and more predictable code while avoiding pitfalls like type coercion. Irrespective of the programming language you are working with, understanding operator polymorphism is essential to master nuanced manipulation of data types.

Top comments (0)