Troubleshooting of Sonar issue: Difference between revisions

Jump to navigation Jump to search
+ How to resolve "Define a constant instead of duplicating this literal"
mNo edit summary
(+ How to resolve "Define a constant instead of duplicating this literal")
Line 55: Line 55:
* Grant the execution permission {{kbd | key=chmod +x add_newline_to_php_files.sh}}
* Grant the execution permission {{kbd | key=chmod +x add_newline_to_php_files.sh}}
* Usage {{kbd | key=<nowiki>./add_newline_to_php_files.sh /path/to/php/directory_of_scripts</nowiki>}}
* Usage {{kbd | key=<nowiki>./add_newline_to_php_files.sh /path/to/php/directory_of_scripts</nowiki>}}
=== How to resolve "Define a constant instead of duplicating this literal" ===
Error condition which met "Define a constant instead of duplicating this literal" - violates DRY (Don't Repeat Yourself) principle and creates maintenance issues <ref>[Clean Code principles - Avoid Magic Numbers/Strings]</ref>
Original problematic code:
<pre>
def parse_date(row):
    if isinstance(row['time_field'], pd.Timestamp):
        formatted_date = row['time_field'].strftime("%Y-%m")
    elif isinstance(row['time_field'], str):
        date_obj = datetime.strptime(row['time_field'], "%Y-%m-%d %H:%M:%S")
        formatted_date = date_obj.strftime("%Y-%m")
    elif isinstance(row['time_field'], datetime):
        formatted_date = row['time_field'].strftime("%Y-%m")
</pre>
Possible solution:
<pre>
# Date format constants
DATE_FORMAT_YEAR_MONTH = "%Y-%m"
def parse_date(row):
    if isinstance(row['time_field'], pd.Timestamp):
        formatted_date = row['time_field'].strftime(DATE_FORMAT_YEAR_MONTH)
    elif isinstance(row['time_field'], str):
        date_obj = datetime.strptime(row['time_field'], "%Y-%m-%d %H:%M:%S")
        formatted_date = date_obj.strftime(DATE_FORMAT_YEAR_MONTH)
    elif isinstance(row['time_field'], datetime):
        formatted_date = row['time_field'].strftime(DATE_FORMAT_YEAR_MONTH)
</pre>
Benefits:
# Maintainability: Format strings can be updated in one central location
# Consistency: All date formatting uses the same format definitions
# Error Prevention: Reduces risk of typos in repeated string literals


=== How to resolve "Define and throw a dedicated exception instead of using a generic one" ===
=== How to resolve "Define and throw a dedicated exception instead of using a generic one" ===

Navigation menu