Skip to content

Instantly share code, notes, and snippets.

@vestel
Created August 7, 2009 07:42
Show Gist options
  • Save vestel/163772 to your computer and use it in GitHub Desktop.
Save vestel/163772 to your computer and use it in GitHub Desktop.
public void testAccountExceptionDiffCaseFailed() {
try {
Account a = new Account("Hacker");
fail(a.getName() + " isn't legal name");
} catch (AccountException e) {
assertEquals(e.getMessage(),
AccountException.NAME_TOO_SIMPLE);
}
}
public void testAccountExceptionDiffCaseCorrect() {
try {
Account a = new Account("c00l_hax0r");
assertEquals(a.getName(),"c00l_hax0r");
} catch (AccountException e) {
fail(e.getName() + " is legal name");
}
}
package sef.module8.activity;
/**
* This class represents the exception that can be thrown if the
* name given to an Account instance violates naming rules
*
* @author John Doe
*
*/
public class AccountException extends Exception {
public static final String NAME_TOO_SHORT = "Name must be longer than 4 characters";
public static final String NAME_TOO_SIMPLE = "Name must contain a combination of letters and numbers";
private String name;
/**
* Constructs an AcountException
*
* @param message
* The message to be set explaining the name
* violation (see static attributes)
* @param name
* The actual name
*/
public AccountException(String message, String name) {
super(message);
this.name = name;
}
/**
* Returns the name passed to this Account exception
*
* @return
*/
public String getName() {
return this.name;
}
}
package sef.module8.activity;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Thsi class represents a simple representation of an account
* encapsulating a name
*
* @author John Doe
*
*/
public class Account {
private String name;
final static int MIN_LENGTH = 4;
/**
* Creates an Account object with the specified name. If the
* account name given violates the minimum requirements, then
* an AccountException is thrown
*
* @param accountName
* @throws AccountException
*/
public Account(String accountName) throws AccountException {
if (accountName.length() < MIN_LENGTH) {
throw new AccountException(
AccountException.NAME_TOO_SHORT, accountName);
}
boolean flagL = false;
boolean flagD = false;
boolean flag = false;
for (int i = 1; (i < accountName.length() && !flag); i++) {
flagL = flagL
|| Character.isLetter(accountName.charAt(i));
flagD = flagD
|| Character.isDigit(accountName.charAt(i));
flag = flagL && flagD;
}
if (flag) {
this.name = accountName;
} else {
throw new AccountException(
AccountException.NAME_TOO_SIMPLE, accountName);
}
}
/**
* Returns the account name
*
* @return the account name
*/
public String getName() {
return this.name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment