Home
String literals should not be duplicated
Description
The rule "String literals should not be duplicated" states that when writing PL/SQL code, string literals should not be repeated unnecessarily. This means that when a string literal is used multiple times in a code block, it should be assigned to a variable and then the variable should be used instead of the literal. This helps to improve code readability and maintainability, as well as reducing the amount of code that needs to be written.
Key Benefits
- Reduced Memory Usage - String literals should not be duplicated, reducing memory usage.
- Improved Performance - By avoiding duplication, the performance of the application is improved.
- Better Code Readability - By avoiding duplication, the code is easier to read and understand.
Non-compliant Code Example
DECLARE
NO_DATA_FOUND EXCEPTION;
BEGIN
FOR i IN 1 .. CUSTOMER_TABLE.COUNT
LOOP
IF CUSTOMER_TABLE(i) IS NOT NULL THEN
DBMS_OUTPUT.PUT( i || ' = (' || CUSTOMER_TABLE(i).Name || ', ' || CUSTOMER_TABLE(i).PhoneNumber || ')' );
END IF;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
Log_Errors ( 'No data found');
WHEN ERRORS THEN
Log_Errors ( 'Error Log...' || Chr(10) || DBMS_UTILITY.FORMAT_ERROR_STACK() ); Log_Errors ( 'Error Log...' || Chr(10) || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE() ); --Non compliant code (String literals are duplicated)
DBMS_OUTPUT.PUT_LINE ( '----------' );
RAISE;
END CUSTOMER_TABLE_ITERATION;
Compliant Code Example
DECLARE NO_DATA_FOUND EXCEPTION; ERROR_MESSAGE VARCHAR2(20):='Error Log...'; --Compliant code (Added variable with string literals) BEGIN FOR i IN 1 .. CUSTOMER_TABLE.COUNT LOOP IF CUSTOMER_TABLE(i) IS NOT NULL THEN DBMS_OUTPUT.PUT( i || ' = (' || CUSTOMER_TABLE(i).Name || ', ' || CUSTOMER_TABLE(i).PhoneNumber || ')' ); END IF; END LOOP; EXCEPTION WHEN NO_DATA_FOUND THEN Log_Errors ( 'No data found'); WHEN ERRORS THEN Log_Errors ( ERROR_MESSAGE || Chr(10) || DBMS_UTILITY.FORMAT_ERROR_STACK() ); Log_Errors ( ERROR_MESSAGE || Chr(10) || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE() ); --Compliant code (Added string literals variable and used at all locations) DBMS_OUTPUT.PUT_LINE ( '----------' ); RAISE; END CUSTOMER_TABLE_ITERATION;