Hard to Get

--人生在世 难得二字

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

PL/SQL Best Practices [8][Data Structures]-Avoid Hardcoding Literals

Avoid all forms of “magic values” in your applications, such as:
    *  Maximum number of accounts allowed.
The codes used for “closed”, opened”, etc.

MoreThis package below collects together a set of configuration constants which apply to a session. The CONSTANT declaration makes certain that these values cannot be changed. Names are given to “magic values” so that developers can avoid hard-coding these kinds of literals in their programs.

 1PACKAGE config 
 2IS
 3   closed_status   CONSTANT CHAR(1) := 'C';
 4   open_status     CONSTANT CHAR(1) := 'O';
 5   active_status   CONSTANT CHAR(1) := 'A';
 6   inactive_status CONSTANT CHAR(1) := 'I';
 7   min_diff CONSTANT NUMBER := 1;
 8   max_diff CONSTANT NUMBER := 100;
 9   earliest_date CONSTANT DATE := SYSDATE;
10   latest_date CONSTANT DATE 
11      := ADD_MONTHS (SYSDATE, 120); 
12END config;

Example
Using explicit literals:

1IF footing_difference BETWEEN 1 and 100
2THEN 
3   adjust_line_item;
4END IF;
5IF cust_status = 'C' 
6THEN 
7   reopen_customer; 
8END IF;

Using the package constants, the code is more readable and much more maintainable:

 1IF footing_difference BETWEEN 
 2      config.min_diff AND config.max_diff
 3THEN 
 4   adjust_line_item;
 5END IF;
 6IF cust_status = config.closed_status 
 7THEN 
 8   reopen_customer; 
 9END IF;

Replace literal values (outside of 1, that is) with a named constant, preferably within a package.
Other forms of hard-coding in PL/SQL:

    *  Declaring a variable as VARCHAR2 even if it represents a database value.
    *  Implicit cursors (embedding SQL statements directly in your code).
    *  Explicit cursors which do not use parameters.
    *  Dispersion of redundant code.

posted on 2005-09-12 22:31  Del  阅读(157)  评论(0)    收藏  举报