Introduction
This week I was tasked to refactor the ReadmeGenie. If you just arrived here, ReadmeGenie is my open-source project that uses AI to generate readmes based on the files that the user inputs.
Initially, my thoughts were, "The program is working fine. I’ve been developing it in an organized way since day one... so why change it?"
Well, after taking a week-long break from the project, I opened it up again and immediately thought, "What is this?"
Why refactor?
To give you some context, here’s an example: One of my core functions, which I once thought was perfect, turned out to be much more complex than necessary. During the refactoring process, I broke it down into five separate functions—and guess what? The code is much cleaner and easier to manage now.
Take a look at the original version of this function:
def generate_readme(file_paths, api_key, base_url, output_filename, token_usage): try: load_dotenv() # Check if the api_key was provided either as an environment variable or as an argument if not api_key and not get_env(): logger.error(f"{Fore.RED}API key is required but not provided. Exiting.{Style.RESET_ALL}") sys.exit(1) # Concatenate content from multiple files file_content = "" try: for file_path in file_paths: with open(file_path, 'r') as file: file_content += file.read() + "\\n\\n" except FileNotFoundError as fnf_error: logger.error(f"{Fore.RED}File not found: {file_path}{Style.RESET_ALL}") sys.exit(1) # Get the base_url from arguments, environment, or use the default chosenModel = selectModel(base_url) try: if chosenModel == 'cohere': base_url = os.getenv("COHERE_BASE_URL", "https://api.cohere.ai/v1") response = cohereAPI(api_key, file_content) readme_content = response.generations[0].text.strip() + FOOTER_STRING else: base_url = os.getenv("GROQ_BASE_URL", "https://api.groq.com") response = groqAPI(api_key, base_url, file_content) readme_content = response.choices[0].message.content.strip() + FOOTER_STRING except AuthenticationError as auth_error: logger.error(f"{Fore.RED}Authentication failed: Invalid API key. Please check your API key and try again.{Style.RESET_ALL}") sys.exit(1) except Exception as api_error: logger.error(f"{Fore.RED}API request failed: {api_error}{Style.RESET_ALL}") sys.exit(1) # Process and save the generated README content if readme_content[0] != '*': readme_content = "\n".join(readme_content.split('\n')[1:]) try: with open(output_filename, 'w') as output_file: output_file.write(readme_content) logger.info(f"README.md file generated and saved as {output_filename}") logger.warning(f"This is your file's content:\n{readme_content}") except IOError as io_error: logger.error(f"{Fore.RED}Failed to write to output file: {output_filename}. Error: {io_error}{Style.RESET_ALL}") sys.exit(1) # Save API key if needed if not get_env() and api_key is not None: logger.warning("Would you like to save your API key and base URL in a .env file for future use? [y/n]") answer = input() if answer.lower() == 'y': create_env(api_key, base_url, chosenModel) elif get_env(): if chosenModel == 'cohere' and api_key != os.getenv("COHERE_API_KEY"): if api_key is not None: logger.warning("Would you like to save this API Key? [y/n]") answer = input() if answer.lower() == 'y': create_env(api_key, base_url, chosenModel) elif chosenModel == 'groq' and api_key != os.getenv("GROQ_API_KEY"): if api_key is not None: logger.warning("Would you like to save this API Key? [y/n]") answer = input() if answer.lower() == 'y': create_env(api_key, base_url, chosenModel) # Report token usage if the flag is set if token_usage: try: usage = response.usage logger.info(f"Token Usage Information: Prompt tokens: {usage.prompt_tokens}, Completion tokens: {usage.completion_tokens}, Total tokens: {usage.total_tokens}") except AttributeError: logger.warning(f"{Fore.YELLOW}Token usage information is not available for this response.{Style.RESET_ALL}") logger.info(f"{Fore.GREEN}File created successfully") sys.exit(0)
1. Eliminate Global Variables
Global variables can lead to unexpected side effects. Keep the state within the scope it belongs to, and pass values explicitly when necessary.
2. Use Functions for Calculations
Avoid storing intermediate values in variables where possible. Instead, use functions to perform calculations when needed—this keeps your code flexible and easier to debug.
3. Separate Responsibilities
A single function should do one thing, and do it well. Split tasks like command-line argument parsing, file reading, AI model management, and output generation into separate functions or classes. This separation allows for easier testing and modification in the future.
4. Improve Naming
Meaningful variable and function names are crucial. When revisiting your code after some time, clear names help you understand the flow without needing to re-learn everything.
5. Reduce Duplication
If you find yourself copying and pasting code, it’s a sign that you could benefit from shared functions or classes. Duplication makes maintenance harder, and small changes can easily result in bugs.
Commiting and pushing to GitHub
1. Create a branch
I started by creating a branch using:
git checkout -b <branch-name> </branch-name>
This command creates a new branch and switches to it.
2. Making a Series of Commits
Once on the new branch, I made incremental commits. Each commit represents a logical chunk of work, whether it was refactoring a function, fixing a bug, or adding a new feature. Making frequent, small commits helps track changes more effectively and makes it easier to review the history of the project.
git status git add <file_name> git commit -m "Refactored function" </file_name>
3. Rebasing to Keep a Clean History
After making several commits, I rebased my branch to keep the history clean and linear. Rebasing allows me to reorder, combine, or modify commits before they are pushed to GitHub. This is especially useful if some of the commits are very small or if I want to avoid cluttering the commit history with too many incremental changes.
git rebase -i main
In this step, I initiated an interactive rebase on top of the main branch. The -i flag allows me to modify the commit history interactively. I could squash some of my smaller commits into one larger, cohesive commit. For instance, if I had a series of commits like:
Refactor part 1
Refactor part 2
Fix bug in refactor
I could squash them into a single commit with a clearer message
4. Pushing Changes to GitHub
Once I was satisfied with the commit history after the rebase, I pushed the changes to GitHub. If you’ve just created a new branch, you’ll need to push it to the remote repository with the -u flag, which sets the upstream branch for future pushes.
git push -u origin <branch-name> </branch-name>
5. Merging
In the last step I did a fast-forward merge to the main branch and pushed again
git checkout main # change to the main branch git merge --ff-only <branch-name> # make a fast-forward merge git push origin main # push to the main </branch-name>
Takeaways
Everything has room to improve. Refactoring may seem like a hassle, but it often results in cleaner, more maintainable, and more efficient code. So, the next time you feel hesitant about refactoring, remember: there’s always a better way to do things.
Even though I think it's perfect now, I will definitely have something to improve on my next commit.
以上がReadmeGenie のリファクタリングの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Pythonは学習と使用が簡単ですが、Cはより強力ですが複雑です。 1。Python構文は簡潔で初心者に適しています。動的なタイピングと自動メモリ管理により、使いやすくなりますが、ランタイムエラーを引き起こす可能性があります。 2.Cは、高性能アプリケーションに適した低レベルの制御と高度な機能を提供しますが、学習しきい値が高く、手動メモリとタイプの安全管理が必要です。

