一次典型的重构
1256
版权声明
我们非常重视原创文章,为尊重知识产权并避免潜在的版权问题,我们在此提供文章的摘要供您初步了解。如果您想要查阅更为详尽的内容,访问作者的公众号页面获取完整文章。
Background Description:
The author decided to refactor a C# program calculating arithmetic expressions as an example for an upcoming talk on refactoring. The original code computed expressions with brackets and four arithmetic operations. The program was simplified by removing brackets, assuming the first character is a digit, and considering only valid expressions.
Refactoring Techniques Used:
- Renaming Variables: The original program used abbreviated pinyin for variable names, making them hard to understand. The refactored code uses meaningful English names.
- Extracting Methods: The original code used one large method, while the refactored code is split into four methods, improving understandability and reusability.
- Extracting Classes: A new class was introduced to encapsulate the calculation methods.
- Algorithm Optimization: The original logic was inconsistent and complicated, especially in handling multiplication and division.
- Correcting Logical Errors: The original program had hidden logical errors, evident when inputting expressions like "3*3/3/3".
- Adding Simple Comments: The original program lacked comments.
Original Code:
The original code is provided, showing a lack of clarity in variable naming and structure. It uses a single method to handle all operations and lacks comments.
Refactored Code:
The refactored code introduces a new class with private members to store operators and numbers. It includes methods to divide the expression into operators and numbers, determine if a character is an operator, and rebuild the expression after each operation. The code handles multiplication and division first, followed by addition and subtraction. Clear variable names and structure are used to enhance readability and maintainability.
麦哲思科技任甲林
麦哲思科技(北京)有限公司总经理 敏捷性能合弄模型评估师 认证的Scrum Master 认证的大规模敏捷顾问SPC CMMI高成熟度主任评估师 COSMIC MPC,IAC 成员,中国分部主席
还在用多套工具管项目?
一个平台搞定产品、项目、质量与效能,告别整合之苦,实现全流程闭环。
水生
2007年的夏天我去厦门售前,早晨到酒店的餐厅吃饭,刚进餐厅,见一老一少两个穿黄色僧袍的和尚坐在里面吃饭,老和尚慈眉善目,看到我,像我微笑致意,我也点头还礼,我一直认为自己是很有佛缘的人,所以心里想,大概老和尚看我面善,所以和我打招呼吧,自我感觉甚好。在自助取餐的过程中,老和尚频频向我致意。
早餐吃完,经过两位的位置时,老和尚招手叫住了我,说要聊聊,我没有拒绝。坐下后,老和尚说是到福建什么一个出名的名寺开什么法会,看我有缘,和我聊聊,还送我一个开光的佛像,给了我名片,
白皮书上线