Re: What do you think of these coding strategies?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Ron,

>I have been told that global variables are bad...

Global variables are "bad" for the following reasons:

1. [minor] they pollute the global name space (but so do classes and function names)

2. [major] they can be modified by anything anywhere in the code, and tracking down co-dependent bugs can be a daunting challenge.

In C++...

#1 is addressed by putting what would otherwise be a global variable into a class.

#2 is addressed by encapsulation -- making the variable private, and having operations that can be performed on the data done in member functions. That localizes all manipulation of the data, greatly reduces the amount of code you need to look at for co-dependent bugs, and gives much more assurance of the data being changed from one consistent valid state into another consistent valid state.

For C++, single instance global data would be held in a monostate pattern class object or singleton pattern class object.

In C...

#1 and #2 can be addressed by putting otherwise global data as a static data or static data structure inside a C source (.c) file, and have the manipulators be functions which are declared in a header (.h) file.

For C, the data-hiding paradigm is sometimes done by programmers -- but C does little to encourage and support the practice in the language proper.

So those globals that you mentioned, and asked if it was "bad" to have them as globals -- they're only "bad" for the aforementioned reasons.

For a small program, that's a lot of extra work to protect (encapsulate) the variables and have manipulation routines (mutators and accessors). Your call whether or not to employ those techniques, regardless of C or C++. (I'd use them even for small programs, since small programs tend to grow into medium or large programs.)

For a medium or large size program (C or C++), I strongly encourage you to use the data hiding techniques.

>When I finish my Star-Trek game, is there a place I can post it for critique?

Sourceforge?

Sincerely,
--Eljay


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux