Home > OS >  How can I improve the code in which I use function extensions at present in Kotlin?
How can I improve the code in which I use function extensions at present in Kotlin?

Time:02-28

I hope to place a line in new coordinate system, the new origin coordinate is val orig=Point(100,50), the new X axis is to right, and new Y axis is to up.

At present, I use function extensions, just like Code A.

I find it's not good, there are many repeated code such as .toX(orig), .toY(orig).

How can I design the data structure to improve the code?

Code A

val orig=Point(100,50)

it.drawLine(
    Offset(x = 0f.toX(orig), y = 0f.toY(orig)),
    Offset(x = (size.width- 200).toX(orig), y = 0f.toY(orig)),
    axisPaint
)



fun Float.toX(originCoordinate: Point) : Float {
    return originCoordinate.x this
}

fun Float.toY(originCoordinate: Point): Float {
    return originCoordinate.y-this
}

CodePudding user response:

I second Ivo that the extension functions do not really increase readability. What I would do is to not focus on x and y, but on the Points. An offset in a two-dimensional layout is a new Point, so you're probably better off doing something like this:

fun Point.offset(offsetX: Float, offsetY: Float): Point {
  return Point(this.x   offsetX, this.y   offsetY)
}

And you use it like this:

it.drawLine(
  orig.offset(0f, 0f),   // which is of course the same as: orig
  orig.offset(size.width - 200f, 0f),
  axisPaint
)

CodePudding user response:

I guess the question and answer are kind of subjective, but in my opinion do the extensions not add anything. And actually make it unnecessarily complex.

Just writing

it.drawLine(
    Offset(x = orig.x   0f, y = orig.y   0f),
    Offset(x = orig.x   (size.width- 200), y = orig.y - 0f),
    axisPaint
)

is better in my opinion. Also no point to add 0f to it so for this example I would just go with

it.drawLine(
    Offset(x = orig.x, y = orig.y),
    Offset(x = orig.x   (size.width- 200), y = orig.y),
    axisPaint
)
  • Related