First Assignment 832401127 zexin zhang

832401127 张泽新 2026-10-04 00:36:22

Table of Contents

  1. Course & Assignment Introduction
  2. GitHub Repository Links & Code Style Links
  3. PSP Table
  4. Demonstration of Finished Product
  5. Design & Implementation Process
  6. Core Code Explanation
  7. Development Experience & Learnings

Course & Assignment Introduction

Course: Software Engineering

Assignment: Develop a calculator system based on front-end and back-end separation architecture

Assignment Objectives: Master the separated front-end and back-end architecture. The front-end handles UI interaction only. The back-end independently completes expression parsing, mathematical calculation, exception handling and persistent storage of calculation history in database. The front-end sends raw expression string to backend.

The front-end cannot compute the result directly. All core calculation logic runs on the backend.

Main Requirements:

  1. Implement basic arithmetic operations: + - * /
  2. Support compound expressions, including operator precedence, parentheses, unary minus, decimal numbers. Catch division-by-zero and invalid expression errors. Expression parsing is implemented manually, eval() is forbidden.
  3. Store calculation history persistently in backend database. The history includes expression, result and timestamp. History will not disappear after page refresh.
  4. Front-end can fetch history and delete single history record via API.
  5. Deploy the project and provide public accessible address.
  6. Upload source code into two independent GitHub repositories: frontend repo and backend repo.
  7. Write PSP table, codestyle.md and README.md for both repositories.
  8. Publish this blog with sufficient screenshots to demonstrate functions.

GitHub Repository Links & Code Style Links

PSP Table

表格

PhaseEstimated Time(min)Actual Time(min)
Requirement Analysis4055
System Design4050
Frontend Development4550
Backend Development7085
Expression Parser Module6075
Database Design3025
History CRUD Module4045
Frontend & Backend Integration5055
Testing & Bug Fix4045
Project Deployment2020
Blog Writing5055
Total485560

Demonstration of Finished Product

  1. Calculator Main UI 【Image 1】 
  2. Basic arithmetic test: 12+8 【Image 2】 
  3. *Compound expression with parentheses: (1+2)3 【Image 3】 
  4. Unary minus at start: -5+8 【Image 4】 
  5. Unary minus after operator: 3*-2【Image 5】 
  6. Division by zero exception:10/0 【Image 6】 
  7. Invalid expression:1++2 【Image 7】 
  8. Decimal calculation 【Image 8】 
  9. Query history and persistence after page refresh 【Image 9】 
  10. Delete single history record 【Image 10】 

 

 

 

 

 

 

 

 

 

 

Design & Implementation Process

1. Requirement Analysis

This project adopts front-end and back-end separation architecture.

  • Frontend responsibility: Render UI, listen button click, concatenate expression string; send HTTP POST request with expression; receive and display result; fetch history list; send delete request; display error messages from backend.
  • Backend responsibility: Receive expression string from frontend; lexical and syntax analysis; calculate following math rules; catch exceptions; save successful calculation records into SQLite database; provide REST API for history query and deletion; return standardized JSON response.

Hard constraint: All calculations are done on backend. Frontend cannot compute anything. eval() is forbidden.

2. System Architecture

Frontend HTML Page
    ↓ HTTP JSON API
Backend Express Server
    ↓
SQLite Database

Function Structure Diagram

Calculator System
├── Calculator Core Module
│   ├── Basic Arithmetic
│   ├── Compound Expression Parser
│   └── Exception Handler (Division by zero, invalid syntax)
├── Calculation History Module
│   ├── Save History
│   ├── Query History
│   └── Delete Single Record
├── Frontend
│   ├── User Button Input
│   ├── Result Display
│   └── History Display & Delete Operation
└── Backend
    ├── API Layer
    ├── Expression Parser Service
    ├── Calculation Service
    └── Database Persistence

3. Frontend Design

Frontend uses native HTML+CSS+JavaScript, no framework.

  • Button click handler: append characters to expression input box.
  • Equal button triggers fetch POST request, send expression to /calculate.
  • Refresh history button: GET /history to get record array and render page.
  • Delete button: send DELETE request to /history/:id. After deletion, reload history.
  • Parse JSON response: if success, show result; if failed, show error message from backend.

4. Backend Design

Backend based on Node.js Express, better-sqlite3 for SQLite database. Modules:

  1. server.js: entry point, listen port 3000, enable CORS and JSON parser.
  2. src/routes/api.js: API router for /calculate, /history, /history/:id.
  3. src/calculator/ExpressionParser.js: hand-written expression parser, infix to postfix, handle priority, parentheses and unary minus.
  4. src/calculator/CalculatorService.js: wrapper for parser, catch exceptions and throw standardized errors.
  5. src/database/model.js: database model, encapsulate insert, query, delete functions.

 

5. API Design

表格

MethodEndpointFunctionRequest BodyResponse Example
POST/calculateCalculate expression and save record{"expression":"(1+2)*3"}{"success":true,"expression":"(1+2)*3","result":9}
GET/historyGet all historynone{"success":true,"data":[{id,expr,result,create_time}]}
DELETE/history/:idDelete one record by idnone{"success":true}

Error response example:

 

6. Database Design

SQLite table history

表格

ColumnTypeDescription
idINTEGER PRIMARY KEY AUTOINCREMENTUnique primary key
exprTEXT NOT NULLOriginal expression string
resultTEXT NOT NULLCalculation result
create_timeDATETIME DEFAULT CURRENT_TIMESTAMPRecord timestamp

