SDSU CS 596 Client-Server Programming
Names, Style, Frameworks

[To Lecture Notes Index]
San Diego State University -- This page last updated May 2, 1996
----------

Contents of Names, Style, Frameworks Lecture

  1. References
  2. Names
    1. Conceptual Level Definition
  3. Comments
    1. Kinds of Comments
    2. Commenting Efficiently
    3. Commenting Techniques
      1. Commenting Individual Lines
      2. Commenting Paragraphs of Code
    4. Commenting Data Declarations
    5. Commenting Routines
  4. Frameworks and Libraries

References


Code Complete, Steve McConnell, Microsoft Press, 1993, chapter 19, chapter 9

Part of these notes follow very closely chapter 19 in Code Complete. Nearly all examples are taken directly from Code Complete. I have used the same headers and main points of the text.

Names


"Finding good names is the hardest part of OO Programming"

"Names should fully and accurately describe the entity the variable represents"

What role does the variable play in the program?
Data StructureRole, function
InputRecEmployeeData
BitFlagPrinterReady

Some Examples of Names, Good and Bad
TrainVelocityVelt, V, X, Train
CurrentDateCD, Current, C, X, Date
LinesPerPageLPP, Lines, L, X

OOP Names - Common Problems
class Stack 
	{
	Vector theStack = new Vector();

	public void push( object x )
		{
		theStack.add( x );
		}

	// code deleted
	}

class DriverProgram 
	{
	public void static main( String[] args )
		{
		// blah blah blah

		Stack stack;

		aFooFunction( stack );

		// more blah
		}

	void aFooFunction( Stack aStack )
		{
		}
	}

Object-Oriented Programming

Conceptual Level Definition

Abstraction

"Extracting the essential details about an item or group of items, while ignoring the unessential details."
Edward Berard


"The process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use."
Richard Gabriel

Example
Pattern: 	Priority queue

Essential Details:	length 
	items in queue 
	operations to add/remove/find item

Variation:	link list vs. array implementation
	stack, queue

Object-Oriented Programming
Conceptual Level DefinitionEncapsulation


Enclosing all parts of an abstraction within a container



Example


Object-Oriented Programming
Conceptual Level DefinitionInformation Hiding


Hiding parts of the abstraction



Example


Object-Oriented Programming
Conceptual Level DefinitionHierarchy

Abstractions arranged in order of rank or level


Class Hierarchy

Object-Oriented Programming
Conceptual Level DefinitionHierarchy


Object Hierarchy


Comments


"Comments are easier to write poorly than well, and comments can be more damaging than helpful"
What does this do?
for i := 1 to Num do
 MeetsCriteria[ i ] := True;
for  i := 1 to Num / 2  do begin
 j := i + i;
 while ( j <= Num ) do begin
  MeetsCriteria[ j ] := False;
  j := j + i;
 end;
for i := 1 to Mun do
 if MeetsCriteria[ i ] then
  writeln( i, ' meets criteria ' );



How many comments does this need?



for PrimeCandidate:= 1 to Num do
	IsPrime[ PrimeCandidate] := True;

for  Factor:= 1 to Num / 2  do begin
	FactorableNumber := Factor + Factor ;
	while ( FactorableNumber <= Num ) do begin
		IsPrime[ FactorableNumber ] := False;
		FactorableNumber := FactorableNumber + Factor ;
	end;
end;

for PrimeCandidate:= 1 to Num do
	if IsPrime[ PrimeCandidate] then
		writeln( PrimeCandidate, ' is Prime ' );



Good Programming Style is the Foundation of Well Commented Program

Kinds of Comments

X := X + 1 	/* add one to X



/* if allocation flag is zero */

if ( AllocFlag == 0 ) ...


Used to explain complicated or tricky code
*p++->*c = a

/* first we need to increase p by one, then ..
Make code simpler before commenting
(*(p++))->*c = a



ObjectPointerPointer++;
ObjectPointer = *ObjectPointerPointer;
ObjectPointer ->*DataMemberPointer = a;
/*  **** Need to add error checking here  **** */




Distills a few lines of code into one or two sentences
Explains the purpose of a section of code
{ get current employee information }   intent


{ update EmpRec structure }     what

Commenting Efficiently

/***********************************
 * module: Print                   *
 *                                 *
 * author: Roger Whitney           *
 * date:   Sept. 10, 1995          *
 *                                 *
 * blah blah blah                  *
 *                                 *
 ***********************************/



/***********************************
  module: Print          
                         
  author: Roger Whitney  
  date:   Sept. 10, 1995 
                         
  blah blah blah         
                         
 ***********************************/



Commenting Techniques


Commenting Individual Lines


Avoid self-indulgent comments
MOV AX,  723h	     ;    R. I. P. L. V. B.



Endline comments have problems

MemToInit := MemoryAvailable(); { get memory available }

Not much room for comment
Must work to format the comment



Use endline comments on
Data declarations
Maintenance notes
Mark ends of blocks

