1. Trang chủ
  2. » Công Nghệ Thông Tin

OReilly perl best practices jul 2005 ISBN 0596001738

1,1K 426 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.106
Dung lượng 2,56 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

With Perl Best Practices, Damian shows specifically how and why, so everyone else can see, too." -- Andy Lester "Damian's done what many thought impossible: show how to build large, main

Trang 1

By Damian Conway

Publisher: O'Reilly Pub Date: July 2005 ISBN: 0-596-00173-8 Pages: 542

Trang 2

and practices Damian lays down will help bring Perl out from under the embarrassing heading of "scripting languages" Many of us have known Perl is a real programming

language, worthy of all the tasks normally delegated to Java and C++ With Perl Best Practices, Damian shows specifically how and why, so everyone else can see, too." Andy Lester

"Damian's done what many thought impossible: show how to build large, maintainable Perl applications, while still letting Perl be the powerful, expressive language that programmers have loved for years." Bill Odom

"Finally, a means to bring lasting order to the process and product of real Perl

development teams." Andrew Sundstrom

"Perl Best Practices provides a valuable education in how to write robust, maintainable

Perl, and is a definitive citation source when coaching other programmers." Bennett Todd

"I've been teaching Perl for years, and find the same question keeps being asked: Where can I find a reference for writing reusable, maintainable Perl code? Finally I have a decent answer." Paul Fenwick

"At last a well researched, well thought-out, comprehensive guide to Perl style Instead of each of us developing our own, we can learn good practices from one of Perl's most prolific and experienced authors I recommend this book to anyone who prefers getting on with the job rather than going back and fixing errors caused by syntax and poor style issues." -

Trang 3

By Damian Conway

Publisher: O'Reilly Pub Date: July 2005 ISBN: 0-596-00173-8 Pages: 542

Trang 4

Section 3.10 Utility Subroutines

Chapter 4 Values and Expressions Section 4.1 String Delimiters

Section 4.2 Empty Strings

Section 4.3 Single-Character Strings Section 4.4 Escaped Characters

Trang 5

Section 6.6 Unnecessary Subscripting Section 6.7 Necessary Subscripting

Section 6.8 Iterator Variables

Section 6.9 Non-Lexical Loop Iterators Section 6.10 List Generation

Section 6.11 List Selections

Section 6.12 List Transformation

Section 6.13 Complex Mappings

Section 6.14 List Processing Side Effects Section 6.15 Multipart Selections

Trang 6

Section 7.9 Algorithmic Documentation Section 7.10 Elucidating Documentation Section 7.11 Defensive Documentation Section 7.12 Indicative Documentation Section 7.13 Discursive Documentation Section 7.14 Proofreading

Section 9.8 Contextual Return Values Section 9.9 Multi-Contextual Return Values Section 9.10 Prototypes

Trang 8

Section 12.13 Unconstrained Repetitions Section 12.14 Capturing Parentheses Section 12.15 Captured Values

Section 12.16 Capture Variables

Section 12.17 Piecewise Matching

Section 12.18 Tabular Regexes

Section 12.19 Constructing Regexes Section 12.20 Canned Regexes

Section 12.21 Alternations

Section 12.22 Factoring Alternations Section 12.23 Backtracking

Section 13.14 Unpacking Exceptions Chapter 14 Command-Line Processing Section 14.1 Command-Line Structure Section 14.2 Command-Line Conventions Section 14.3 Meta-options

Section 14.4 In-situ Arguments

Section 14.5 Command-Line Processing Section 14.6 Interface Consistency

Section 14.7 Interapplication Consistency Chapter 15 Objects

Section 15.1 Using OO

Section 15.2 Criteria

Section 15.3 Pseudohashes

Trang 10

Section B.1 Chapter 2, Code Layout

Section B.2 Chapter 3, Naming Conventions Section B.3 Chapter 4, Values and Expressions Section B.4 Chapter 5, Variables

