I was given a task and I'm not sure how to get it to work. All the test cases must pass.
Assertions.assertDoesNotThrow(() -> p3.equals(null));
Assertions.assertFalse(p3.equals(null), "equals to null should return false");
I figured out the first one, the one that is tricking me is the Assertions.assertfalse(p3.equals(null)).
I created the object p3 from Point as such:
Point p3 = new Point(x+1, y-1);
In my Point class I have an equals method which I override as such:
#Override
public boolean equals(Object obj) {
Point p = (Point) obj;
try {
if (x != p.x) {
return false;
}
if (y != p.y) {
return false;
}
} catch (NullPointerException e) {
System.err.println("null");
}
return true;
}
I used this to pass other tests not mentioned.
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int x() {
return x;
}
public int y() {
return y;
}
Where x and y are random integers between 0-30.
When I run the test, it always returns p3 equal to null which is confusing me. I know it is something to do with checking if the object passed through is of same type (Point) & downcasting, but I am not sure.
If you look at the signature of the equals method you are implementing you'll see it takes an argument of type Object. That means the thing passed in can be any reference type. It can be null. Currently your equals method blindly casts whatever it gets to a Point, so if it gets anything other than a Point then an exception gets thrown. Then later, if the thing passed in is null, referencing an instance member (like p.x) will cause a NullPointerException.
There are at least four tests you need to write for your equals method:
Pass in another Point with the same x and y values,
Pass in a Point with different x and y values.
Pass in some object with a totally different type, like String or Integer.
Pass in null.
These need to be in different test methods, so that they can fail independently of each other. Cramming them into the same test means that when one assertion fails, the ones after it don't run; fixing tests turns into a whack-a-mole situation where you fixed one problem but now another one pops up.
You can use instanceof to check that what you are getting is the right type and is non-null. Since your current code catches a NPE, it lets execution continue from the catch block to the line with return true; , which isn't what you want.
So start your equals method with something like
if (!(object instanceof Point)) {
return false;
}
before you cast. Once you know the object is a non-null Point then you can continue with
Point p = (Point)object;
return x == p.x && y == p.y;
Since && short-circuits this doesn't do any more work than the posted code, they both stop checking if the first check evaluates to false.
Related
I am new to programming and have a simple question: is there a "better" or more efficient way of doing this...
if (x != 0) {
y = x;
}
or
if (getMethod() != null) {
value = getMethod();
}
I'm new to programming and above code (esp the 2nd one) seems inefficient.
Thanks in advance.
You second example can suffer from a "Time of check, to time of use" weakness. If the first invocation of getMethod() returns non-null, it is possible that your second invocation will return null. A better way to do it would be:
value = getMethod();
if(NULL != value)
{
/* use value as planned */
}
else
{
/* handle a null value, probably an error */
}
if interested, you can read more about TOCTTOU weaknesses here.
For your first example, I don't really see a better way of doing this.
N.B. This answer is from the perspective of a C programmer (seeing as how C was one of your tags).
Hope this helps
- T.
You can make it shorter
if ( x ) y = x;
is the same as
if (x != 0) {
y = x;
}
And
if ( getMethod() ) value = getMethod();
is the same as
if (getMethod() != null) {
value = getMethod();
}
First code snippet:
In C any non-zero value is treated as true and 0 treated as false. So, for the first example, you can rewrite it as:
if (x) {
y = x; // this line will be executed if x not equal to zero
}
Second code snippet:
You called getMethod() twice which is not efficient. As per your code, you are assigning the return value of getMethod() into value if getMethod() returns anything but NULL. So you can use a temporary variable to check the return value of getMethod(), like following:
temp = getMethod();
if (temp != null) {
value = temp;
}
That will reduce calling same method twice.
I’m trying to make a position, length and circle classes based on given JUnit in order to eventually output them graphically. But I’m stuck in one of the methods for days now.
I tried to truncate precisions but then my equals method failed.
JUnit for Scale:
public void testScale(){
Length inch2 = Length.unit.scale(320.0);
assertTrue(inch2 != null);
assertEquals(Length.inch,inch2);
assertFalse(inch2.equals(Length.unit));
Length unit2 = Length.cm.scale(1.0/125.98425197);
assertTrue(unit2 != null);
assertEquals(Length.unit,unit2); // This is the line my scale method fails
// Here my unit2 has a length of 1.0001249999881234
// and my constant cm has a length of 1.0 but
// truncating those precisions caused my equals
// method to fails.
assertFalse(unit2.equals(Length.cm));
Length z = Length.meter.scale(0);
assertTrue(z != null);
assertEquals(Length.zero,z);
assertFalse(z.equals(Length.meter));
assertFalse(Length.zero.equals(null));
}
My scale method:
public Length scale(double d) {
if (d < 0)
throw new IllegalArgumentException();
else {
return new Length(d* this.length);
}
}
I suspect maybe the problem is coming from my equals method but in the given JUnit it is passing the tests.
JUnit for Equals:
public void testEquals(){
assertFalse(Length.unit.equals("Not a length"));
assertFalse(Length.inch.equals(null));
assertEquals(Length.zero,Length.unit.scale(0.0000001));
assertTrue(Length.unit.scale(0.0000001).compareTo(Length.zero) == 0);
assertTrue(Length.zero.compareTo(Length.unit.scale(0.0000001)) == 0);
assertFalse(Length.unit.scale(0.0000015).equals(Length.zero));
assertTrue(Length.unit.scale(0.0000015).compareTo(Length.zero) > 0);
assertTrue(Length.zero.compareTo(Length.unit.scale(0.0000015)) < 0);
}
My Equals Method:
#Override
public boolean equals(Object other) {
if (other == null || !(other instanceof Length)) {
return false;
}
Length o = (Length) other;
if (Math.abs(this.length - o.length) < 0.000001) {
return true;
} else {
return false;
}
}
Please help
Link for all my code:
https://www.dropbox.com/sh/bz400f8y0ufx381/59aUTilrBt
You are testing too many things at once.
A unit test should be one unit of code - one aspect of the code as opposed to everything at once.
I also notice that you don't have any of your test methods annotated with #Test; you should be doing this with JUnit4 tests.
So, for your first test, you have a relatively small scale method you want to exercise. Let's enumerate the cases:
d < 0. I should expect an IllegalArgumentException.
d >= 0. I should expect a new instance of Length with a size some multiple of d and whatever the set length of the instance is.
What this looks like is two discrete tests:
#Test(expected = IllegalArgumentException.class)
public void scaleShouldThrowExceptionWhenInvalidLength() {
}
#Test
public void scaleShouldBehaveNormally() {
}
I leave you to fill in the blanks, since I don't know what object scale is attached to.
Equals is the same way - you want to exercise each condition of the equivalence.
By the way, you can do return Math.abs(this.length - o.length) < 0.000001 for your conditions. return true and return false scream bad practice.
The object you're passing in is null.
The object you're passing in is not an instance of Length.
The object you're passing in fails Math.abs(this.length - o.length) < 0.000001.
The object you're passing in passes Math.abs(this.length - o.length) < 0.000001.
So the above are four discrete tests.
#Test
public void equalsShouldFailIfNull() {
}
#Test
public void equalsShouldFailIfNotInstanceOfLength() {
}
#Test
public void equalsDoesNotMeetCondition() {
}
#Test
public void equalsMeetsCondition() {
}
Filling in the blanks, I leave as an exercise to the reader.
Be very careful when dealing with floating-point numbers. You won't always get an exact representation back (that is, you may get an imprecise value when dealing with fractions). Be certain that your equals method is well-defined to respect what could happen when you don't have an exact decimal value to work with.
Alternatively, if you really need the decimal precision, use a BigDecimal instead.
I have to create an object that uses an "is" method, basically declaring the state of the object. I am not sure how this should work. Right now am writing the method as a boolean but I am wondering if I should use a different approach, here is the code,
public class Cell
{
public int move;
public Cell(int xmove)
{
xmove = 0;
}
public boolean isempty(int x)
{
if(x == 0)
{
return true;
}
else
{
return false;
}
}
}
You are kind of on the right track but there are a bunch of issues.
First, this is much simpler
public boolean isEmpty(){
return move == 0;
}
I assumed that an instance of Cell is empty if its move is 0.
Note that I've camel cased your method name. Also, isEmpty is supposed to say something about the state of an object. It doesn't make sense to pass in x (unless you want to compare x to some property on the object instance).
Second, you constructor takes an argument, then sets it to 0. That's not going to do anything. You probably want
public Cell(int move){
this.move = move;
}
Which takes an argument and sets the field on the current instance that is being constructed to the value passed in (you defined a field move, so you probably want to set it.).
So you could do something like
Cell cell1 = new Cell(1);
Cell cell2 = new Cell(0);
cell1.isEmpty() // false;
cell2.isEmpty() // true;
What is wrong with this method ? it seems but I am not sure that the comparison of adjacent children in the tree does not take place.
I roughly traced the workings of this algorithm by hand and I think the idea is correct maybe something wrong with the implementation or I have no Idea how recursion works, the second helper (compare) method seems to be the issue
public static int MAX(BST B) {
int m = ((Integer) B.root.data).intValue();
return call(B.root, m);
}
public static int call(node current, int max) {
//first helper method gets the max from two different levels in the tree
if(current == null)
return -1;
if(current.left == null && current.right == null)
return max;
else {
if(((Integer) current.data).intValue()>max)
max = ((Integer) current.data).intValue();
return compare(call(current.left,max),call(current.right,max));
}
}
//second helper method gets the max
static int compare(int m1, int m2) {
if(m1>m2)
return m1;
else
return m2;
}
Since you are searching the entire tree, I'm going to assume that the structure is not properly ordered.
The bug is in your call function with:
if(current.left==null&¤t.right==null) return max;
Imagine you have a tree with a root with two leaf nodes (three nodes total). The root has value 3, right has value 2, and left has value 5. The algorithm should return 5, but your code will return 3. This is because you ignore the value of any leaf (a node with no "children") with that line of code. So your code ignores the value 5, in this example, and returns max, which is 3.
You can fix this by returning compare(current.value, max) when left and right are null.
I think (not 100%) that you may have an issue because you only check if BOTH children are null if for example right is null and left is not you will attempt to call the method call on both right and. Perhaps add a case checking if one child is null and if so return call of the non null child.
... I have no Idea how recursion works ...
Recursion means the method you are in gets called from inside itself with some other arguments , and there is some check that exits by returning a value or continues to call itself recursively.
call() is indirectly recursive, as it either exits with a return of -1 or max or it calls itself again with new arguments and continues to do this until it either exits or crashes with an OutOfMemory error as the stack fills up.
This method isn't recursive: It is poorly named though.
static int compare(int m1, int m2) {
if(m1>m2)
return m1;
else
return m2;
}
and could be written ( and renamed ) as
static int min(final int m1, final int m2)
{
return Math.min(m1,m2);
}
or just inlined into
return Math.min(call(current.left,max),call(current.right,max));
either way, you are getting the minimum of the two values, not really comparing them that implies different logic and a different return value.
Either way that method isn't recursive and if the logic of m1 > m2 is appropriate it can't be the problem, more like the input to that function is not what you expect.
Step debugging is a powerful tool and one all experienced developers use every day!
I am using Gson to parse Json. What I don't understand what the return type will be if you don't catch the Runtime Exception. I was expecting it to be null, but it is not null when evaluating with a simple if statement.
My code looks something like this:
public X x(final String jsonString) {
return gson.fromJson(jsonString, X.class);
}
then from another function I call the function:
public void y() {
final X x = x();
if (x == null) {
System.out.println("x == null");
}
}
I was expecting x to be null, but it isn't because the print statement is not called? What is the value of x? I have solved my problem by using a catch block in the x() function and returning null from inside the catch block. But I am just wondering what the value of function x() is(if any?)? Hopefully I make any sense at all.
If x() is throwing an exception, the x variable remains uninitialized, since the control flow was interrupted. Without a try/catch, the exception keeps going up the stack and x is never usable. With a try/catch, x is only valid within the block, so if an exception happens it won't be usable.
If you try to do something like:
X x;
try {
x = x();
} catch(RuntimeException e) {}
if (x == null) {
...
you'll get the error "variable x might not have been initialized", since control flow can bypass the assignment