|
| 1 | +package org.codefx.demo.java10.lang.var; |
| 2 | + |
| 3 | +import java.math.BigDecimal; |
| 4 | + |
| 5 | +public class AdHocMethods { |
| 6 | + |
| 7 | + /* |
| 8 | + * DOWNSIDES |
| 9 | + * |
| 10 | + * - verbose |
| 11 | + * - combination of non-trivial language features (anonymous types & type inference) |
| 12 | + * - falls apart when extracting methods |
| 13 | + * |
| 14 | + * ALTERNATIVES |
| 15 | + * |
| 16 | + * - extension type collecting all needed methods |
| 17 | + * - utility methods |
| 18 | + */ |
| 19 | + |
| 20 | + public void report(Megacorp megacorp) { |
| 21 | + var corp = new SimpleMegacorp(megacorp) { |
| 22 | + final BigDecimal SUCCESS_BOUNDARY = new BigDecimal("500000000"); |
| 23 | + |
| 24 | + boolean isSuccessful() { |
| 25 | + return earnings().compareTo(SUCCESS_BOUNDARY) > 0; |
| 26 | + } |
| 27 | + |
| 28 | + boolean isEvil() { |
| 29 | + return true; |
| 30 | + } |
| 31 | + }; |
| 32 | + System.out.printf( |
| 33 | + "Corporation %s is %s and %s.\n", |
| 34 | + corp.name(), |
| 35 | + corp.isSuccessful() ? "successful" : "a failure", |
| 36 | + corp.isEvil() ? "evil" : "a failure" |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + // important domain concept, used throughout the system |
| 41 | + interface Megacorp { |
| 42 | + |
| 43 | + String name(); |
| 44 | + |
| 45 | + BigDecimal earnings(); |
| 46 | + |
| 47 | + BigDecimal taxes(); |
| 48 | + |
| 49 | + } |
| 50 | + |
| 51 | + // some implementation |
| 52 | + class SimpleMegacorp implements Megacorp { |
| 53 | + |
| 54 | + private final String name; |
| 55 | + private final BigDecimal earnings; |
| 56 | + private final BigDecimal taxes; |
| 57 | + |
| 58 | + SimpleMegacorp(String name, BigDecimal earnings, BigDecimal taxes) { |
| 59 | + this.name = name; |
| 60 | + this.earnings = earnings; |
| 61 | + this.taxes = taxes; |
| 62 | + } |
| 63 | + |
| 64 | + public SimpleMegacorp(Megacorp megacorp) { |
| 65 | + this(megacorp.name(), megacorp.earnings(), megacorp.taxes()); |
| 66 | + } |
| 67 | + |
| 68 | + @Override |
| 69 | + public String name() { |
| 70 | + return name; |
| 71 | + } |
| 72 | + |
| 73 | + @Override |
| 74 | + public BigDecimal earnings() { |
| 75 | + return earnings; |
| 76 | + } |
| 77 | + |
| 78 | + @Override |
| 79 | + public BigDecimal taxes() { |
| 80 | + return taxes; |
| 81 | + } |
| 82 | + |
| 83 | + } |
| 84 | + |
| 85 | +} |
0 commit comments