Section B.5 Chapter 6, Control Structures Section B.6 Chapter 7, Documentation

Trang 11

Section B.12 Chapter 13, Error Handling

Section B.13 Chapter 14, Command-Line Processing Section B.14 Chapter 15, Objects

Section B.15 Chapter 16, Class Hierarchies

Section B.16 Chapter 17, Modules

Section B.17 Chapter 18, Testing and Debugging Section B.18 Chapter 19, Miscellanea

Trang 12

most titles (safari.oreilly.com) For more information, contactour corporate/institutional sales department: (800) 998-9938 or

Trang 13

Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and O'Reilly Media, Inc.was aware of a trademark claim, the designations have beenprinted in caps or initial caps

While every precaution has been taken in the preparation of thisbook, the publisher and author assume no responsibility for

errors or omissions, or for damages resulting from the use ofthe information contained herein

ISBN: 0-596-00173-8

[M]

Trang 14

For Linda

Trang 15

This book is designed to help you write better Perl code: in fact,the best Perl code you possibly can It's a collection of 256

guidelines covering various aspects of the art of coding,

including layout, name selection, choice of data and controlstructures, program decomposition, interface design and

implementation, modularity, object orientation, error handling,testing, and debugging These guidelines have been developedand refined over a programming career spanning 22 years

They're designed to work well together, and to produce codethat is clear, robust, efficient, maintainable, and concise

Mind you, that's not easy to achieve Conciseness can be thenatural enemy of clarity; efficiency the nemesis of

assessments Each programmer and each programming teamwill have their own opinions about the most important and

desirable attributes of code

What this book offers instead is a set of best practices: a set

that is coherent, widely applicable, balanced in its aims, andthat is based on real-world experience of how code is actuallywritten, rather than on someone's ivory-tower theories on howcode ought be created Most of all, it's a set of practices thatactually work, and that many developers around the world arealready using Much like Perl itself, these guidelines are abouthelping you to get your job done, without getting in the way

Trang 16

of them unnatural or counterintuitive; others may feel

excessively rigid and un-Perlish Maybe they'll just seem

unnecessarily different from the ways you're used to writingsoftware, and from the long-ingrained coding habits you find socomfortable

Try to put those feelings aside as you read through the advice inthis book Review it as you would any other proposed code

enhancement: analyze the arguments that are made for thesenew practices; ask yourself whether you've ever fallen into thetraps they seek to avoid; consider whether the coding

techniques suggested here might be worth trying

Just thinking about these issuesbecoming conscious of the wayyou currently write codecan be of enormous benefit, even if youdon't adopt a single one of the recommendations that follow

Trang 17

consistent use of whitespace; the optimal width for code linesand block indents; how to set out lists of values; and where tobreak long expressions It concludes by recommending a

convenient tool that automates most of these layout tasks

Chapter 3, Naming Conventions, presents a series of guidelinesthat can help you choose more descriptive names for variables,subroutines, and namespaces It also demonstrates how thevarious components of a consistent naming scheme can worktogether to improve the overall maintainability of code, both bymaking it more readable and by reducing the need for

deobfuscatory comments

Chapter 4, Values and Expressions, provides a simple set ofrules that can help you avoid common pitfalls when creatingcharacter strings, numbers, and lists Topics include how to

avoid unintended variable interpolation (and non-interpolation),reliable and readable approaches to nonprintable characters,defining constants, avoiding barewords, and taming heredocs,commas, long numbers, and lists

Chapter 5, Variables, explores a robust approach to using

Trang 18

punctuation variables, suggesting safer alternatives where

possible, and safer practices where there are no alternatives.The second half of the chapter presents several efficient andmaintainable techniques of handling data in arrays and hashesusing the "container slicing" mechanism

Chapter 6, Control Structures, examines Perl's rich variety ofcontrol structures, encouraging the use of those that are easier

to maintain, less error-prone, or more efficient The chapterprovides a set of simple guidelines for deciding which of for,

while, or map is most appropriate for a given task The effectiveuse of iterator variables is also discussed, including the commoncase of needing to iterate hash entries by key and value

simultaneously

Chapter 7, Documentation, suggests a series of techniques thatcan make documenting your code less tedious, and thereforemore likely It advocates a template-based approach to bothuser and technical documentation, and discusses when, where,and how to write useful and accurate comments

Chapter 8, Built-in Functions, discusses better ways of usingsome of Perl's most popular built-in functions, including sort,

reverse, scalar, eval, unpack, split, substr, values, select, sleep, map,and grep It also summarizes the many other useful "non-built-in" builtins provided by two modules from the standard Perl

distribution and one from CPAN

Chapter 9, Subroutines, describes efficient and maintainableways to write subroutines in Perl, including the use of

positional, named, and optional arguments, argument validationand defaults, safe calling and return conventions, predictablereturn values in various contexts, and why subroutine

prototypes and implicit returns should be avoided

Chapter 10, I/O, explains how to open and close files reliably,when to use line-based input, how to correctly detect

Trang 19

Chapter 11, References, offers advice on demystifying Perl'smany dereferencing syntaxes, discusses why symbolic

references create more problems than they solve, and

recommends ways to prevent cyclic reference chains from

causing memory leaks

Chapter 12, Regular Expressions, presents guidelines for usingregular expressions It recommends the use of extended

formatting, suggests a simple but unusual fix for Perl's

confusing "single-line" and "multiline" matching modes, warns

of the perils of matching whitespace too precisely, shows how toavoid using the error-prone numeric variables, presents a

, Error Handling, advocates a coherent exception-recommends the use of exception objects, and explores in detailhow they can be declared, created, thrown, caught, and

handled

Chapter 14, Command-Line Processing, addresses the designand implementation of command-line interfaces, both for

individual programs and for application suites It recommendsseveral modules that can make your command-line interfacesmore consistent and predictable, and at the same time can

considerably reduce the effort required to implement those

interfaces

Chapter 15, Objects, and Chapter 16, Class Hierarchies, offer arobust and efficient approach to creating objects and class

Trang 20

collision, incomplete initialization, partial destruction, or

incorrect method autoloading Chapter 16 also introduces a newmodule that allows these robust and efficient classes to be builtsemi-automatically

Chapter 17, Modules, looks at non-object-oriented modules,exploring the best ways to create them, design their interfaces,declare and check their version numbers, and refactor existingcode into them This chapter also discusses the many existingmodules that are freely available as part of the Perl standardlibrary and on CPAN

Chapter 18, Testing and Debugging, encourages the use of

testing, advocating test-driven design and development usingthe core Test:: modules It also offers tips on effective

debugging techniques, including a description of various

modules and other free tools that can make debugging easier

Chapter 19, Miscellanea, offers several additional guidelines onmiscellaneous topics such as revision control, interfacing to

code written in other languages, processing configuration files,text formatting, tied variables, benchmarking and profiling yourcode, caching techniques, and some general advice on

refactoring

Appendix A, Essential Perl Best Practices, summarizes the 30most important guidelines in the book in three one-page lists

Appendix B, Perl Best Practices, lists all 256 guidelines, withcross-references to their chapters and locations Appendix C,Editor Configurations, provides some useful configuration

options for the Vim, Vile, Emacs, TextWrangler, and BBEdit texteditors Appendix D, Recommended Modules and Utilities, listsand cross-references the various modules recommended

throughout the book, and provides a brief summary of theirmost useful subroutines Appendix E offers a short bibliography

Trang 21

The following typographical conventions are used in the text ofthis book:

Italic

Indicates emphasis, new terms, URLs, email addresses,filenames, paths, and Unix utilities

Constant-width regular

Indicates commands, variables, attributes, functions,

classes, namespaces, methods, modules, values, the

contents of files, the output from commands, and codeexamples that break recommended practices

Constant-width bold

Indicates commands and other text that should be typedliterally by the user, and code examples that demonstraterecommended practices

Constant-width italic

Indicates text that should be replaced with user-suppliedvalues and comments within code examples

Trang 22

This book is intended to help you get your job done In general,you may use the code in this book in your programs and

documentation You do not need to contact O'Reilly for

permission unless you're reproducing a significant portion of thecode For example, writing a program that uses several chunks

of code from this book does not require permission Selling ordistributing a CD-ROM of examples from O'Reilly books doesrequire permission Answering a question by citing this bookand quoting example code does not require permission

Incorporating a significant amount of example code from thisbook into your product's documentation does require

specific request to permissions@oreilly.com

Trang 23

Please address comments and questions concerning this book tothe publisher:

http://www.oreilly.com/catalog/perlbp

To comment or ask technical questions about this book, sendemail to:

bookquestions@oreilly.com

For more information about books, conferences, Resource

Centers, and the O'Reilly Network, see:

http://www.oreilly.com

Trang 24

Every book is the work of a multitude In writing this one, I

have benefitted from the help, advice, and support of many ofthe most talented people in the Perl community I would like toexpress my deepest gratitude:

To Linda Mui, my first editor, for her seemingly limitless

patience and continuing faith, which gave me the freedom toeventually find my true subject

To Nat Torkington, my second editor, for refiring my enthusiasmfor writing, and for his extraordinary encouragement, support,and mateship over the past decade

To Allison Randal and Tatiana Apandi, my third editors, for theirgrace, composure, understanding, good advice, quiet efficiency,and very practical assistance

To Sean M Burke, for his careful technical analysis, invaluablegrammatical advice, salient questions, and for an especiallybrilliant footnote that I sorely wish I could have used

To Nancy Kotary, for gently improving my writing with her

superb copy-editing

To Larry Wall, for his friendship and wisdom over the past fiveyears, and for teaching me so much in that time, not the least

of all: humility

To Abigail, for bringing a no-nonsense approach to Perl codingand for invaluable advice on many topicsin particular, regularexpressions and inside-out objects

To Nate Bailey, for his unfailing support over the past few years,for helping me craft sentences that make sense the first time,and for his expert second-hand knowledge of sociopathy

Trang 25

realities of developing in large team environments, and for

considerably more good suggestions than I was able to use in asingle book

To Chris Devers, for consistently better wordings throughout thebook, and for saving me from writing an entire extra chapter,when a paragraph turned out to be enough

To Richard Dice, for marshalling compelling economic

arguments to keep the review process on track, and for finding

me the perfect business-like operands

To Stephen Edmonds, for unearthing three very subtle codingerrors that would otherwise have passed most annoyingly intoprint

To Paul Fenwick, for the much-needed teacher's perspective hebrought to the presentation of these ideas, and for duly

withholding biscuits when I broke my own guidelines

To Garrett Goebel, for his extraordinary attention to detail andhis remarkable ability to extrapolate from those particulars toexcellent general advice

To Mick Goulish, for enthusiastic encouragement, sound

skeptical advice when I was under pressure, and some of thebest laughs I've ever had, right when I most needed them

To Uri Guttman, for seeing things no-one else did, in ways thatno-one else could

To Trey Harris, for so ably representing the expert programmerand thereby inspiring me to find better ways, instead of justeasy ways

To Brand Hilton, for unsurpassed typo correction, his uncannyability to spot bugs in code samples, and his valiant defence of

"unless"

Trang 26

developers

To Andy Lester, for inspiring me with his deep understanding of,and passion for, the best coding practices

To Greg London, for his insights into the needs of real

programmers, and for telling me honestly when the humourdidn't work

To Tim Maher, for his friendship and support over many years,and for occasionally being the essential voice of dissent

To Bill Odom, for sharing so much of his wisdom and

experience, and graciously allowing me to steal so many of hisbest ideas

