“方法参数多的时候,考虑封装为对象入参” 感觉有点问题

// 方法参数较多

public void test(int width, int height, int length) {

    func1(width, height, length);

    func2(width, height, length);

}

private void func1(int width, int height, int length) {
    //...
}

private void func2(int width, int height, int length) {
    //...
}

改为

// 参数封装成对象形式
public void test(Rectangle rect) {

    func1(rect);

    func2(rect);

}

private void func1(Rectangle rect) {
    int width = rect.getWidth();
    int height = rect.getHeight();
    int length = rect.getLength();
    //...
}

private void func2(Rectangle rect) {
    int width = rect.getWidth();
    int height = rect.getHeight();
    int length = rect.getLength();
    //...
}

问题来了:

参数封装成对象的形式,这样每个方法都有一段重复代码:从rect对象中获取属性

int width = rect.getWidth();
int height = rect.getHeight();
int length = rect.getLength();

还不如第一种写的代码少

 

这就是面向对象,你现在把三个参数封装成一个对象的三个属性,那你访问时自然要向这个对象去要。你觉得要着很麻烦。但是这样才保证了封装性。事实上,你的fun1,fun2也许应该是成员方法,那访问的时候就是访问自己的属性了。调用时不仅方法内部可以直接使用了,而且调用方也不需要传递参数了。甚至调用方不需要关心这个方法内部用了什么属性。如果有一天fun1,fun2改了内部实现,调用方也不用修改调用方式。

 

public void test(Rectangle rect) {

 

    rect.func1();

 

    rect.func2();

 

}

class Rectangle {
    private int width;
    private int height;
    private int length;

    public void func1() {

    //...

    }

 

    public void func2() {


    //...

    }
}