Tải bản đầy đủ - 0 (trang)
Chapter 41.  Make data members private, except in behaviorless aggregates (C-style structs)

Chapter 41.  Make data members private, except in behaviorless aggregates (C-style structs)

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

Summary

They'renoneofyourcaller'sbusiness:Keepdatamembers

private.OnlyinthecaseofsimpleC-stylestructtypesthat

aggregateabunchofvaluesbutdon'tpretendtoencapsulateor

providebehavior,makealldatamemberspublic.Avoidmixesof

publicandnonpublicdata,whichalmostalwayssignala

muddleddesign.



Discussion

Informationhidingiskeytogoodsoftwareengineering(see

Item11).Prefermakingalldatamembersprivate;privatedata

isthebestmeansthataclasscanusetopreserveitsinvariants

now,andtokeeppreservingtheminthefaceoffuturechanges.

Publicdataisbadifaclassmodelsanabstractionandmust

thereforemaintaininvariants.Havingpublicdatameansthat

partofyourclass'sstatecanvaryuncontrollably,unpredictably,

andasynchronouslywiththerestofitsstate.Itmeansthatan

abstractionissharingresponsibilityformaintainingoneormore

invariantswiththeunboundedsetofallcodethatusesthe

abstraction,andthatisobviously,fundamentally,and

indefensiblyflawed.Rejectsuchdesignsoutright.

Protecteddatahasallthedrawbacksofpublicdata,because

havingprotecteddatastillmeansthatanabstractionissharing

theresponsibilityofmaintainingsomeinvariantwithan

unboundedsetofcodeinthiscase,withtheunboundedsetof

currentandfuturederivedclasses.Further,anycodecanread

andmodifyprotecteddataaseasilyaspublicdatabyderivinga

newclassandusingthattogetatthedata.

Mixingpublicandnonpublicdatamembersinthesameclassis

confusingandinconsistent.Privatedatademonstratesthatyou

haveinvariantsandsomeintenttopreservethem;mixingit

withpublicdatameansafailuretodecideclearlywhetherthe

classreallyissupposedtobeanabstractionornot.

Nonprivatedatamembersarealmostalwaysinferiortoeven

simplepassthroughget/setfunctions,whichallowforrobust

versioning.

Considerhidingaclass'sprivatemembersusingthePimpl

idiom.(SeeItem43)



Examples

Example1:Properencapsulation.Mostclasses(e.g.,Matrix,

File,Date,BankAccount,Security)shouldhaveallprivate

datamembersandexposeadequateinterfaces.Allowingcalling

codetomanipulatetheirinternalsdirectlywoulddirectlywork

againsttheabstractiontheyprovideandtheinvariantsthey

mustsustain.

ANodeaggregate,ascommonlyusedintheimplementationof

aListclass,typicallycontainssomedataandtwopointersto

Node:next_andprev_.Node'smembersdon'tneedtobe

hiddenfromList.ButnowconsiderExample3.

Example2:treeNode.ConsideraTReecontainer

implementedintermsoftreeNode,anaggregateused

withinTReethatholdsprevious//pointersandaTobject

payload.treeNode'smemberscanallbepublicbecausethey

don'tneedtobehiddenfromTRee,whichdirectlymanipulates

them.ButtreeshouldhidetreeNodealtogether(e.g.,asa

privatenestedclass,ordefinedonlyintree'simplementation

file),becauseitisaninternaldetailoftreethatcallers

shouldn'tdependonormanipulate.Finally,TReedoesnothide

thecontainedTobjects,becausethepayloadisthecaller's

responsibility;containersusetheiteratorabstractiontoexpose

thecontainedobjectswhilehidinginternalstructures.

Example3:Gettersandsetters.Ifthereisnobetterdomain

abstractionavailable,publicandprotecteddatamembers(e.g.,

color)canatleastbemadeprivateandhiddenbehindgetand

setfunctions(e.g.,GetColor,SetColor);theseprovidea

minimalabstractionandrobustversioning.

Usingfunctionsraisesthelevelofdiscourseabout"color"from

thatofaconcretestatetothatofanabstractstatethatweare



freetoimplementaswewant:Wecanchangetoaninternal

colorencodingotherthanint,addcodetoupdatethedisplay

whenchangingcolor,addinstrumentation,andmakemany

otherchangeswithoutbreakingcallingcode.Atworst,callers

justrecompile(i.e.,wepreservesource-levelcompatibility);at

best,theydon'thavetorecompileorrelinkatall(ifthechange

alsopreservesbinarycompatibility).Neithersourcenorbinary

compatibilityispossibleforsuchchangesifthestartingdesign

hasapubliccolormembervariabletowhichcallingcode

becomestightlycoupled.



Exceptions

Get/setfunctionsareuseful,butaclassconsistingmostlyof

gets/setsisprobablypoorlydesigned:Decidewhetheritwants

toprovideanabstractionorbeastruct.

Valueaggregates(alsocalled"C-stylestructs")simplykeepa

bunchofdatatogetherbutdonotactuallyaddsignificant

behaviororattempttomodelanabstractionandenforce

invariants;theyarenotmeanttobeabstractions.Theirdata

membersshouldallbepublicbecausethedatamembersare

theinterface.Forexample,std::pairisusedbythe

standardcontainerstoaggregatetwootherwiseunrelated

elementsoftypeTandU,andpairitselfdoesn'taddbehavior

orinvariants.



References

[Dewhurst03]Đ80[Henricson97]pg.105[Koenig97]Đ4

[Lakos96]Đ2.2[Meyers97]Đ20[Murray93]Đ2.3

[Stroustrup00]Đ10.2.8,Đ15.3.1.1,Đ24.4.2-3[SuttHysl04a]



42.Don'tgiveawayyourinternals

Summary

Discussion

Exceptions

References



Summary

Don'tvolunteertoomuch:Avoidreturninghandlestointernal

datamanagedbyyourclass,soclientswon'tuncontrollably

modifystatethatyourobjectthinksitowns.



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

Chapter 41.  Make data members private, except in behaviorless aggregates (C-style structs)

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

×