Is there an elegant way to make every method in a class start with a certain block of code?

JavaDesign Patterns

Java Problem Overview


I have a class where every method starts the same way:

class Foo {
  public void bar() {
    if (!fooIsEnabled) return;
    //...
  }
  public void baz() {
    if (!fooIsEnabled) return;
    //...
  }
  public void bat() {
    if (!fooIsEnabled) return;
    //...
  }
}

Is there a nice way to require (and hopefully not write each time) the fooIsEnabled part for every public method in the class?

Java Solutions


Solution 1 - Java

I don't know about elegant, but here is a working implementation using Java's built-in java.lang.reflect.Proxy that enforces that all method invocations on Foo begin by checking the enabled state.

main method:

public static void main(String[] args) {
    Foo foo = Foo.newFoo();
    foo.setEnabled(false);
    foo.bar(); // won't print anything.
    foo.setEnabled(true);
    foo.bar(); // prints "Executing method bar"
}

Foo interface:

public interface Foo {
    boolean getEnabled();
    void setEnabled(boolean enable);

    void bar();
    void baz();
    void bat();

    // Needs Java 8 to have this convenience method here.
    static Foo newFoo() {
        FooFactory fooFactory = new FooFactory();
        return fooFactory.makeFoo();
    }
}

FooFactory class:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class FooFactory {

    public Foo makeFoo() {
        return (Foo) Proxy.newProxyInstance(
                this.getClass().getClassLoader(),
                new Class[]{Foo.class},
                new FooInvocationHandler(new FooImpl()));
    }

    private static class FooImpl implements Foo {
        private boolean enabled = false;

        @Override
        public boolean getEnabled() {
            return this.enabled;
        }

        @Override
        public void setEnabled(boolean enable) {
            this.enabled = enable;
        }

        @Override
        public void bar() {
            System.out.println("Executing method bar");
        }

        @Override
        public void baz() {
            System.out.println("Executing method baz");
        }

        @Override
        public void bat() {
            System.out.println("Executing method bat");
        }

    }

    private static class FooInvocationHandler implements InvocationHandler {

        private FooImpl fooImpl;

        public FooInvocationHandler(FooImpl fooImpl) {
            this.fooImpl = fooImpl;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getDeclaringClass() == Foo.class &&
                !method.getName().equals("getEnabled") &&
                !method.getName().equals("setEnabled")) {

                if (!this.fooImpl.getEnabled()) {
                    return null;
                }
            }

            return method.invoke(this.fooImpl, args);
        }
    }
}

As others have pointed out, it does seem like overkill for what you need if you only have a handful of methods to worry about.

That said, there certainly are benefits:

  • A certain separation of concerns is achieved, because Foo's method implementations don't have to worry about the enabled check cross-cutting concern. Instead, the method's code only needs to worry about what the method's primary purpose is, nothing more.
  • There is no way for an innocent developer to add a new method to the Foo class and mistakenly "forget" to add the enabled check. The enabled check behavior is automatically inherited by any newly added method.
  • If you need to add another cross-cutting concern, or if you need to enhance the enabled check, it's very easy to do so safely and in one place.
  • It is kind of nice that you can get this AOP-like behavior with built-in Java functionality. You are not forced into having to integrate some other framework like Spring, though they can definitely be good options too.

To be fair, some of the downsides are:

  • Some of the implementation code that handles the proxy invocations is ugly. Some would also say that having inner classes to prevent instantiation of the FooImpl class is ugly.
  • If you want to add a new method to Foo, you have to make a change in 2 spots: the implementation class and the interface. Not a big deal, but it's still a bit more work.
  • Proxy invocations are not free. There is a certain performance overhead. For general use though, it won't be noticeable. See here for more information.

EDIT:

Fabian Streitel's comment got me thinking about 2 annoyances with my above solution that, I'll admit, I'm not happy about myself:

  1. The invocation handler uses magic strings to skip the "enabled-check" on the "getEnabled" and "setEnabled" methods. This can easily break if the method names are refactored.
  2. If there was a case where new methods need to be added that should not inherit the "enabled-check" behavior, then it can be pretty easy for the developer to get this wrong, and at the very least, it would mean adding more magic strings.

To resolve point #1, and to at least ease the problem with point #2, I would create an annotation BypassCheck (or something similar) that I could use to mark the methods in the Foo interface for which I don't want to perform the "enabled check". This way, I don't need magic strings at all, and it becomes a lot easier for a developer to correctly add a new method in this special case.

Using the annotation solution, the code would look like this:

main method:

public static void main(String[] args) {
    Foo foo = Foo.newFoo();
    foo.setEnabled(false);
    foo.bar(); // won't print anything.
    foo.setEnabled(true);
    foo.bar(); // prints "Executing method bar"
}

BypassCheck annotation:

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BypassCheck {
}

Foo interface:

public interface Foo {
    @BypassCheck boolean getEnabled();
    @BypassCheck void setEnabled(boolean enable);

    void bar();
    void baz();
    void bat();

    // Needs Java 8 to have this convenience method here.
    static Foo newFoo() {
        FooFactory fooFactory = new FooFactory();
        return fooFactory.makeFoo();
    }
}

FooFactory class:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class FooFactory {

    public Foo makeFoo() {
        return (Foo) Proxy.newProxyInstance(
                this.getClass().getClassLoader(),
                new Class[]{Foo.class},
                new FooInvocationHandler(new FooImpl()));
    }

    private static class FooImpl implements Foo {

        private boolean enabled = false;

        @Override
        public boolean getEnabled() {
            return this.enabled;
        }

        @Override
        public void setEnabled(boolean enable) {
            this.enabled = enable;
        }

        @Override
        public void bar() {
            System.out.println("Executing method bar");
        }

        @Override
        public void baz() {
            System.out.println("Executing method baz");
        }

        @Override
        public void bat() {
            System.out.println("Executing method bat");
        }

    }

    private static class FooInvocationHandler implements InvocationHandler {

        private FooImpl fooImpl;

        public FooInvocationHandler(FooImpl fooImpl) {
            this.fooImpl = fooImpl;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getDeclaringClass() == Foo.class
                    && !method.isAnnotationPresent(BypassCheck.class) // no magic strings
                    && !this.fooImpl.getEnabled()) {

                return null;
            }

            return method.invoke(this.fooImpl, args);
        }
    }
}

Solution 2 - Java

There is a lot of good suggestions.. what you can do to strike your problem is think in the State Pattern and implement it.

Take a look at this code snippet.. perhaps it will get you to an idea. In this scenario looks like you want to modify the entire methods implementation based on the internal state of the object. Please recall that the sum of the methods in a object is knows as behavior.

public class Foo {
      
      private FooBehaviour currentBehaviour = new FooEnabledBehaviour (); // or disabled, or use a static factory method for getting the default behaviour
      
      public void bar() {
        currentBehaviour.bar();
      }
      public void baz() {
        currentBehaviour.baz();
      }
      public void bat() {
        currentBehaviour.bat();
      }
      
      public void setFooEnabled (boolean fooEnabled) { // when you set fooEnabel, you are changing at runtime what implementation will be called.
        if (fooEnabled) {
          currentBehaviour = new FooEnabledBehaviour ();
        } else {
          currentBehaviour = new FooDisabledBehaviour ();
        }
      }

      private interface FooBehaviour {
        public void bar();
        public void baz();
        public void bat();
      }
      
      // RENEMBER THAT instance method of inner classes can refer directly to instance members defined in its enclosing class
      private class FooEnabledBehaviour implements FooBehaviour {
        public void bar() {
          // do what you want... when is enabled
        }
        public void baz() {}
        public void bat() {}
        
      }
      
      private class FooDisabledBehaviour implements FooBehaviour {
        public void bar() {
          // do what you want... when is desibled
        }
        public void baz() {}
        public void bat() {}
        
      }
}

Hope you like it!

P.D: Is an implementation of the State Pattern (also knows as Strategy depending on the context.. but the principles are just the same).

Solution 3 - Java

Yes, but it's a bit of work, so it depends how important it is to you.

You can define the class as an interface, write a delegate implementation, and then use java.lang.reflect.Proxy to implement the interface with methods that do the shared portion and then conditionally call the delegate.

interface Foo {
    public void bar();
    public void baz();
    public void bat();
}

class FooImpl implements Foo {
    public void bar() {
      //... <-- your logic represented by this notation above
    }

    public void baz() {
      //... <-- your logic represented by this notation above
    }

    // and so forth
}

Foo underlying = new FooImpl();
InvocationHandler handler = new MyInvocationHandler(underlying);
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
     new Class[] { Foo.class },
     handler);

