Skip to content

Chex4j

June 2, 2011

Today got the reference from java.dzone.com on chex4j and wanted to try it out with Eclipse and here it goes. The code written here are from the java.dzone.com article.

SimpleAccount.java

package com.jagan.chex4j;

import java.math.BigDecimal;

import net.sf.chex4j.Contract;
import net.sf.chex4j.Post;
import net.sf.chex4j.Pre;

@Contract
public class SimpleAccount {

private BigDecimal balance;

@Post(“amount.doubleValue() >= 0.0d”)
public SimpleAccount(BigDecimal amount) {
this.balance = amount;
}

@Post(“$_.doubleValue() >= 0.0d”)
public BigDecimal getBalance() {
return this.balance;
}

@Pre(message = “Negative deposit.”)
// invokes deposit$Pre(amount)
@Post(message = “Balance exceeds 25k.”)
// invokes deposit$Post(amount)
public BigDecimal deposit(BigDecimal amount) {
this.balance = this.balance.add(amount);
return this.balance;
}

@SuppressWarnings(“unused”)
private boolean deposit$Pre(BigDecimal amount) {
return amount.doubleValue() >= 0.0d;
}

@SuppressWarnings(“unused”)
private boolean deposit$Post(BigDecimal amount) {
return this.balance.doubleValue() <= 25000;
}

}

SimpleAccountTest.java

package com.jagan.chex4j;

import java.math.BigDecimal;

public class SimpleAccountTest {

public static void main(String[] args) {
SimpleAccount saA = new SimpleAccount(new BigDecimal(100));
System.out.println(saA.getBalance());
saA.deposit(new BigDecimal(50000));
}

}

I use Maven and hence add the following dependency to your pom.xml.

<dependency>
<groupId>net.sf.chex4j</groupId>
<artifactId>chex4j-core</artifactId>
<version>1.0.2</version>
</dependency>

To run the code in Eclipse do the following (credits)

chex4j-Eclipse config

chex4j-Eclipse config

Already got a query on whether the post and pre conditions can be parametrized…..

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: