How can we code a program such that we will never get a MAPFAIL error?
Short answer: there is no way to code a program to avoid a possible MAPFAIL. From the CICS
Application Programming Reference manual on the RECEIVE MAP command (emphasis added):
MAPFAIL
occurs if the data to be mapped has a length of zero or does not contain a set-buffer-address (SBA) sequence. It applies only to 3270 devices. The receiving data area contains the unmapped input data stream. The amount of unmapped data moved to the user's area is limited to the length specified in the LENGTH option. The input map is not set to nulls. This condition also arises if a program issues a RECEIVE MAP command to which the terminal operator responds by pressing a CLEAR or PA key, or by pressing ENTER or a PF key without entering data. Default action: terminate the task abnormally.
So if you can educate your terminal users to NEVER use a CLEAR key, or PA key, or hit the enter key by accident before entering data -- then you could prevent a MAPFAIL. Barring that, however, you program MUST be able to handle the condition.