From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=0.2 required=5.0 tests=BAYES_00,INVALID_MSGID, REPLYTO_WITHOUT_TO_CC autolearn=no autolearn_force=no version=3.4.4 X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: 103376,8d182ecfa9220b7d X-Google-Attributes: gid103376,public From: "Norman H. Cohen" Subject: Re: Global Varibles!! Date: 1997/02/21 Message-ID: <330DD315.6562@watson.ibm.com>#1/1 X-Deja-AN: 220615976 References: <330B6914.22CD@hotmail.com> Content-Type: text/plain; charset=us-ascii Organization: IBM Thomas J. Watson Research Center Mime-Version: 1.0 Reply-To: ncohen@watson.ibm.com Newsgroups: comp.lang.ada X-Mailer: Mozilla 3.0 (Win95; I) Date: 1997-02-21T00:00:00+00:00 List-Id: Matthew Heaney wrote: > If you wish to save the state of a variable across subprogram invokations, > then the variable must be declared in a static scope, which means in a > package spec or body. For example, > > package Global is > > X : Integer; > > end; > > with Global; > procedure Set_X is > begin > Global.X := 1; > end; > > with Global; > procedure Get_X is > begin > ... := Global.X; > end; > > However, using a package to declare global variables shared by subprograms > is a very old style of software architecture. You see it when Fortran > programmers first program in Ada: they have a global mindset. > > Realize that this creates danderous coupling amoung pieces of the system. > If you change Global.X, then how do you know what will break because of the > change? > > Better is to encapsulate the data, and expose its representation to only a > few subprograms. ... In other words, if Set_X and Get_X are the only subprograms that will be using Global.X, enclose the subprogram in a package and hide the variable in the package body: package X_State is procedure Set_X; procedure Get_X; end X_State; package body X_State is X: Integer; procedure Set_X is begin X := 1; end Set_X; procedure Get_X is begin ... end Get_X; end X_State; It's quite reasonable to write a package that provides only a single subprogram, but encapsulates a persistent variable: package Serial_Numbers is procedure Get_Next (Number: out Natural); end Serial_Numbers; package body Serial_Numbers is Next: Natural := 0: procedure Get_Next (Number: out Natural) is begin Number := Next; if Number = Natural'Last then Number := 0; else Number := Number + 1; end if; end Get_Next; end Serial_Numbers; -- Norman H. Cohen mailto:ncohen@watson.ibm.com http://www.research.ibm.com/people/n/ncohen