Skip to content

Instantly share code, notes, and snippets.

@rmpestano
Last active October 28, 2015 18:49
Show Gist options
  • Save rmpestano/db8db6ea97bd06591aec to your computer and use it in GitHub Desktop.
Save rmpestano/db8db6ea97bd06591aec to your computer and use it in GitHub Desktop.
A simple component for building "ifless" assertions
package com.myapp.util;

import java.io.Serializable;
import java.util.*;


/**
 * Created by rafael-pestano on 15/03/2015.
 *
 * A simple utility component for building "ifless" assertions
 *
 */
/**
 * Created by rafael-pestano on 26/06/2015.
 * utilitario para "ifless" assertions
 *
 */
public class Assert implements Serializable {

  private List<Boolean> assertions = new ArrayList<>();

  private static Assert instance;

  private Assert(){

  }

  public static synchronized Assert getInstance(){
    if(instance == null){
      instance = new Assert();
    }
    instance.assertions.clear();
    return instance;
  }

  /**
   * reset queued assertions
   */
  public Assert reset() {
    assertions.clear();
    return instance;
  }

  /**
   * verifies if there is FALSE asserions
   *
   * @return true if there is at least a FALSE assertion queued
   */
  public boolean hasFalse() {
    return assertions.contains(Boolean.FALSE);
  }

  /**
   * verifies if there is FALSE assertions
   *
   * @param reset
   *          flag used to clear queued assertions
   * @return true if there is at least a FALSE assertion queued
   */
  public boolean hasFalse(boolean reset) {
    boolean result = hasFalse();
    if (reset) {
      reset();
    }
    return result;
  }

  /**
   * verifies if there is TRUE asserions
   *
   * @return true if there is at least a FALSE assertion queued
   */
  public boolean hasTrue() {
    return assertions.contains(Boolean.TRUE);
  }

  /**
   * verifies if there is TRUE assertions
   *
   * @param reset
   *          flag used to clear queued assertions
   * @return true if there is at least a FALSE assertion queued
   */
  public boolean hasTrue(boolean reset) {
    boolean result = hasTrue();
    if (reset) {
      reset();
    }
    return result;
  }

  /**
   * verifies if there is no TRUE asserions queued
   *
   * @return true if there is at least a FALSE assertion queued
   */
  public boolean allFalse() {
    return !assertions.contains(Boolean.TRUE);
  }

  /**
   * verifies if there is no TRUE asserions queued
   *
   * @param reset
   *          flag used to clear queued assertions
   * @return true if there is at least a FALSE assertion queued
   */
  public boolean allFalse(boolean reset) {
    boolean result = allFalse();
    if (reset) {
      reset();
    }
    return result;
  }

  /**
   * verifies if there is no FALSE assertion queued
   *
   * @return true if there is is no FALSE assertion
   */
  public boolean allTrue() {
    return assertions.isEmpty() || !assertions.contains(Boolean.FALSE);
  }

  /**
   * verifies if there is no FALSE assertions queued
   *
   * @param reset
   *          flag used to clear queued assertions
   * @return true if there is no FALSE assertion queued
   */
  public boolean allTrue(boolean reset) {
    boolean result = allTrue();
    if (reset) {
      reset();
    }
    return result;
  }


  /**
   * queue TRUE assertion when given expression evaluates to TRUE, queue FALSE
   * otherwise
   */
  public Assert isTrue(boolean expression) {
    instance.assertions.add(expression);
    return instance;
  }

  /**
   * queue TRUE assertion when given expression evaluates to FALSE, queue FALSE
   * otherwise
   */
  public Assert notTrue(boolean expression) {
    assertions.add(!expression);
    return instance;
  }

  /**
   * queue TRUE assertion when given objects are equal, queue FALSE otherwise
   */
  public <T extends Object> Assert equals(T obj1, T obj2) {
    assertions.add(obj1.equals(obj2));
    return instance;
  }

  /**
   * queue TRUE assertion when given objects are not equal, queue FALSE
   * otherwise
   */
  public <T extends Object> Assert notEquals(T obj1, T obj2) {
    assertions.add(!obj1.equals(obj2));
    return instance;
  }

