Do not program "defensively"

September 25th, 2007

(From Erlang Programming Rules )

A defensive program is one where the programmer does not “trust” the input data to the part of the system they are programming. In general one should not test input data to functions for correctness. Most of the code in the system should be written with the assumption that the input data to the function in question is correct. Only a small part of the code should actually perform any checking of the data. This is usually done when data “enters” the system for the first time, once data has been checked as it enters the system it should thereafter be assumed correct.

Example:

%% Args: Option is all|normal
get_server_usage_info(Option, AsciiPid) ->
  Pid = list_to_pid(AsciiPid),
  case Option of
    all -> get_all_info(Pid);
    normal -> get_normal_info(Pid)
  end.
The function will crash if Option neither normal nor all, and it should do that. The caller is responsible for supplying correct input.

1 Response to “Do not program "defensively"”

  1. yuchifang Says:
    这只是一个程序或者说一个模块内部吧,API或者模块接口就不好这么干了。

Leave a Reply