Skip to content
This repository was archived by the owner on Aug 30, 2022. It is now read-only.

Files

Latest commit

 

History

History
453 lines (396 loc) · 7.6 KB

LANG.md

File metadata and controls

453 lines (396 loc) · 7.6 KB

Tenshi's Java Language Extensions

Tenshi uses a number of extensions to make the java code more readable and to avoid repetitive code.

Function Interfaces

Tenshi includes multiple classes providing generic function interfaces (eg. for callbacks):

Return/Parameters No Parameters 1 Parameter 2 Parameters
Without Return Method Consumer BiConsumer
With Return Action Function BiFunction

LanguageUtils

The main extension class.
This class is 'historically grown' and may require some cleanup...

Usage

import static io.github.shadow578.tenshi.lang.LanguageUtils.*;


listOf

Creates a list of values.

Instead of

ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
...

Write

ArrayList<String> list = listOf("1", "2", ...);

Also works to join collections together:

Instead of

ArrayList<String> list = new ArrayList<>();
list.addAll(listA);
list.addAll(listB);
...

Write

ArrayList<String> list = listOf(listA, listB, ...);

isNull/ notNull

Null check operation

Instead of

if(obj == null)
    // obj is null
...
if(obj != null)
    // obj is not null

Write

if(isNull(obj))
    // obj is null
...
if(notNull(obj))
    // obj is not null

with

Run a function with a null- checked parameter

Instead of

if(obj != null)
{
    function(obj);
}

Write

with(obj, p -> function(obj));

usage with default parameter value

Instead of

if(obj != null)
{
    function(obj);
}
else
{
    function("fallback");
}

Write

with(obj, "fallback", p -> function(p));

with return value

Instead of

Object result = null;
if(obj != null)
{
    result = function(obj);
}

Write

Object result = withRet(obj, p -> function(p));

with Default Value

Object result = new Object();
if(obj != null)
{
    result = function(obj);
}

Write

Object result = withRet(obj, new Object(), p -> function(p));

conversion of parameter to string

Instead of

if(obj != null)
{
    function(obj.toString());
}
else
{
    function("fallback");
}

Write

withStr(obj, "fallback", p -> function(p));

elvis

Imitates the elvis (?:) parameter in other languages

Instead of

String s = x != null ? x : "foo";

Write

String s = elvis(x, "foo");

elvisEmpty

Similar to the elvis operator, but for strings. Check if the string is null or empty.

Instead of

String s = (x != null && !x.isEmpty()) ? x : "foo";

Write

String s = elvisEmpty(x, "foo");

nullSafe

Run a function swallowing all NullPointerExceptions. Warning: this does not differentiate NullPointerExceptions because a variable was null and ones because of some other error => this may swallow unwanted / unexpected Exceptions, so handle with care.

Instead of

String result = null;
if(response != null)
{
    if(response.data != null)
    {
        if(response.data.node != null)
        {
            ...
            result = function(response.data.node);
        }
    }
}

Write

String result = function(nullSafe(response, p -> p.data.node));

By default, nullSafe returns null if a NullPointerException is thrown. But a default value can be assigned too.

fmt

Shorthand for String.format() AND NumberFormat.getInstance().format() depending on parameters.
The shorthand for String.format() also accepts android string resources

String.format

Instead of

String s1 = String.format("test %d", 2);

Write

String s = fmt("test %d", 2);

AND

Instead of

String s1 = String.format(this.getString(R.string.some_string), 2);

Write

String s = fmt(this, R.string.some_string, 2);

NumberFormat.format

Instead of

String s1 = NumberFormat.getInstance().format(2000);

Write

String s = fmt(2000);

concat

Concatenate multiple strings, without delimiter

Instead of

String s = "abc" + someStringVariable + "ghi";

Write

String s = concat("abc", someStringVariable, "ghi")

join

Concatenate multiple strings, with delimiter Instead of

String s = s1 + ", " + s2 + ", " + ...;

Write

String s = join(", ", s1, s2, ...);

also works with collections

Instead of

List<SomeDataClass> list = ...;
StringBuilder builder = new StringBuilder();
for(SomeDataClass item : list)
{
    builder.append(item.someValue).append(", ");
}

String s = builder.toString();

Write

List<SomeDataClass> list = ...;
String s = join(", " list, itm -> itm.someValue);

nullOrEmpty

Check if a string or list is null OR empty

Instead of

if(someString != null && !someString.isEmpty())
{
    // do something
}

Write

if(!nullOrEmpty(someString))
{
    // do something
}

nullOrWhitespace

Check if a string is null, empty, or only whitespace

Instead of

if(someString != null && !someString.isEmpty() && !someString.trim().isEmpty())
{
    // do something
}

Write

if(!nullOrWhitespace(someString))
{
    // do something
}

foreach

As the name implies, a foreach loop. However, this one does allow the use of null collections.

Instead of

List<String> someList = ...
if(someList != null)
{
    for(String itm : someList)
    {
        // do something
    }
}

Write

List<String> someList = ...;
foreach(someList, itm -> {
    // do something
})

Or, if you need the index as well

Instead of

List<String> someList = ...
if(someList != null)
{
    for(int i = 0; i < someList.size(); i++)
    {
        String itm = someList.get(i);
        // do something
    }
}

Write

List<String> someList = ...;
foreach(someList, (itm, i) -> {
    // do something
})

where

filters a collection using a function

Usage:

List<String> someList = ...;
List<String> filtered = where(someList, (s) -> {
    if(...){
        // keep this item
        return true;
    }
    else{
        // remove this item
        return false;
    }
});

collect

Collects the results of a function call for all items in a collection

Instead of

List<MyNiceObject> someList = new List<>();
List<String> results = new List<>();
for(MyNiceObject obj : someList)
{
    results.add(obj.function())
}

Write

List<String> results = collect(someList, obj -> obj.function());

repeat

Repeats a function, returning the return values to a collection or array

Instead of

List<String> someList = new List<>();
for(int i = 0; i < 11; i++)
{
    someList.add(function(i))
}

Write

List<String> someList = repeat(0, 10, i -> function(i));

cast

Safely cast a object to a type. If the cast fails (object to cast is null or incompatible types), null is returned. Also supports defining a default value to return instead of null.

Instead of

ClassB casted = null;
if(obj != null && obj instanceof ClassB)
{
    casted = (ClassB)obj;
}

Write

ClassB casted = cast(obj);

with default value

Instead of

ClassB casted = new ClassB();
if(obj != null && obj instanceof ClassB)
{
    casted = (ClassB)obj;
}

Write

ClassB casted = cast(obj, new ClassB());

async

Runs a action on a background thread, optionally with a callback that is called on the main (ui) thread.

Instead of using AsyncTask (now deprecated), just do:

async(() -> someLongFunction("this is a parameter"));

Or, with a callback to the ui thread

async(() -> someLongFunction("this is a parameter"), r -> Log.i("Test", "async return is " + r));