  /**
   * queue TRUE assertion when given objects is null, queue FALSE otherwise
   */
  public  Assert isNull(Object object) {
    assertions.add(object == null);
    return instance;
  }

  /**
   * queue TRUE assertion when given objects is NOT null, queue FALSE otherwise
   */
  public Assert notNull(Object object) {
    assertions.add(object != null);
    return instance;
  }

  /**
   * queue TRUE assertion when given text has length, queue FALSE otherwise
   */
  public Assert hasLength(String text) {
    assertions.add(text != null && text.length() > 0);
    return instance;
  }

  /**
   * queue TRUE when given text has any character, queue FALSE otherwise
   */
  public Assert hasText(String text) {

    if ((text == null || text.length() == 0)) {
      assertions.add(Boolean.FALSE);
      return instance;
    }
    int strLen = text.length();
    for (int i = 0; i < strLen; i++) {
      if (!Character.isWhitespace(text.charAt(i))) {
        assertions.add(Boolean.TRUE);
        return instance;// has text
      }
    }
    // if reach here then does not has text
    assertions.add(Boolean.FALSE);
    return instance;
  }

  /**
   * queue TRUE when given text contains the given substring, queue FALSE
   * otherwise
   */
  public Assert contains(String textToSearch, String substring) {
    if (!instance.containsInternal(textToSearch, substring)) {
      assertions.add(Boolean.FALSE);
    } else {
      assertions.add(Boolean.TRUE);
    }
    return instance;
  }

  /**
   * queue TRUE when given text does NOT contains the given substring, queue
   * FALSE otherwise
   */
  public Assert notContains(String textToSearch, String substring) {
    if (instance.containsInternal(textToSearch, substring)) {
      assertions.add(Boolean.FALSE);
    } else {
      assertions.add(Boolean.TRUE);
    }
    return instance;
  }

  /**
   * queue TRUE when given array has elements; that is, it must not be
   * {@code null} and must have at least one element. Queue FALSE otherwise
   */
  public Assert notEmpty(Object[] array) {
    if (array == null || array.length == 0) {
      assertions.add(Boolean.FALSE);
      return instance;
    }
    for (Object element : array) {
      if (element != null) {
        assertions.add(Boolean.TRUE);
        return instance;
      }
    }
    assertions.add(Boolean.FALSE);
    return instance;
  }

  /**
   * Assert that an array has no null elements. Note: Does not complain if the
   * array is empty!
   *
   * <pre class="code">
   * Assert.noNullElements(array, &quot;The array must have non-null elements&quot;);
   * </pre>
   *
   * @param array
   *          the array to hasFalse
   */
  /**
   * queue TRUE when given array has no null elements; Note: Does not queue if
   * the array is empty!
   */
  public Assert notNull(Object[] array) {
    if (array != null) {
      for (Object element : array) {
        if (element == null) {
          assertions.add(Boolean.FALSE);
          return instance;
        }
      }
    }
    assertions.add(Boolean.TRUE);
    return instance;
  }

  /**
   * queue TRUE when given array has at least one not null element; queue FALSE
   * otherwise
   */
  public Assert hasElements(Object[] array) {
    if (instance.hasElementsInternal(array)) {
      assertions.add(Boolean.TRUE);
    } else {
      assertions.add(Boolean.FALSE);
    }
    return instance;
  }

  /**
   * queue TRUE when given collection has elements; that is, it must not be
   * {@code null} and must have at least one element. queue FALSE otherwise
   */
  public Assert notEmpty(Collection<?> collection, String message) {
    if (collection == null || collection.isEmpty()) {
      assertions.add(Boolean.FALSE);
    } else {
      assertions.add(Boolean.TRUE);
    }
    return instance;
  }

  /**
   * Queue TRUE if given Map has entries; that is, it must not be {@code null}
   * and must have at least one entry. Queue FALSE otherwise
   */
  public Assert notEmpty(Map<?, ?> map) {
    if (map == null) {
      assertions.add(Boolean.FALSE);
      return instance;
    }
    if (instance.hasElementsInternal(map.entrySet().toArray())) {
      assertions.add(Boolean.TRUE);
      return instance;
    }
    assertions.add(Boolean.TRUE);
    return instance;
  }