Commenting Paragraphs of Code


Write comments at the level of the code's intent

Comment the why rather than the how

Make every comment count

Document suprises

Avoid abbreviations
How verses Why
How
/* if allocation flag is zero */

if ( AllocFlag == 0 ) ...

Why
/* if allocating a new member */

if ( AllocFlag == 0 ) ...

Even Better
/* if allocating a new member */

if ( AllocFlag == NEW_MEMBER ) ...

Summary comment on How
{ check each character in "InputStr" until a 
  dollar sign is found or all characters have 
  been checked }

Done   := false;
MaxPos := Length( InputStr );
i      := 1;
while ( (not Done) and (i <= MaxLen) ) begin
	if ( InputStr[ i ] = '$' ) then
		Done := True
	else
		i := i + 1
end;




Summary comment on Intent
{ find the command-word terminator }

Done   := false;
MaxPos := Length( InputStr );
i      := 1;

while ( (not Done) and (i <= MaxPos ) ) begin
	if ( InputStr[ i ] = '$' ) then
		Done := True
	else
		i := i + 1
end;


Summary comment on Intent with Better Style
{ find the command-word terminator }

FoundTheEnd      := false;
MaxCommandLength := Length( InputStr );
Index            := 1;

while ((not FoundTheEnd) and 
       (Index <= MaxCommandLength)) begin

	if ( InputStr[ Index ] = '$' ) then
		FoundTheEnd := True;
	else
		Index := Index + 1;
end;

Commenting Data Declarations


Comment the units of numeric data

Comment the range of allowable numeric values

Comment coded meanings
var
	CursorX:		1..MaxCols;	{ horizontal screen position of cursor }
	CursorY:		1..MaxRows;	{ vertical position of cursor on screen }

	AntennaLength:	Real;	{ length of antenna in meters: >= 2 }
	SignalStrength:	Integer;	{ strength of signal in kilowatts: >= 1 }

	CharCode:		0..255;	{ ASCII character code }
	CharAttib:		Integer;	{ 0=Plain; 1=Italic; 2=Bold  }
	CharSize:			4..127;	{ size of character in points }

Comment limitations on input data

Document flags to the bit level


Commenting Routines


Avoid Kitchen-Sink Routine Prologs

Keep comments close to the code they describe

Describe each routine in one or two sentences at the top of the routine

Document input and output variables where they are declared

Differentiate between input and output data

Document interface assumptions

Keep track of the routine's change history

Comment on the routine's limitation

Document the routine's global effects

Document the source of algorithms that are used
procedure InsertionSort 
	{
	Var	Data:		SortArray;    { sort array elements }
		FirstElement:	Integer	     {index of first element to sort}
		LastElement:	Integer	     {index of last element to sort}
	}

Frameworks and Libraries


"A framework is a set of cooperating classes that make up a reusable design for a specific class of software"
Peter Deutsch


Java API
AppletDatagramSocketImageProducerRandomAccessFile
AppletContextDateIndexColorModelRectangle
AppletStubDebuggerCallbackInetAddressRunnable
AudioClipDialogInsetsRuntime
BitSetDictionaryIntegerRuntimeConstants
BooleanDimensionLabelScrollbar
BorderLayoutDirectColorModelLayoutManagerSecurityManager
ButtonDoubleListServerSocket
CanvasEnumerationLocalVariableSocket
CardLayoutEventLongSocketImpl
CharacterFieldMathSocketImplFactory
CheckboxFileMediaTrackerStack
CheckboxGroupFileDescriptorMemoryImageSourceStackFrame
CheckboxMenuItemFileDialogMenuString
ChoiceFilenameFilterMenuBarStringBuffer
ClassFilteredImageSourceMenuComponentStringTokenizer
ClassLoaderFloatMenuContainerSystem
CloneableFlowLayoutMenuItemTextArea
ColorFontNumberTextComponent
ColorModelFontMetricsObjectTextField
CompilerFrameObservableThread
ComponentGraphicsObserverThreadDeath
ConstantsGridBagConstraintsPanelThreadGroup
ContainerGridBagLayoutPixelGrabberThrowable
ContentHandlerGridLayoutPointToolkit
ContentHandlerFactoryHashtablePolygonURL
CropImageFilterImageProcessURLConnection
DataInputImageConsumerPropertiesURLEncoder
DataOutputImageFilterRGBImageFilterVector
DatagramPacketImageObserverRandomWindow
STREAMS
BufferedInputStreamInputStream
BufferedOutputStreamLineNumberInputStream
ByteArrayInputStreamOutputStreamPipedInputStream
ByteArrayOutputStreamPipedOutputStreamPrintStream
DataInputStreamPushbackInputStream
DataOutputStreamSequenceInputStreamStreamTokenizer
FileInputStreamStringBufferInputStream
FileOutputStreamURLStreamHandler
FilterInputStreamURLStreamHandlerFactory
FilterOutputStream

----------