Tải bản đầy đủ - 0 (trang)
Chapter 17.  Avoid magic numbers

Chapter 17.  Avoid magic numbers

Tải bản đầy đủ - 0trang

Summary

Programmingisn'tmagic,sodon'tincantit:Avoidspelling

literalconstantslike42or3.14159incode.Theyarenotselfexplanatoryandcomplicatemaintenancebyaddingahard-todetectformofduplication.Usesymbolicnamesandexpressions

instead,suchaswidth*aspectRatio.



Discussion

Namesaddinformationandintroduceasinglepointof

maintenance;rawnumbersduplicatedthroughoutaprogram

areanonymousandamaintenancehassle.Constantsshouldbe

enumeratorsorconstvalues,scopedandnamedappropriately.

One42maynotbethesameasanother42.Worse,"in-head"

computationsmadebytheprogrammer(e.g.,"this84comes

fromdoublingthe42usedfivelinesago")makeittediousand

error-pronetolaterreplace42withanotherconstant.

Preferreplacinghardcodedstringswithsymbolicconstants.

Keepingstringsseparatefromthecode(e.g.,inadedicated

.cpporresourcefile)letsnon-programmersreviewandupdate

them,reducesduplication,andhelpsinternationalization.



Examples

Example1:Importantdomain-specificconstantsatnamespace

level.

constsize_tPAGE_SIZE=8192,

WORDS_PER_PAGE=PAGE_SIZE/sizeof(int),

INFO_BITS_PER_PAGE=32*CHAR_BIT;



Example2:Class-specificconstants.Youcandefinestatic

integralconstantsintheclassdefinition;constantsofother

typesneedaseparatedefinitionorashortfunction.



//Filewidget.h

classWidget{

staticconstintdefaultWidth=400;//valueprovided

staticconstdoubledefaultPercent;//valueprovided

staticconstchar*Name(){return"Widget";}

};



//Filewidget.cpp

constdoubleWidget::defaultPercent=66.67;//valueprovided

constintWidget::defaultWidth;//definitionrequ



References

[Dewhurst03]Đ2[Kernighan99]Đ1.5[Stroustrup00]Đ4.8,

Đ5.4



18.Declarevariablesaslocallyas

possible

Summary

Discussion

Exceptions

References



Summary

Avoidscopebloat,aswithrequirementssotoowithvariables):

Variablesintroducestate,andyoushouldhavetodealwithas

littlestateaspossible,withlifetimesasshortaspossible.This

isaspecificcaseofItem10thatdeservesitsowntreatment.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 17.  Avoid magic numbers

Tải bản đầy đủ ngay(0 tr)

×