Skip to content

Commit

Permalink
Refactor token state management in MeasureUnitImpl
Browse files Browse the repository at this point in the history
- Introduced an enum `TokenState` to improve clarity and maintainability of token state definitions.
- Replaced integer state management with the new enum for better readability in the `nextSingleUnit` method.
- Updated conditional checks to utilize the new `TokenState` enum, enhancing code consistency.
  • Loading branch information
younies committed Jan 20, 2025
1 parent dbcd061 commit 7fcd356
Showing 1 changed file with 17 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,18 @@ private MeasureUnitImpl parse() {
return result;
}

/**
* Token states definitions.
*/
enum TokenState {
// No tokens seen yet (will accept power, SI or binary prefix, or simple unit)
NO_TOKENS_SEEN,
// Power token seen (will not accept another power token)
POWER_TOKEN_SEEN,
// SI or binary prefix token seen (will not accept a power, or SI or binary prefix token)
PREFIX_TOKEN_SEEN
}

/**
* Returns the next "single unit" via result.
* <p>
Expand All @@ -627,13 +639,7 @@ private MeasureUnitImpl parse() {
private SingleUnitOrConstant nextSingleUnit() {
SingleUnitImpl result = new SingleUnitImpl();

// State definitions:
// 0 = No tokens seen yet (will accept power, SI or binary prefix, or simple
// unit)
// 1 = Power token seen (will not accept another power token)
// 2 = SI or binary prefix token seen (will not accept a power, or SI or binary
// prefix token)
int state = 0;
TokenState state = TokenState.NO_TOKENS_SEEN;

boolean atStart = fIndex == 0;
Token token = nextToken();
Expand Down Expand Up @@ -704,21 +710,21 @@ private SingleUnitOrConstant nextSingleUnit() {
while (true) {
switch (token.getType()) {
case TYPE_POWER_PART:
if (state > 0) {
if (state != TokenState.NO_TOKENS_SEEN) {
throw new IllegalArgumentException();
}

result.setDimensionality(result.getDimensionality() * token.getPower());
state = 1;
state = TokenState.POWER_TOKEN_SEEN;
break;

case TYPE_PREFIX:
if (state > 1) {
if (state == TokenState.PREFIX_TOKEN_SEEN) {
throw new IllegalArgumentException();
}

result.setPrefix(token.getPrefix());
state = 2;
state = TokenState.PREFIX_TOKEN_SEEN;
break;

case TYPE_SIMPLE_UNIT:
Expand Down

0 comments on commit 7fcd356

Please sign in to comment.