Use cases for static methods in Java
I. Overview
Static methods are common in most object-oriented programming languages, including Java. The difference between static methods and instance methods is that they do not have an object that owns them. Instead, static methods are defined at the class level and can be used without creating an instance.
In this tutorial, we'll look at the definitions of static methods in Java and their limitations. We'll then look at common use cases that use static methods and suggest when to apply them to our code.
Finally, we will see how to test static methods and how to simulate them.
2. Static methods
Instance methods are polymorphic parsing based on the runtime type of the object. Static methods, on the other hand, are parsed at compile time according to the class that defines them.
2.1。 Class level
Static methods in Java are part of the class definition. We can define a static method by adding keywords to the method:static
private static int counter = 0;
public static int incrementCounter() {
return ++counter;
}
public static int getCounterValue() {
return counter;
}
To access static methods, we use the class name followed by a dot and method name:
int oldValue = StaticCounter.getCounterValue();
int newValue = StaticCounter.incrementCounter();
assertThat(newValue).isEqualTo(oldValue + 1);
We should note that this static method can access the static state of the class. Static methods are often stateless, but they can work with class-level data as part of a variety of techniques, including singleton patterns.StaticCounter
Although static methods can also be referenced using objects, this anti-pattern is often flagged as an error by tools such as Sonar.
2.2. Restrictions
Since static methods do not operate on instance members, we should be aware of some limitations:
Static methods cannot directly reference instance member variables
Static methods cannot call instance methods directly
Subclasses cannot override static methods
We cannot use keyword sums in static methods
this
super
Each of these items results in a compile-time error. We should also note that if we declare a static method with the same name in a subclass, it does not override but hides the base class method.
3. Use cases
Now let's look at common use cases where applying static methods makes sense in our Java code.
3.1。 Standard behavior
When we develop methods with standard behavior that operate on their input parameters, it makes sense to use static methods.
An operation from Apache is a good example:StringUtils
String
String str = StringUtils.capitalize("baeldung");
assertThat(str).isEqualTo("Baeldung");
Another good example is the class, as it contains common methods for manipulating different collections:Collections
List<String> list = Arrays.asList("1", "2", "3");
Collections.reverse(list);
assertThat(list).containsExactly("3", "2", "1");
3.2. Cross-instance reuse
One valid reason to use static methods is when we reuse standard behavior across instances of different classes.
For example, we typically use Java and Apache in domains and business classes:Collections
StringUtils
Since these functions don't have their own state and aren't bound to specific parts of our business logic, it makes sense to keep them in modules that can be shared.
3.3. Do not change the status
Because static methods cannot reference instance member variables, they are a good choice for methods that do not require any object state manipulation.
Method calls are more practical when we use static methods for operations where state is unmanaged. The caller can call the method directly without creating an instance.
When we share state through all instances of a class, such as in the case of static counters, then the methods operating on that state should be static. Managing global state can be the source of errors, so Sonar reports a critical issue when instance methods write directly to static fields.
3.4. Pure Functions
If the return value of a function depends only on the input parameters passed, the function is called a pure function. Pure functions take all the data from their arguments and compute something from that data.
Pure functions do not operate on any instances or static variables. Therefore, executing pure functions should also have no side effects.
Because static methods do not allow you to override and reference instance variables, they are an excellent choice for implementing pure functions in Java.
4. Utility classes
Since Java does not reserve a specific type to accommodate a set of functions, we often create a utility class. Utility classes provide a home for purely static functions. Instead of writing the same logic over and over again, we can combine pure functions that are reused throughout the project.
Utility classes in Java are stateless classes that we should never instantiate. Therefore, it is advisable to declare it as , so it cannot be subclassed (which does not add value). Also, to prevent anyone from trying to instantiate it, we can add a private constructor:final
public final class CustomStringUtils {
private CustomStringUtils() {
}
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}
}
We should note that all the methods we put in the utility class should be.static
5. Testing
Let's examine how static methods are unit tested and simulated in Java.
5.1。 Unit tests
Unit testing a well-designed, purely static approach with JUnit is simple. We can use the class name to call our static method and pass some test parameters to it.
Our unit under test will calculate the result based on its input parameters. Thus, we can assert the results and test different combinations of inputs and outputs:
@Test
void givenNonEmptyString_whenIsEmptyMethodIsCalled_thenFalseIsReturned() {
boolean empty = CustomStringUtils.isEmpty("baeldung");
assertThat(empty).isFalse();
}
5.2. Ridicule
Most of the time, we don't need to emulate static methods, we can simply use real function implementations in testing. The need to simulate static methods often implies code design problems.
If necessary, then we can use Mockito to simulate static functions. However, we need to add an additional mockito-inline dependency to the
pom .xml:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
Now, we can use the method to mock the call to the static method call: Mockito.mockStatic
try (MockedStatic<StringUtils> utilities = Mockito.mockStatic(StringUtils.class)) {
utilities.when(() -> StringUtils.capitalize("karoq")).thenReturn("Karoq");
Car car1 = new Car(1, "karoq");
assertThat(car1.getModelCapitalized()).isEqualTo("Karoq");
}
Sixth, the conclusion
In this article, we explore common use cases for using static methods in Java code. **We learned about the definition of static methods in Java and their limitations.
In addition, we explored when it makes sense to use static methods in your code. We see that static methods are a good choice for pure functions with standard behavior that can be reused across instances without changing their state. Finally, we looked at how to test and simulate static methods.
atorvastatin cheap & lt;a href="https://lipiws.top/"& gt;order atorvastatin 80mg online cheap& lt;/a& gt; order generic lipitor 40mg
Aqvwod
2024-03-08