I haven't had a lot of practice with patterns and application architecture. In a nutshell, I have to find certain attributes which object features. Some code will better describe task:
IAttribute {
IAttribute analyze();
}
//up to 10 different attributes
ConcreteAttribute1 {
int x = 0;
IAttribute analyze() {
//analyze smth which results in changing x if this attribute has been found
if (x != 0) return this;
return null;
}
}
ConcreteAttribute2 {
String s = "";
IAttribute analyze() {
//analyze smth which results in chanhing x if this attribute has been found
if (!s.equals("")) return this;
return null;
}
}
AttributeAnalyzer {
List<Attributes> analyzeAttributes() {
List<IAttribute> attributes = new ArrayList<IAttribute>();
attributes.add(new ConcreteAttribute1());
attributes.add(new ConcreteAttribute2());
...
for (IAttribute attr : attributes) {
attr = attr.analyze;
if (null == attr) attributes.remove(attr);
}
return attributes;
}
}
However, this implementation seems to be a little strange. I don't like the fact that Attribute is sort of holder, but it has to implement method to find itself. In my opinion, the best practice would be an opportunity to overload static methods, but obviously its not possible. In this way, we would separate holder from analyzing logic without adding new abstractions(maybe I am not right).
IAttribute {
static IAttribute analyze();
}
ConcreteAttribute1 {
int x = 0;
static IAttribute analyze() {
...
if (x != 0) return new ConcreteAttribute1();
return null;
}
}
ConcreteAttribute2 {
String s = "";
static IAttribute analyze() {
...
if (!s.equals("")) return new ConcreteAttribute2();
return null;
}
}
AttributeAnalyzer {
List<Attributes> analyzeAttributes() {
List<IAttribute> attributes = new ArrayList<IAttribute>();
attributes.add(ConcreteAttribute1.analyze());
attributes.add(ConcreteAttribute2.analyze());
...
for (IAttribute attr : attributes) {
if (null == attr) attributes.remove(attr);
}
return attributes;
}
}
In addition, I have to filter spoiled Attributes. So, are there any ways of refactoring to make this code looks better?
Aucun commentaire:
Enregistrer un commentaire