Think about the differences between functions and methods (in Java)

The opportunity to write this article

What is the difference between a function and a method? I overheard the story. So, I decided to reconfirm my recognition and write it down. Also, I hope it will be helpful for those who have just started system development and are not familiar with this area. Why Java? That is because it seems that there are many users, and as I will explain later, function-like things will also be on the mechanism of the method, so I thought it would be difficult to distinguish.

First of all, what is a function?

Thinking about the definition of a function "Receives some value (argument) and returns the result value (return value), processing catalog" I think that will be the case. And when it comes to a purer function, the following conditions come out. -It is not affected by anything other than arguments. -Do no work other than returning a value. -If the arguments are the same, the same result will be returned no matter how many times it is executed. It is a concept that is said to have no side effects or referential transparency.

In other words, the following pattern is not a pure function. ** ・ The current time is acquired and used by Date, Calendar, LocalDate, etc. ** → Results vary depending on execution time **-Getting a value from a file or DB and using it ** → If the acquired content has changed a while ago, the result will be different. **-Updating files and DB ** → Doing work other than returning values (causing side effects) ** ・ Something is output by System.out.println etc. ** → Standard output is also a type of side effect **-Accessing a field in the class ** → Changing the field value is a side effect, and changing the field value will change the result.

It's also a subtle feeling, but this is also a side effect ant.

final public void someMethod(final List<String> list, final String text){
    list.add(text); //Affects the caller's list
}

On the other hand, things like ↓ can be called purely functions.

final public String twice(final String text){
    return text + text; // text ==If null, don't think about it now
}

No matter how many times you call it, the same result will be returned if the argument strings are the same.

In Java, it is not possible to put a catalog of such processing outside the class. Therefore, the function is expressed using the method as described above. (For Java 8 or later, there is a way to create a functional interface implementation, but without that)

Lead to static

So far we have considered what a function is, especially a pure function. And in Java, such "functional methods" are used as functions. Functional methods belong to some class, but they are functional and do not interfere with the fields of that class. The same result (ABCABC) is output for the 1st, 2nd, 2nd', and 3rd times of the following processing.

final public class Sample {
    public static void main(String args[]){
        //First time
        final TextSomething obj1 = new TextSomething();
        System.out.println(obj1.twice("ABC"));

        //Second time
        final TextSomething obj2 = new TextSomething();
        System.out.println(obj2.twice("ABC"));
        //Second time'
        System.out.println(obj2.twice("ABC"));

        //Third time
        final TextSomething obj3 = new TextSomething();
        System.out.println(obj3.twice("ABC"));
    }
}

final public class TextSomething {
    //Functional method
    final public String twice(final String text){
        return text + text;
    }
}

However, if you think about it, twice can be called from any instance of obj1, obj2, obj3 any number of times. It returns the same result regardless of its internal data state. If so, you don't bother to create a new instance to use it. So declare a functional method as static. And classes that consolidate functional and static methods of a similar family are often created. This is what is called ** utility class **.

final public class TextUtil {
    final public static String twice(final String text){
        return text + text;
    }
	
    final public static String twice2(final String text){
        return text.toUpperCase() + text.toLowerCase();
    }
}

final public class Sample2 {
    public static void main(String args[]){
        System.out.println(TextUtil.twice("aBc")); // aBcaBc
        System.out.println(TextUtil.twice2("aBc")); // ABCabc
    }
}

If it is a static method, accessing the field variable in the class will result in a compile error and is impossible.

So what is the original method?

Methods are often referred to as "class behavior." However, I personally think this expression is subtle. The expression class behavior is a class perspective. ClassA can do this and this, Class B can do this and this ... It feels like anthropomorphic of a class, but we are not a class. System development We are programmers in a standing position to proceed with development using classes. The word method is also a literal translation of "method", so it's easier to think of this as ** "how to manipulate a class" **. The method is ** "Object (instance) operating system" **. What you do is basically the variables of the fields that the instance has. For example, there is a method like this that manipulates variables declared private.

final public class DataClass {
	
    private Integer bet;

    //Operation to get the value of the variable bet
    final public Integer getBet() {
        return bet;
    }
    //Operation to change the value of the variable bet
    final public void setBet(Integer bet) {
        this.bet = bet;
    }
}

Getters and setters, so-called accessor methods. There may be other methods that multiply the bet value by 10 or halve it. Depending on the class, database connection settings (server name, user name, password, etc.) are passed in each setter, You may have a method called public void dbConnect () that makes a DB connection based on that information and holds the connection status as internal data.

