All authors

Claude Skills by HoangNguyen0403
github.com/HoangNguyen04031,434 skills30 installs1,975 views
- Ios NetworkingCommon iOS networking anti-patterns to avoid: - Building URLs with string interpolation instead of `URLComponents` and `URLQueryItem` - Doing JSON parsing manually with `JSONSerialization` when `Codable` is safer and cleaner - Skipping timeout configuration and letting requests hang too long - Updating UI from background threads instead of hopping back to the main actor - Scattering networking code across view controllers instead of keeping a dedicated client/service layer - Ignoring HTTP sta...Votes: 0GitHub stars: 549
- Ios NotificationsUse Apple’s `UserNotifications` framework end to end and structure it around four pieces: 1. Prime before prompting Explain why notifications are useful before showing the system permission dialog. Then request authorization with `.alert`, `.badge`, and `.sound`. 2. Set up the notification center delegate Make your app delegate or notification manager conform to `UNUserNotificationCenterDelegate`, and assign: `UNUserNotificationCenter.current().delegate = self` This is what enables foreground...Votes: 0GitHub stars: 549
- Ios NotificationsCommon iOS notification anti-patterns to avoid: - Requesting notification permission unconditionally on first launch, before explaining the value to the user. - Failing to implement `UNUserNotificationCenterDelegate`, which breaks proper foreground presentation and tap handling. - Not using the `UserNotifications` framework consistently for notification handling. - Forgetting to register for remote notifications in `AppDelegate` when using APNs. - Neglecting badge management, especially leavi...Votes: 0GitHub stars: 549
- Ios NotificationsHere’s a quick-start example for iOS notifications using `UserNotifications` and APNs. ```swift import UIKit import UserNotifications @main class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { let center = UNUserNotificationCenter.current() center.delegate = self // Ideally show an in-ap...Votes: 0GitHub stars: 549
- Ios PerformanceStart by profiling, not guessing. For iOS performance best practices: - Use Instruments regularly: - Time Profiler for CPU hotspots and main-thread stalls - Allocations for memory growth - Leaks for retain cycles and leaked objects - Keep scrolling views cheap: - Always reuse cells with `dequeueReusableCell` - Keep `cellForRowAt` lightweight - Avoid expensive layout, decoding, or transformation work during scrolling - Move heavy work off the main thread: - Parsing - Encryption - Image process...Votes: 0GitHub stars: 549
- Ios PerformanceCommon iOS performance anti-patterns to avoid: - Doing heavy work on the main thread, like JSON parsing, image decoding, encryption, or large computations. - Keeping `cellForRowAt` or `cellForItemAt` heavy instead of using lightweight configuration with reusable cells. - Not using `dequeueReusableCell`, which increases allocation and scrolling cost. - Relying on uncached remote images in scrolling lists. - Manually clearing caches aggressively instead of letting the system respond to memory p...Votes: 0GitHub stars: 549
- Ios PerformanceQuick start: 1. Open Instruments and run Time Profiler to find CPU hot spots, then run Allocations and Leaks to catch memory growth and retain cycles. 2. Keep scrolling views cheap: use `dequeueReusableCell`, avoid heavy work in `cellForRowAt`, and cache remote images with something like Kingfisher or SDWebImage. 3. Move expensive parsing, formatting, and crypto off the main thread with GCD or Swift concurrency. 4. Use Xcode Analyze and treat warnings as errors in Release to catch issues earl...Votes: 0GitHub stars: 549
- Ios PersistenceUse the storage tier based on the data: - SwiftData if you target iOS 17+ - Core Data if you need older iOS support or a mature persistence stack - Keychain or other secure storage for tokens, credentials, and sensitive PII - UserDefaults only for tiny simple preferences like flags or onboarding state For a modern app, I’d default to SwiftData. Define your entities with `@Model`, attach a `ModelContainer` at the app boundary, and read/write through `modelContext`. ```swift import SwiftData im...Votes: 0GitHub stars: 549
- Ios PersistenceUse the container that matches your persistence tier: - SwiftData on iOS 17+: configure a `ModelContainer` and keep it on the main actor. - Core Data for older apps: configure an `NSPersistentContainer`. SwiftData example: ```swift import SwiftData @Model final class Note { var title: String init(title: String) { self.title = title } } @MainActor final class PersistenceController { let container: ModelContainer init(inMemory: Bool = false) throws { let config = ModelConfiguration(isStoredInMe...Votes: 0GitHub stars: 549
- Ios PersistenceThe main anti-patterns in iOS persistence are: - Doing heavy I/O on the main `viewContext` instead of using a private or background context - Using string-based predicates instead of typed KeyPaths or generated helpers - Omitting an explicit merge policy, which can cause conflict-resolution bugs - Storing sensitive data like tokens or PII in `UserDefaults` instead of secure storage - Using `UserDefaults` as a general database instead of limiting it to small flags and preferencesVotes: 0GitHub stars: 549
- Ios SecurityFor iOS security best practices, focus on a few non-negotiables: - Store tokens, credentials, and PII in the Keychain using `SecItemAdd`, `SecItemUpdate`, and `SecItemDelete` with `kSecClassGenericPassword`. Do not store secrets in `UserDefaults`. - Use biometrics through `LocalAuthentication` and `LAContext`. Check `canEvaluatePolicy` before prompting, and handle cases like `userCancel` and `authenticationFailed`. - Protect files written to disk with `Data.WritingOptions.completeFileProtecti...Votes: 0GitHub stars: 549
- Ios SecurityCommon iOS security anti-patterns to avoid: - Storing tokens, passwords, or PII in `UserDefaults` instead of Keychain (`SecItemAdd` / `SecItemUpdate`). - Skipping biometric prechecks and error handling, such as not calling `canEvaluatePolicy` first or ignoring `LAError` cases like `userCancel` and `authenticationFailed`. - Writing sensitive files without iOS data protection, instead of using options like `.completeFileProtection`. - Disabling App Transport Security broadly to make networking ...Votes: 0GitHub stars: 549
- Ios SecurityHere’s a quick-start iOS security example that covers secure token storage, biometric unlock, and protected file writes: ```swift import Foundation import LocalAuthentication import Security enum SecureStore { static func saveToken(_ token: String, account: String = "authToken") throws { let data = Data(token.utf8) let query: [String: Any] = [ kSecClass as String: kSecClassGenericPassword, kSecAttrAccount as String: account, kSecValueData as String: data ] SecItemDelete(query as CFDictionary)...Votes: 0GitHub stars: 549
- Ios State ManagementFor iOS, I’d choose the state approach based on platform support: - Use `@Observable` for modern SwiftUI on iOS 17+. - Use Combine with `@Published` when you need UIKit support or broader OS compatibility. A solid pattern is unidirectional data flow: - Define an `Input` enum for user/system events. - Expose an `Output` struct or a single `ViewState` enum for UI state. For example, prefer a single state model like: - `.loading` - `.success(data)` - `.error(error)` Important practices: - Keep U...Votes: 0GitHub stars: 549
- Ios State ManagementCommon iOS state management anti-patterns include: - Mutating UI state off the main thread instead of using `@MainActor` or delivering updates on the main queue. - Letting Combine subscriptions leak by not storing them in `Set<AnyCancellable>`. - Calling `objectWillChange.send()` manually when `@Published` or `@Observable` should drive updates automatically. - Splitting view state across many loose booleans and optionals instead of using one explicit state model such as `.loading`, `.success`...Votes: 0GitHub stars: 549
- Ios State ManagementRepresent view state as a single exhaustive type, usually a `ViewState` enum, so the UI can switch over every case explicitly. ```swift enum ViewState { case loading case success([Item]) case error(String) } ``` Then expose that state from a ViewModel using the observation system that fits your app: - Use `@Observable` for modern SwiftUI on iOS 17+. - Use `ObservableObject` with `@Published` for older SwiftUI or Combine/UIKit setups. A solid pattern is unidirectional data flow: - `Input`: use...Votes: 0GitHub stars: 549
- Ios SwiftuiOn iOS 17+, the rule of thumb depends on whether your view model uses the new `@Observable` system or the older `ObservableObject` pattern. If your view model is `@Observable`: - Use `@State` when the view owns and creates the view model. - Use a plain stored property like `let viewModel: MyViewModel` when the parent passes it in. - Do not use `@ObservedObject` or `@StateObject` for new `@Observable` models. Example: ```swift @Observable final class ProfileViewModel { var name = "Huy" } struc...Votes: 0GitHub stars: 549
- Ios SwiftuiNot really — heavy calculations inside `body` are a SwiftUI anti-pattern. `body` should stay cheap because SwiftUI may recompute it frequently. If you do expensive work there, you can hurt scrolling, animations, and overall UI responsiveness. Better options: - Move expensive logic into a view model - Precompute values before rendering - Put simple derivations in lightweight computed properties - Trigger async or one-time work outside `body` when appropriate Example: ```swift struct ScoreView:...Votes: 0GitHub stars: 549
- Ios SwiftuiYes. SwiftUI modifiers are applied in order, and each modifier wraps the result of the previous one, so changing the order can change the final layout and appearance. For example: - `.padding().background(.blue)` adds padding first, then paints the background behind the padded area. - `.background(.blue).padding()` paints the background behind the original view first, then adds outer padding around that result. So modifier order matters, especially for layout and visual modifiers. A common gu...Votes: 0GitHub stars: 549
- Ios Ui NavigationFor iOS UI navigation, favor UIKit patterns that are predictable, accessible, and easy to maintain. Use programmatic layout instead of hard-coded frames. Build screens with Auto Layout, preferably `NSLayoutAnchor` or SnapKit, and constrain content to `view.safeAreaLayoutGuide`. For simple vertical or horizontal groups, prefer `UIStackView` so the constraint graph stays small and readable. For navigation, use standard UIKit containers such as `UINavigationController` and keep flows aligned wit...Votes: 0GitHub stars: 549
- Ios Ui NavigationCommon anti-patterns to avoid in iOS UI navigation and layout include: - Hard-coding frames with `CGRect(...)` instead of using Auto Layout. - Ignoring the safe area, which can cause content to clash with notches, bars, or device edges. - Putting complex constraint logic directly inside a view controller instead of using `UIStackView` or custom `UIView` subclasses. - Overloading view controllers with too much UI composition instead of extracting reusable views. - Relying heavily on Storyboard...Votes: 0GitHub stars: 549
- Ios Ui NavigationHere’s a quick-start UIKit navigation example that follows the iOS UI navigation skill: ```swift import UIKit final class HomeViewController: UIViewController { private let detailsButton: UIButton = { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Open Details", for: .normal) button.titleLabel?.font = .preferredFont(forTextStyle: .headline) button.accessibilityLabel = "Open details screen" return button }() override func viewDidL...Votes: 0GitHub stars: 549
- Java Best PracticesRefactor it to a Builder. A constructor with 6 parameters is a strong signal that the call site is carrying too much positional meaning. It is hard to scan, easy to misorder, and usually gets worse over time. In Java, a good default is: - use a builder when an object has 4+ parameters - keep fields private and final where possible - validate required inputs up front - make the built object immutable Example: ```java public final class ReportJob { private final String name; private final Path ...Votes: 0GitHub stars: 549
- Java Best PracticesUsually, yes — returning `Optional<T>` is better than returning `null` when “no result” is a normal, expected outcome. Why: - `Optional` makes the absence explicit in the method signature. - It reduces accidental `NullPointerException`s. - It forces callers to handle the empty case intentionally. Example: ```java public Optional<User> findUserById(String id) { return repository.lookup(id); } ``` Then the caller can do: ```java findUserById(id).ifPresent(this::sendEmail); ``` or ```java User u...Votes: 0GitHub stars: 549
- Java Best PracticesPrefer composition, not inheritance. Adding SMS by extending `EmailNotification` couples two different delivery channels into an `is-a` relationship that usually is not true. SMS is not a kind of email notification; they are both notification strategies. A better Java design is: - define a small interface like `NotificationSender` - implement `EmailNotificationSender` and `SmsNotificationSender` - inject the sender where it is used That keeps responsibilities focused, makes testing easier, an...Votes: 0GitHub stars: 549
- Java ConcurrencyThe modern Java 21 approach is structured concurrency with virtual threads. ```java import java.util.concurrent.StructuredTaskScope; public class ApiService { private final RemoteClient client; public ApiService(RemoteClient client) { this.client = client; } public CombinedResponse fetchAll(String userId) throws Exception { try (var scope = new StructuredTaskScope.ShutdownOnFailure()) { StructuredTaskScope.Subtask<ResponseA> a = scope.fork(() -> client.fetchA(userId)); StructuredTaskScope.Sub...Votes: 0GitHub stars: 549
- Java ConcurrencyUse Virtual Threads if your REST server is mostly I/O-bound and spends a lot of time waiting on databases, HTTP calls, or disk. In Java 21, that is usually the better default for “thousands of concurrent requests” because you can keep the simple thread-per-request model without maintaining a large platform-thread pool. Keep using a traditional thread pool for CPU-bound work, or when you need to strictly cap access to a scarce resource. Virtual threads improve scalability for blocking workload...Votes: 0GitHub stars: 549
- Java ConcurrencyYes — your colleague is right. With Java virtual threads, blocking I/O is usually fine, but blocking while inside a `synchronized` block is a problem because it can pin the virtual thread to its carrier platform thread. That defeats a big part of the scalability benefit of virtual threads. Why this matters: - `synchronized` uses a monitor tied to the OS thread machinery. - If a virtual thread enters `synchronized` and then performs blocking work, the JVM may be unable to unmount it cleanly. -...Votes: 0GitHub stars: 549
- Java LanguageYes—if the DTO is meant to be an immutable data carrier, use a Java 21 `record`: ```java public record UserDto( String id, String name, String email, String department, boolean active ) {} ``` The record provides the canonical constructor, accessors (`id()`, `name()`, etc.), `equals`, `hashCode`, and `toString` automatically. It intentionally has no setters, so use it when the values should not change after construction. If a framework requires JavaBean-style `getX()` methods, setters, or a m...Votes: 0GitHub stars: 549
- Java LanguageUse Java 21 pattern matching for `switch` instead of an `instanceof` chain: ```java static void handle(Object value) { switch (value) { case TypeA a -> a.methodA(); case TypeB b -> b.methodB(); case TypeC c -> c.methodC(); case TypeD d -> d.methodD(); default -> throw new IllegalArgumentException( "Unsupported type: " + value.getClass().getName()); } } ``` The pattern variable (`a`, `b`, etc.) is automatically scoped to its matching case, so no explicit cast is needed. If the values belong to...Votes: 0GitHub stars: 549
- Java LanguageUse a sealed interface to make the allowed variants compiler-checked: ```java public sealed interface Payment permits Card, Cash, Voucher { } public record Card(String last4) implements Payment { } public record Cash() implements Payment { } public record Voucher(String code) implements Payment { } ``` Java 21 can then use an exhaustive pattern-matching switch: ```java static String describe(Payment payment) { return switch (payment) { case Card card -> "Card ending in " + card.last4(); case ...Votes: 0GitHub stars: 549
- Java TestingUse Mockito with JUnit 5’s `MockitoExtension` to inject a mock `UserRepository` into the `UserService`, then stub the repository and verify the interaction. ```java import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import...Votes: 0GitHub stars: 549
- Java TestingUse a JUnit 5 parameterized test. `@ValueSource` is convenient when each case has one input value: ```java import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; class MyCodeTest { @ParameterizedTest @ValueSource(ints = {1, 2, 3, 4, 5}) void calculate_WithInput_ReturnsExpectedResult(int input) { int result = myCode.calculate(input); assertThat(result).isEqualTo(expectedResultFor(input))...Votes: 0GitHub stars: 549
- Java TestingUse Testcontainers: it runs a real, disposable PostgreSQL container for the test suite, so you do not need a separately managed PostgreSQL server. You do need a Docker-compatible runtime such as Docker Desktop, Podman, or Colima. For Maven, add the PostgreSQL JDBC driver and Testcontainers modules. Import the Testcontainers BOM so the module versions stay aligned: ```xml <dependencyManagement> <dependencies> <dependency> <groupId>org.testcontainers</groupId> <artifactId>testcontainers-bom</ar...Votes: 0GitHub stars: 549
- Java ToolingUse the Gradle wrapper and make Spotless part of the normal verification lifecycle. In `build.gradle.kts`, apply a pinned Spotless plugin version and configure Google Java Format: ```kotlin plugins { id("com.diffplug.spotless") version "<approved-version>" } spotless { java { googleJavaFormat() target("src/**/*.java") } } tasks.named("check") { dependsOn("spotlessCheck") } ``` Developers can run `./gradlew spotlessApply` to fix formatting and `./gradlew spotlessCheck` to verify it. Run `./gra...Votes: 0GitHub stars: 549
- Java ToolingUse a checked-in JDK declaration plus a Gradle toolchain so local and CI builds select the same LTS JDK. For example, choose Java 21 and add `.sdkmanrc`: ```text java=21.0.\<vendor-distribution\> ``` You can also use `.java-version` for tools that support it. In `build.gradle.kts`, make the compiler choice explicit: ```kotlin java { toolchain { languageVersion = JavaLanguageVersion.of(21) } } ``` Commit the version file and configure CI to install/use that JDK before invoking `./gradlew`. Kee...Votes: 0GitHub stars: 549
- Java ToolingUse a multi-stage, layered Docker build with an `eclipse-temurin` runtime image. Keep dependency resolution in an earlier layer so source changes do not invalidate it, and avoid an uber/fat jar when layered packaging is available. One practical shape is: ```dockerfile FROM eclipse-temurin:21-jdk AS build WORKDIR /workspace COPY gradlew gradle/ build.gradle.kts settings.gradle.kts ./ RUN ./gradlew dependencies --no-daemon COPY src ./src RUN ./gradlew bootJar --no-daemon FROM eclipse-temurin:21...Votes: 0GitHub stars: 549
- Javascript Best PracticesFor a maintainable JavaScript implementation: - Use `camelCase` for variables and functions, `PascalCase` for classes, and `UPPER_SNAKE` for constants. - Keep one main entity per file. Put the public named exports in `index.js`, and order imports as external packages, internal modules, then relative modules. - Throw `Error` objects rather than strings, and handle rejected promises at the boundary that can recover or report them. - Add JSDoc to public APIs, explaining the reason for non-obviou...Votes: 0GitHub stars: 549
- Javascript Best PracticesCommon anti-patterns to avoid in JavaScript include: - Throwing strings or arbitrary values. Throw an `Error` object, and make sure every async operation has deliberate rejection handling. - Defining mutable state on the global object. Keep state inside a module or function instead. - Scattering magic numbers through business logic. Give them descriptive names, such as `const REQUEST_TIMEOUT_MS = 5000`. - Deeply nested conditionals. Validate invalid input early and return or throw before the ...Votes: 0GitHub stars: 549
- Javascript Best PracticesA small, idiomatic starting point is a pure named-exported function with validation, a named constant, and a JSDoc comment: ```js const MAX_NAME_LENGTH = 80; /** * Normalizes a display name so callers receive one predictable representation. * @param {string} value * @returns {string} */ export function normalizeName(value) { if (typeof value !== 'string') { throw new Error('name must be a string'); } const name = value.trim(); if (name.length === 0 || name.length > MAX_NAME_LENGTH) { throw ne...Votes: 0GitHub stars: 549
- Javascript Tooling**Priority: P1 (HIGH).** Implement JavaScript tooling as follows: - **Linting:** Use ESLint with recommended rules and Prettier integration. Fix issues on save. - **Formatting:** Use Prettier, running it on save and before commits. - **Testing:** Use Jest or Vitest. Co-locate tests with source files and enforce more than 80% coverage. - **Build:** Use Vite for applications and Rollup for libraries. - **Pkg Manager:** Choose npm, yarn, or pnpm, and keep versions synchronized across environment...Votes: 0GitHub stars: 549
- Javascript ToolingPriority: P1 (HIGH). Assuming an existing JavaScript project: - No formatting wars: use Prettier consistently; run it on save and commit. - No untested code: use TDD or add post-code tests with Jest/Vitest, co-located and targeting >80% coverage. - No dirty commits: run ESLint and formatting checks before push. - Avoid unsynchronized Pkg Manager versions across `npm`, `yarn`, or `pnpm`. - Avoid mixing build tools unnecessarily: use Vite for apps and Rollup for libraries. - Avoid disabling lin...Votes: 0GitHub stars: 549
- Javascript ToolingPriority: P1 (HIGH). Use ESLint with Prettier; enforce formatting on save and commit. ```bash npm install -D eslint prettier eslint-config-prettier jest ``` `.eslintrc.js` ```js module.exports = { extends: ['eslint:recommended', 'prettier'], rules: { 'no-console': 'warn', 'prefer-const': 'error', }, }; ``` `.prettierrc` ```json { "semi": true, "singleQuote": true, "printWidth": 80 } ``` `jest.config.js` ```js export default { coverageThreshold: { global: { lines: 80 } } }; ``` `package.json` ...Votes: 0GitHub stars: 549
- Kotlin Best PracticesUse `apply` for object configuration and return its receiver, `also` for side effects while returning the receiver, `let` for null checks or mapping and returning the mapped result, `run` for configuration plus a computed result, and `with` to group calls. Limit scope-function nesting to two levels so receiver changes remain readable.Votes: 0GitHub stars: 549
- Kotlin Best PracticesUse the backing-property pattern: `private val _state = MutableStateFlow(initial)` and `val state = _state.asStateFlow()`. The public surface is read-only and mutation stays in the ViewModel; avoid a public `var` and minimize public visibility.Votes: 0GitHub stars: 549
- Kotlin Best PracticesDo not expose `MutableList`. Keep mutable collections private or internal and return `List` or `Map` from repository APIs. This defines ownership and prevents callers from mutating repository state accidentally.Votes: 0GitHub stars: 549
- Kotlin CoroutinesDo not use `GlobalScope`: it leaks and has no lifecycle ownership. Use `viewModelScope` on Android or structured `coroutineScope`, so children are joined and cancelled with their owner; inject dispatchers rather than hardcoding `Dispatchers.IO`.Votes: 0GitHub stars: 549
- Kotlin CoroutinesRun the loop in an owned structured scope and cooperate with cancellation by checking `isActive` or calling `yield()`. Ensure child tasks are joined or awaited, let scope cancellation propagate, clean up on lifecycle termination, and do not use `runBlocking` in production.Votes: 0GitHub stars: 549
- Kotlin CoroutinesInject a dispatcher rather than hardcoding `Dispatchers.IO`, for example via a dispatcher provider passed to the class. Production binds the real dispatcher and tests bind a test dispatcher, letting `withContext` and scopes run deterministically under coroutine test control.Votes: 0GitHub stars: 549
- Kotlin LanguageUse Kotlin null-safety instead of `!!`: ```kotlin val name = user?.name ?: "Unknown" ``` - `?.` safely accesses nullable values. - `?:` (Elvis) supplies a fallback or can throw: ```kotlin val name = user?.name ?: error("User name is required") ``` - Use `requireNotNull(value)` when null indicates invalid input: ```kotlin val name = requireNotNull(user.name) { "User name is required" } ``` Prefer nullable types, safe calls, and Elvis expressions; avoid `!!` in production.Votes: 0GitHub stars: 549