猿问

如何避免java类的这个帮助器方法中的代码重复?

我有一个这样的java类(通过龙目岛的getters/setters):


public class Foo

{

  @Getter

  @Setter

  private byte[] byte1;


  @Getter

  @Setter

  private String byte1String;


  @Getter

  @Setter

  private String byte1Value;


  @Getter

  @Setter

  private byte[] byte2;


  @Getter

  @Setter

  private String byte2String;


  @Getter

  @Setter

  private String byte2Value;

}

以及以下用于填充对象值的帮助器方法:Foo


private static final String DEFAULT_BYTE_VALUE = "someDefaultValue";


private Foo getWithBytesAndValues(Foo foo)

{

    if (foo.getByte1String() != null)

    {

        foo.setByte1(new Base64(foo.getByte1String()).decode());

        if (foo.getByte1Value() == null)

        {

            foo.setByte1Value(DEFAULT_BYTE_VALUE);

        }

    }

    if (foo.getByte2String() != null)

    {

        foo.setByte2(new Base64(foo.getByte2String()).decode());

        if (foo.getByte2Value() == null)

        {

            foo.setByte2Value(DEFAULT_BYTE_VALUE);

        }

    }

    return foo;

}

我的助手方法看起来很乱。而且似乎我重复了两次相同的代码。有没有办法简化方法?


慕容3067478
浏览 93回答 2
2回答

蝴蝶不菲

在类 Foo 中,您可以将@Getter和@Setter注释放在类上以避免重复(请注意,如果在此类上添加另一个不能公开的私有属性,则应删除@Getter注释,以免公开私有属性):@Getter@Setterpublic class Foo关于getWithBytesAndValues方法,我建议你把这种方法放在Foo类中,因为这种方法使get on Foo attrs并设置另一个Foo attrs(业务规则来自域Foo - 参见域驱动设计)。您还可以通过两种方法分离内部逻辑:public class Foo {...    public void setBytes()        setByte1();        setByte2();    }    private void setByte2() {        if (getByte2String() != null) {            setByte2(new Base64(getByte2String()).decode());            if (getByte2Value() == null) {                setByte2Value(DEFAULT_BYTE_VALUE);            }        }    }    private void setByte1() {        if (getByte1String() != null) {            setByte1(new Base64(getByte1String()).decode());            if (getByte1Value() == null) {                setByte1Value(DEFAULT_BYTE_VALUE);            }        }    }}

慕尼黑8549860

每个人都原谅我。JB Nizet的建议要好得多,但我想看看我能做些什么。public static void touch(&nbsp; &nbsp; &nbsp; &nbsp; final Consumer<byte[]> setByte,&nbsp; &nbsp; &nbsp; &nbsp; final Consumer<? super String> setByteValue,&nbsp; &nbsp; &nbsp; &nbsp; final Supplier<String> byteString,&nbsp; &nbsp; &nbsp; &nbsp; final Supplier<String> byteValue) {&nbsp; &nbsp; if (byteString != null) {&nbsp; &nbsp; &nbsp; &nbsp; setByte.accept(Base64.getDecoder().decode(byteString.get()));&nbsp; &nbsp; }&nbsp; &nbsp; if (byteValue.get() == null) {&nbsp; &nbsp; &nbsp; &nbsp; setByteValue.accept(DEFAULT_BYTE_VALUE);&nbsp; &nbsp; }}touch(&nbsp; &nbsp; &nbsp; &nbsp; foo::setByte1,&nbsp; &nbsp; &nbsp; &nbsp; foo::setByte1Value,&nbsp; &nbsp; &nbsp; &nbsp; foo::getByte1String,&nbsp; &nbsp; &nbsp; &nbsp; foo::getByte1Value);touch(&nbsp; &nbsp; &nbsp; &nbsp; foo::setByte2,&nbsp; &nbsp; &nbsp; &nbsp; foo::setByte2Value,&nbsp; &nbsp; &nbsp; &nbsp; foo::getByte2String,&nbsp; &nbsp; &nbsp; &nbsp; foo::getByte2Value);
随时随地看视频慕课网APP

相关分类

Java
我要回答