Anti if: the missing patterns — turn

@H_ 3010 @ original address: http://code.joejag.com/2016/anti-if-the-missing-patterns.html

But then it gets you thinking. Do you remember that heavily nested code you had to understand last week? That kinda sucked right? If only there was a way to make it simpler.

The anti-if campaign site is sadly low on practical advice. This post intends to remedy that with a collection of patterns you can adopt when the need arises. But first let’s look at the problem that if statements pose.

The first problem with if statements is that they often make it easy to modify code in bad ways. Let’s start with the birth of a new if statement: } This isn’t too bad at this point,but we’ve already given us some problems. When I read this code I have to check how CodeBlockA and CodeBlockB are modifying the same SharedState. This can be easy to read at first but can become difficult as the CodeBlocks grow and the coupling becomes more complicated. You’ll often see the above CodeBlocks abused with further nested if statements and local returns. Making it hard to see what the business logic is through the routing logic. The second problem with if statements is when they are duplicated. This means means a domain concept is missing. It’s all too easy to increase coupling by bringing things together than don’t need to be. Making code harder to read and change. The third problem with if statements is that you have to simulate execution in your own head. You must beome a mini-computer. That’s taking away from your mental energy,energy that would be better spent thinking about solving the problem,rather than how the intracate code branches weave together. I want to get to the point of telling you patterns we can do instead,but first a word of warning.

If statements usually make your code more complicated. But we don’t want to outright ban them. I’ve seen some pretty heinous code created with the goal of removing all traces of if statements. We want to avoid falling into that trap. For each pattern we’ll read about I’m going to give you a tolerance value for when to use it. A single if statement which isn’t duplicated anywhere else is probably fine. It’s when you have duplicated if statements that you want your spider sense to be tingling. At the outside of your code base,where you talk to the dangerous outside world,you are going to want to validate incoming responses and change your beahaviour accordingly. But inside our own codebases,where we behind those trusted gatekeepers,I think we have a great opportunity to use simple,richer and more powerful alternatives.

Context: You have a method that takes a boolean which alters its behaviour public class FileUtils { public static void createFile(String name,String contents, boolean temporary) { if(temporary) { // save temp file } else { // save permanent file } } } Problem: Any time you see this you actually have two methods bundled into one. That boolean represents an opportunity to name a concept in your code. Tolerance: Usually when you see this context you can work out at compile time which path the code will take. If that is the case then always use this pattern. Solution: Split the method into two new methods. Voilà,the if is gone. < span class="kd">public class FileUtils { public static void createFile(String name,String contents) { // save permanent file }

Context: You are switching based on type. < span class="kd"> private } Problem: When we add a new type we have to remember to update the switch statement. Additionally the cohesion is suffering in this Bird class as multiple concepts of different birds are being added. Tolerance: A single switch on type is fine. It’s when their are multiple switches then bugs can be introduced as a person adding a new type can forget to update all the switches that exist on this hidden type. There is an excellent write up on the on this context. @ H_ 301_ 0@Solution : Use Polymorphism. Anyone introducing a new type cannot forget to add the associated behavIoUr, } public class EuropeanBird extends Bird { public double getSpeed() { return getBaseSpeed() ; < span class="o">} } public class AfricanBird extends Bird { public double getSpeed() { return getBaseSpeed() - getLoadFactor(); < span class="o">} } public class NorwegianBird extends Bird { private boolean isNailed;

@H_ 301_ 0@Context : A outsider asked to understand the primary purpose of your code base answers with “to check if things equal null”. < span class="kd">private int sumOf(List<Integer> numbers) { if(numbers == null) { return 0; } } @H_ 301_ 0@Problem : Your methods have to check if they are being passed non null values. @ H_ 301_ 0@Tolerance : It’s necessary to be defensive at the outer parts of your codebase,but being defensive inside your codebase probably means the code that you are writing is offensive. Don’t write offensive code. @ H_ 301_ 0@Solution : Use a or type instead of ever passing a null. An empty collection is a great alternative. ()); < span class="kd">private int sumOf(List<Integer> numbers) { return numbers.stream().mapToInt(i -> i).< span class="na">sum(); < span class="o">}

@H_ 301_ 0@Context : You have an if statement tree that calculates a boolean expression. < span class="k"> if } @H_ 301_ 0@Problem : This code forces you to use your brain to simulate how a computer will step through your method. @ H_ 301_ 0@Tolerance : Very little. Code like this is easier to read on one line. Or broken into different parts. @ H_ 301_ 0@Solution : Simplify the if statements into a single expression.

@H_ 301_ 0@Context : You are calling some other code,but you aren’t sure if the happy path will succeed. < span class="kd">public class Finder { public String displayRecord(Repository repository) { String record = repository.< span class="na">getRecord(123); < span class="k">if(record == null) { return "Not found"; } else { return record; } } } @H_ 301_ 0@Problem : These sort of if statements multiply each time you deal with the same object or data structure. They have a hidden coupling where ‘null’ means someting. Other objects may return other magic values that mean no result. @ H_ 301_ 0@Tolerance : It’s better to push this if statement into one place,so it isn’t duplicated and we can remove the coupling on the empty object magic value. @ H_ 301_ 0@Solution : Give the code being called a coping strategy. Ruby’s is a good example which . This pattern can be taken even . < span class="k"> if } public class Finder { public String displayRecord(Repository repository) { return repository.< span class="na">getRecord(123,"Not found"); < span class="o">} }

@H_ 301_ 0@Hopefully you can use some of these patterns on the code you are working on just Now. I find them useful when refactoring code to better understand it. @ H_ 301_ 0@Remember if statements aren’t all evil. But we have a rich set of features in modern languages to use instead which we should take advantage of.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>