To Jacinta Richardson, for her many excellent suggestions, bothgrammatical and syntactical, and for her uncompromising

opposition to lazy writing

To Bill Ricker, for his invaluable documenting of guidelines,

modules, and versions; his eagle eye for corporate-unfriendlysuggestions; and his extraordinary knowledge of computingtheory, practice, and history

To Randal Schwartz, for finding the time to offer feedback on

my book despite the heavy demands of concurrently revisingtwo of his own

To Peter Scott, for sharing his unparalleled experience,

knowledge, and wisdom, and for his and Grace's kindness andsupport in times of sorrow

To Mike Stok, for his unique perspective on Perl programming,and the many insightful suggestions that flowed from it

To Tony Stubblebine, for not being afraid to criticize when

Trang 27

To Andrew Sundstrom, for the unique way he blends the

warrior, the philosopher, and the poet in all aspects of his life,including his programming

To Bennett Todd, whose encouragement and advice I have nowrelied upon across five years and two books

To Merijn Broeren, Dave Cross, and Tom Christiansen for theirgenerous offers to help with this book

To Dave Rolsky, Brian Ingerson, and Eric J Roode, for being soopen to my impertinent suggestions for improving their alreadyexcellent modules

To my fellow Perl Monks: Joe Hourcle, for his detailed and

timely help with BBEdit and TextWrangler; John McNamara, JimMahoney, Scott Lanning, and Michael Joyce, to whom belongsall credit for the Emacs advice herein; and all the other

And above all, to my beloved Linda, who is the wellspring of all

my inspiration, and the reason for everything I do

Trang 28

unique coding style Programmers' styles are based on theirearliest experiences in programmingthe linguistic idiosyncrasies

of their first languages, the way in which code was presented intheir initial textbooks, and the stylistic prejudices of their earlyinstructors That style will develop and change as the

programmer's experience and skills increase Indeed, most

programmers' style is really just a collection of coding habitsthat have evolved in response to the opportunities and

pressures they have experienced throughout their careers

Just as in natural evolution, those opportunities and pressuresmay lead to a coding style that is fit, strong, and well-adapted

Trang 29

Syndrome

Many programmers code by instinct They aren't conscious ofthe hundreds of choices they make every time they code: howthey format their source, the names they use for variables, thekinds of loops they use (while vs for vs map), whether to put thatextra semicolon at the end of the block, whether to grep with aregex or a block, where and when to put comments, whether touse an object-oriented or procedural approach, how to explaintheir programs in their documentation, whether to return undef

or throw an exception on failure, how to decompose the

different components of a system into subroutines, how to

bundle those subroutines into modules, how to interact with theprogram's user

Developers are usually focused entirely on the problems they'resolving, the solutions they're creating, and the algorithms

they're implementing So when it comes to choosing a variablename, they use the first one that comes to mind[*]; when it

comes to using a loop they use the one they always use[ ]; andwhen it comes to that trailing semicolon, well, sometimes they

do and sometimes they don't Just as the spirit moves them

[*] Often whatever is short, vaguely relevant, and easy to spell: $value , @data , $next , %tmp , $obj , $key ,

@nums , %opt , $arg , $foo , $in , %to , $fh , $x , $y , @q , and so on.

[ ] The three-part C-style for loop: "It's so flexible! What more do you need?"

In The Importance of Being Earnest, Oscar Wilde captures the

nature of the Intuitive Programmer perfectly:

Trang 30

Good afternoon, dear Algernon, I hope you are behaving very well.

Unfortunately, if you're earnest about your profession, comfortisn't enough "Behaving very well" may seem stuffy and

conventional and uncreative and completely at odds with thewhole outlaw hacker ethos, but it has one important advantage:

it works Good social manners help societies run smoothly;

good programming manners help programsand programmingteamsdo the same

Rules, conventions, standards, and practices help programmerscommunicate and coordinate with one another They provide auniform and predictable framework for thinking about problems,

Trang 31

