通常的做法是在方法签名中使用args以达到合同的唯一目的

时间:2011-09-17 23:12:32

标签: java interface

我对我在学校看到的一些代码以及这是否是该领域的常见做法或只是糟糕的设计感到有些好奇。

考虑以下界面和实现它的两个类......

public abstract interface Anchor
{
    public abstract double x(double x);

    public abstract double y(double y);
}

注意在Cycle类中,实际使用x()和y()中的参数......

public class Cycle implements Anchor
{
    public Anchor anchor;
    public double radius;
    public double period;
    public double phase = 4.0D;

    public Cycle(Anchor anchor, double radius, double period) {
        this.anchor = anchor;
        this.radius = radius;
        this.period = period;
    }

    public double angle(double day) {
        return this.phase * 3.141592653589793D * (day / this.period) / 2.0D;
    }

    public double x(double x) {
        return this.anchor.x(x) + Math.cos(angle(x)) * this.radius;
    }

    public double y(double y) {
        return this.anchor.y(y) + Math.sin(angle(x)) * this.radius;
    }
}

但是在Center类中,x()和y()中的参数仅用于实现与Anchor接口的联系,并且实际上并未在方法中使用...

public class Center implements Anchor
{
    public double x;
    public double y;

    public Center(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double x(double x) { return this.x; }
    public double y(double y) { return this.y; }
}

这是生产java代码中常见的东西吗?这是一种公认​​的做法还是糟糕的工作?

3 个答案:

答案 0 :(得分:11)

是的,这对所有OOP代码都很常见。

接口定义了一组在实现该接口的对象上可用的方法。这些方法的实现是调用者不应该关心的,并且在接口中看到的某些参数不适用于某些实现并不罕见。

答案 1 :(得分:1)

虽然adpalumbo是正确的,但这并不是一个不常见的情况,它也可能表明存在设计问题,特别是如果您有一长串参数并且每个实现使用不同的参数。 E.g。

interface Waffle {
    void iron(int a, int b, int c, int d, int e);
}

class Belgian implements Waffle {
    void iron(int a, int b, int c, int d, int e) {
        doSomethingWith(a);
    }
}

class American implements Waffle {
    void iron(int a, int b, int c, int d, int e) {
        doSomethingElseWith(b);
    }
}

class Scandinavian implements Waffle {
    void iron(int a, int b, int c, int d, int e) {
        andYetAgainWith(c);
    }
}

// etc.

我喜欢华夫饼,但这只是讨厌。

真正的问题是,作为一个整体的参数是否在界面应该表示的任何上下文中都有意义。

答案 2 :(得分:1)

要添加上面的2个帖子,我想指出以下内容。

  1. 在接口声明中使用abstract关键字被认为是非常糟糕的做法,因为这被认为是过时的,因为接口被隐式地视为抽象。

  2. 在界面中的方法声明中使用abstract关键字被认为是非常糟糕的做法,原因与上面第1点中指出的相同。方法声明是隐式抽象的。

  3. 出于同样的原因,在方法声明中使用Public关键字也被认为是非常糟糕的做法,因为在interface中声明的方法是隐式公开的。

  4. 接口中的方法不能是静态的,因为静态方法不能是抽象的。

相关问题