将过程Java代码重构为功能代码

时间:2017-07-20 03:18:44

标签: java functional-programming refactoring

我的代码库中有以下代码,我正在努力以更实用的方式重构它,我希望这里的任何人都可以帮助我。想法是找到人的地址id。请参阅以下代码:

public Integer findAddressId(String name) {
    List<Person> persons = getPersons(name);

    Integer addressId = -1;

    for (Person person : persons) {
        List<Address> addresses = findAddresses(person);

        for (Address address : addresses) {
            if (livesAtAddress(person, address)) {
                addressId = address.getId();
            }
        }
    }

    if(addressId > 0 ) {
        return addressId;
    } else {
        throw new RuntimeException("Cannot find address for person " + name);
    }
}

这些是很少的辅助方法:

private boolean livesAtAddress(Person person, Address address) {
    return false;
}

private List<Address> findAddresses(Person person) {
    return null;
}

private List<Person> getPersons(String name) {
    return null;
}

2 个答案:

答案 0 :(得分:2)

试试这个。

public Integer findAddressId(String name) {
    return getPersons(name).stream()
        .flatMap(person -> findAddresses(person).stream()
            .filter(address -> livesAtAddress(person, address)))
        .findFirst()
        .map(address -> address.getId())
        .orElseThrow(() -> new RuntimeException("Cannot find address for person " + name));
}

此代码将返回第一个找到的地址的ID,而不是返回最后一个地址的代码。

答案 1 :(得分:0)

使用Java 1.8(因为你正在寻找功能性的东西):

public Integer findAddressId(String name) {
  Integer addressID = getPersons(name).stream().reduce(-1, (acc, person)->{
    findAddresses(person).forEach(address->{
      if(livesAtAddress(person, address))
        acc = address.getId();
    });
    return acc;
  });

  if(addressID > 0)
    return addressID;
  else
    throw new RunTimeException("Couldn't find address for person "+name);
}

希望这会有所帮助,我对Java 8还是比较陌生的,所以如果&#34;那么可能会有比#34;更好的方式。但这应该正常工作。