在我的春/啓動Java項目我有一組的服務方法,例如像以下之一:春季服務方法和複雜的驗證邏輯/規則
@Override
public Decision create(String name, String description, String url, String imageUrl, Decision parentDecision, Tenant tenant, User user) {
name = StringUtils.trimMultipleSpaces(name);
if (org.apache.commons.lang3.StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("Decision name can't be blank");
}
if (!org.apache.commons.lang3.StringUtils.isEmpty(url) && !urlValidator.isValid(url)) {
throw new IllegalArgumentException("Decision url is not valid");
}
if (!org.apache.commons.lang3.StringUtils.isEmpty(imageUrl) && !urlValidator.isValid(imageUrl)) {
throw new IllegalArgumentException("Decision imageUrl is not valid");
}
if (user == null) {
throw new IllegalArgumentException("User can't be empty");
}
if (tenant != null) {
List<Tenant> userTenants = tenantDao.findTenantsForUser(user.getId());
if (!userTenants.contains(tenant)) {
throw new IllegalArgumentException("User doesn't belong to this tenant");
}
}
if (parentDecision != null) {
if (tenant == null) {
if (findFreeChildDecisionByName(parentDecision.getId(), name) != null) {
throw new EntityAlreadyExistsException("Parent decision already contains a child decision with a given name");
}
} else {
if (findTenantedChildDecisionByName(parentDecision.getId(), name, tenant.getId()) != null) {
throw new EntityAlreadyExistsException("Parent decision already contains a child decision with a given name");
}
}
Tenant parentDecisionTenant = tenantDao.findTenantForDecision(parentDecision.getId());
if (parentDecisionTenant != null) {
if (tenant == null) {
throw new IllegalArgumentException("Public decision cannot be added as a child to tenanted parent decision");
}
if (!parentDecisionTenant.equals(tenant)) {
throw new IllegalArgumentException("Decision cannot belong to tenant other than parent decision tenant");
}
} else {
if (tenant != null) {
throw new IllegalArgumentException("Tenanted decision cannot be added as a child to public parent decision");
}
}
} else {
if (tenant == null) {
if (findFreeRootDecisionByName(name) != null) {
throw new EntityAlreadyExistsException("Root decision with a given name already exists");
}
} else {
if (findTenantedRootDecisionByName(name, tenant.getId()) != null) {
throw new EntityAlreadyExistsException("Root decision with a given name for this tenant already exists");
}
}
}
Decision decision = createOrUpdate(new Decision(name, description, url, imageUrl, parentDecision, user, tenant));
if (parentDecision != null) {
parentDecision.addChildDecision(decision);
}
criterionGroupDao.create(CriterionGroupDaoImpl.DEFAULT_CRITERION_GROUP_NAME, null, decision, user);
characteristicGroupDao.create(CharacteristicGroupDaoImpl.DEFAULT_CHARACTERISTIC_GROUP_NAME, null, decision, user);
return decision;
}
正如你所看到的,大多數的來自這個方法的代碼行被驗證邏輯佔據,我繼續在那裏添加一個新的驗證案例。
我想重構此方法並在更合適的位置移動此方法之外的驗證邏輯。請建議如何用Spring框架來完成。
使用JSR-303對於大多數的這一點,也許有檢查複合logiv一個自定義的驗證類。例如,您的前幾次檢查可以縮減爲'@ NotEmpty'。 – chrylis