패키지, 저장소 및 앱 카테고리 검색

패키지 상세v2.0.0

either_option

함수형 프로그래밍 개념을 사용한 오류 처리를 위한 간단한 라이브러리

AndroidiOSWebmacOSWindowsLinux
30일 다운로드
570
좋아요
42
Pub 점수
150

패키지 설치

flutter pub add either_option

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

함수형 프로그래밍에서 영감을 받은 가벼운 Dart 라이브러리로, 견고한 오류 처리를 위한 `Either` 타입을 제공합니다. 성공적인 값(`Right`) 또는 오류(`Left`)로 결과를 표현함으로써 안전한 계산을 가능하게 합니다. 이 접근법은 예외를 피하고 코드 내에서 명시적인 오류 관리를 촉진합니다. 비동기 및 함수형 워크플로에서 더 깔끔하고 예측 가능한 제어 흐름을 원하는 개발자에게 이상적입니다. Dart 생태계와 원활하게 통합되며 모든 주요 플랫폼을 지원합니다.

사용 사례

  • 비동기 작업에서의 오류 처리
  • 기능형 스타일의 데이터 처리
  • 안전한 파싱 및 검증
  • try-catch 블록 교체
  • 오류가 발생하기 쉬운 함수 작성
  • 유연한 비즈니스 로직 구축

주요 기능

  • `Either<Left, Right>` 유형을 제공합니다
  • 기능적 조합을 지원합니다
  • 불변이며 타입 안전
  • 최소한의 보일러플레이트
  • async/await와 함께 작동
  • 크로스 플랫폼 호환성

적합한 대상

  • 함수형 프로그래밍 패턴을 사용하는 개발자
  • 오류 안전성을 우선시하는 팀
  • 깨끗한 오류 전파가 필요한 프로젝트
  • Dart 개발자들이 예외를 피하는 방법
  • 재사용 가능하고 조합 가능한 논리를 구축하는 사람들
  • 예측 가능한 상태 전이가 필요한 응용 프로그램

고려 사항

  • 함수형 개념을 이해해야 합니다
  • 초보자에게 학습 곡선이 증가할 수 있음
  • 간단한 오류 사례에는 적합하지 않습니다
  • 명시적인 오류 유형과 함께 사용 제한
  • 다른 FP 유틸리티와 가장 잘 어울림
  • 복잡한 체인에서는 신중한 형식 정렬이 필요합니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

either_option

either_option is a simple library typed for easy and safe error handling with functional programming style in Dart. It aims to allow flutter/dart developpers to use the 2 most popular patterns and abstractions : Either and Option, mainly used in FP language like Scala, Haskell, OCaml,...

Installation

Prerelease versions that support null safety

Package link on pub either_option In your pubspec.yaml dependencies add

   either_option: ^2.0.0

Overview

Either

Either Represents a value of one of two possible types. By convention we put missing or error value in an instance of Left and expected success value in an instance of Right.

For example, we fetch an url from a repository repository to get an User details and use Either<ServerError,User> :

  Future<Either<ServerError, User>> getUser(int id) async {
    final baseUrl = "https://fakerestapi.azurewebsites.net/api/Users/$id";

    final res = await http.get(baseUrl);

    if (res.statusCode == 200) {
      dynamic body = json.decode(res.body);
      User user = User.fromJson(body);
      return Right(user);
    }
    if (res.statusCode == 404)
      return Left(ServerError("This user doesn't exist"));

    return Left(ServerError("Unknown server error"));
  }

So now to consume result we can use for example fold method and say what to do with value :

main() async {
  final Repository repository = Repository();

  final Either<ServerError, User> res = await repository.getUser(3);
  final defaultUser = User(id: 0, username: "ko", password: "ko");
  final userName = res.fold((_) => defaultUser.username, (user) => user.username);
  print(userName); // "User 3"
  
//if res was a Left, print(userName) would give "ko"
}

Option

Option Represents a value of one of two possible types. By convention we consider missing value as an instance of None and expected success value in an instance of Some.

  Future<Option<User>> getUserOpt(int id) async {
    final res = await http.get(baseUrl);
    return Option.cond(
        res.statusCode == 200, User.fromJson(json.decode(res.body)));
  }
  // -----------------------------------------
  main() async {
  final Repository repository = Repository();

  final Option<User> res = await repository.getUserOpt(3);
  final defaultUser = User(id: 0, username: "ko", password: "ko");
  final userName = res.getOrElse(defaultUser).username;
  print(userName); // "User 3"

  //if res was a None, print(userName) would give "ko"
}

Ressources & explanation

Medium article

Features

Functions available :

Option Either
fold :+1: :+1:
map :+1: :+1:
flatMap :+1: :+1:
getOrElse :+1:
orElse :+1:
toLeft :+1:
toRight :+1:
toEither :+1:
Option.empty :+1:
Option.of :+1:
filter :+1:
exists :+1:
contains :+1:
swap :+1:
cond :+1: :+1:

Example

Tests

카테고리

의존성

의존성 목록 1 개

소스 저장소

이 패키지를 사용하는 프로젝트

아직 데이터가 없습니다.