Skip to content

Functions

Functions#

Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce duplication, and make programs easier to maintain.

Key Benefits:

  • Reusability: Write once, use many times.
  • Modularity: Break complex problems into smaller pieces.
  • Maintainability: Update logic in one place.

How Functions Work#

When you call a function, the program follows a specific sequence: it passes your parameters to the function, executes the function's code, and returns a result back to where it was called. This process is shown in the diagram below:

graph TD
    A[Program Execution] --> B[Function Call]
    B --> C[Pass Parameters]
    C --> D[Execute Function Body]
    D --> E[Return Result]
    E --> F[Continue Program]

    G[Function Benefits] --> H[Code Reusability]
    G --> I[Modularity]
    G --> J[Easier Testing]
    G --> K[Better Organization]

    style B fill:#e3f2fd
    style D fill:#fff3e0
    style E fill:#c8e6c9
    style H fill:#c8e6c9
    style I fill:#c8e6c9
    style J fill:#c8e6c9
    style K fill:#c8e6c9

The diagram shows both the execution flow (top) and the benefits (bottom) of using functions in your programs.

Function Components#

Every function has four main parts:

  1. Name: What you call the function (e.g., calculateArea).
  2. Parameters: Input values the function receives.
  3. Body: The code that does the work.
  4. Return Value: What the function gives back.
public static int calculateFret(int string, int fret) {
    return string + fret;
}

int note = calculateFret(1, 5); // E string, 5th fret = A note
fun calculateFret(string: Int, fret: Int): Int {
    return string + fret
}

val note = calculateFret(1, 5) // E string, 5th fret = A note
function calculateFret(string: number, fret: number): number {
    return string + fret;
}

const note = calculateFret(1, 5); // E string, 5th fret = A note
int calculateFret(int string, int fret) {
    return string + fret;
}

int note = calculateFret(1, 5); // E string, 5th fret = A note
func calculateFret(string: Int, fret: Int) -> Int {
    return string + fret
}

let note = calculateFret(string: 1, fret: 5) // E string, 5th fret = A note
def calculate_fret(string, fret):
    return string + fret

note = calculate_fret(1, 5)  # E string, 5th fret = A note

Optional Parameters vs Default Values#

Optional Parameters are parameters that can be omitted when calling a function. They can be implemented in different ways:

  1. With Default Values: The parameter gets a specific default value when omitted
  2. Nullable/Optional Types: The parameter can be null/undefined and must be checked

Default Values are specific values assigned to parameters that are used when no value is provided. This is the most common way to implement optional parameters.

Optional Parameters#

Java doesn't support optional parameters directly. Use method overloading instead.

// Optional parameter with null checking
fun playChord(root: String, type: String? = null) {
    val chordType = type ?: "major"
    println("Playing $root $chordType chord")
}

playChord("C")                    // Playing C major chord
playChord("G", "minor")          // Playing G minor chord
// Optional parameter with undefined checking
function playChord(root: string, type?: string) {
    const chordType = type || "major";
    console.log(`Playing ${root} ${chordType} chord`);
}

playChord("C");                  // Playing C major chord
playChord("G", "minor");         // Playing G minor chord
// Optional parameter with null checking
void playChord(String root, {String? type}) {
    String chordType = type ?? "major";
    print('Playing $root $chordType chord');
}

playChord("C");                          // Playing C major chord
playChord("G", type: "minor");           // Playing G minor chord
// Optional parameter with nil checking
func playChord(root: String, type: String? = nil) {
    let chordType = type ?? "major"
    print("Playing \(root) \(chordType) chord")
}

playChord(root: "C")                     // Playing C major chord
playChord(root: "G", type: "minor")     // Playing G minor chord
# Optional parameter with None checking
def play_chord(root: str, type: str = None):
    chord_type = type if type is not None else "major"
    print(f"Playing {root} {chord_type} chord")

play_chord("C")                  # Playing C major chord
play_chord("G", "minor")         # Playing G minor chord

Default Values#

Default values are specific values assigned to parameters that are used when no value is provided. This is one way to implement optional parameters.

Java doesn't support default parameter values. Use method overloading instead.

fun tuneGuitar(string: Int, tuning: String = "standard"): String {
    return "Tuning string $string to $tuning tuning"
}

val eString = tuneGuitar(1)                    // Uses default "standard" tuning
val customTuning = tuneGuitar(1, "drop D")     // Uses provided "drop D" tuning
function tuneGuitar(string: number, tuning: string = "standard"): string {
    return `Tuning string ${string} to ${tuning} tuning`;
}

const eString = tuneGuitar(1);                  // Uses default "standard" tuning
const customTuning = tuneGuitar(1, "drop D");  // Uses provided "drop D" tuning
String tuneGuitar(int string, {String tuning = "standard"}) {
    return 'Tuning string $string to $tuning tuning';
}

String eString = tuneGuitar(1);                           // Uses default "standard" tuning
String customTuning = tuneGuitar(1, tuning: "drop D");    // Uses provided "drop D" tuning
func tuneGuitar(string: Int, tuning: String = "standard") -> String {
    return "Tuning string \(string) to \(tuning) tuning"
}

let eString = tuneGuitar(string: 1)                    // Uses default "standard" tuning
let customTuning = tuneGuitar(string: 1, tuning: "drop D") // Uses provided "drop D" tuning
def tune_guitar(string: int, tuning: str = "standard") -> str:
    return f"Tuning string {string} to {tuning} tuning"

e_string = tune_guitar(1)                    # Uses default "standard" tuning
custom_tuning = tune_guitar(1, "drop D")   # Uses provided "drop D" tuning