跳到正文
DEV Community· Xsilent Dev·· 6 小時前AI 評分30

HEZX 如何設計 Android 每次使用成本追蹤器:計算、狀態與資料完整性

Designing a Cost-Per-Use Tracker for Android: Calculations, State and Data Integrity

AI 導讀

HEZX 是一款本機優先的 Android 購物及每次使用成本追蹤器,文章探討其計算規則、狀態轉換、資料建模與可靠性設計。使用次數為零時,每次使用成本應顯示為尚未計算;淨持有成本則計入維修費,並扣除已確認的退款及轉售收入,另須支援更正誤記的使用紀錄。

正文

Most personal finance applications focus on transactions.

You buy something, record the amount, assign a category, and move on.

But what if the interesting part of a purchase begins after the transaction?

Consider a pair of shoes, a laptop, or a power tool.

The purchase price is fixed, but its practical value changes as the item is used, repaired, returned, or eventually sold.

At TSI Dev Studio, this question influenced the development of HEZX, our local-first Android purchase and cost-per-use tracker.

HEZX helps users follow an item from its return window through years of recorded usage and ownership history.

Building a useful product around that concept raises several interesting software design questions.

This article explores the calculation rules, state transitions, data-modeling decisions, and reliability principles involved.

The code examples illustrate general implementation approaches rather than HEZX's private source code.

1. Model the Item as an Ongoing Record

A typical expense tracker might store a transaction containing an amount, a date, and a category.

A cost-per-use tracker needs a more extensive model.

An item can have:

  • An original purchase price and currency.
  • A purchase date.
  • A return deadline.
  • Standard and extended warranty dates.
  • A recorded usage count.
  • Repair expenses.
  • Confirmed refunds.
  • A confirmed resale amount.
  • A history of relevant events.

These values have different meanings.

The original price represents the initial purchase.

The usage count changes over time.

Repairs increase the recorded ownership cost.

Confirmed refunds and resale proceeds reduce it.

One possible Kotlin model for illustrating the concept is:

data class TrackedItem(
    val id: String,
    val name: String,
    val purchasePriceMinor: Long,
    val currencyCode: String,
    val usageCount: Int,
    val purchaseDate: LocalDate,
    val returnDeadline: LocalDate?
)

Using minor currency units, where appropriate, can avoid common floating-point rounding errors.

However, not every currency has two decimal places. A production implementation must respect currency-specific precision rules rather than assuming that every amount represents cents.

The larger lesson is that financial records should have explicit semantics.

A generic numeric field is not enough when different amounts affect calculations in different ways.

2. Cost Per Use Is Simple — Until There Are Zero Uses

The basic formula is:

Cost per use = Purchase price / Recorded uses

Imagine purchasing a camera for $600.

After 10 uses, its purchase-price cost per use is $60.

After 100 uses, it falls to $6.

The mathematics is straightforward.

But what should happen before the first use?

Dividing by zero is invalid.

Displaying $0 would also be misleading because the item has not yet delivered any recorded usage.

A safer approach is to represent the result as unavailable until the usage count becomes positive.

For example:

fun costPerUse(
    purchasePrice: BigDecimal,
    usageCount: Int
): BigDecimal? {
    require(purchasePrice >= BigDecimal.ZERO)
    require(usageCount >= 0)

    if (usageCount == 0) return null

    return purchasePrice.divide(
        BigDecimal(usageCount),
        2,
        RoundingMode.HALF_UP
    )
}

The null result communicates that the calculation is not yet available.

In the interface, it might be displayed as:

Not calculated — no recorded uses yet

This is preferable to showing an incorrect number simply because a dashboard expects every field to contain a value.

The exact rounding precision and formatting should follow the product's currency and reporting requirements.

3. Usage Tracking Needs an Undo Path

HEZX allows users to record usage from the application or a widget.

It also provides an undo action when a use is recorded accidentally.

This sounds like a small feature, but it addresses a fundamental reliability concern.

User interactions are not always intentional.

Someone might tap a widget twice.

They might record the wrong item.

They might misunderstand what counts as one use.

A tracker should make mistakes easy to correct.

A simple conceptual model could expose two operations:

fun recordUse(itemId: String)
fun undoLastUse(itemId: String)

But undo should not blindly subtract one from any counter.

Consider two different interactions that update the same item.

If the user attempts to undo an earlier operation, the application needs a consistent definition of which event is being reversed.

A production design could use event identifiers or a transaction history to ensure that undo reverses the intended operation.

This does not imply that HEZX uses a particular internal event-storage architecture.

It illustrates the problem a reliable usage tracker must solve.

Undo is not merely a convenience feature. It is part of data integrity.

4. Net Ownership Cost Requires Clear Rules

Purchase-price cost per use answers one question.

Net ownership cost answers another.

A simplified ownership calculation can be expressed as:

Net ownership cost = Purchase price + Repair costs − Confirmed refunds − Confirmed resale proceeds

Consider a hypothetical purchase:

Event Amount
Initial purchase $800
Repair +$100
Confirmed partial refund −$50
Confirmed resale −$250
Net ownership cost $600

After 300 recorded uses:

Net cost per use = $600 / 300 = $2.00

The calculation becomes more complicated when events are recorded incorrectly or prematurely.

A refund request is not necessarily a completed refund.

An item listed for sale has not necessarily been sold.

A repair estimate is not the same as a paid repair expense.

These distinctions matter.

HEZX specifically distinguishes confirmed refunds and confirmed sale amounts when calculating recovered money.

For a developer, the underlying design principle is to separate intentions and estimates from completed financial events.

A record representing a pending refund should not automatically reduce confirmed net ownership cost.

Similarly, the calculation should not silently combine unsupported currencies.

5. Never Add Different Currencies Without Conversion

Suppose a user owns three items:

Item Purchase price
Headphones $120 USD
Shoes €80 EUR
Backpack £65 GBP

Adding 120 + 80 + 65 produces 265.

But that number has no meaningful currency.

A developer may be tempted to convert everything automatically.

That introduces new requirements:

  • A reliable exchange-rate source.
  • A timestamp associated with each conversion.
  • Rules for historical versus current rates.
  • Transparent handling of offline availability.
  • Correct rounding for each currency.

HEZX takes a simpler approach: amounts in different currencies remain separate.

This is a deliberate product-level constraint described in its Google Play listing.

For local-first financial utilities, choosing not to convert can be more accurate than presenting an apparently precise total without sufficient context.

Financial correctness sometimes means refusing to calculate a misleading aggregate.

6. Returns Are State Transitions, Not Just Dates

A return deadline is a date.

A return process is a sequence of events.

An item might be:

  1. Purchased and being evaluated.
  2. Kept by the user.
  3. Marked for return.
  4. Awaiting a refund.
  5. Refunded after the payment is confirmed.

These states should not be confused.

For example, initiating a return does not mean that the retailer has already refunded the payment.

A conceptual Kotlin representation might look like:

enum class ReturnStatus {
    EVALUATING,
    KEPT,
    RETURN_INITIATED,
    AWAITING_REFUND,
    REFUND_CONFIRMED
}

This model is illustrative.

Real-world workflows may need additional states for rejected returns, partial refunds, cancelled requests, or other retailer-specific outcomes.

A good design also separates the tracking state from legal eligibility.

An application cannot guarantee that a retailer will accept a return merely because the user entered a deadline.

HEZX helps users track the process while leaving the actual return decision and retailer interaction to the user.

That boundary should remain explicit in the interface and documentation.

7. Reminders Should Support Decisions, Not Promise Outcomes

HEZX tracks return deadlines and warranty dates and provides configurable reminders.

On Android, notification delivery is influenced by permissions, background execution rules, and device-specific restrictions.

A well-designed reminder system should therefore avoid implying that a notification will always arrive at an exact moment.

The product should help users prepare before important dates.

For developers, the broader principle is to make reminder behavior understandable and communicate dependencies on operating-system settings.

This is particularly important when a missed notification could affect a user's ability to act before a deadline.

8. Receipt Scanning: Assistance Without Overwriting User Intent

HEZX includes an optional on-device receipt scanner.

Its purpose is to help users enter purchase details.

That distinction is important.

Optical recognition can misread dates, numbers, decimal separators, or currency symbols.

