# 如何成为更好的程序员？

## 3.代码指标

### 3.1. LOC

“LOC”表示“代码行”，是代码中非空行的数量。

### 3.4。认知复杂性

SonarCube声称：

“认知复杂性改变了使用数学模型来评估软件可维护性的实践。它从Cyclomatic Complexity设定的先例开始，但是使用人为判断来评估结构应该如何计算，并决定应该将什么添加到模型中作为一个整体结果，它产生了方法复杂性分数，这使得程序员对可维护性模型的评估比以前更公平。“

## 4.迭代数组

public interface SumArray {
long sum(int[] arr);
}

### 4.1.命令式解决方案

public class SumArrayImperative implements SumArray {
@Override
public long sum(int[] arr) {
long sum = 0;
for (int i : arr) {
sum += i;
}
return sum;
}
}

### 4.2声明式解决方案

public class SumArrayDeclarative implements SumArray {
@Override
public long sum(int[] arr) {
return IntStream.of(arr)
.mapToLong(i -> i)
.sum();
}
}

### 4.3.分析

SonarQube提供以下分析：

SumArray的代码度量标准如下表所示（通常更低）：

Imperative 12 5 2 1
Functional 11 2 2 0

## 5.并行聚合值

public final class Person {
private final String firstName;
private final String lastName;
private final int birthYear;
private final String country;
private final double salary;
public Person(String firstName,
String lastName,
int birthYear,
String country,
double salary) {
this.firstName = requireNonNull(firstName);
this.lastName = requireNonNull(lastName);
this.birthYear = birthYear;
this.country = requireNonNull(country);
this.salary = salary;
}
public String firstName() { return firstName; }
public String lastName() { return lastName; }
public int birthYear() { return birthYear; }
public String country() { return country; }
public double salary() { return salary; }
// equals, hashCode and toString not shown for brevity
}

public final class YearCountry {
private final int birthYear;
private final String country;
public YearCountry(Person person) {
this.birthYear = person.birthYear();
this.country = person.country();
}
public int birthYear() { return birthYear; }
public String country() { return country; }
// equals, hashCode and toString not shown for brevity
}

public interface GroupingBy {
Map average(Collection persons);
}

### 5.1.命令式的解决方案

public class GroupingByImperative implements GroupingBy {
@Override
public Map average(Collection persons) {
final List personList = new ArrayList(persons);
final int step = personList.size() / threads;
// Divide the work into smaller work items
final List<List> subLists = new ArrayList();
for (int i = 0; i < threads - 1; i++) {
subLists.add(personList.subList(i * step, (i + 1) * step));
}
final ConcurrentMap accumulators = new ConcurrentHashMap();
// Submit the work items to the common ForkJoinPool
final List<CompletableFuture> futures = new ArrayList();
for (int i = 0; i < threads; i++) {
final List subList = subLists.get(i);
}
// Wait for completion
for (int i = 0; i < threads; i++) {
futures.get(i).join();
}
// Construct the result
final Map result = new HashMap();
accumulators.forEach((k, v) -> result.put(k, v.average()));
return result;
}
private void average(List subList, ConcurrentMap accumulators) {
for (Person person : subList) {
final YearCountry bc = new YearCountry(person);
accumulators.computeIfAbsent(bc, unused -> new AverageAccumulator())
}
}
private final class AverageAccumulator {
int count;
double sum;
count++;
sum += term;
}
double average() {
return sum / count;
}
}
}

### 5.2. 声明式解决方案

public class GroupingByDeclarative implements GroupingBy {
@Override
public Map average(Collection persons) {
return persons.parallelStream()
.collect(
groupingBy(YearCountry::new, averagingDouble(Person::salary))
);
}
}

### 5.3.分析

SonarQube提供以下分析：

GroupingBy 的代码度量标准如下表所示（通常更低）：

Imperative 52 27 11 4
Functional 17 1 1 0

## 6.实现REST接口

public interface Rest {

/**

* Returns an unmodifiable list from the given parameters.
*
* @param persons as the raw input list
* @param predicate to select which elements to include
* @param order in which to present persons
* @param page to show. 0 is the first page
* @return an unmodifiable list from the given parameters
*/

List page(List persons,
Predicate predicate,
Comparator order,
int page);
}

public final class RestUtil {
private RestUtil() {}
public static final int PAGE_SIZE = 50;
}

### 6.1.命令式实现方法

public final class RestImperative implements Rest {
@Override
public List page(List persons,
Predicate predicate,
Comparator order,
int page) {
final List list = new ArrayList();
for (Person person:persons) {
if (predicate.test(person)) {
}
}
list.sort(order);
final int from = RestUtil.PAGE_SIZE * page;
if (list.size() <= from) {
return Collections.emptyList();
}
return unmodifiableList(list.subList(from, Math.min(list.size(), from + RestUtil.PAGE_SIZE)));
}
}

### 6.2.声明式解决方法

public final class RestDeclarative implements Rest {
@Override
public List page(List persons,
Predicate predicate,
Comparator order,
int page) {
return persons.stream()
.filter(predicate)
.sorted(order)
.skip(RestUtil.PAGE_SIZE * (long) page)
.limit(RestUtil.PAGE_SIZE)
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
}
}

### 6.3.分析

SonarQube提供以下分析：

Rest 的代码度量标准如下表所示（通常更低）：

Imperative 27 10 4 4
Functional 21 1 1 0

## 7.Java 11改进

@Override
public List page(List persons,
Predicate predicate,
Comparator order,
int page) {
final var list = new ArrayList();
...

public final class RestDeclarative implements Rest {
@Override
public List page(List persons,
Predicate predicate,
Comparator order,
int page) {
return persons.stream()
.filter(predicate)
.sorted(order)
.skip(RestUtil.PAGE_SIZE * (long) page)
.limit(RestUtil.PAGE_SIZE)
.collect(toUnmodifiableList());
}

## 8.摘要

### 8.1.在数据库应用程序中使用声明性构造

public Stream page(Predicate predicate,
Comparator order,
int page) {
return persons.stream()
.filter(predicate)
.sorted(order)
.skip(RestUtil.PAGE_SIZE * (long) page)
.limit(RestUtil.PAGE_SIZE);
}

Manager persons 由Speedment提供，并构成数据库表“Person”的句柄，可以通过Spring使用@AutoWired注解。

8月福利准时来袭，关注公众号