So, for a pure function, when you think of a "pure method", it seems to be a catastrophe of the processing that affects or is given to the state of the instance.

Is static object-oriented?

Now, if the original form of Java object-oriented methods is the operating system for objects, Is a functional static method with no side effects a correct method? In the first place, is the utility class that has only static methods and therefore does not have fields (states) (it is not new) is object-oriented correct in the first place? This is a troublesome story about object-oriented programming, so I'll leave it aside, but if you remake the utility class in an object-oriented manner (functional → original method), it will look like this. I don't usually write in this way, so it's delicate whether this is okay. How about that?

final public class TextObject {
	
    private String text;
	
    final public void setText(String text){
        this.text = text;
    }

    final public String twice(){
        return text + text;
    }

    final public String twice2(){
        return text.toUpperCase() + text.toLowerCase();
    }
}

final public class Sample3 {
    public static void main(String args[]){
        final TextObject obj = new TextObject();
        obj.setText("aBc");
		
        System.out.println(obj.twice()); // aBcaBc
        System.out.println(obj.twice2()); // ABCabc
    }
}

Well, personally, I think it's faster to write using utility classes (in Java). The theory of which is better is not the main subject, so let's leave it ...

Summary

** What is a method ** Changing the internal state of an object and retrieving the internal state ** "How to operate an object" **. The internal state is roughly the value of a variable of an object (instance). (Or something that ignites functions such as output to a file and update to DB)

** What is a function ** ** "A process that takes one or more arguments and returns the result of some calculation as a return value" **. In Java, functions are written based on the method mechanism.

Recommended Posts

Think about the differences between functions and methods (in Java)
A note on the differences between interfaces and abstract classes in Java
About the difference between classes and instances in Ruby
About the relationship between HTTP methods, actions and CRUD
Think about the JAVA = JAVAscript problem (needed in the future)
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
Differences between "beginner" Java and Kotlin
About the equals () and hashcode () methods
About the difference between "(double quotation)" and "single quotation" in Ruby
Differences in how to handle strings between Java and Perl
Differences between Java and .NET Framework
Regarding the difference between Java array and ArrayList, I compared and corresponded methods with similar functions.
About the relationship between the Java String equality operator (==) and initialization. Beginners
Difference between final and Immutable in Java
[Java] Differences between instance variables and class variables
About the difference between irb and pry
Difference between int and Integer in Java
Functions and methods
Interpret the relationship between Java methods and arguments into a biochemical formula
Let's think about what declarative programming is in Java and Elm (Part 1)
Understand the difference between int and Integer and BigInteger in java and float and double
[Java] Understand the difference between List and Set
Regarding the transient modifier and serialization in Java
About the confusion seen in startup Java servers
Think about the combination of Servlet and Ajax
[Rails / ActiveRecord] About the difference between create and create!
About the idea of anonymous classes in Java
A story about the JDK in the Java 11 era
[Understanding] Differences between hashes and arrays in Ruby
Differences in writing Java, C # and Javascript classes
Check static and public behavior in Java methods
Distinguish between positive and negative numbers in Java
Ruby: Differences between class methods and instance methods, class variables and instance variables
Impressions and doubts about using java for the first time in Android Studio
Differences between Java, C # and JavaScript (how to determine the degree of obesity)
Organize your own differences in writing comfort between Java lambda expressions and Kotlin lambda expressions.
Azure functions in java
[Ruby] I thought about the difference between each_with_index and each.with_index
[Rails] I learned about the difference between resources and resources
Write ABNF in Java and pass the email address
Differences between Ruby syntax error statements in Ruby and binary
[Java] Difference between static final and final in member variables
Differences between browser sessions and cookies and Rails session and cookies methods
Java classes and instances to understand in the figure
Differences between Fetch Type LAZY and EAGER in Hibernate
Differences in code when using the length system in Java
What is the difference between Java EE and Jakarta EE?
[Java] Note about the difference between equivalence judgment and equality judgment when comparing String classes
Let's sort out the differences between Java substring and C # Substring, and how to port them.
[Java] The difference between the Stream.of () and Arrays.stream () methods that you do not know unexpectedly
Learn about the spec while shortening FizzBuzz written in Java
[Java Bronze learning] Differences between encapsulation, data hiding, and information hiding
JSON in Java and Jackson Part 1 Return JSON from the server
Differences between namespace, module, scope and as in Rails routing
[Java] Difference between == and equals
Difference between Java and JavaScript (how to find the average)
[Java] Generics classes and generics methods
[Rails] Differences between redirect_to and render methods and how to output render methods
[Java] About String and StringBuilder
Create Azure Functions in Java
About the same and equivalent