平时容易忽视的地方之一:java在抽取方法时,什么时候该用void

当一个类中多个方法有相同编码,或该部分编码可以作为一个整体,适合抽取出一个方法时,要注意这个抽取的方法的返回值,什么时候可以用void,什么时候不能用void?

先看代码:

import lombok.Data;
import org.junit.Test;

public class MyTest {
    @Test
    public void test(){
        Student student = new Student();
        student.setName("Jacky");
        int age = 18;
        Double score = 80.0;
        this.setValue(student, age, score);

        System.out.println("age = " + age);
        System.out.println("score = " + score);
        System.out.println(student);
    }

    private void setValue(Student student, int age, Double score){
        age += 1;
        score += 10.0;
        student.setAge(age);
        student.setScore(score);
    }

    @Data
    class Student{
        String name;
        int age;
        Double score;
    }
}

运行结果:

age = 18
score = 80.0
MyTest.Student(name=Jacky, age=19, score=90.0)

上面例子说明,当抽取方法参数是普通类时,方法返回值适合用void,相当于“把该类在一个地方过了一遍”;当抽取方法的参数是基本类型或包装类型时,该方法应该有返回值。

猜你喜欢

转载自www.cnblogs.com/steven0325/p/11697623.html