Giter Club home page Giter Club logo

tryme's Introduction

TryMe

A try/catch alternative when you don't need an explicit catch.

We've all been there, neglecting the catch in try/catch. Maybe your use case only needs the same redundant task if an exception is thrown (like logging). Or maybe your catch only needs to return a default value if ever hit. Or maybe your catch... does absolutely nothing. For all these cases, TryMe is the perfect alternative. TryMe allows for less code to be written, and less redundant code to be added.


Before when using Try/Catch Try.me (Equivalent to Try/Catch)
val arr = arrayOf("test", "array")

//Ex 1: try code, no return
try {
    val elm = arr[5]
    exampleFun(elm)
} catch (e: Exception) {
    Log.d("Tag", e.message, e)
}

//Ex 2: set from array or null
val arrValueOrNull: String? =
    try {
        arr[5]
    } catch (e: Exception) {
        Log.d("Tag", e.message, e)
        null
    }

//Ex 3: set from array or "fail"
val arrValueOrDefault: String =
    try {
        arr[3]
    } catch (e: Exception) {
        Log.d("Tag", e.message, e)
        "fail"
    }
val arr = arrayOf("test", "array")

//Optional, set once, catchAction empty by default
Try.GlobalConfig.catchAction = {
    Log.d("Tag", it.message, it)
}

//Ex 1: try code, no return
Try.me {
    val elm = arr[5]
    exampleFun(elm)
}

//Ex 2: set from array or null
val arrValueOrNull: String? =
    Try.me {
        arr[5]
    }

//Ex 3: set from array or "fail"
val arrValueOrDefault: String =
    Try.me(defaultReturnValue = "fail") {
        arr[5]
    }


For "I don't care that an exception was thrown, just keep going" uses.

  • No setup code required before using TryMe. Just call the static Try.me() function with your block of code and TryMe handles the rest!
    • Optionally, a defaultReturnValue argument can be included where that value is returned only if an exception is caught.
  • Rather than a mandatory catch block, optionally and just once, create a global catch block (see GlobalConfig) that will only be called when TryMe throws an exception anywhere in your app!
  • No code compromise using TryMe over the standard try. The same code that can handled in a try can be handled in TryMe!

Table of Contents

Examples

Example 1: No Return, just TryMe!

The following tries to take a value from the String array, arr, and pass it to a function. If an ArrayIndexOutOfBoundsException is thrown, exampleFun() is not called, Try.GlobalConfig.catchAction is called, then the program continues without crashing.

Try.me {
    val elm = arr[5]
    exampleFun(elm)
}

Example 2: Set value or null

The following tries to take a value from the String array, arr, to return it and set arrValueOrNull with that value. Since defaultReturnValue was not passed into TryMe, if an ArrayIndexOutOfBoundsException is thrown, Try.GlobalConfig.catchAction is called first, then null will be returned from TryMe setting arrValueOrNull.

val arrValueOrNull: String? =
    Try.me {
        arr[5]
    }

Example 3: Set value or default

The following tries to take a value from the String array, arr, to return it and set arrValueOrDefault with that value. Because a non-null defaultReturnValue was passed in, the set type for arrValueOrDefault is never null. If an ArrayIndexOutOfBoundsException is thrown, Try.GlobalConfig.catchAction is called first, then the passed value "failed" will be returned from TryMe setting arrValueOrDefault.

val arrValueOrDefault: String =
    Try.me(defaultReturnValue = "failed") {
        arr[5]
    }

Syntax

Main Syntax

Usage is simply calling the static Try.me() function passing your block of code (and optionally a default return value):

  • defaultReturnValue - T / Optional (Defaults to inferred type passed in. T? if undefined)
    • When an exception is caught calling Try.me, Try.GlobalConfig.catchAction is always called first, then the passed defaultReturnValue will be returned. When undefined, null is returned which also changes the TryMe return type to nullable.
  • attempt - () -> T / Required
    • The block of code you wish to have TryMe run and handle exceptions caught. Same code can be used here as would in a standard try.

See Examples section for code using these arguments.

Global Settings

Try.GlobalConfig has all the public configurable settings (currently just one) that can be updated anytime during runtime. If any are intended to be updated, it is recommended to do so as early as possible (like in your main activity's OnCreate()).

The following are the settings set to their default values.

  • /**
     * Only called when Try.me throws an exception (allowing for the same redundant code to be called everywhere Try.me is used).
     * By default does nothing.
     * Reassigning Example: Try.GlobalConfig.catchAction = { Log.d("TryMeCaught", it.message, it) }
     */
    Try.GlobalConfig.catchAction = {}

Installation

Install with AAR and gradle (Local)

  1. Download the latest tryme.aar.
  2. Move tryme.aar to your project's libs directory (Example: YourProject/app/libs/).
  3. In your build.gradle, add only one of the following to your dependencies { }:
  • // adds only tryme.aar
    implementation fileTree(dir: "libs", include: ["tryme.aar"])
    
    // OR
    
    // adds all .aar files in your libs directory.
    implementation fileTree(dir: "libs", include: ["*.aar"]) 
  1. Sync gradle successfully.
  2. Done! Your Android project is now ready to use Try Me. Go to Examples or Syntax for Try Me usage!

Install with gradle (Remote)

Coming soon!


Versioning

  • SemVer is used for versioning.
  • Given a version number MAJOR . MINOR . PATCH
    1. MAJOR version - Incompatible API changes.
    2. MINOR version - Functionality added in a backwards-compatible manner.
    3. PATCH version - Backwards-compatible bug fixes.

License

Try Me created by Adam Steinberg of DIGIDEMIC, LLC

Copyright 2023 DIGIDEMIC, LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

tryme's People

Contributors

digidemic avatar

Stargazers

Matthew L. Sawyer avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.