especially critical in Perl, where the language itself is

deliberately designed to offer many ways to accomplish thesame task, and consequently supports many incompatible

dialects in which to express any solution

The goal of this book is to help you to develop a consciousprogramming style: to train yourselfand your teamto do thingsconsistently in a way you've decided is correct, rather than inwhatever way feels good at the time Or, if you prefer yourmetaphors more Eastern than Edwardian: to help you movebeyond the illusion of the sensual programming life, and

become stylistically enlightened

Trang 32

A good coding style is one that reduces the costs of your

software project There are three main ways in which a codingstyle can do that: by producing applications that are more

robust, by supporting implementations that are more efficient,and by creating source code that is easier to maintain

1.1.1 Robustness

When deciding how you will write code, choose a style that islikely to reduce the number of bugs in your programs There areseveral ways that your coding style can do that:

A coding style can minimize the chance of introducing errors

in the first place For example, appending _ref to the name

of every variable that stores a reference (see Chapter 3)makes it harder to accidentally write $array_ref[$n] instead of

$array_ref->[$n], because anything except an arrow after _ref

will soon come to look wrong

A coding style can make it easy to detect incorrect edgecases, where bugs often hide For example, constructing aregular expression from a table (see Chapter 12) can

prevent that regex from ever matching a value that the

table doesn't cover, or from failing to match a value that itdoes

A coding style can help you avoid constructs that don't scalewell For example, avoiding a cascaded if-elsif-elsif-

elsif- in favour of table look-ups (see Chapter 6) can

ensure that the cost of any selection statement stays nearlyconstant, rather than growing linearly with the number of

Trang 33

A coding style can improve how code handles failure Forexample, mandating a standard interface for I/O prompting(see Chapter 10) can encourage developers to habituallyverify terminal input, rather than simply assuming it willalways be correct

A coding style can improve how code reports failure Forexample, a rule that every failure must throw an exception,rather than returning an undef (see Chapter 13), will ensurethat errors cannot be quietly ignored or accidentally

propagated into unrelated code

A coding style can improve the structure of code For

pasting (see Chapter 17) can force developers to abstractprogram components into subroutines and then aggregatethose subroutines into modules

example, a prohibition against reusing code via cutting-and-1.1.2 Efficiency

Of course, it doesn't matter how bug-free or error-tolerant yourcode is if it takes a week to predict tomorrow's weather, an hour

to execute someone's stock trade, or even just one full second

to deploy the airbags Correctness is vital, but so is efficiency.

Efficient code doesn't have to be fragile, complex, or hard tomaintain Coding for efficiency is often simply a matter of

working with Perl's strengths and avoiding its weaknesses Forexample, reading an entire file of text (possibly gigabytes of it)into a variable just to change each occurrence of 'C#' to 'D-flat'

is vastly slower than reading and changing the data line-by-line(see Chapter 10) On the other hand, when you do need to read

an entire file into your program, then doing so line-by-line

Trang 34

Efficiency can be a particularly thorny goal, though Changes inPerl's implementation from version to version, and platform-specific differences within the same version, can change therelative efficiency of particular constructs So whenever you'rechoosing between two possible solutions on the basis of

efficiency, it's critical to benchmark each candidate on the

actual platform on which you'll be deploying code, using realdata (see Chapter 19)

1.1.3 Maintainability

You will typically spend at least four times longer maintainingcode than you spent writing it[*] So it makes sense to optimizeyour programming style for readability, not writability Betteryet, try to optimize for comprehensibility: easy-to-read and

a profound way It's easy to "see" problems directly and locatebugs quickly, sometimes without even quite knowing how you

knew You truly grok the source.

Six months later, the code might just as well have been written

by someone else[ ] You've moved on from it, forgotten the

clever intricacies of the design, lost the implicit understanding

Trang 35

And to do that, you need to preserve as much of your mentalmodel of the code as you can, in some medium more