  // internal checks, they not queue assertions

  private boolean hasTextInternal(String text) {
    if ((text == null || text.length() == 0)) {
      return false;
    }
    int strLen = text.length();
    for (int i = 0; i < strLen; i++) {
      if (!Character.isWhitespace(text.charAt(i))) {
        return true;// has text
      }
    }
    // if reach here then does not has text
    return false;
  }

  private boolean containsInternal(String textToSearch, String substring) {
    if (textToSearch == null || substring == null) {
      return false;
    }
    // if blank
    if (textToSearch.trim().equals("") || substring.trim().equals("")) {
      return false;
    }

    return textToSearch.contains(substring);
  }

  private boolean hasElementsInternal(Object[] array) {
    if (array == null || array.length == 0) {
      return false;
    }
    for (Object element : array) {
      if (element != null) {
        return true;
      }
    }
    return false;
  }

}

Using it:

public void aMethod(Foo foo){
  boolean and = Assert.getInstance().
  notNull(foo). //hasText also test notNull otherwise we would end up with a NPE in hasText
  hasText(foo.aProperty).
  isFalse(someLogic()).
  allTrue();//allTrue return true if there is no false assertion enqueued

 if(isOk){
 ....
 }

 //same as
  if(foo != null && "".equals(foo.aProperty) && !someLogic()){
    ...
  }

  boolean or = Assert.getInstance().
  isEmpty(foo.array).isFalse(someLogic()).hasFalse();


  //same as
  if(foo.array != null || someLogic()){
    ...
  }


}

another version

package util;

/**
 * Created by rafael-pestano on 26/06/2015. assertions utils
 *
 */
public class Assert implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private Assert() {

    }

    /**
     * @return TRUE assertion when given objects is not null, FALSE otherwise
     */
    public static boolean has(Object object) {
        return object != null;
    }

    /**
     * @return TRUE when given text has any character, FALSE otherwise
     */
    public static boolean has(String text) {
        if (text != null && text.trim().length() > 0) {
            return true;
        }
        return false;
    }

    /**
     * @return TRUE when given text contains the given substring, FALSE otherwise
     */
    public static boolean contains(String textToSearch, String substring) {
        if (textToSearch != null && textToSearch.contains(substring)) {
            return true;
        }
        return false;
    }

    /**
     * @return TRUE when given array has elements; that is, it must not be {@code null} and must
     *         have at least one element. FALSE otherwise
     */
    public static boolean has(Object[] array) {
        if (array == null || array.length == 0) {
            return false;
        }
        for (Object element : array) {
            if (element != null) {
                return true;
            }
        }
        return false;
    }

    /**
     * @return TRUE when given collection has elements; that is, it must not be {@code null} and
     *         must have at least one element. @return FALSE otherwise
     */
    public static boolean has(Collection<?> collection) {
        if (collection != null && !collection.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @return TRUE if given Map has entries; that is, it must not be {@code null} and must have at
     *         least one entry. Queue FALSE otherwise
     */
    public static boolean has(Map<?, ?> map) {
        if (map == null) {
            return false;
        }
        if (has(map.entrySet().toArray())) {
            return true;
        }
        return false;
    }

}

Using it:

import static util.Assert.*

public void aMethod(Foo foo){
  boolean isOk =
  has(foo) &&
  has(foo.aProperty) &&
  has(someLogic());

 if(isOk){
 ....
 }
@rmpestano
Copy link
Author

using it:

public void aMethod(Foo foo){
  assertion.notNull(foo).
  hasText(foo.aProperty).isFalse(someLogic()).
  thowIfAnyFalse("error message")
  //if nothing is thown you can still asserting
  .isEmpty(foo.array).isFalse(someLogic()).thowIfAllFalse("another message");

  //same as
  if(foo == null || "".equals(foo.aProperty) || !someLogic()){
     throw new RuntimeException("error message");
  }

  if(foo.array != null && foo.array.isEmpty() && !someLogic()){
    throw new RuntimeException("another message");
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment