A thought experiment: can we have C++ programs without source files (that it, without .cpp files)?
The typical C++ program consists of header files (.h) and source files (.cpp). The header files provide definitions for classes, and the source files provide the definition of the implementations.
Yet the C++ language allows one to define function implementation in the header files. We typically see this only for short functions. To wit:
random_file.h
class random_class
{
private:
int foo_;
public:
random_class( int foo ) : foo_(foo);
int foo( void ) { return foo_ };
}
This code defines a small class that contains a single value and has no methods. The sole member variable is initialized in the constructor.
Here's my idea: Using the concepts of functional programming (namely immutable variables that are initialized in the constructor), one can define a class as a constructor and a bunch of read-only accessors.
If we keep class size to a minimum, we can define all classes in header files. The constructors are simple, and the accessor functions simply return calculated values. There is no need for long methods.
(Yes, we could define long functions in headers, but that seems to be cheating. We allow short functions in headers and exile long functions into .cpp files.)
Such a design is, I think, possible, although perhaps impractical. It may be similar to the chemists' "perfect gas", an abstraction that is nice to conceive but unseen in the real world.
Yet a "perfect gas" of a class (perhaps a "perfect class") may be possible for some classes in a program. Those perfect classes would be small, with few member variables and only accessor functions. Its values would be immutable. The member variables may be objects of smaller classes (perhaps perfect classes) with immutable values of their own.
This may be a way to improve code quality. My experience shows that immutable objects are much easier to code, to use, and to debug. If we build simple immutable classes, then we can code them in header files and we can discard the source files.
Coding without source files -- no there is an idea for the future.
Sunday, April 28, 2013
C++ without source (cpp) files
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment