programo issues cora pérez ariza ~ decsai ~ ugr granada, january 28 th & 29 th, 2009
TRANSCRIPT
Programo IssuesProgramo Issues
Cora Pérez Ariza ~ DECSAI ~ UGR
Granada, January 28th & 29th, 2009
IndexIndex
JUnit◦Introduction to the topic◦Tags◦Example
Design Decisions◦equals and hashCode methods◦toString method
2
JUnitIntroduction
3
Why a JUnit?They reassure us that the expected behavior of our
work is the actual behavior (and will stay like that in the future)
How to use it?• Creation is easy: short methods that test critical
parts of the project’s classes.• Integrated on NetBeans• Few “tags” to learn
JUnitTags
4
Tags:
• @Test
• @Before and @After
• @BeforeClass and @AfterClass
• @Ignore
JUnitExample: Beginning
5
package programo.core.potential;
import org.junit.After;import org.junit.AfterClass;import org.junit.Before;import org.junit.BeforeClass;import org.junit.Test;import org.junit.Ignore;import static org.junit.Assert.*;
import programo.core.variable.*;import programo.core.assignation.*;
You should import as many classes as tags you are going to use
JUnitExample: data members
6
public class PotentialTableTest {
PotentialTable pot1, pot2, resNorm, resMarg, resComb, resProj; CategoricalVariable X1, X2, X3, X4; CategoricalAssignation configurationToProject; VariableSet setOfVars1, setOfVars2;
You can declare variables as class members, to use as global variables for your tests
JUnitExample: before/after the tests
7
@BeforeClass public static void setUpClass() throws Exception { …. }
@AfterClass public static void tearDownClass() throws Exception { … }
These methods will run before/after the bunch of tests (only once)
JUnitExample: before/after each test
8
@Before public void setUp() { … }
@After public void tearDown() { … }
These methods will run before/after each test (so one time per test)
JUnitExample: auxiliar methods
9
public void initializeVariables(){ …}
You can define auxiliar methods to perform specific operations within your JUnit file
JUnitExample: test cases
10
@Testpublic void testNormalizePotential() {
initializeVariables();
pot1.normalizePotential();
assertTrue(resNorm.equalValues(pot1));
}
@Test tag marks the method as a test
Body of the test case
Assertion to check if the test has worked
JUnitExample: test cases
11
@Ignore("Not ready to run")@Testpublic void testSumMarginalize() {
initializeVariables();
Potential result = pot1.sumMarginalize(setOfVars2);
assertTrue(resMarg.equalValues(result));
}
You may not want to execute one or more test cases: use @Ignore
JUnitResult in NetBeans
12
JUnitOther useful utilities
13
Other utilities:
• Exception Handling• Use “expected” parameter with @Test tag for
test cases that expect exception:• @Test(expected = ArithmeticException.class)
• Timeout• Define a timeout period in miliseconds:
• @Test(timeout = 1000)
Design DecisionsOverview: equals General Contract
14
public boolean equals(Object obj):• Implements an equivalence relation:
• It is reflexiveo For any reference value x, x.equals(x) should return true
• It is symmetrico For any x and y, x.equals(y) == y.equals(x)
• It is transitiveo For any x, y, z, if x.equals(y) and y.equals(z), then x.equals(z)
• It is consistento For any x and y, x.equals(y) should return the same in every
invocation if both remains inmutable• For any non-null reference value x, x.equals(null) should return
false• Equal objects must have equal hash codes
Design DecisionsOverview: hashCode General Contract
15
public int hashCode():
• Must be consistent during the same execution of the application
• Equal objects must produce equal hash codes, however unequal objects need not produce distinct hash codesoDifferent hash codes for different objects may
improve the performance of hashtables
Design Decisionsequals and hashCode: when to override
16
Do not override:• Each instance of the class is inherently unique• You don’t care whether the class provides a “logical equality”
test• A super class has already overridden equals appropriately for
this class• The class is private or package private, and you are certain that
its equals method will never be invoked
Override:• When a class has a notion of logical equality that differs from
mere object identity, and a super class has not already overridden equals to implement the desired behavior
Design Decisionsequals and hashCode: possible problems
17
Problems with sets and hash maps:
Overriding equals enables instances of the class to serve as map keys or set elements with predictable, desirable behavior
Design Decisionsequals and hashCode: possible problems: Example
18
Problems with sets and hash maps: public class Point{ private final int x; private final int y; public Point(int x, int y){ this.x = x; this.y = y; }}
… HashMap tabla = new HashMap(); tabla.put(new Point(1,3), 1);if(tabla.containsKey(new Point(1,3))) System.out.println("both points are the same");else System.out.println("two different objects");
Design Decisionsequals and hashCode: possible problems: Example
19
Problems with sets and hash maps:public class Point{ private final int x; private final int y; public Point(int x, int y){ this.x = x; this.y = y; } @Override public boolean equals(Object obj){ if(this == obj) return true; if(obj == null) || (obj.getClass() != this.getClass()) return false; Point p = (Point) obj; return (p.x == this.x && p.y == this.y) }}
Design Decisionsequals and hashCode: possible problems: Example
20
Problems with sets and hash maps:
Design Decisionsequals and hashCode: general advice
21
equals:• Do not change the type of the argument, it takes java.lang.Object• Review your method to verify that it fulfills all the requirements stated
by the general contract• Do not forget to override hashCode method whenever you override
equals method• Primitives can be compared directly with equality operator (==)
• float to Float.floatToIntBits• double to Double.doubleToLongBits
• instance of VS getClass• Instance of checks if same class or subclass
• May break symmetry requirement• Use only if class final
• getClass checks if same class exclusively
Design Decisionsequals and hashCode: general advice
22
hashCode:
• Involve significant variables of your object in the calculation of the hash code
• Review your hashCode method and check if it is returning equal hash codes for equals objects
• Different hash codes for different objects is not mandatory, but advisable
Design Decisionsequals method in ProGraMo
23
When should two objects be equals?
• When they refer to the same object?• Shallow comparison
• When although they are different objects, their data members’ values are the same?• Deep comparison
Design DecisionstoString method
24
We should always override toString()
• Providing a good toString implementation makes a class much more pleasant to use
• toString method should return all of the interesting information contained in the object
Thanks!Thanks!DECSAI ~ UGR
“Effective Java”, by Joshua Bloch. Addison Wesley
“Equals and HashCode”, by Manish Hatwalnehttp://www.geocities.com/technofundo/tech/java/equalhash.html
“Junit 4 in 60 Seconds”, by cavdar.nethttp://www.cavdar.net/2008/07/21/junit-4-in-60-seconds/