In Java, would all these methods be considered pure functions?

1k views Asked by At

This program determines whether the string the user has input is a palindrome or not.

import acm.program.ConsoleProgram;

public class PurePalindrome extends ConsoleProgram {

public void run() {
    String originalString;
    String reversedString;
    boolean isPalindrome;

    originalString = readLine("? ");
    reversedString = reverseString(originalString);
    isPalindrome = checkPalindrome(originalString, reversedString);

    println("The word you entered " + determineWord(isPalindrome)
            + " a palindrome. " + originalString + " reversed is: "
            + reversedString + ".");
}

private boolean checkPalindrome(String word, String revWord) {
    if (revWord.equals(word)) {
        return true;
    } else {
        return false;
    }
}

private String reverseString(String wordToReverse) {
    String reversedWord = "";
    for (int i = 0; i < wordToReverse.length(); i++) {
        reversedWord = wordToReverse.charAt(i) + reversedWord;
    }
    return reversedWord;
}

private String determineWord(boolean palindrome) {
    if (palindrome) {
        return "is";
    } else {
        return "is not";
    }

}

}

Would all these methods be considered pure functions? If not, why not? I'm having a bit of trouble determining whether a method is a pure function or not.

1

There are 1 answers

3
JB Nizet On BEST ANSWER

A method is a pure function if its returned value depends exclusively on its arguments, and not on anything else, and if it doesn't have any side effect.

So the last three methods are pure functions, whereas the first one is not: it doesn't return anything, depends on the user input, and has the side effect of printing on the screen.

Side note:

if (revWord.equals(word)) {
    return true;
} else {
    return false;
}

should be replaced by

return revWord.equals(word);