How can I simplify this code?

Started by EnterTheStory (aka tolworthy), Thu 16/04/2009 12:05:20

Previous topic - Next topic

EnterTheStory (aka tolworthy)

My pointer skills are very rusty, so I'm appealing to all you programming jocks out there. This code requires me to write the same variable name twice on each line. I'm sure this must be bad practice. Is there any way to re-write it ina simpler form? Thanks!

Code: ags

function readWriteBetweenGames(bool read) //
{	File	*f;	
	if(read) { f = File.Open("between games.dat", eFileRead);	if (f==null) return 999;}
	else	 { f = File.Open("between games.dat", eFileWrite);if (f==null) return 999;}	
	// rc people
	if(read){if(f.EOF)return 1; rightClickedPerson = f.ReadStringBack();} else f.WriteString(rightClickedPerson);	
	if(read){if(f.EOF)return 1; rcPersonX 			 	 = f.ReadInt();			  } else f.WriteInt(rcPersonX);	
	if(read){if(f.EOF)return 1; rcPersonRoom	  	 = f.ReadInt();			  } else f.WriteInt(rcPersonRoom);	
	if(read){if(f.EOF)return 1; rcPersonGame		   = f.ReadInt();			  } else f.WriteInt(rcPersonGame);	
	// memory objects
	int n =1; while(n <=10)
	{	if(read){if(f.EOF)return 1; memoryWhat[n] 	 = f.ReadStringBack();} else f.WriteString(memoryWhat[n]);	
		if(read){if(f.EOF)return 1; memoryWhatWho[n] = f.ReadInt();			  } else f.WriteInt(memoryWhatWho[n]);	
		if(read){if(f.EOF)return 1; memoryWhatGame[n]= f.ReadInt();			  } else f.WriteInt(memoryWhatGame[n]);	
		if(read){if(f.EOF)return 1; memoryWhatRoom[n]= f.ReadInt();			  } else f.WriteInt(memoryWhatRoom[n]);	
		n++;
	}	if(read){if(f.EOF)return 1; memoryWhatNow		 = f.ReadInt();			  } else f.WriteInt(memoryWhatNow);	
	f.Close();
}


Thanks in advance. (PS the actual function is a lot longer)

Khris

The only way to shorten this I can think of is to separate reading and writing:

Code: ags
function readWriteBetweenGames(bool read) // {
  File*f;
  if (read) { f = File.Open("between games.dat", eFileRead);	if (f==null) return 999;}
  else { f = File.Open("between games.dat", eFileWrite);if (f==null) return 999;}	

  // rc people
  if (read) {
    if (!f.EOF) rightClickedPerson = f.ReadStringBack();
    if (!f.EOF) rcPersonX = f.ReadInt();
    if (!f.EOF) rcPersonRoom = f.ReadInt();
    if (!f.EOF) rcPersonGame = f.ReadInt();
  }
  else {
    f.WriteString(rightClickedPerson);	
    f.WriteInt(rcPersonX);	
    f.WriteInt(rcPersonRoom);	
    f.WriteInt(rcPersonGame);
  }
}


Also, all the EOF checks shouldn't really be necessary?

There's another method to save the data:
Load/Read all ints into/from an int array and all strings into/from a string array, save/load the arrays using a while loop.
You'll still have to write all var names twice though.

EnterTheStory (aka tolworthy)

Thanks. There's no way to avoid duplicate names then? Fair enough. My original method was to have separate input and output functions, but found that keeping each item on the same line means I make fewer errors.

SMF spam blocked by CleanTalk