After successful calculation, backend inserts a new row. Query records ordered by id DESC so newest records appear first. Delete operation uses id to locate target row.

7. Calculation Module & Exception Handling

Hand-written expression parser in three steps:

  1. Lexical analysis (tokenize): split raw string into tokens (number, operator, parenthesis). Reject invalid characters.
  2. Infix to postfix notation: use stack, manage operator priority, identify unary minus.
  3. Evaluate postfix expression: stack-based calculation. Check divisor=0 and throw division-by-zero error.

Exception capture:

  • Division by zero → return Division by zero
  • Syntax error, mismatched parentheses, consecutive operators → return Invalid expression

8. Frontend Backend Interaction Workflow

  1. User clicks buttons on frontend to build expression.
  2. Click =, frontend sends POST request with expression string.
  3. Backend receives expression, parse and compute.
  4. If calculation success: insert record into database and return success JSON. If failed, return error JSON.
  5. Frontend renders result and refresh history list on success; show alert message on error.
  6. Click refresh history: frontend GET /history, render records from database.
  7. Click delete button: frontend send DELETE request. Backend deletes row in database, frontend reload history.

9. Deployment

Node.js backend deployed on cloud server with port 3000 open. Static frontend HTML deployed on Github Pages, public accessible.

Core Code Explanation

1. Frontend: Request calculation API

 

Explanation: Frontend only sends raw expression string without any calculation. Show result returned by backend and refresh history after success.

2. Backend: Calculate API router

 

Explanation: Receive expression, invoke calculation service. Save record to database after success. Catch exceptions and return standardized error response with HTTP 400 for client input error.

3. Expression parser: judge unary minus

 

Explanation: Distinguish subtraction operator and unary minus. Mark - as unary minus in cases like -5+8 and 3*-2, assign higher priority in postfix conversion.

4. Database model: query history

 

Explanation: Read all history records from SQLite, sorted by id descending. Pass data to API router via callback.

5. Delete history API

 

Explanation: Receive id from url parameter, call database delete function. Return 404 if target record not found.

Development Experience & Learnings

Problems & Solutions

  1. Unrecognized unary minus The parser could not tell the difference between subtraction and negative sign, 3*-2 failed. Solution: mark unary minus during infix-to-postfix conversion and assign higher priority.
  2. SQLite file locked When node service is running, better-sqlite3 locks calculator.db and prevents manual deletion. Solution: use CREATE TABLE IF NOT EXISTS, no need manually delete database file.
  3. CORS cross origin error Browser blocks fetch request from static frontend to backend. Solution: add cors middleware on backend.
  4. History list not refresh after deletion After delete API call, page content stayed unchanged. Solution: call loadHistory() again to fetch latest data from backend after deletion.

Knowledge Gained

  1. Deep understanding of front-end/back-end separation: frontend only handles view and interaction. Core calculation and data persistence must be on backend. If backend stops, frontend cannot compute new expressions.
  2. Use stack to implement infix expression parsing, learn operator precedence, parentheses and unary minus. Understand security risk of eval() executing raw user input.
  3. RESTful API design, semantic of GET/POST/DELETE, proper HTTP status code usage.
  4. SQLite persistent storage and callback-based database operation.
  5. Git version control, separate frontend and backend repositories, .gitignore to ignore node_modules and database file.
  6. PSP personal software process: estimate working time before development, track defects and quantify development progress.

Future Improvement

  1. Add pagination for history records when there are many entries.
  2. Support keyboard direct input in text box.
  3. Add scientific calculation functions (square root, power) as bonus extension.
  4. Write unit tests for expression parser module
...全文
56 回复 打赏 收藏 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
内容概要:本文介绍了“Java+大数据+AI架构师实战营”这一系统性人才培养方案,旨在帮助具备Java基础的开发者在26周内完成向融合Java、大数据与人工智能技术的复合型架构师跃迁。课程围绕五大核心模块展开:架构基本功(微服务演进、分布式锁与ID设计)、数据引擎(亿级数据存储与Flink CDC实时同步)、网关与可观测性(Gateway源码改造、限流与日志采样)、AI融入架构(推荐系统、大模型应用开发)以及架构思维培养。通过“小绿书”项目贯穿始终,强调整合三域技术的系统设计能力而非孤立技能堆叠。; 适合人群:具备1-5年Java开发经验,希望突破技术瓶颈、拓展大数据与AI领域能力的中高级研发人员;适合有志于成长为全栈架构师的技术从业者。; 使用场景及目标:①掌握高并发、分布式系统下的架构设计方法;②理解海量数据的存储分层与实时计算架构;③学会将AI能力如大模型、RAG、向量检索等深度集成到业务系统中;④构建完整的系统可观测性与网关控制能力;⑤形成跨技术域的系统性架构思维。; 阅读建议:此资源以实战项目驱动学习,强调动手实践与架构思维并重。建议学习者结合课程代码与实际调试,深入理解每一环节的技术选型与设计权衡,尤其关注真实生产环境中难以复现的复杂约束,从而建立可迁移的架构“手感”。

173

社区成员

发帖
与我相关
我的任务
社区描述
梅努斯-软件工程
软件工程 高校 福建省·福州市
社区管理员
  • FZU_SE_LQF
  • zjcTander
  • 木村修
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