Header image

Xử Lý Lỗi Theo Phong Cách Lập Trình Hàm Trong Kotlin Với Arrow-kt

07/04/2022

1.53k

Xử Lý Lỗi Theo Phong Cách Lập Trình Hàm Trong Kotlin Với Arrow-kt

Bài viết này sẽ giới thiệu một số cách để xử lý lỗi trong Kotlin theo phong cách lập trình hàm sử dụng thư viện Arrow-kt. Những ví dụ được đưa ra sẽ theo thứ tự từ đơn giản đến phức tạp nhưng mạnh mẽ hơn.

Kotlin là gì?

Kotlin là một ngôn ngữ lập trình kiểu tĩnh, ban đầu được thiết kế để chạy trên máy ảo Java (JVM), sau này có thể biên dịch sang JavaScript và Native binaries sử dụng công nghệ LLVM. Kotlin có cú pháp hiện đại, ngắn gọn, an toàn và hỗ trợ cả lập trình hướng đối tượng (OOP)lập trình hàm (FP).

Arrow-kt là gì?

Arrow-kt (https://arrow-kt.io/) là một thư viện Typed Functional Programming trong Kotlin. Arrow cung cấp một ngôn ngữ chung của các interface và sự trừu tượng hóa trên các thư viện Kotlin. Nó bao gồm các kiểu dữ liệu phổ biến nhất như Option, Either, Validated, v.v … và các functional operator như traversecomputation blocks giúp cho người dùng viết các ứng dụng và thư viện pure FP dễ dàng hơn.

Setup

Trong file build.gradle.kts của root project, thêm mavenCentral vào danh sách:

allprojects {
    repositories {
        mavenCentral()
    }
}

Thêm dependency vào file build.gradle.kts của project:

val arrow_version = "1.0.1"
dependencies {
    implementation("io.arrow-kt:arrow-core:$arrow_version")
}

Pure function và exceptions

Pure function

Trong lập trình hàm, pure function là những function có hai tính chất:

  • Giá trị trả về chỉ phụ thuộc vào tham số truyền vào nó (tức là nếu cùng input thì cùng output).
  • Không tạo ra các side effect.

Side effect là những tác dụng xảy ra khi thực hiện một function mà không phải công dụng chính của nó. Ví dụ: ngoài việc trả về các giá trị, nó gây ra những tương tác thay đổi môi trường, thay đổi các biến toàn cục, thực hiện các hoạt động I/O như HTTP request, in dữ liệu ra console, đọc và ghi files Trong Kotlin, tất cả các function trả về Unit rất có thể tạo ra side effect. Đó là bởi vì giá trị trả về là Unit biểu thị “không có giá trị hữu ích được trả về”, điều này ngụ ý rằng function không làm gì khác ngoài việc thực hiện các side effect.

Một số ví dụ pure function trong Kotlin là những hàm toán học như sin, cos, max, …

Lợi ích của pure functions: dễ dàng combine, dễ dàng test, dễ dàng debug, dễ dàng parallelize, … Vì thế trong lập trình hàm, chúng ta sẽ cố gắng sử dụng nhiều pure functions nhất có thể, và tách biệt các phần pure và impure.

Exceptions

Kotlin có thể throwcatch các Exception tương tự như ngôn ngữ Java, JavaScript, C++,… Sử dụngtry { } catch(e) { } finally { } là cách xử lý lỗi phổ biến trong các ngôn ngữ lập trình mệnh lệnh.

Tuy nhiên việc throw và catch các Exception, chúng ta có thể thay đổi hành vi của function, khiến cho các function không còn pure nữa (catch Exception là một side effect). Ví dụ, một function catch hai Exception là ex1ex2 từ một function khác và tính toán kết quả, lúc đó kết quả đó sẽ phụ thuộc vào thứ tự thực thi của các câu lệnh, thậm chí có thể thay đổi giữa hai lần thực thi khác nhau của cùng một hệ thống.

Partial function

Ngoài ra, việc throw các Exception khiến cho các function trở thành một Partial function, tức là một function không hoàn toàn – không được xác định cho tất cả các giá trị input có thể có, bởi vì trong một số trường hợp, nó có thể không bao giờ trả về bất cứ thứ gì. Ví dụ, trong trường hợp một vòng lặp vô hạn hoặc nếu một Exception được throw.

Ví dụ: findUserById ở ví dụ dưới là một partial function.

@JvmInline
value class UserId(val value: String)

@JvmInline
value class Username(val value: String)

@JvmInline
value class PostId(val value: String)

data class User(
    val id: UserId,
    val username: Username,
    val postIds: List<PostId>
)

class UserException(message: String?, cause: Throwable?) : Exception(message, cause)

/**
 * @return an [User] if found or `null` otherwise.
 * @throws UserException if there is any error (eg. database error, connection error, ...)
 */
suspend fun findUserById(id: UserId): User? = TODO()

Đề làm cho findUserById trở thành một total function, chúng ta thay vì throw UserException, chúng ta có thể return nó như một giá trị, thay return type của findUserById thành UserResult.

sealed interface UserResult {
    data class Success(val user: User?) : UserResult
    data class Failure(val error: UserException) : UserResult
}

suspend fun findUserById(id: UserId): UserResult = TODO()

Các vấn đề với Exceptions

Exception có thể được xem như là những câu lệnh GOTO như trong C/C++, vì chúng làm gián đoạn luồng chương trình bằng cách quay lại nơi gọi nó. Các Exception không nhất quán, đặc biệt là khi trong lập trình Multithread, chúngta try...catch một function nhưng Exception được throw ở một Thread khác mà không thể catch nó được.

Một vấn đề khác là việc lạm dụng catch Exception: catch nhiều hơn những gì cần thiết và cả những Exception từ hệ thống như VirtualMachineError, OutOfMemoryError,…

try {
    doExceptionalStuff() //throws IllegalArgumentException
} catch (e: Throwable) {
    // too broad, `Throwable` matches a set of fatal exceptions and errors
    // a user may be unable to recover from:
    /*
    VirtualMachineError
    OutOfMemoryError
    ThreadDeath
    LinkageError
    InterruptedException
    ControlThrowable
    NotImplementedError
    */
}

Và cuối cùng, nhìn vào một signature của một function, chúng ta không thể biết được, nó sẽ throw ra Exception nào, ngoài việc đọc docs hay là đọc source code của nó, thay vào đó, chúng ta hay để signature của function đó biểu hiện rõ ràng những lỗi nào có thể xảy ra khi gọi function đó.

Vì vậy, để xử lý lỗi, chúng ta cần một type có thể được compose với nhau, và biểu thị một kết quả hợp lệ hoặc một lỗi. Những type đó là Discriminated union/ tagged union, trong Kotlin đó được triển khai thông qua sealed class/sealed interface/enum class. Chúng ta sẽ cùng tìm hiểu kotlin.Result được cung cấp bởi Kotlin Sdtlib từ version 1.3 , và sau đó là arrow.core.Either đến từ thư viện Arrow-kt.

Sử dụng kotlin.Result để xử lý lỗi

Chúng ta có thể sử dụng Result<T> như là một type để biểu thị: hoặc là giá trị thành công với type là T, hoặc là là một lỗi xảy ra với một một Throwable. Nếu theo cách hiểu đơn giản, Result<T> = T | Throwable.

Để tạo ra giá trị Result, ta có thể dụng các function có sẵn như

  • Result.success
  • Result.failure
  • runCatching (tương tự như try { } catch { }
    nhưng trả về Result).
suspend fun findUserByIdFromDb(id: String): UserDb? = TODO()

fun UserDb.toUser(): User = TODO()

suspend fun findUserById(id: UserId): Result<User?> = runCatching { findUserByIdFromDb(id.value)?.toUser() }

Chúng ta có thể kiểm tra Result là giá trị thành công hay không, thông qua hai property là isSuccessisFailure. Để thực hiện các hành động ứng với mỗi trường hợp của Result thông qua function onSuccessonFailure.

val userResult: Result<User?> = findUserById(UserId("#id"))
userResult.isSuccess
userResult.isFailure
userResult.onSuccess { u: User? -> println(u) }
userResult.onFailure { e: Throwable -> println(e) }

Để có thể lấy giá trị bên trong Result, chúng ta sử dụng các function getOr__. Sử dụng exceptionOrNull để truy cập giá trị Throwable bên trong nếu Result đại diện cho giá trị thất bại. Ngoài ra, còn có function fold có thể handle một trong hai case dễ dàng.

val userResult: Result<User?> = findUserById(UserId("#id"))

// Access value
userResult.getOrNull()
userResult.getOrThrow()
userResult.getOrDefault(defaultValue)
userResult.getOrElse { e: Throwable -> defaultValue(e) }

// Access Throwable
userResult.exceptionOrNull()

fun handleUser(u: User?) {}
fun handleError(e: Throwable) {
    when (e) {
        is UserException -> {
            // handle UserException
        }
        else -> {
            // handle other cases
        }
    }
}

userResult.fold(
    onSuccess = { handleUser(it) },
    onFailure = { handleError(it) }
)

Tuy nhiên, sức mạnh thực sự của Result nằm ở việc chain các hoạt động trên nó. Ví dụ: nếu bạn muốn truy cập một property của User:

val userResult: Result<User?> = findUserById(UserId("#id"))
val usernameNullableResult: Result<Username?> = userResult.map { it?.username }

Chú ý rằng, nếu việc gọi lambda truyền vào function map throw Exception, thì Exception đó sẽ bị throw ra ngoài. Nếu muốn Exception đó được catch và chuyển thành giá trị Result, sử dụng mapCatching để vừa map vừa catching.

val usernameResult: Result<Username> = userResult.map {
    checkNotNull(it?.username) { "user is null!" }
}

Một vấn đề đặt ra là làm sao để chain các Result mà phụ thuộc lẫn nhau

// (UserId) -> Result<User?>
suspend fun findUserById(id: UserId): Result<User?> = TODO()

// User -> List<Post>
suspend fun getPostsByUser(user: User): Result<List<Post>> = TODO()

// List<Post> -> Result<Unit>
suspend fun doSomethingWithPosts(posts: List<Post>): Result<Unit> = TODO()

Chúng ta tạo một function flatMap (mapflatten).

// Map and flatten
inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> = mapCatching { transform(it).getOrThrow() }

// or
inline fun <T, R> Result<T>.flatMap(transform: (T) -> Result<R>): Result<R> = map(transform).flatten()
inline fun <T> Result<Result<T>>.flatten(): Result<T> = getOrElse { Result.failure(it) }

Bằng việc sử dụng flatMap, chúng ta có thể chain các Result với nhau

val unitResult: Result<Unit> = findUserById(UserId("#id"))
    .flatMap { user: User? -> runCatching { checkNotNull(user) { "user is null!" } } }
    .flatMap { getPostsByUser(it) }
    .flatMap { doSomethingWithPosts(it) }

Thư viện Arrow-kt cũng cung cấp block result { ... } để có thể handle việc chain các Result với nhau, tránh một số trường hợp sử dụng quá nhiều các nested flatMap. Trong block result { ... }, sử dụng function bind() để lấy giá trị T từ Result<T>. Nếu bind được gọi trên một Result đại diện một lỗi, thì phần code ở phía dưới nó trong block result { ... } sẽ bị bỏ qua (cơ chế short-circuits).

import arrow.core.*

val unitResult: Result<Unit> = result { /*this: ResultEffect*/
    val userNullable: User? = findUserById(UserId("#id")).bind()
    val user: User = checkNotNull(userNullable) { "user is null!" }
    val posts: List<Post> = getPostsByUser(user).bind()
    doSomethingWithPosts(posts).bind()
}

Một số tình huống khác có thể yêu cầu các chiến lược xử lý lỗi phức tạp có thể bao gồm khôi phục hoặc báo cáo lỗi. Ví dụ, chúng ta fetch data từ remote server, nếu bị lỗi thì sẽ lấy data từ cache. Chúng ta có thể sử dụng 2 function recoverrecoverCatching,

class MyData(...)

fun getFromRemote(): MyData = TODO()
fun getFromCache(): MyData = TODO()

val result: Result<MyData> = runCatching { getFromRemote() }
    .recoverCatching { e: Throwable ->
        logger.error(e, "getFromRemote")
        getFromCache()
    }

Sử dụng Result là một cách tiếp cận này tốt hơn, tuy nhiên vấn đề là lỗi luôn luôn là một Throwable, ta phải đọc docs hoặc đọc source code của nó. Một vấn đề nữa là runCatching khi kết hợp với suspend function, nó sẽ catch mọi Throwable, kể cả kotlinx.coroutines.CancellationException, CancellationException là một Exception đặc biệt, được coroutines sử dụng để đảm bảo cơ chế cooperative cancellation (xem issues 1814 Kotlin/kotlinx.coroutines).

Một cách tiếp cận tốt hơn là sử dụng arrow.core.Either, khắc phục các nhược điểm của Result.

Sử dụng arrow.core.Either để xử lý lỗi

Chúng ta có thể sử dụng Either<L, R> như là một type để biểu thị: hoặc là giá trị Left(value: L) , hoặc là giá trị Right(value: R). Nếu theo cách hiểu đơn giản, Either<L, R> = L | R.

public sealed class Either<out A, out B> {
    public data class Left<out A> constructor(val value: A) : Either<A, Nothing>()
    public data class Right<out B> constructor(val value: B) : Either<Nothing, B>()
}

Trong đó, Left thường đại diện cho các giá trị lỗi, giá trị không mong muốn, và Right thường đại diện cho các giá trị thành công, giá trị mong muốn. Nhìn chung Either<L, R> tương tự với Result<T>, Result<T> chỉ tập trung vào type của giá trị thành công mà không quan tâm đến type của giá trị lỗi, và chúng ta có thể xem Result<R> ~= Either<Throwable, R>. Eitherright-biased, tức là các function như map, filter, flatMap, … sẽ theo nhánh Right, nhánh Left bị bỏ qua (được return trực tiếp mà không có hành động nào trên nó cả).

Để tạo ra giá trị Either, ta có thể dụng các function có sẵn như:

  • Left constructor, ví dụ: val e: Either<Int, Nothing> = Left(1)
  • Right constructor, ví dụ: val e: Either<Nothing, Int> = Right(1)
  • left extension function, ví dụ val e: Either<Int, Nothing> = 1.left().
  • right extension function, ví dụ val e: Either<Nothing, Int> = 1.right().
  • Either.catch functions, catch các Exceptions nhưng nó sẽ bỏ qua các fatal Exception
    như kotlinx.coroutines.CancellationException, VirtualMachineError, OutOfMemoryError,…
  • Và nhiều cách được cung cấp bởi arrow.core.Either.Companion.
suspend fun findUserByIdFromDb(id: String): UserDb? = TODO()

fun UserDb.toUser(): User = TODO()

fun Throwable.toUserException(): UserException = TODO()

suspend fun findUserById(id: UserId): Either<UserException, User?> =
    Either
        .catch { findUserByIdFromDb(id.value)?.toUser() } // Either<Throwable, User?>
        .mapLeft { it.toUserException() }                 // Either<UserException, User?>

Chúng ta có thể kiểm tra Either là giá trị Left hay Right, thông qua hai function là isLeft()isLeft(). Either cũng cung cấp hai function tap (tương tự onSucesscủa Result) và tapLeft (tương tự onFailure của Result).

val result: Either<UserException, User?> = findUserById(UserId("#id"))
result.isLeft()
result.isRight()
result.tap { u: User? -> println(u) }
result.tapLeft { e: UserException -> println(e) }

Tương tự như Result, chúng ta sử dụng các function getOrElse, orNull, getOrHandle để lấy giá trị mà Right chứa nếu nó là Right. Một số function hữu ích nữa là fold, bimap, mapError, filter,…

val result: Either<UserException, User?> = findUserById(UserId("#id"))

// Access value
result.getOrElse { defaultValue }
result.orNull()
result.getOrHandle { e: UserException -> defaultValue(e) }

fun handleUser(u: User?) {}
fun handleError(e: UserException) {
    // handle UserException
}

result.fold(
    ifRight = { handleUser(it) },
    ifLeft = { handleError(it) }
)

Tương tự ví dụ khi sử dụng Result, chúng ta cũng muốn chain nhiều giá trị Either với nhau

// (UserId) -> Either<UserException, User?>
suspend fun findUserById(id: UserId): Either<UserException, User?> = TODO()

// User -> Either<UserException, List<Post>>
suspend fun getPostsByUser(user: User): Either<UserException, List<Post>> = TODO()

// List<Post> -> Either<UserException, Unit>
suspend fun doSomethingWithPosts(posts: List<Post>): Either<UserException, Unit> = TODO()

Thư viện Arrow-kt đã cung cấp sẵn function flatMap và block either { ... } để có thể chain các Either với nhau dễ dàng. Trong either { ... } block, sử dụng function bind() để lấy giá trị R từ Either<L, R>. Nếu bind được gọi trên một Either chứa giá trị Left, thì phần code ở phía dưới nó trong block either { ... } sẽ bị bỏ qua (cơ chế short-circuits).

import arrow.core.*

class UserNotFoundException() : UserException("User is null", null)

val result: Either<UserException, Unit> = findUserById(UserId("#id"))
    .flatMap { user: User? ->
        if (user == null) UserNotFoundException().left()
        else user.right()
    }
    .flatMap { getPostsByUser(it) }
    .flatMap { doSomethingWithPosts(it) }

// or either block

val result: Either<UserException, Unit> = either { /*this: EitherEffect*/
    val userNullable: User? = findUserById(UserId("#id")).bind()
    val user: User = ensureNotNull(userNullable) { UserNotFoundException() }
    val posts: List<Post> = getPostsByUser(user).bind()
    doSomethingWithPosts(posts).bind()
}

Cuối cùng là cách khôi phục lỗi. Tương tự như recoverrecoverCatching của Result, chúng ta có thể sử dụng hai function handleErrorhandleErrorWith (giống như flatMap nhưng theo nhánh Left).

class MyData(...)

suspend fun getFromRemote(): MyData = TODO()
suspend fun getFromCache(): MyData = TODO()

val result: Either<Throwable, MyData> =
    Either
        .catch { getFromRemote() }
        .handleErrorWith { e: Throwable ->
            Either.catch {
                logger.error(e, "getFromRemote")
                getFromCache()
            }
        }

Kết luận

Chúng ta đã cùng tìm hiểu Result và sau đó là Either, cả hai type giúp xử lý lỗi và làm giảm side effect. Either còn chỉ rõ về những lỗi có thể xảy ra mà chỉ cần nhìn vào signature của một function. Ngoài ra, Either hỗ trợ cho suspend function mà không làm mất đi cơ chế cancellation, và Arrow-kt cũng có module Fx (https://arrow-kt.io/docs/fx/) giúp cho việc sử dụng Kotlin Coroutines dễ dàng hơn, khi viết các chương trình asyncconcurrent.

Hy vọng bạn thích bài viết này và hôm nay bạn đã học được điều gì đó hữu ích!

Tài liệu tham khảo

  • Arrow-kt – Either docs
  • Arrow-kt – Error handlding
  • Arrow-kt – Monad comprehension
  • Ciocîrlan, D. (2021) Idiomatic error handling in scala, Rock the JVM Blog. Available at: https://blog.rockthejvm.com/idiomatic-error-handling-in-scala/ (Accessed: 04 October 2024).

Author: st-hocnguyen

Related Blog

Our culture

+0

    Tour “Đại lộ QC” – Hành trình khám phá nghề kiểm thử cùng ST

    Chào mừng bạn đến với series “Chuyện ngành chuyện nghề - Team QC”, nơi chúng mình kể lại những câu chuyện thật nhất về hành trình làm nghề, những niềm vui và… những pha “dở khóc dở cười” phía sau mỗi bản build. Để bắt đầu nghề QC thì không khó, nhưng để trở thành QC giỏi không phải điều dễ dàng. Trước khi lên đường khám phá, hãy cùng mình “bóc tem” một vài hiểu lầm kinh điển về nghề QC nhé! Có phải bạn đã từng nghĩ rằng: - Ai cũng học QC được? - Ai cũng làm QC được? - QC chỉ cần bấm bấm test test và report bug? Vậy thì hôm nay, hãy cùng gặp gỡ hướng dẫn viên du lịch - Nguyễn Quang Vũ (QC Team)  - người sẽ đưa các bạn tham quan một con đường huyền thoại mang tên “Đại lộ QC”. Thắt dây an toàn, cầm vé trên tay và chúng ta sẽ xuất phát ! Km 0 – Cổng “Khởi Đầu” Trước khi trở thành “người gác cổng chất lượng”, mỗi QC đều bắt đầu bằng giai đoạn… bấm mọi thứ có thể bấm. Đây là lúc bạn làm quen sản phẩm, hiểu người dùng, và tập làm bạn với bug. Bạn sẽ cần mô phỏng hành vi người dùng, bấm - nhìn - ghi để xem sản phẩm có chạy đúng như mong đợi. Tưởng đơn giản mà không hề đơn giản: phải quan sát và đặt câu hỏi đúng chỗ. ❓ Vì sao ai cũng nên dừng ở đây? - Đây là nơi hình thành tư duy kiểm thử và hiểu quy trình phát triển. Như học lái xe: nắm vững gương, đèn, phanh rồi mới tính chuyện đổ đèo. 💡 Mẹo sống còn: - Học cách viết test case rõ ràng. - Biết phân biệt bug vs feature (phao cứu sinh tình bạn với dev). - Ghi chép gọn gàng, ảnh/chụp màn hình là tem visa cho mỗi phát hiện. 🔌 Trạm tiếp năng lượng:  Kiểm thử các luồng “hơi đời” như mất mạng, pin 2%, nhập emoji vào ô số, đổi ngôn ngữ giữa chừng. Đây là nơi rất kích thích sự tò mò của các bạn! Km 10 – Ngã rẽ “Phát Triển” Ở Km 10, bạn chọn đường mình muốn đi, miễn đi sâu một nhánh: ⬅️ Nếu bạn chọn làn trái: Automation Test, nơi còn gọi là “Làng Code”. Bạn sẽ nhận được: - Bản đồ: biết code và tư duy code để tự động hoá những thứ lặp lại. - Điểm check-in: Script chạy qua đêm, CI/CD, báo cáo xanh lè sáng sớm. - Quà lưu niệm: Khả năng đọc API, log, mock data, dựng pipeline nhoáng cái là xong. ➡️ Còn nếu bạn chọn làn phải: Performance Test, được ví như “Thung lũng Hạ Tầng”. Bạn sẽ có 1 chuyến trải nghiệm thú vị khác: - Bản đồ: cần hiểu hệ thống, kiến trúc, infra logic; đo độ bền, độ tải, độ chịu nhiệt. - Điểm check-in: JMeter/K6, profiling, bottleneck, tuning database. - Quà lưu niệm: Biểu đồ đẹp như tranh, nơi có lời giải cho câu hỏi vì sao “chạy một mình thì nhanh, có người xem livestream thì… khựng”. 📍 Nguyên tắc vàng của Km 10:  “Biết nhiều một chút, nhưng phải biết sâu một phần.” Có chiều rộng để phối hợp, có chiều sâu để gánh trách nhiệm.  Ở đoạn đường này, QC không chỉ tìm lỗi mà còn đề xuất cải tiến, thiết kế trải nghiệm, góp phần tạo ra chất lượng toàn diện. Related Blogs: > Must-Have Tools for Business Analyst > How to Step Out of the “Forwarder” Shadow? Km 25 – Quảng trường “Tư Duy Làm Chủ” Sau một thời gian quen tay với việc test bug và viết test case, bạn sẽ nhận ra: QC không chỉ là người tìm lỗi, mà còn là người giúp sản phẩm tốt lên từng ngày. Đây là lúc bạn bắt đầu bước ra khỏi “vùng kiểm thử” quen thuộc để nhìn sản phẩm ở góc độ rộng hơn: người dùng đang cần gì, team đang gặp khó ở đâu, và giá trị thực mà sản phẩm mang lại là gì. Bạn bắt đầu làm gì? - Điều phối nhịp sprint, push tiến độ, sắp hàng ưu tiên, nhìn rủi ro bằng ống nhòm và nói chuyện người dùng như hàng xóm thân. ❓ Để ở lại quảng trường này lâu, bạn cần: - Hiểu quy trình từ yêu cầu → phát triển → phát hành. - Nắm sản phẩm & người dùng hơn cả tên thú cưng nhà mình. - “Thấu” team sản xuất: dev cần gì, design lo gì, PM sợ gì, khách hàng kỳ vọng gì. Bài học đường dài: QC giỏi có “la bàn hệ thống” - biết hướng về giá trị người dùng, không chỉ về “màu xanh của report”. Km 40 – Ghé thăm đặc khu “ST QC”  và Về đích  Sau khi băng qua những chặng đường đầy bug và deadline, mời bạn ghé trạm dừng chân tại đặc khu “ST QC”. Đây là nơi những người làm kiểm thử thật sự trưởng thành và tìm thấy hướng đi cho riêng mình. Tại đây, bạn sẽ được “đi tour” qua đủ mọi cung đường nghề QC. Từ Manual Test đến Automation hay Performance Testing, thử sức để biết bản thân phù hợp với hướng nào. Ở ST luôn được khuyến khích học hỏi, có mentor tận tình chỉ đường, và rất nhiều ngã rẽ nghề nghiệp cho bạn mở rộng: từ QA, QC Technical Lead, cho đến BA hay PM. Chúng mình tin vào văn hoá “đi thực chiến trước, giáo trình hoá sau”. Nghĩa là không học để biết, mà học để dùng, để làm cho sản phẩm tốt hơn mỗi ngày. Vé VIP cho người mới Mentor thâm niên luôn đồng hành cùng bạn.Starter Kit “xịn”: test template, bug report, release checklist, sample pipeline.Nhớ câu thần chú:  “Chất lượng là thói quen mỗi ngày, không phải phép màu cuối sprint.” Phụ lục cho hành khách yêu khám phá. Trên “Đại lộ QC”, bạn sẽ bắt gặp những biển báo quen thuộc: ⚠️ Cảnh báo dốc: Thiếu kiên trì, kỷ luật hay tư duy hệ thống rất dễ tụt dốc.🆘 Làn khẩn cấp: Khi hoang mang, hãy quay lại acceptance criteria và dữ liệu gốc.🏥 Trạm y tế: Nếu burnout, dừng lại nghỉ, xem lại ưu tiên và xin hỗ trợ đoàn mình không ai bị bỏ lại. Combo “Túi đồ nghề QC” Checklist / Test Case, Mindmap risk, Template Bug Report, Common Edge Case, Script tiện tay. Trang bị đủ hành trang để bạn tự tin băng qua mọi sprint nhé. “Đại lộ QC” không phải đường cao tốc thẳng tắp, mà nó còn có dốc, có đèo, có khúc cua tay áo. Nhưng đổi lại là một hành trình đáng nhớ: sản phẩm chạy mượt, người dùng mỉm cười, team tin tưởng nhau hơn. Con đường này dễ xuất phát nhưng khó về đích. Vì thế hãy  luôn vững tin với chiếc vé mang tên kiên trì, kỷ luật, tư duy hệ thống, chúng sẽ giúp bạn đến được nơi mình muốn. Nếu bạn đã sẵn sàng, mời lên xe chuyến sau. Hướng dẫn viên “trái ngành” vẫn ở đây, tay trái cầm bản đồ, tay phải cầm… checklist. Hẹn gặp bạn ở một cột mốc mới trên Đại lộ QC!

    12/11/2025

    51

    Our culture

    +0

      Tour “Đại lộ QC” – Hành trình khám phá nghề kiểm thử cùng ST

      12/11/2025

      51

      Knowledge

      Others

      +0

        Must-Have Tools for Business Analyst

        In today’s fast-evolving tech world, working smart has become even more crucial than working hard. In IT environments — and in any modern business — managing a growing amount of complex work can’t rely solely on memory, scattered emails, or individual Excel sheets. One of the most effective ways to boost productivity intelligently is through the use of supporting tools.This isn’t just a trend anymore — it’s quickly becoming the standard in many companies. For Business Analysts (BAs), the right tools don’t just make you more efficient — they make you more professional. Let’s explore some essential tools every BA should have in their toolkit 👇 1. Draw.io A free, intuitive diagramming tool to visualize processes, systems, data, or ideas.It’s ideal for modeling workflows and mapping business logic. Key Features: Free and no registration required — just go to diagrams.net.Flexible storage — save files locally or to Google Drive, OneDrive, GitHub, GitLab.Rich icon library — supports UML, BPMN, flowcharts, network diagrams, and more.UML & BPMN ready — perfect for use cases, activity diagrams, and business flows.Easy collaboration when stored on shared drives.Cross-platform — available on web, desktop, and as a VS Code extension. Limitations: Real-time collaboration isn’t as strong as tools like Figma.Performance may drop with very large or complex diagrams. 2. Miro Miro is an online collaborative whiteboard designed for teams to brainstorm, plan, and visualize ideas in real-time. Key Features: Infinite canvas — visualize projects without space limits.Real-time collaboration — comment, vote, and co-edit instantly.Rich templates — includes user story maps, journey maps, mindmaps, Kanban boards, and wireframes.Integrations — connects with Jira, Confluence, Slack, Teams, Google Drive, and more.Great for mapping processes, use cases, roadmaps, or even UI mockups. Limitations: Free plan limits the number of boards.Large boards with many assets may slow down performance. 3. Trello Trello is a Kanban-based task management tool that helps teams visualize and track progress easily. Key Features: Simple drag-and-drop interface.Highly customizable boards, lists, and cards.Each card can include checklists, attachments, labels, due dates, and assignees.Seamless integration with Google Drive, Slack, Jira, GitHub, and others.Real-time updates across all team members.Works on web, desktop, and mobile. Limitations: Free plan limits the number of integrations (Power-Ups). 4. Jira Jira by Atlassian is the industry-standard project management tool for Agile teams. Key Features: Built for Scrum and Kanban teams.Highly customizable workflows, fields, and automation rules.Transparent tracking of tasks, blockers, and progress.Integrates with hundreds of DevOps, CI/CD, and testing tools.Scales from individual tasks to enterprise-level project portfolios. Limitations: Steep learning curve for beginners.Can be costly for large teams.Requires experienced admins for setup and maintenance.May run slower on large, complex projects. 5. Typescale A handy tool for generating consistent typography systems (font size, line height, spacing) for web or app design. Key Features: Automates type scale creation.Multiple presets and flexible customizations.Preview and export CSS directly.Ensures responsive and accessible typography. Limitations: Not suitable for all design systems or content types.Limited control over detailed responsive behavior. 6. Adobe Color An intuitive color palette generator to create harmonious and accessible color schemes. Key Features: Easy-to-use color wheel with real-time updates.Auto-generates color harmonies based on color theory.Supports HEX, RGB, and CMYK formats.Integrates seamlessly with Adobe tools like Photoshop, Illustrator, and XD.Community palette sharing and inspiration gallery. Limitations: Contrast still needs manual checking for accessibility.Some auto-generated palettes may need manual tweaking.Colors can look different on various screens. 7. Contrast Checker A simple but vital tool to ensure readability and accessibility by checking text and background contrast per WCAG standards. Key Features: Simple interface — input colors and get instant feedback.Ensures compliance with accessibility guidelines.Real-time updates as you adjust colors.Bridges design and development — everyone can validate contrast easily. Limitations: Doesn’t reflect results accurately for complex backgrounds.Doesn’t account for font size, spacing, or user testing conditions. Why Use These Tools? Transparency: Everything — from tasks to deadlines — is clearly tracked. For example, Trello helps answer questions like “Who’s doing what?” and “What’s the current status?”Visualization: Tools like Draw.io help transform abstract logic into clear, easy-to-understand diagrams.Collaboration: Integrating tools like Miro, Jira, or Slack ensures everyone stays aligned and reduces miscommunication. Tips for Getting Started Start small: You don’t need every tool at once. Begin with Jira or Trello, then expand.Build shared habits: Tools only work when the whole team uses them consistently.Learn by doing: Explore free trials and tutorials, then apply them directly in your current projects.Stay updated: Tools evolve fast — keeping up helps you stay ahead. Using tools isn’t just about having more software — it’s about changing the way we work.They make our processes more transparent, our teamwork more seamless, and our output more efficient. For Business Analysts, these tools are not just “nice-to-have” — they’re what turn you from a task executor into a strategic enabler for your team. Read more related articles from SupremeTech!

        31/10/2025

        143

        Sang Ngo

        Knowledge

        +1

        • Others

        Must-Have Tools for Business Analyst

        31/10/2025

        143

        Sang Ngo

        Knowledge

        Others

        Our culture

        +0

          How to Step Out of the “Forwarder” Shadow?

          Have you ever, as a Comtor or Business Analyst (BA), felt like… a messenger? Every time the client asks something, you turn to the team, copy their answer, translate it, and send it back — just passing messages instead of actually owning the conversation. At SupremeTech, our BA team jokingly calls this role the “Professional Forwarder.” Through many “lost in translation” moments, we’ve learned valuable lessons on how to step out of that shadow — to become real connectors between the client and the team. Let’s hear from our BA team as they share practical tips to help you move beyond being a “forwarder” drawn directly from real project experience. Signs You Might Be Forwarding Too Much 1. The classic line: “Let me check with the team.”It’s not wrong — but if you’re saying it too often, it might mean you don’t fully understand the issue. 2. Lack of confidence in meetings: Many new BAs struggle with open-ended questions. When you don’t fully understand the product, you can’t confidently answer questions from both the client and your internal team. The PM asks about progress, you look at the Sprint Backlog full of numbers — and still don’t know where to start. 3. Avoiding technical talk: The moment you hear technical terms, you “pass the ball” to the PTL — without really understanding what’s being discussed. 3 Steps to Escape the “Forwarder Manager” Role So, how can you move from being a Forwarder to becoming a true communicator — someone who understands, connects, and leads discussions effectively? Here are three simple but powerful steps you can start practicing right away: 1. Before Forwarding, Ask Yourself: Do I understand at least 70% of this content?Have I tried to reproduce the bug, test the feature in the DEV environment, or explore the possible cause myself?If I were the dev/tester receiving this message, would I have enough context to understand it?Can I classify the issue — is it about UI/UX, logic, data, or business flow?Can I try to answer part of it first, then confirm later? 👉 This habit helps you learn something new every day, instead of just finishing tasks every day. 2. In Every Meeting – Observe and Lead What is the team really discussing? Do I understand the big picture?If the conversation is technical, how does it relate to the overall context?Is anyone confused? Can I help clarify? If you find yourself unsure about all three — take notes, take notes, and take notes.Meeting minutes and your own notes will help you retain details and follow up later for deeper understanding. 3. Build Strong Foundations Whether you’re a Comtor, BA, or PO, a solid foundation in product knowledge, business logic, and basic technical understanding helps you make better decisions — and lead your team effectively. Don’t get stuck thinking “that’s not my task.” Instead, learn actively by: Reading about technical keywords used in your project.Redrawing the business flow yourself to truly understand it.Asking devs, QCs, PTLs, and clients for their perspectives.Finding a technical advisor who can review your understanding and answer your tech-related questions. Every time you’re about to forward a message, pause for a minute — dig a little deeper.Each pause adds to your knowledge and analytical mindset. These small daily efforts will sharpen your skills and confidence — helping you grow not only as a professional BA, but also as a potential Project Leader who truly adds value to the team.

          31/10/2025

          156

          BA Team

          Knowledge

          +2

          • Others
          • Our culture

          How to Step Out of the “Forwarder” Shadow?

          31/10/2025

          156

          BA Team

          Team Người Việc: Winning with AI-Assisted Development at SupremeTech

          AI

          AI-assisted development

          +0

            How Team Người Việc Won SupremeTech’s AI Hackathon 2025 with AI-Assisted Development and Agile Thinking

            24 hours. 10 teams. Countless lines of code. One team claimed the spotlight and took half of the 100 million VND prize pool. SupremeTech’s first-ever AI Hackathon was more than just a competition, it was a test of endurance, creativity, and teamwork. For one intense day and night, our participants pushed the limits of AI-assisted development, turning raw ideas into functioning prototypes under extreme time pressure. Among them, three teams rose above the rest. Their solutions not only showcased strong technical execution but also revealed how AI hackathon use cases can bring real business value in areas such as customer experience, automation, and data-driven decision-making. These top three use cases highlight the future potential of AI and the passion of SupremeTech’s people to turn vision into reality. Brought home the Top Prize - Team Người Việc stood out for their sharp strategy and teamwork. Their winning project solved a familiar yet complex issue in the tourism industry: managing group travel efficiently while ensuring every participant enjoys a seamless experience. Presented in clear business logic, executed with agile methodology, and powered by AI-assisted development, their solution proved that innovation thrives when technology meets human insight. Introducing the Team: Small but Strong Team Người Việc brought together a crew of four: Hung Dinh, Huy Nguyen, and Dung Nguyen as front-end engineers, and Khanh Nguyen as the business analyst. While other teams had five members, this smaller team turned their size into strength. With Khanh shaping the business logic and user journey, and the three engineers transforming those ideas into a functional product, they created a strong link between business insight and technical execution. Each member brought a distinct perspective: one focused on monetization and business value, another on operational flow, and others on technical quality and user experience. Together, they created a strong team that has both business insight and technical execution. Khanh shared that: “Everyone respected each other’s opinions. We weren’t chasing perfection, we were building something real, something that worked”. The Challenge: Turning Hot and Heavy Topic into Opportunity When the AI Hackathon began, the participating teams didn’t get to choose their challenge. Each team drew a topic randomly from a pool of three, and fate handed team Người Việc a challenge that was both broad and complex: Destination and Experience Management System for Tourism. Instead of seeing it as an obstacle, the team saw great potential in this topic: “It’s actually very close to what SupremeTech does,” one member shared. “Tourism and service coordination are among the industries where our clients face similar pain points. If developed further, this could even become a real product for the company”. For most teams, tackling something this wide in just 24 hours would be overwhelming. But for Người Việc, it became the perfect opportunity to combine business logic, agile thinking, and AI-assisted development into a single solution. Dũng, one of the front-end engineers shared: “We didn’t see it as just a travel problem. It’s a coordination problem that every company faces because of too many people, too little time, and too many things to track.” The Idea: Transforming Tourism Coordination with AI Manual planning and coordination often create time-consuming processes, lack of feedback, and fragmented communication across travel agencies, corporate HR departments, and trip participants. To solve this, Người Việc envisioned an end-to-end platform that connects all stakeholders, from travel agencies and corporate planners to event organizers and trip participants.The system enables users to: Create and customize travel itinerariesConnect directly with travel agencies through a marketplace modelTrack schedules via QR codeProvide instant feedback during the trip. In short, it bridges the gap between demand and supply in hospitality, creating a more transparent, interactive, and seamless travel experience. The Process: From Brainstorming to AI-Assisted Development What set Người Việc apart was their strategic mindset before touching a single line of code. Instead of rushing to use AI tools right-away, the team began with a face-to-face brainstorming session, mapping out what a real group trip looks like from start to finish: from planning and agency communication to real-time updates and user feedback. To validate their ideas, they even called friends working in hospitality to understand pain points from the field such as: how agencies handle client requests, where information gets lost, and what travelers actually expect. Only after this discovery phase, the team moved into design and development. They first created clear user stories and workflows on their own, then applied story-based prompting by feeding those stories into ChatGPT and Copilot to generate database schemas, API endpoints, and code snippets. This structured use of AI helped them align technical output with business logic and speed up development. Their approach became a model of how AI-assisted development and agile methodology can complement each other, keeping logic clear while boosting speed. Their mantra throughout the process was simple yet powerful: Think first, then use AI smartly. This mindset kept their workflow focused, turning AI into a productivity multiplier instead of a shortcut, and became a highlight in their AI hackathon journey.Without a QC member, the team stayed flexible and shared responsibilities across roles. Each member could take on multiple tasks when needed, but they still kept a clear structure in how they worked. The PTL and BA stepped in as real users, testing features and giving feedback from a user’s point of view. After defining their user roles and business logic, Team Người Việc translated their ideas into a working prototype. Their platform acts as a bridge between corporate planners and travel agencies, creating a space where requests, itineraries, and feedback flow seamlessly in real time. The system’s core features included: Trip creation and customization: HR or operation teams can build itineraries, adjust timelines, and submit requests tailored to their needs.Agency collaboration: Travel agencies receive those requests, update details, and negotiate directly through the platform, no more back-and-forth emails or lost messages.Participant tracking: Each trip generates a public QR code, allowing members to follow updates, view schedules, and send instant feedback during the journey.Transparency and engagement: The platform closes the communication loop, giving every stakeholder a clearer view of the process. With these key flows completed, the team delivered a functional MVP, a product with clean logic, smooth handoffs between roles, and enough structure to be reused or scaled for other industries. Modern Tech Stack Built for AI-Driven Innovation To bring their concept to life within 24 hours, Team Người Việc designed a tech stack that was modern, lightweight, and AI-friendly. Every layer from frontend to deployment was chosen to balance speed, scalability, and maintainability. Frontend Layer: Fast and Built for Clarity The team developed the user interface using Next.js 15 to handle both page rendering and API routes. Combined with TypeScript, it provided type safety and consistency across all modules, reducing human errors in the rush of development. For styling and components, they used Tailwind CSS and shadcn/ui, which allowed them to quickly create a clean, responsive design without spending time reinventing basic UI elements. Despite the tight schedule, the frontend still delivered a cohesive experience from trip creation to QR-based tracking, proving that with the right stack, agility doesn’t mean sacrificing structure. Backend Layer: Structured Logic and Data Flow Behind the interface, the team used Prisma ORM to manage the database layer. Its schema-first approach, paired with TypeScript integration, helped them maintain data consistency while iterating rapidly. The backend services were also written in Next.js, utilizing server functions to keep everything unified and easy to deploy. This setup gave the team clear control over their data models and allowed them to focus on the business logic, ensuring that trip creation, feedback collection, and participant interactions all flowed smoothly without manual handling. Infrastructure & Deployment: Stability under Pressure To keep their development-to-demo pipeline fast and reliable, Người Việc deployed their system on AWS using Dokploy - a self-hosted CI/CD solution that automates Docker-based deployments. This environment allowed them to push code, test changes, and release updates seamlessly without dependency conflicts. By using Docker containers, they replicated production conditions from the start, ensuring that the MVP remained stable and demo-ready throughout the hackathon. The setup was simple enough for rapid iteration yet robust enough to be scaled for real client use. AI Tools: A Smarter, Not Faster, Way to Build AI played a key role in the team’s workflow but only after the foundation was set.ChatGPT acted as their assistant for ideation and logic design, helping refine user stories, define acceptance criteria, and clarify user flows. Meanwhile, GitHub Copilot served as their pair programmer, generating clean snippets, suggesting improvements, and handling repetitive coding tasks. Instead of using AI as a shortcut, Người Việc used it as an accelerator by integrating it at the right moments to enhance productivity while keeping control of direction and logic. >>> Read more related articles: AI-Assisted Ecommerce Solution Wins Third Place at SupremeTech AI Hackathon 2025How Human Intelligence and AI Capabilities Can Redefine Software Development | Featuring The 1st Runner-Up of SupremeTech AI Hackathon 2025 Judges’ Feedbacks Business Perspective From a business perspective, the judges saw Team Người Việc as a perfect example of practicality and vision. Their solution showed how AI-driven development can address real client needs, especially in industries like travel and hospitality. However, the judges also provided constructive feedback for future improvement. While the idea covered a broad scope from sales to operations, they suggested narrowing the focus to one specific stage in the travel management cycle. By doing so, the solution could achieve higher feasibility and faster adoption in real-world scenarios. The judges also encouraged documenting the team’s AI-assisted project management workflow as a reference for future AI hackathon journeys within SupremeTech. The final presentation showcased all the best qualities of their teamwork. The judges highlighted Người Việc’s clear storytelling, strong time management, and smooth demo delivery that effectively illustrated how their system worked. The team’s confident, structured presentation left a lasting impression and perfectly captured the spirit of SupremeTech’s AI Hackathon. Technical and Engineering Perspective From a technical point of view, the judges recognized Người Việc as a team that combined strong engineering skill with thoughtful use of modern tools. They developed their product on a well-defined code base with clear development standards, following a structured flow from analysis and design to implementation, which is remarkable under the time pressure of a 24-hour hackathon. The highlight of their approach was the story-based prompting technique, which kept the project’s logic coherent from start to finish. By crafting prompts around user stories rather than isolated tasks, the team ensured that every AI-generated piece of code served a real business purpose. This balance between automation and human reasoning became one of the defining features of their success. Teamwork: Staying Calm When Things Went Wrong No hackathon story is complete without chaos and Người Việc had their moment too. Just before the final presentation, disaster happened: the team’s slide suddenly became inaccessible because their shared drive was locked by the judges. With only minutes left, they borrowed a laptop, rebuilt the slides from scratch, and walked onto the stage calm and composed delivering a confident demo that looked effortless to the audience. The team recalled “After 22 hours of coding, what stayed with us wasn’t exhaustion. It was that moment when everyone looked at each other and said: We'll make it work, no matter what.” Voices from the Winners For Team Người Việc, winning the hackathon was not just about the prize, it was about learning how humans and AI can truly collaborate. Reflecting on the experience, Dũng shared: “We realized that AI isn’t just a tool, it’s a real teammate, if you know how to ‘talk’ to it. Each team used AI differently: some for brainstorming, some for UI design, others for presentation. But the prompts we gave were never the same, and that’s why the results were so different. AI only shows its real power when people know how to guide it.” As winners, the team also offered advice for those who will join future hackathons: “Prepare everything you can beforehand: boilerplate code, deployment setup, tools, and your fighting spirit. Once the event starts, every minute counts. And above all, trust your team” Conclusion Team Người Việc proved that real innovation is not only about technology, but about people working together with purpose. By combining business insight, teamwork, and the smart use of AI, they turned a difficult 24-hour challenge into a real achievement. For SupremeTech, this victory is more than just a competition result. It’s a reminder that the future of development starts with clear thinking, strong teamwork, and the courage to explore new ways of building with AI. Appendix: 1. How the Team Applied AI Throughout the Project StageApproachAI Application/ Tools UsedAnalysis & DesignThe whole team brainstormed together, role-playing as real users to map out workflows and features.No AI used — this was the most human-driven stage focused on critical thinking.User Story writingConverted rough ideas into logical workflows, defined goals, and acceptance criteria.ChatGPT acted as a virtual BA, turning brainstorm notes into professional User Stories and Acceptance Criteria.Coding (User Story Based)Developers implemented each User Story while communicating directly with the AI assistant for suggestions and refactoring.GitHub Copilot served as a coding partner, reading stories, suggesting code, refining syntax, and accelerating implementation.Testing & ReleaseThe PTL and BA acted as real users to test the product, identify bugs, and refine the UX before release.No AI used — manual testing for real-user validation. 2. Team Tech Stack LayerTech StackFrontend & Backend (Fullstack)Next.js 15 (App Router)UI Libraryshadcn/ui + TailwindCSSAI AssistantChatGPT + GitHub CopilotInfra / DeployAWS + Dokploy 📩 Read more articles about us here: SupremeTech’s Blog

            22/10/2025

            289

            Quy Huynh

            AI

            +1

            • AI-assisted development

            How Team Người Việc Won SupremeTech’s AI Hackathon 2025 with AI-Assisted Development and Agile Thinking

            22/10/2025

            289

            Quy Huynh

            Customize software background

            Want to customize a software for your business?

            Meet with us! Schedule a meeting with us!