PythonとCは、メモリ管理と制御に大きな違いがあります。 1。Pythonは、参照カウントとガベージコレクションに基づいて自動メモリ管理を使用し、プログラマーの作業を簡素化します。 2.Cには、メモリの手動管理が必要であり、より多くの制御を提供しますが、複雑さとエラーのリスクが増加します。どの言語を選択するかは、プロジェクトの要件とチームテクノロジースタックに基づいている必要があります。

科学コンピューティングにおけるPythonのアプリケーションには、データ分析、機械学習、数値シミュレーション、視覚化が含まれます。 1.numpyは、効率的な多次元配列と数学的関数を提供します。 2。ScipyはNumpy機能を拡張し、最適化と線形代数ツールを提供します。 3. Pandasは、データ処理と分析に使用されます。 4.matplotlibは、さまざまなグラフと視覚的な結果を生成するために使用されます。

PythonまたはCを選択するかどうかは、プロジェクトの要件に依存するかどうかは次のとおりです。1)Pythonは、簡潔な構文とリッチライブラリのため、迅速な発展、データサイエンス、スクリプトに適しています。 2)Cは、コンピレーションと手動メモリ管理のため、システムプログラミングやゲーム開発など、高性能および基礎となる制御を必要とするシナリオに適しています。

Pythonは、データサイエンスと機械学習で広く使用されており、主にそのシンプルさと強力なライブラリエコシステムに依存しています。 1)Pandasはデータ処理と分析に使用され、2)Numpyが効率的な数値計算を提供し、3)SCIKIT-LEARNは機械学習モデルの構築と最適化に使用されます。これらのライブラリは、Pythonをデータサイエンスと機械学習に理想的なツールにします。

Pythonを1日2時間学ぶだけで十分ですか?それはあなたの目標と学習方法に依存します。 1)明確な学習計画を策定し、2)適切な学習リソースと方法を選択します。3)実践的な実践とレビューとレビューと統合を練習および統合し、統合すると、この期間中にPythonの基本的な知識と高度な機能を徐々に習得できます。

Web開発におけるPythonの主要なアプリケーションには、DjangoおよびFlaskフレームワークの使用、API開発、データ分析と視覚化、機械学習とAI、およびパフォーマンスの最適化が含まれます。 1。DjangoandFlask Framework:Djangoは、複雑な用途の迅速な発展に適しており、Flaskは小規模または高度にカスタマイズされたプロジェクトに適しています。 2。API開発:フラスコまたはdjangorestFrameworkを使用して、Restfulapiを構築します。 3。データ分析と視覚化:Pythonを使用してデータを処理し、Webインターフェイスを介して表示します。 4。機械学習とAI:Pythonは、インテリジェントWebアプリケーションを構築するために使用されます。 5。パフォーマンスの最適化:非同期プログラミング、キャッシュ、コードを通じて最適化

Pythonは開発効率でCよりも優れていますが、Cは実行パフォーマンスが高くなっています。 1。Pythonの簡潔な構文とリッチライブラリは、開発効率を向上させます。 2.Cのコンピレーションタイプの特性とハードウェア制御により、実行パフォーマンスが向上します。選択を行うときは、プロジェクトのニーズに基づいて開発速度と実行効率を比較検討する必要があります。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

SublimeText3 中国語版
中国語版、とても使いやすい

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境

PhpStorm Mac バージョン
最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール
