优化代码的建议

Pho*_*nix 1 java

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;
}
Run Code Online (Sandbox Code Playgroud)

ValueItem是的interface这是由执行ListValueImpl,MapValueImpl等等.我想返回值是一个object.代码工作正常但我想知道这是否可以以任何方式改进?

Joa*_*uer 6

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

public Object getValue()
{
    Object returnValue = null;
    if(this.value!=null)
        returnValue = this.value.getValue();
    return returnValue;
}
Run Code Online (Sandbox Code Playgroud)

甚至更短:

public Object getValue()
{
    return this.value!=null ? this.value.getValue() : null;
}
Run Code Online (Sandbox Code Playgroud)

如果this.value没有类型的ValueItem ,但必须包含一个ValueItem,那么你在你的手有一个设计问题.

  • @ user384706:不是真的.****当我告诉你,你不会在**级别找到任何相关的性能优化时,请相信我.*大多数*你的表演将在设计问题中丢失,其余的你将不得不用剖析器寻找:**在性能方面不要试图猜测**.你错了.*当他们试图猜测性能问题在哪里时,每个人都错了. (2认同)