Function - Learning notes of Clean Code (3)

Function

  1. Small

    • The first rule of functions is that they should be small.
    • The second rule of functions is that they should be smaller than that.
    • Functions should not be large enough to hold nested structures. Therefore, the indent level of a function should not be greater than one or two. This, of course, makes the functions easier to read and understand.
  2. Do one thing

    • Functions should do one thing. They should do it well. They should do it only.
    • We can describe the one thing as a brief “To” paragraph. The one thing could include more than one step. And those steps should one level of abstraction below the stated of the function. After all, the reason we write functions is to decompose a larger concept (in other words, the name of the function) into a set of steps at the next level of abstraction.
  3. One level of abstraction per function

    • In order to make sure our functions are doing “one thing,” we need to make sure that the statements within our function are all at the same level of abstraction.
    • Mixing levels of abstraction within a function is always confusing. Readers may not be able to tell whether a particular expression is an essential concept or a detail.
    • Mixing levels of abstraction within a function is always confusing. Readers may not be able to tell whether a particular expression is an essential concept or a detail. Worse, like broken windows, once details are mixed with essential concepts, more and more details tend to accrete within the function.
  4. Reading code from top to bottom: the Stepdown rule.

    • We want the code to read like a top-down narrative.5 We want every function to be fol- lowed by those at the next level of abstraction so that we can read the program, descending one level of abstraction at a time as we read down the list of functions. I call this The Step- down Rule.
  5. Switch statement

    • Bury the switch statement in the basement of an abstract factory and never let anyone see it.
    • General rule for switch statements is that they can be tolerated if they appear only once, are used to create polymorphic objects, and are hidden behind an inheritance relationship so that the rest of the system can’t see them.
  6. Use descriptive name

    • Don’t be afraid to make a name long. A long descriptive name is better than a short enigmatic name.
    • Choosing descriptive names will clarify the design of the module in your mind and help you to improve it. It is not at all uncommon that hunting for a good name results in a favorable restructuring of the code.
    • Be consistent in your names. Use the same phrases, nouns, and verbs in the function names you choose for your modules.
  7. Function argument

    • The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldn’t be used anyway.
    • The argument is at a different level of abstraction than the function name and forces you to know a detail (in other words, StringBuffer) that isn’t particularly important at that point.
    • Arguments are even harder from a testing point of view.
    • Output arguments are harder to understand than input arguments.
  8. Common monadic form

    • There are two very common reasons to pass a single argument into a function. You may be asking a question about that argument, as in boolean fileExists(“MyFile”). Or you may be operating on that argument, transforming it into something else and returning it.
    • A somewhat less common, but still very useful form for a single argument function, is an event. In this form there is an input argument but no output argument.
    • Flag arguments are ugly. Passing a boolean into a function is a truly terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing. It does one thing if the flag is true and another if the flag is false.
  9. Dynamic functions

    • A function with two arguments is harder to understand than a monadic function.
    • Dyads aren’t evil, and you will certainly have to write them. However, you should be aware that they come at a cost and should take advantage of what mechanims may be available to you to convert them into monads.
  10. Triads

    • Functions that take three arguments are significantly harder to understand than dyads. The issues of ordering, pausing, and ignoring are more than doubled. I suggest you think very carefully before creating a triad.
    • When a function seems to need more than two or three arguments, it is likely that some of those arguments ought to be wrapped into a class of their own.
    • If the variable arguments are all treated identically, then they are equivalent to a single argument of type List.
  11. Verbs and keywords

    • Choosing good names for a function can go a long way toward explaining the intent of the function and the order and intent of the arguments.
    • In the case of a monad, the function and argument should form a very nice verb/noun pair. For example, write(name) is very evocative.
  12. Have no side effects

    • Side effects are lies. Your function promises to do one thing, but it also does other hidden things. Sometimes it will make unexpected changes to the variables of its own class. Sometimes it will make them to the parameters passed into the function or to system globals. In either case they are devious and damaging mistruths that often result in strange temporal couplings and order dependencies.
  13. Output argument

    • Arguments are most naturally interpreted as inputs to a function.
    • In general output arguments should be avoided. If your function must change the state of something, have it change the state of its owning object.
  14. Command Query Separation

    • Functions should either do something or answer something, but not both. Either your function should change the state of an object, or it should return some information about that object. Doing both often leads to confusion. Consider, for example, the following function
  15. Prefer exceptions to returning error code

    • Returning error codes from command functions is a subtle violation of command query separation. It promotes commands being used as expressions in the predicates of “if” statements.
    • This does not suffer from verb/adjective confusion but does lead to deeply nested struc- tures. When you return an error code, you create the problem that the caller must deal with the error immediately.
    • On the other hand, if you use exceptions instead of returned error codes, then the error processing code can be separated from the happy path code and can be simplified.
  16. Error handling is one thing

    • Try/catch blocks are ugly in their own right. They confuse the structure of the code and mix error processing with normal processing. So it is better to extract the bodies of the try and catch blocks out into functions of their own.
    • Functions should do one thing. Error handing is one thing. Thus, a function that handles errors should do nothing else.
  17. Don’t repeat yourself

    • Duplication may be the root of all evil in software. Many principles and practices have been created for the purpose of controlling or eliminating.
  18. Structured programming

Writing software is like any other kind of writing. When you write a paper or an article, you get your thoughts down first, then you massage it until it reads well. The first draft might be clumsy and disorganized, so you wordsmith it and restructure it and refine it until it reads the way you want it to read.

When I write functions, they come out long and complicated. They have lots of indenting and nested loops. They have long argument lists. The names are arbitrary, and there is duplicated code. But I also have a suite of unit tests that cover every one of those clumsy lines of code

So then I massage and refine that code, splitting out functions, changing names, elim- inating duplication. I shrink the methods and reorder them. Sometimes I break out whole classes, all the while keeping the tests passing.

Every system is built from a domain-specific language designed by the programmers to describe that system. Functions are the verbs of that language, and classes are the nouns. This is not some throwback to the hideous old notion that the nouns and verbs in a require- ments document are the first guess of the classes and functions of a system. Rather, this is a much older truth. The art of programming is, and has always been, the art of language design.

Master programmers think of systems as stories to be told rather than programs to be written. They use the facilities of their chosen programming language to construct a much richer and more expressive language that can be used to tell that story. Part of that domain-specific language is the hierarchy of functions that describe all the actions that take place within that system. In an artful act of recursion those actions are written to use the very domain-specific language they define to tell their own small part of the story.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值