Model Constraint Validation
Given a generic tree based (Java) data model. Let's say
abstract class XModel {
long id;
XModel parent;
}
class ProjectModel extends XModel {
String customer;
}
class FileModel extends XModel {
String name;
}
class FolderModel extends XModel {
String name;
String attributes;
}
My challenge is to make sure that FileModels are only used in FolderModels (or PrjectModels) and FolderModels are only used in ProjectModels. Since the model 开发者_运维问答should be extensible - is there any generic way to do this constraint validation (like XML Schema does) without hardcoding the parent-child-realtions in a validation method?
I'm not sure how useful it would be - depends on how you create the tree, but this might work:
abstract class XModel<T extends XModel> {
long id;
T parent;
}
class ProjectModel extends XModel { ... }
class FolderModel extends XModel<ProjectModel> { ... }
class FileModel extends XModel<FolderModel> { ... }
UPDATE
To separate validation logic from model itself you could use some runtime validators like Hibernate or Spring validators.
I would use generics and interfaces that describe the restrictions
interface Model {
}
abstract class AbstractModel<P extends Model> implements Model {
Long id;
P parent;
}
class ProjectModel extends AbstractModel implements HasFileModel,
HasFolderModel {
}
interface HasFileModel extends Model {
}
static class FileModel extends AbstractModel<HasFileModel> {
}
interface HasFolderModel extends Model {
}
class FolderModel extends AbstractModel<HasFolderModel> implements
HasFileModel {
}
This way the child only restricts the parent to an interface not a concrete type
If you don't want to put those constraints into code, you'd have to write a validation method that is fed by some external data yourself. AFAIK there's no such built in option (in the compiler) besides using Generics, which would require you to express the constraints in code.
精彩评论