Your MyInvocationHandler can look something like this (error handling and class scaffolding omitted, assuming fooIsEnabled is defined somewhere accessible):

public Object invoke(Object proxy, Method method, Object[] args) {
    if (!fooIsEnabled) return null;
    return method.invoke(underlying, args);
}

It's not incredibly pretty. But unlike various commenters, I'd do it, as I think repetition is a more important risk than this kind of density, and you'll be able to produce the "feel" of your real class, with this somewhat inscrutable wrapper added on very locally in just a couple of lines of code.

See the [Java documentation][1] for details on dynamic proxy classes.

[1]: http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Proxy.html "documentation"

Solution 4 - Java

This question is closely related to aspect-oriented programming. AspectJ is an AOP extension of Java and you may give it a look to get some ispiration.

As far as I know there is no direct support for AOP in Java. There are some GOF patterns that relate to it, like for instance Template Method and Strategy but it will not really save you lines of code.

In Java and most other languages you could define the recurrent logic you need in functions and adopt a so-called disciplined coding approach in which you call them at the right time.

public void checkBalance() {
    checkSomePrecondition();
    ...
    checkSomePostcondition();
}

However this would not fit your case because you would like the factored-out code to be able to return from checkBalance. In languages that support macros (like C/C++) you could define checkSomePrecondition and checkSomePostcondition as macros and they would simply be replaced by the preprocessor before the compiler is even invoked:

#define checkSomePrecondition \
    if (!fooIsEnabled) return;

Java does not have this out of the box. This may offend someone but I did use automatic code generation and template engines to automate repetitive coding tasks in the past. If you process your Java files before compiling them with a suitable preprocessor, for instance Jinja2, you could do something similar to what is possible in C.

Possible pure Java approach

If you are looking for a pure Java solution, what you may find is probably not going to be concise. But, it could still factor out common parts of your program and avoid code duplication and bugs. You could do something like this (it's some sort of Strategy-inspired pattern). Note that in C# and Java 8, and in other languages in which functions are a little easier to handle, this approach may actually look nice.

public interface Code {
    void execute();
}

...

public class Foo {
  private bool fooIsEnabled;

  private void protect(Code c) {
      if (!fooIsEnabled) return;
      c.execute();
  }

  public void bar() {
    protect(new Code {
      public void execute() {
        System.out.println("bar");
      }
    });
  }

  public void baz() {
    protect(new Code {
      public void execute() {
        System.out.println("baz");
      }
    });
  }

  public void bat() {
    protect(new Code {
      public void execute() {
        System.out.println("bat");
      }
    });
  }
}

Kinda of a real-world scenario

You are developing a class to send data frames to an industrial robot. The robot takes time to complete a command. Once the command is completed, it sends you a control frame back. The robot may get damaged if it receives a new command while the previous is still being executed. Your program uses a DataLink class to send and receive frames to and from the robot. You need to protect access to the DataLink instance.

The user interface thread calls RobotController.left, right, up or down when the user clicks the buttons, but also calls BaseController.tick at regular intervals, in order to reenable command forwarding to the private DataLink instance.

interface Code {
    void ready(DataLink dataLink);
}

class BaseController {
    private DataLink mDataLink;
    private boolean mReady = false;
    private Queue<Code> mEnqueued = new LinkedList<Code>();
        
    public BaseController(DataLink dl) {
        mDataLink = dl;
    }
        
    protected void protect(Code c) {
        if (mReady) {
            mReady = false;
            c.ready(mDataLink);
        }
        else {
            mEnqueue.add(c);
        }
    }
    
    public void tick() {
        byte[] frame = mDataLink.readWithTimeout(/* Not more than 50 ms */);
        
        if (frame != null && /* Check that it's an ACK frame */) {
          if (mEnqueued.isEmpty()) {
              mReady = true;
          }
          else {
              Code c = mEnqueued.remove();
              c.ready(mDataLink);
          }
        }
    }
}

class RobotController extends BaseController {
    public void left(float amount) {
        protect(new Code() { public void ready(DataLink dataLink) {
            dataLink.write(/* Create a byte[] that means 'left' by amount */);
        }});
    }

    public void right(float amount) {
        protect(new Code() { public void ready(DataLink dataLink) {
            dataLink.write(/* Create a byte[] that means 'right' by amount */);
        }});
    }

    public void up(float amount) {
        protect(new Code() { public void ready(DataLink dataLink) {
            dataLink.write(/* Create a byte[] that means 'up' by amount */);
        }});
    }

    public void down(float amount) {
        protect(new Code() { public void ready(DataLink dataLink) {
            dataLink.write(/* Create a byte[] that means 'down' by amount */);
        }});
    }
}

Solution 5 - Java

I would consider refactoring. This pattern is heavily breaking DRY pattern (Don't repeat yourself). I believe this break this class responsibility. But this depends on your control of code. Your question is very open - where are you calling Foo instance?

I suppose you have code like

foo.bar(); // does nothing if !fooEnabled
foo.baz(); // does also nothing
foo.bat(); // also

maybe you should call it something like this way:

if (fooEnabled) {
   foo.bat();
   foo.baz();
   ...
}

And keep it clean. For example, logging:

this.logger.debug(createResourceExpensiveDump())

a logger is not asking himself, if debug is enabled. It just logs.

Instead, calling class need to check this:

if (this.logger.isDebugEnabled()) {
   this.logger.debug(createResourceExpensiveDump())
}

If this is a library and you cannot control calling of this class, throw an IllegalStateException which explains why, if this calling is illegal and cause trouble.

Solution 6 - Java

IMHO the most elegant and best performing solution to this is to have more than one implementation of Foo, together with a factory method for creating one:

class Foo {
  protected Foo() {
    // Prevent direct instantiation
  }

  public void bar() {
    // Do something
  }

  public static void getFoo() {
    return fooEnabled ? new Foo() : new NopFoo();
  }
}

class NopFoo extends Foo {
  public void bar() {
    // Do nothing
  }
}

Or a variation:

class Foo {
  protected Foo() {
    // Prevent direct instantiation
  }

  public void bar() {
    // Do something
  }

  public static void getFoo() {
    return fooEnabled ? new Foo() : NOP_FOO;
  }

  private static Foo NOP_FOO = new Foo() {
    public void bar() {
      // Do nothing
    }
  };
}

As sstan points out, even better would be to use an interface:

public interface Foo {
  void bar();

  static Foo getFoo() {
    return fooEnabled ? new FooImpl() : new NopFoo();
  }
}

class FooImpl implements Foo {
  FooImpl() {
    // Prevent direct instantiation
  }

  public void bar() {
    // Do something
  }
}

class NopFoo implements Foo {
  NopFoo() {
    // Prevent direct instantiation
  }

  public void bar() {
    // Do nothing
  }
}

Adapt this to the rest of your circumstances (are you creating a new Foo every time or reusing the same instance, etc.)

Solution 7 - Java

I have another approach: have a

interface Foo {
  public void bar();
  public void baz();
  public void bat();
}

class FooImpl implements Foo {
  public void bar() {
    //...
  }
  public void baz() {
    //...
  }
  public void bat() {
    //...
  }
}

class NullFoo implements Foo {
  static NullFoo DEFAULT = new NullFoo();
  public void bar() {}
  public void baz() {}
  public void bat() {}
}

}

and then you can do

(isFooEnabled ? foo : NullFoo.DEFAULT).bar();

Maybe you can even replace the isFooEnabled with a Foo variable which either holds the FooImpl to be used or the NullFoo.DEFAULT. Then the call is simpler again:

Foo toBeUsed = isFooEnabled ? foo : NullFoo.DEFAULT;
toBeUsed.bar();
toBeUsed.baz();
toBeUsed.bat();

BTW, this is called the "Null pattern".

Solution 8 - Java

In a similar functional approach to @Colin's answer, with Java 8's lambda functions, it is possible to wrap the conditional feature toggle enable / disable code into a guard method (executeIfEnabled) which accepts the action lambda, to which code to be conditionally executed can be passed.

Although in your case, this approach won't save any lines of code, by DRYing this up, you now have the option to centralize other feature toggle concerns, plus AOP or debugging concerns like logging, diagnostics, profiling et al.

One benefit of using lambdas here is that closures can be used to avoid the need to overload the executeIfEnabled method.

For example:

class Foo {
    private Boolean _fooIsEnabled;

    public Foo(Boolean isEnabled) {
        _fooIsEnabled = isEnabled;
    }

    private void executeIfEnabled(java.util.function.Consumer someAction) {
        // Conditional toggle short circuit
        if (!_fooIsEnabled) return;

        // Invoke action
        someAction.accept(null);
    }

    // Wrap the conditionally executed code in a lambda
    public void bar() {
        executeIfEnabled((x) -> {
            System.out.println("Bar invoked");
        });
    }

    // Demo with closure arguments and locals
    public void baz(int y) {
        executeIfEnabled((x) -> {
            System.out.printf("Baz invoked %d \n", y);
        });
    }

    public void bat() {
        int z = 5;
        executeIfEnabled((x) -> {
            System.out.printf("Bat invoked %d \n", z);
        });
    }

With a test:

public static void main(String args[]){
    Foo enabledFoo = new Foo(true);
    enabledFoo.bar();
    enabledFoo.baz(33);
    enabledFoo.bat();

    Foo disabledFoo = new Foo(false);
    disabledFoo.bar();
    disabledFoo.baz(66);
    disabledFoo.bat();
}

Solution 9 - Java

As is pointed out in other answers, the [Strategy Design Pattern][1] is an appropriate design pattern to follow to simplify this code. I've illustrated it here using method invocation through reflection, but there are any number of mechanisms that you could use to get the same effect.

class Foo {

  public static void main(String[] args) {
      Foo foo = new Foo();
      foo.fooIsEnabled = false;
      foo.execute("bar");
      foo.fooIsEnabled = true;
      foo.execute("baz");
  }
  
  boolean fooIsEnabled;
  
  public void execute(String method) {
	if(!fooIsEnabled) {return;}
    try {
	   this.getClass().getDeclaredMethod(method, (Class<?>[])null).invoke(this, (Object[])null);
    }
    catch(Exception e) {
       // best to handle each exception type separately
       e.printStackTrace();
    }
  }

  // Changed methods to private to reinforce usage of execute method
  private void bar() {
    System.out.println("bar called");
	// bar stuff here...
  }
  private void baz() {
    System.out.println("baz called");
	// baz stuff here...
  }
  private void bat() {
    System.out.println("bat called");
	// bat stuff here...
  }
}

[1]: https://en.wikipedia.org/wiki/Strategy_pattern "Strategy"

Solution 10 - Java

If only java was a bit better at being functional. It think the most OOO solution is to create class that wraps a single function so it is called only when foo is enabled.

abstract class FunctionWrapper {
    Foo owner;

    public FunctionWrapper(Foo f){
        this.owner = f;
    }

    public final void call(){
        if (!owner.isEnabled()){
            return;
        }
        innerCall();
    }

    protected abstract void innerCall();
}

and then implement bar, baz and bat as anonymous classes that that extend FunctionWrapper.

class Foo {
    public boolean fooIsEnabled;

    public boolean isEnabled(){
        return fooIsEnabled;
    }

    public final FunctionWrapper bar = new FunctionWrapper(this){
        @Override
        protected void innerCall() {
            // do whatever
        }
    };

    public final FunctionWrapper baz = new FunctionWrapper(this){
        @Override
        protected void innerCall() {
            // do whatever
        }
    };

    // you can pass in parms like so 
    public final FunctionWrapper bat = new FunctionWrapper(this){
        // some parms:
        int x,y;
        // a way to set them
        public void setParms(int x,int y){
            this.x=x;
            this.y=y;
        }

        @Override
        protected void innerCall() {
            // do whatever using x and y
        }
    };
}

Another Idea

Use glglgl's nullable solution but make FooImpl and NullFoo inner classes (with private constructors) of the below class:

class FooGateKeeper {

    public boolean enabled;

    private Foo myFooImpl;
    private Foo myNullFoo;

    public FooGateKeeper(){
        myFooImpl= new FooImpl();
        myNullFoo= new NullFoo();
    }

    public Foo getFoo(){
        if (enabled){
            return myFooImpl;
        }
        return myNullFoo;
    }  
}

this way you don't have to worry about remembering to use (isFooEnabled ? foo : NullFoo.DEFAULT).

Solution 11 - Java

It seems like the class does nothing when Foo is not enabled so why not express this at a higher level where you create or get the Foo instance?

class FooFactory
{
 static public Foo getFoo()
 {
   return isFooEnabled ? new Foo() : null;
 }
}
 ...
 Foo foo = FooFactory.getFoo();
 if(foo!=null)
 {
   foo.bar();
   ....
 }     

This only works if isFooEnabled is a constant though. In a general case, you could create your own annotation.

Solution 12 - Java

I am not familiar with Java syntax. Assumption that in Java, there is polymorphism, static property, abstract class & method:

    public static void main(String[] args) {
	Foo.fooIsEnabled = true; // static property, not particular to a specific instance  
	
    Foo foo = new bar();
    foo.mainMethod();
	
	foo = new baz();
    foo.mainMethod();
	
	foo = new bat();
    foo.mainMethod();
}

    public abstract class Foo{
      static boolean fooIsEnabled;
      
      public void mainMethod()
      {
    	  if(!fooIsEnabled)
    		  return;
    	  
    	  baMethod();
      }  	
      protected abstract void baMethod();
    }
    public class bar extends Foo {
    	protected override baMethod()
    	{
    		// bar implementation
    	}
    }
    public class bat extends Foo {
    	protected override baMethod()
    	{
    		// bat implementation
    	}
    }
    public class baz extends Foo {
    	protected override baMethod()
    	{
    		// baz implementation
    	}
    }

Solution 13 - Java

Basically you have a flag that if it's set, the function call should be skipped. So I think my solution would be silly, but here it is.

Foo foo = new Foo();

if (foo.isEnabled())
{
    foo.doSomething();
}

Here's the implementation of a simple Proxy, in case you want to execute some code before executing any function.

class Proxy<T>
{
    private T obj;
    private Method<T> proxy;

    Proxy(Method<T> proxy)
    {
        this.ojb = new T();
        this.proxy = proxy;
    }

    Proxy(T obj, Method<T> proxy)
    {
        this.obj = obj;
        this.proxy = proxy;
    }

    public T object ()
    {
        this.proxy(this.obj);
        return this.obj;
    }
}

class Test
{
    public static void func (Foo foo)
    {
        // ..
    }
    
    public static void main (String [] args)
    {
        Proxy<Foo> p = new Proxy(Test.func);
    
        // how to use
        p.object().doSomething();
    }
}

class Foo
{
    public void doSomething ()
    {
        // ..
    }
}

Solution 14 - Java

There is another solution, using delegate (pointer to function). You can have a unique method that first is doing the validation and then is calling to the relevant method according to the function (parameter) to be called. C# code:

internal delegate void InvokeBaxxxDelegate();

class Test
{
    private bool fooIsEnabled;

    public Test(bool fooIsEnabled)
    {
        this.fooIsEnabled = fooIsEnabled;
    }

    public void Bar()
    {
        InvokeBaxxx(InvokeBar);
    }

    public void Baz()
    {
        InvokeBaxxx(InvokeBaz);
    }

    public void Bat()
    {
        InvokeBaxxx(InvokeBat);
    }

    private void InvokeBaxxx(InvokeBaxxxDelegate invoker)
    {
        if (!fooIsEnabled) return;
        invoker();
    }

    private void InvokeBar()
    {
        // do Invoke bar stuff
        Console.WriteLine("I am Bar");
    }

    private void InvokeBaz()
    {
        // do Invoke bar stuff
        Console.WriteLine("I am Baz");
    }

    private void InvokeBat()
    {
        // do Invoke bar stuff
        Console.WriteLine("I am Bat");
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkristinaView Question on Stackoverflow
Solution 1 - JavasstanView Answer on Stackoverflow
Solution 2 - JavaVictorView Answer on Stackoverflow
Solution 3 - JavaDavid P. CaldwellView Answer on Stackoverflow
Solution 4 - Javadamix911View Answer on Stackoverflow
Solution 5 - JavaGondyView Answer on Stackoverflow
Solution 6 - JavaPepijn SchmitzView Answer on Stackoverflow
Solution 7 - JavaglglglView Answer on Stackoverflow
Solution 8 - JavaStuartLCView Answer on Stackoverflow
Solution 9 - JavaLJ2View Answer on Stackoverflow
Solution 10 - JavaColinView Answer on Stackoverflow
Solution 11 - JavaKonrad HöffnerView Answer on Stackoverflow
Solution 12 - JavaehhView Answer on Stackoverflow
Solution 13 - JavaKhaled.KView Answer on Stackoverflow
Solution 14 - JavaehhView Answer on Stackoverflow