Default Argument in Programming

Default arguments are one of the powerful features in programming that allows developers to specify a default value for one or more parameters in a function and provides flexibility as it enables functions to be called with different numbers of arguments. When calling a function, the programmer can omit some of the arguments for parameters that have default values, and the function will use those default values instead which makes functions more versatile and user-friendly. Languages like C++, Python, etc. allow the programmer to specify default arguments that always have a value, even if one is not specified when calling the function.

Table of Content

  • What are Default Arguments?
  • Syntax of Default Argument
  • Default Argument in C++
  • Default Argument in Python
  • Default Argument in Javascript
  • Default Argument in Java
  • Advantages of Default Argument
  • Disadvantages of Default Argument

What are Default Arguments?

Default Arguments are parameters in a function or method that have a default value assigned to them. These default values are used when a value for that parameter is not provided during the function call.

Here are some key points about default arguments:

  • Automatic Assignment: If the function is called without providing a value for the argument, the default value is automatically assigned.
  • Overriding: If a value is passed for the argument, the default value is overridden.
  • Order of Arguments: Typically, default arguments are placed after non-default arguments in the function definition.
  • Flexibility: Default arguments provide flexibility, allowing a function to be called with varying numbers of arguments.
  • Use Cases: Default arguments are particularly useful when a function has many parameters, and only a few of them need to be specified most of the time

Syntax of Default Argument:

Depending on the programming language, different syntaxes are used to express default arguments. Default arguments are usually declared in the signature of a function by setting the parameter’s value.

C++
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
    return (x + y + z + w);
}
Python3
def default_Aargument(default_arg = 'This is defaults argument'):
print(default_arg)
JavaScript
function fnName(param1 = defaultValue1, /* …, */ paramN = defaultValueN) {
  // …
}

Default Argument in C++:

Here is the implementation of the default argument in C++:

C++
// CPP Program to demonstrate Default Arguments
#include <iostream>
using namespace std;

// A function with default arguments,
// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
    return (x + y + z + w);
}

// Driver Code
int main()
{
    // Statement 1
    cout << sum(10, 15) << endl;

    // Statement 2
    cout << sum(10, 15, 25) << endl;

    // Statement 3
    cout << sum(10, 15, 25, 30) << endl;
    return 0;
}

Output
25
50
80

Default Arguments and Function Overloading in C++:

Function overloading is a common practice in languages ​​such as C++. There are some rules and restrictions when using preset parameters in function overloading:

  • Consistency: Overloaded functions must have a clear and specific purpose. Default parameters should not cause ambiguity in the calls.
  • Parameter positioning: To avoid confusion/misunderstanding during function calls, default arguments in a function declaration must come after all non-default parameters.
  • Ambiguity in function calls: Sometimes combining overload with presets can be confusing. For example, if there are many overloaded functions with preset parameters, the compiler will have difficulty deciding which overloaded function to call.

In C++, consider the following overloaded functions:

C++
#include <iostream>
using namespace std;

void printMessage(int count, string message = "Hello");
void printMessage(int count, bool includeTimestamp = false);

int main() { printMessage(5); }

The parameter lists for both functions are similar and they share the same name “printMessage”. If you call printMessage(5) with just one integer argument, there might be ambiguity about which function to use.

You must make sure that the parameter types and order of each overloaded function are unique in order to resolve ambiguity.

Default Argument in Python:

Default arguments in Python can be used with two types of arguments:

  • With Keyword Arguments
  • Without Keyword Arguments

Default Argument with Keyword Argument:

Here is the implementation of default argument with keyword:

Python3
def student(firstname, lastname ='Mark', standard ='Fifth'):
    print(firstname, lastname, 'studies in', standard, 'Standard')

# 1 keyword argument
student(firstname ='John')     

# 2 keyword arguments                 
student(firstname ='John', standard ='Seventh') 

# 2 keyword arguments 
student(lastname ='Gates', firstname ='John')     

Output
John Mark studies in Fifth Standard
John Mark studies in Seventh Standard
John Gates studies in Fifth Standard

Default Argument without Keyword Argument:

Here is the implementation of default argument without keyword:

Python3
def student(firstname, lastname ='Mark', standard ='Fifth'):
    print(firstname, lastname, 'studies in', standard, 'Standard')

# 1 positional argument
student('John') 

# 3 positional arguments                         
student('John', 'Gates', 'Seventh')     

# 2 positional arguments 
student('John', 'Gates')                 
student('John', 'Seventh')

Output
John Mark studies in Fifth Standard
John Gates studies in Seventh Standard
John Gates studies in Fifth Standard
John Seventh studies in Fifth Standard

Default Argument in Javascript:

Here is the implementation of the default argument in javascript:

JavaScript
function greet(name) {
    // If name is not provided, use 'World' as the default
    name = typeof name !== 'undefined' ? name : 'World';
    console.log("Hello, " + name + "!");
}

// Test cases
greet(); // Output: Hello, World!
greet("John"); // Output: Hello, John!

Output
Hello, World!
Hello, John!

Default Argument in Java:

In Java, there’s no direct support for default arguments in methods as in some other languages like Python or C++. However, you can achieve similar functionality through method overloading or using the Builder pattern.

Method Overloading: You can define multiple versions of a method with different parameter lists. One version of the method can have fewer parameters and provide default values for those parameters.

Java
public class Example {
    public void greet() {
        greet("World"); // calling the version of greet method with default argument
    }

    public void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }
}

In this example, greet() method without parameters acts as an entry point and calls the greet(String name) method with the default argument "World".

Builder Pattern: The Builder pattern is useful when you have a complex object with many optional parameters. You can use it to set default values for those parameters.

Java
public class Person {
    private String name;

    // Builder pattern to set default values
    public static class Builder {
        private String name = "World";

        public Builder() {}

        public Builder name(String name) {
            this.name = name;
            return this;
        }

        public Person build() {
            return new Person(this);
        }
    }

    private Person(Builder builder) {
        this.name = builder.name;
    }

    public void greet() {
        System.out.println("Hello, " + name + "!");
    }
}

In this example, the Builder class sets the default value for name as "World". When Person object is created without specifying the name, it defaults to "World".

Advantages of Default Argument:

  • Flexibility: Default values can be substituted for some arguments, which makes the function calls more flexible.
  • Readability: Efficient use of default parameters helps to make the code clearer and easily comprehensible.
  • Maintainability: This implies that if you change the default value, this will have an effect on the behaviour of your program without changing much at all.
  • Reduced Code Duplication: Default arguments could potentially cut down on redundant code by letting a single function handle many cases with different parameter values thus saving multiple comparable functions.

Disadvantages of Default Argument:

  • Code ambiguity: If default parameters are used excessively and are not properly managed, this might result in unclear code and unexpected behaviour.
  • Complexity: Default arguments and overloaded functions can often cause confusion and complexity, particularly when function overloading is involved.
  • Increased Execution time: Because the compiler must substitute the missing arguments for their default values in the function call, it lengthens the execution time.
  • Problems with debugging: Debugging code might be more challenging due to the fact that it’s not always possible to see the default arguments in the call stack, which might make it challenging to identify the reason of an error.

Conclusion:

Programming languages provides a very useful and adaptable feature referred to as default arguments that, when used properly, can enhance the clarity, maintainability, and flexibility of programs. Understanding the benefits, how to use them properly, and any potential risks are important for writing clear and efficient code. Developers can successfully add default arguments to their apps if they adhere to best practices and take into account the unique features of the language.