# 命令式到函数式编程

## 逻辑判断和返回 vs. Optional

```if(id != null) {
return find1(id);
}

if(name != null) {
return find2(name);
}

if(type != null) {
return find3(type);
}```

```Supplier<?> chain = find(() -> find1(id), id)
.orElseGet(() -> find(() -> find2(name), name)
.orElse(() -> find3(type), type)));

Optional<Supplier<?>> find(Supplier s, Condtion... conditions) {
return Stream.of(conditions).anyMatch(c -> c == null) ? Optional.empty() : Optinal.of(s);
}```

```static Optional<Supplier<?>> or(Optional<Supplier<?>> hl, Optional<Supplier<?>> hr) {
return hl.isPresent() ? hl : hr;
}

Supplier<?> chain =
or(
or(find(() -> find1(id), id),
find(() -> find2(name), name)),
find(() -> find3(type), type));     ```

```ofNullalbe(id)
.map(id -> find1(id))
.map(r -> nonNull(r) ? r : find2(name)))
.map(r -> nonNull(r) ? r : find3(type)))
.orElse(T t);```

```static <U> Optional<U> orGet(Supplier<? extends U> other) {
return isPresent() ? this : Optional.ofNullable(other.get());
}

ofNullalbe(id)
.map(id -> find1(id))
.orGet(() -> find2(name))
.orGet(() -> find3(type))
.orElse(T t);```

```ofNullalbe(id)
.map(id -> find1(id))
.orGet(() -> ofNullable(name).map(name -> find2(name)))
.orGet(() -> ofNullable(type).map(type -> find3(type)))
.orElse(T t);

static <U> Optional<U> orGet(Supplier<? extends Optional<U>> other) {
return isPresent() ? this : Optional.ofNullable(other.get());
}    ```

## 语句重构到表达式

### if-else -> Optional

```Optional<Rule> rule = ruleOf(id);
if(rule.isPresent()) {
return transform(rule.get());
} else {
throw new RuntimeException();
}

public Rule transform(Rule rule) {
return Rule.builder()
.withName("No." + rule.getId())
.build();
}```

```Optional rule = ruleOf(id);

if(!rule.isPresent()) {
throw new RuntimeException();
}

return transform(rule.get());```

```...
return rule.map(r -> transform(r)).get();```

```...
rule.map(r -> Rule.builder()
.withName("No." + r.getId())
.build()).get();```

```...
rule.map(r -> Rule.builder()
.withName("No." + r.getId())
.build())
.orElseThrow(() -> new RuntimeException());```

```if(!rule.isPresent()) {
// throw new RuntimeException();
} ```

```ruleOf(id).map(r -> Rule.builder()
.withName("No." + r.getId())
.build())
.orElseThrow(() -> new RuntimeException());```

### 重复try...catch->Closure

```// 结构性重复
if(meta.hasURI()) {
try {
return deciderOfURI.decide(attr);
} catch (CustomizedException e) {
//...
LOGGER.error(e);
} catch (Exception e) {
//...
LOGGER.error(e);
}
}

if(meta.hasAction()) {
try {
return deciderOfAction.decide(attr);
} catch (CustomizedException e) {
//...
LOGGER.error(e);
} catch (Exception e) {
//...
LOGGER.error(e);
}
}```

```pubic Decision tryDecide() {
if(meta.hasURI()) {
try {
return deciderOfURI.decide(attr);
} catch (CustomizedException e) {
//...
LOGGER.error(e);
} catch (Exception e) {
//...
LOGGER.error(e);
}
}
}```

```pubic Decision tryDecide(Supplier<Decision> decider) {
if(meta.hasURI()) {
try {
return decider.get();
} catch (CustomizedException e) {
//...
LOGGER.error(e);
} catch (Exception e) {
//...
LOGGER.error(e);
}
}
}```

```// 结构性重复
if(meta.hasURI()) {
return tryDecide(() -> deciderOfAction.decide(attr));
}

if(meta.hasAction()) {
return tryDecide(() -> deciderOfURI.decide(attr));
}```

50 篇文章15 人订阅

0 条评论

## 相关文章

1554

Reduce文件会从Mapper任务中拉取很多小文件，小文件内部有序，但是整体是没序的，Reduce会合并小文件，然后套个归并算法，变成一个整体有序的文件。

2481

### 聊聊storm的WindowedBolt

storm-2.0.0/storm-client/src/jvm/org/apache/storm/topology/IWindowedBolt.java

2314

9052

2031

### SDP（9）：MongoDB-Scala - data access and modeling

MongoDB是一种文件型数据库，对数据格式没有硬性要求，所以可以实现灵活多变的数据存储和读取。MongoDB又是一种分布式数据库，与传统关系数据库不同...

3904

1101

### 位运算的方法，大结

Title:       位操作基础篇之位操作全面总结 Author:     MoreWindows E-mail:      morewindows@126...

6148

### POJ 2492 A Bug's Life

A Bug's Life Time Limit: 10000MS Memory Limit: 65536K Total Submissions:...

28910

### Code forces 719A Vitya in the Countryside

A. Vitya in the Countryside time limit per test:1 second memory limit per test:2...

3496