将依赖关系从一种私有方法传递给另一种私有方法是否是一种有害的依赖关系注入实践?

时间:2019-01-21 18:17:51

标签: java dependency-injection

我有一个适配器-Radius类-据我所知,它是一个依赖项,我不确定是否将其保持不变,但是将其作为参数传递给下一个是令人困惑的私有方法,或者是否有一种更复杂的处理方法?我知道这个问题不是很清楚,但要点是将依赖关系类从一种私有方法传递给另一种私有方法是否是错误的做法?

public void drawClock(Canvas canvas, float clockHandRotationAngles[], Radius radius, ArrayList<ClockElement> clockElements, ArrayList<Paint> clockHandPaintList, ClockHandDrawingType clockHandDrawingType) {
    canvas.drawArc(rect, STARTING_ANGLE_FOR_CIRCLE_DRAWING, DEGREES_IN_CIRCLE, true, circlePaint);
    for (int i = 0; i < clockHandRotationAngles.length; i++) {
        drawClockHand(canvas, clockHandRotationAngles[i], radius.getRadiusOfSpinning(clockElements.get(i)), clockHandPaintList.get(i), clockHandDrawingType);
    }
}

private void drawClockHand(Canvas canvas, float clockHandRotationAngle, int clockHandLength, Paint clockHandPaint, ClockHandDrawingType clockHandDrawingType) {
    switch (clockHandDrawingType) {
        case ARC:
            drawArc(canvas, clockHandRotationAngle, clockHandLength, clockHandPaint);
            break;
        case LINE:
            drawLine(canvas, clockHandRotationAngle, clockHandLength, clockHandPaint);
            break;
    }
}

private void drawArc(Canvas canvas, float angle, int radius, Paint paint) {
    setAppropriateRectForInnerCircle(canvasCenter, radius);
    canvas.drawArc(innerRect, STARTING_ANGLE_FOR_CIRCLE_DRAWING, angle, true, paint);
}

private void drawLine(Canvas canvas, float angle, int length, Paint paint) {
    canvas.drawLine(canvasCenter.getX(), canvasCenter.getY(),
            calculateCoordinateOfRotation(Coordinate.X, angle, length),
            calculateCoordinateOfRotation(Coordinate.Y, angle, length), paint);
}

1 个答案:

答案 0 :(得分:0)

通常通过构造函数实例化类时会注入依赖项。不需要为每个私有方法或类中的任何方法传递依赖项。请将对依赖类实例的引用保留为字段。

Class A{
 B b;
 A(B bb){
 this.b=bb
 }

 private void someMethod(){
 //use b if required
 }
}

其中B是某类A所依赖。