2011-09-30 62 views
1
public Object getValue() 
{ 
    ValueItem valueItem = null; 
    Object returnValue = null; 

    if(this.value instanceof StringValueImpl) 
    { 
     valueItem = (StringValueImpl) this.value; 
    } 
    else if(this.value instanceof ListValueImpl) 
    { 
     valueItem = (ListValueImpl) this.value; 
    } 
    else if(this.value instanceof MapValueImpl) 
    { 
     valueItem = (MapValueImpl) this.value; 
    } 

    if(valueItem!=null) 
     returnValue = valueItem.getValue(); 

    return returnValue; 
} 

ValueIteminterface这是由ListValueImplMapValueImpl等来实现。我想返回值是object。代码工作正常,但我想知道这是否可以在任何方式改善?建议优化代码

+2

public Object getValue(){return this.value; }应该工作得很好 –

+0

“ValueItem”接口有什么意义?如果它的实现拥有像字符串和列表这样的不相关的类型,我怀疑它是它们共有的任何功能的抽象。如果它的目的只是为了调用'getValue()'并接收一个'Object',那么为什么不为变量使用'Object'而不是'ValueItem'呢? – Wyzard

+0

感觉不好谁(如果有人)必须维护你的代码。 – mre

回答

6

this.value是什么类型的?如果是ValueItem那么你不需要做任何的这一点,可以用这个替代方法:

public Object getValue() 
{ 
    Object returnValue = null; 
    if(this.value!=null) 
     returnValue = this.value.getValue(); 
    return returnValue; 
} 

或者更短:

public Object getValue() 
{ 
    return this.value!=null ? this.value.getValue() : null; 
} 

如果this.valueValueItem但是必须包含ValueItem,那么你的设计问题就在你手上。

+1

差不多,除非'ValueItem'的实现比'StringValueImpl','ListValueImpl'和'MapValueImpl'更多的实现。 – Howard

+0

@Howard:如果有更多的实现,那么*不*在这里提及它可能是一个错误无论如何。 –

+0

我同意应该提供这些信息。不过值得一提的是,如果是这样的话,它会改变功能。 – Howard

1

我的倾向是你的getValue()根本没有为你做任何事情。您正在检测它是什么类,将其转换为该类,然后再将其放到一个对象中。 ...所以你必须在getValue()的呼叫者侧做同样的检测!

个人而言,我不喜欢这样写道:

public boolean isaStringValueImpl() { 
    return (this.value instanceof StringValueImpl); 
} 
public boolean isaListValueImpl() { 
    return (this.value instanceof ListValueImpl); 
} 
public boolean isaMapValueImpl() { 
    return (this.value instanceof MapValueImpl); 
} 

public StringValueImpl getAsaStringValueImpl() { 
    return (StringValueImpl)this.value; 
} 
public ListValueImpl getAsaListValueImpl() { 
    return (ListValueImpl)this.value; 
} 
public MapValueImpl getAsaMapValueImpl() { 
    return (MapValueImpl)this.value; 
} 

除了常规的getter:

public ValueItem getValueItem() { 
    return this.value; 
} 

但即使这一切,我会说,你可能有一个可以清理的更大的设计问题。

0

基于泛型的类型安全版本如何?

public abstract class ValueItem<T> { 

    public abstract T getValue(); 

    public class StringValueImpl extends ValueItem<String> { 
     private String value; 

     public String getValue() { 
      return value; 
     } 
    } 

    public class ListValueImpl extends ValueItem<List<?>> { 
     private List<?> value; 

     public List<?> getValue() { 
      return value; 
     } 
    } 

    public class MapValueImpl extends ValueItem<Map<?, ?>> { 
     private Map<?, ?> value; 

     public Map<?, ?> getValue() { 
      return value; 
     } 
    } 
}