An automatically extracted value should not necessarily become an authoritative financial record without review.

A sensible input workflow separates:

Extracted information: values suggested by recognition.

Confirmed information: values accepted or corrected by the user.

For example, a receipt containing 1,299.00 may require locale-aware interpretation.

A system that treats the comma as a decimal separator could turn a large purchase into a completely different number.

The broader engineering principle is that recognition should reduce data-entry effort without removing the user's ability to verify important fields.

HEZX's receipt recognition runs locally on the device, without requiring a HEZX-operated server.

That approach also avoids making receipt processing dependent on uploading images to an external service.

9. Buy or Rent and Repair or Replace Are Decision Models

HEZX includes two practical comparison tools:

  • Buy or Rent.
  • Repair or Replace.

These tools illustrate a useful distinction between calculations and recommendations.

Consider buying a tool for $240 versus renting it for $30 per day.

Ignoring other costs, the purchase price equals eight rental days.

That calculation is useful.

But it does not determine whether buying is always the better choice.

The user may need to consider storage, transportation, maintenance, expected future use, and availability.

A similar issue appears in repair-versus-replace decisions.

A repair may be cheaper today but less attractive if the product is unsafe or likely to fail again.

Good calculation tools make assumptions visible instead of presenting an oversimplified answer as a universal recommendation.

10. Local-First Records Still Need Recovery

HEZX works locally without requiring an account or a developer-operated server.

Its purchase history remains under the user's control.

This reduces external dependencies, but it also makes backup and recovery essential considerations.

A user may change phones, uninstall an application, or lose access to a device.

HEZX provides encrypted backup and restore features, along with PDF and CSV reporting.

These capabilities serve different purposes.

An encrypted application backup is intended to help preserve or recover supported data.

A PDF report is useful for reading and sharing information.

A CSV export supports further analysis in spreadsheet software.

Neither PDF nor CSV should automatically be assumed to contain every element required for complete application restoration.

Exported files also introduce a new privacy boundary: once a report leaves the application, its protection depends on where and how it is stored.

A developer should explain these distinctions rather than treating every downloadable file as equivalent.

11. Design Financial Dashboards Around Meaningful Data

A dashboard can display dozens of metrics.

But more numbers do not necessarily improve understanding.

HEZX focuses on practical indicators related to purchases, usage, deadlines, and ownership history.

For developers designing similar products, several questions are worth asking:

Does every displayed number have a clear definition?

Are pending events separated from confirmed ones?

Can users correct accidental changes?

Are amounts from different currencies being combined incorrectly?

Does a zero value represent a genuine zero, or is the information unavailable?

Can users trace where an important calculation came from?

These questions matter more than visual complexity.

The best financial interfaces make information easier to trust.

12. Engineering Lessons From HEZX

HEZX began with a straightforward idea:

A purchase should not become invisible after checkout.

Following an item through its real-world lifecycle introduces a surprisingly rich set of software-design considerations.

Usage tracking requires correction mechanisms.

Ownership calculations require explicit rules.

Return workflows need meaningful states.

Receipt recognition must handle uncertainty.

Currency handling must avoid false precision.

Local storage requires deliberate recovery options.

And decision calculators should remain transparent about their assumptions.

None of these problems requires an application to become an automated financial adviser.

Instead, the product can help people organize information and make their own decisions.

Reliable software is not defined by how many calculations it performs. It is defined by whether those calculations mean what users think they mean.


About HEZX

HEZX is a local-first Android application developed by TSI Dev Studio.

It helps users track purchases, return deadlines, warranties, recorded usage, repairs, refunds, resale amounts, and cost per use.

Additional tools include Buy or Rent, Repair or Replace, on-device receipt recognition, annual reporting, encrypted backup and restore, and optional Lifetime features.

Official product page: https://tsidevstudio.com/apps/hezx

TSI Dev Studio: https://tsidevstudio.com

Written by TSI Dev Studio — an independent Android software studio focused on practical, privacy-conscious applications.

The Kotlin examples in this article demonstrate general software design patterns. They are not excerpts from HEZX's proprietary source code. All financial scenarios are illustrative.

來源:DEV Community · dev.to