patternjavaMajor
Vector (physics) implementation
Viewed 0 times
physicsimplementationvector
Problem
I recently started learning Java, and I decided to implement a basic vector system for another particle system I was building.
What can be improved? I'm new to Java, so constructive criticism on anything would be nice.
import java.util.*;
class Vector {
int x;
int y;
public Vector(int x, int y) {
this.x = x;
this.y = y;
}
public void add(Vector vector) {
this.x += vector.x;
this.y += vector.y;
}
public void sub(Vector vector) {
this.x -= vector.x;
this.y -= vector.y;
}
public void mul(Vector vector) {
this.x *= vector.x;
this.y *= vector.y;
}
public void div(Vector vector) {
this.x /= vector.x;
this.y /= vector.y;
}
}What can be improved? I'm new to Java, so constructive criticism on anything would be nice.
Solution
Immutable objects are awesome. They are robust, predictable, and inherently thread-safe.
Make the
and change the operations to return the resulting
for example:
As in the example above, I recommend changing the name of the
This way you'll be able to chain operations like this:
It will be also useful to implement a custom
Make the
x, and y fields final, and change the operations to return the resulting
Vector,for example:
class Vector {
private final int x;
private final int y;
public Vector(int x, int y) {
this.x = x;
this.y = y;
}
public Vector add(Vector other) {
return new Vector(x + other.x, y + other.y);
}
public Vector sub(Vector other) {
return new Vector(x - other.x, y - other.y);
}
public Vector mul(Vector other) {
return new Vector(x * other.x, y * other.y);
}
}As in the example above, I recommend changing the name of the
Vector parameter from vector to something else, like other, to make it perfectly clear that the method is dealing with another vector.This way you'll be able to chain operations like this:
new Vector(1, 2).add(new Vector(3, 4)).sub(new Vector(5, 6)).mul(new Vector(7, 8));It will be also useful to implement a custom
toString method to make it easy to print a String representation of the vector, for example:@Override
public String toString() {
return String.format("(%s, %s)", x, y);
}Code Snippets
class Vector {
private final int x;
private final int y;
public Vector(int x, int y) {
this.x = x;
this.y = y;
}
public Vector add(Vector other) {
return new Vector(x + other.x, y + other.y);
}
public Vector sub(Vector other) {
return new Vector(x - other.x, y - other.y);
}
public Vector mul(Vector other) {
return new Vector(x * other.x, y * other.y);
}
}new Vector(1, 2).add(new Vector(3, 4)).sub(new Vector(5, 6)).mul(new Vector(7, 8));@Override
public String toString() {
return String.format("(%s, %s)", x, y);
}Context
StackExchange Code Review Q#68109, answer score: 20
Revisions (0)
No revisions yet.