permanent and reliable than mere neurons You need to encodeyour understanding in your documentation and, if possible, inthe source itself

Having a consistent and coherent approach to coding can help.Consistent coding habits allow you to carry part of your mentalmodel through every project, and to stay at least partially in thesame mindset every time you write code Having an entire teamwith consistent coding habits extends those benefits much

further, making it easier for someone else to reconstruct yourintentions and your understanding, because your code looksand works the same as theirs

Trang 36

To help you develop that consistent and coherent approach, thefollowing 18 chapters explore a coordinated set of coding

practices that have been specifically designed to enhance therobustness, efficiency, and maintainability of Perl code

Each piece of advice is framed as a single imperative sentencea

"Thou shalt " or a "Thou shalt not ", presented like this:

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows

where you live.

Each such admonition is followed by a detailed explanation ofthe rule, explaining how and when it applies Every

recommendation also includes a summary of the reasoningbehind the prescription or proscription, usually in terms of how

it can improve the reliability, performance, or comprehensibility

of your code

Almost every guideline also includes at least one example ofcode that conforms to the rule (set in constant-width bold) as well

as counterexamples that break it (set in constant-width regular).These code fragments aim to demonstrate the advantages offollowing the suggested practice, and the problems that canoccur if you don't All of these examples are also available foryou to download and reuse from

http://www.oreilly.com/catalog/perlbp

The guidelines are organized by topic, not by significance Forexample, some readers will wonder why use strict and use

warnings aren't mentioned on page 1 But if you've already seen

the light on those two, they don't need to be on page 1 And if

you haven't seen the light yet, Chapter 18 is soon enough By

Trang 37

these two ways in which Perl can help your code go right

Other readers may object to "trivial" code layout

recommendations appearing so early in the book But if you'veever had to write code as part of a group, you'll know that

layout is where most of the arguments start Code layout is themedium in which all other coding practices are practised, so the

sooner everyone can admit that code layout is trivial, set aside

their "religious" convictions, and agree on a coherent codingstyle, the sooner your team can start getting useful work done

As you consider these pieces of advice, think about each of

them in the context of the type of coding you typically do

Question your current practice in the particular area being

discussed, and compare it against the recommended approach.Evaluate the robustness, efficiency, and maintainability of yourcurrent coding habits and consider whether a change is

justified

But remember that each of piece of advice is a guideline: a

fellow programmer gladly telling you what his programmingstyle is, and where he thinks other styles are unclear or makehim jump through mental hoops Whether or not you agree withall of them doesn't matter What matters is that you becomeaware of the coding issues these guidelines address, think

through the arguments made in their favour, assess the benefitsand costs of changing your current practices, and then

consciously decide whether to adopt the solutions offered here

Then consider whether they will work for everyone else on yourproject as well Coding is (usually) a collaborative effort;

developing and adopting a team coding style is too Mainly

because a team coding standard will stay adopted only if every

member of your team is willing to sign off on it, support it, use

it, and encourage other team members to follow it as well

Trang 38

a style that suits you all Perhaps everyone will eventually agreethatalthough their personal style is self-evidently superior toanything else imaginablethey are nevertheless graciously willing

to abide by the style suggested here as a reasonable

compromise Or perhaps someone will point out that particularrecommendations just aren't appropriate for your

circumstances, and suggest something that would work better

Be careful, though It's amazing how many arguments aboutcoding practice are actually just rationalizations: carefully

robustness, and efficiency of your code Be wary of any

argumenteither for or against changethat doesn't directly

address at least one of those issues

Trang 40

Openingcurly-Return-Tab, and g-r-e-p-Space-Openingcurly-

Soon enough you'll find yourself typing Closingparen-Space-Space, and Closingslash-x-m-s, all without even thinking about

it At which point, having reprogrammed your intuitions

correctly, you will once again be able to program "correctly" byintuition

Ngày đăng: 19/04/2019, 10:41

TỪ KHÓA LIÊN QUAN