Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Current events
Recent changes
Random page
Help
Categories
LemonWiki共筆
Search
Search
Appearance
Log in
Personal tools
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Troubleshooting of SonarQube issue
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Special pages
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== 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 (Python): <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: define the constants <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
Summary:
Please note that all contributions to LemonWiki共筆 are considered to be released under the Creative Commons Attribution-NonCommercial-ShareAlike (see
LemonWiki共筆:Copyrights
for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)