I am thinking if is there some design pattern to work with objects and its states. In my REST API I have a access token objects, these objects contain information about authenticated clients:
public class AccessToken {
private final String accessToken;
private DateTime expiration;
private DateTime created;
}
but this AccessToken has an expiration time. When I check, whether client is logged in (= token exists), I would like to check whether token is not expired.
Question
Should be this method - e.g. .isValid()
, .isExpired()
for better clarity and simplicity be in AccessToken
class or should I have another class that will do a validation?
-
Could you tell us a bit more about these access tokens? Are they transmitted across the wire or internal? Are they instantiated/hydrated via deserialization or are they constructued from scratch?Ben Aaronson– Ben Aaronson09/15/2015 13:52:39Commented Sep 15, 2015 at 13:52
-
Authentication tokens, every client get one unique token to sign all his API requests.jnemecz– jnemecz09/15/2015 14:05:09Commented Sep 15, 2015 at 14:05
2 Answers 2
I think it's the responsibility of the AccessToken
to provide if it's expired or not.
Naming your method isExpired
seems less ambiguous to me.
public class AccessToken {
private final String accessToken;
private DateTime expiration;
private DateTime created;
public final boolean isExpired() {
return now > expiration;
}
}
I'm not sure if there is a named pattern (or not) for this technique - but either way I would not do it.
The DTO (data transfer object) is there to transfer the data over the wire, the business or application logic is tied to the REST API.
From Wikipedia;
... a DTO does not have any behavior except for storage and retrieval of its own data (accessors and mutators). DTOs are simple objects that should not contain any business logic that would require testing.
If you wish to provide the client with a utility class/method to check first if the token is still valid prior to making the REST call, I would provide the client with such a class outside of the DTO;
class AccessTokenValidation {
public bool isValid(AccessToken token) {
// client side logic as required
return now > token.expiration;
}
}