comp.lang.ada
 help / color / mirror / Atom feed
From: "Norman H. Cohen" <ncohen@watson.ibm.com>
Subject: Re: Global Varibles!!
Date: 1997/02/21
Date: 1997-02-21T00:00:00+00:00	[thread overview]
Message-ID: <330DD315.6562@watson.ibm.com> (raw)
In-Reply-To: mheaney-ya023680002002970056270001@news.ni.net


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




  reply	other threads:[~1997-02-21  0:00 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
1997-02-19  0:00 Global Varibles!! Richard Pearce
1997-02-20  0:00 ` Matthew Heaney
1997-02-21  0:00   ` Norman H. Cohen [this message]
1997-02-23  0:00     ` Robert Dewar
1997-02-25  0:00       ` Norman H. Cohen
1997-02-25  0:00         ` Robert Dewar
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox