-16
\$\begingroup\$

Some people complain about if - statements and I really appreciate that attitude. Actually I plan to abandon the entire keyword in order to awesomize my code, which is:

Algorithm.java:

package net.coderodde.noxx;

import java.util.Arrays;
import java.util.Random;

/**
 * This is algorithm. It works as .. there is no need for .. - statements.
 * It proves that there is no need for .. - statements.
 */
public class Algorithm {

    /**
     * ..less algorithm for finding the index of a maximum integer in an array.
     * 
     * @param  array the array to search.
     * @return the index of the maximum element or -1 if the array is
     *         <code>null</code> or has length zero.
     */
    public static final int indexOfMaximum(final int[] array) {
        int max;
        int index;

        // Here supposed check whether array is null or empty, but we are not
        // supposed to use ..-statements. Use exceptions instead!
        try {
            max = array[0];
            index = 0;
        } catch (final NullPointerException | 
                       ArrayIndexOutOfBoundsException ex) {
            return -1;
        }

        for (int i = 1; i < array.length; ++i) {
            // Why not to use for's test condition instead of ..?
            for (int j = 0; j < testIsGreater(array[i], max); ++j) {
                max = array[i];
                index = i;
            }
        }

        return index;
    }

    /**
     * Life is so much easier now without .. .
     */
    private static int testIsGreater(final int element, final int max) {
        return element - max;
    }

    public static void main(final String... args) {
        final Random rnd = new Random();
        final int[] array = new int[10];

        for (int i = 0; i < array.length; ++i) {
            array[i] = rnd.nextInt(1301) - 300;
        }

        final int index = indexOfMaximum(array);
        final int check = Arrays.stream(array).max().getAsInt();

        System.out.println("Maximum integer: " + array[index] 
                                               + " and " 
                                               + check);
    }
}

AlgorithmTest.java:

package net.coderodde.noxx;

import static net.coderodde.noxx.Algorithm.indexOfMaximum;
import org.junit.Test;
import static org.junit.Assert.*;

public class AlgorithmTest {

    /**
     * My tests use .. neither! Ain't this keeewl??
     */
    @Test
    public void testIndexOfMaximum() {
        int[] array = new int[0];
        assertEquals(-1, indexOfMaximum(array));
        assertEquals(-1, indexOfMaximum(null));

        array = new int[]{3, 2, 1, 4, 5, 1 };

        assertEquals(4, indexOfMaximum(array));

        array = new int[]{3};

        assertEquals(0, indexOfMaximum(array));

        array = new int[]{3, 4, 1, 7};

        assertEquals(3, indexOfMaximum(array));
    }    
}

So is it kewl to awesomize the code this way?

\$\endgroup\$

closed as off-topic by RubberDuck, rolfl May 9 '15 at 13:26

If this question can be reworded to fit the rules in the help center, please edit the question.

  • 3
    \$\begingroup\$ Is this a riddle? Are you like a "Knight Who Says Ni" and can't say a certain two letter word? \$\endgroup\$ – JS1 May 8 '15 at 18:17
  • 5
    \$\begingroup\$ For those who don't get it: .. = if \$\endgroup\$ – Simon Forsberg May 8 '15 at 19:03
  • 1
    \$\begingroup\$ This is cute but it's extremely unclear what the heck you wanted. I thought you mean ... operator. \$\endgroup\$ – Captain Man May 8 '15 at 19:25
  • 1
    \$\begingroup\$ Note also that element - max can overflow (use Integer.compare). \$\endgroup\$ – maaartinus May 8 '15 at 21:23
  • 3
    \$\begingroup\$ Though now i'm wondering what'll happen when OP realizes that every for, while, or ?: expression has an if hidden in it. :) \$\endgroup\$ – cHao May 9 '15 at 4:10
13
\$\begingroup\$

Some people complain about .. - statements and I really appreciate that attitude. Actually I plan to abandon the entire keyword in order to awesomize my code

I'm wondering what complaints you're referring to. In any case, I don't think you succeeded in awesomizing, but rather in suckifying.


// Here supposed check whether array is null or empty, but we are not
// supposed to use ..-statements. Use exceptions instead!
try {
    max = array[0];
    index = 0;
} catch (final NullPointerException | 
               ArrayIndexOutOfBoundsException ex) {
    return -1;
}

The statement in the comment is plain wrong. You are supposed to use if statement to check for nulls and array bounds. (Recommended reading: Item 57 in Effective Java by Joshua Bloch.)

Exceptional logic shouldn't be used for normal program flow. What you're doing here is essentially input validation, which fits well within the bounds of normal program flow. Just use an if statement.


// Why not to use for's test condition instead of ..?
for (int j = 0; j < testIsGreater(array[i], max); ++j) {
    max = array[i];
    index = i;
}

Because this is horrible code, obfuscating an otherwise simple logic, and looping unnecessarily.


/**
 * Life is so much easier now without .. .
 */
private static int testIsGreater(final int element, final int max) {
    return element - max;
}

Is life really easier? Harder to read, with no benefits whatsoever, so no it isn't.

Also a poor name for a function. isGreater would have been better.


Related discussions:

https://stackoverflow.com/questions/299068/how-slow-are-java-exceptions

https://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain

\$\endgroup\$
9
\$\begingroup\$

(please dial your sarcasm meter to Long.MAX_VALUE... it's a slow weekend)

Bug

 * @return the index of the maximum element or -1 if the array is
 *         <code>null</code> or has length zero.

Your Javadoc is using the .. keyword, didn't your custom compiler throw an error for that? Mine did!

Algorithm class name

Algorithm is too generic and does not communicate the awesomeness that you are trying to do here. I have a suggestion below, do consider!

Multiple try-catch is not awesome enough

Ok, so you know a nifty feature, but it's not awesome enough to just catch two of them. Why not just catch on all Throwables? The more things to catch, the more awesome!

Nested for loops is confusing

Your nested for loops uses i and j variables, which may look confusing for the myopic programmer without glasses on. Why not use something, like... recursion? Yes, recursion!

OOP

There is hardly any other classes in use, how else will you be able to demonstrate that you have a SOLID idea about OOP? You should consider using basic classes like those from the Collections framework or primitive wrappers to do so!

Putting all the awesomeness together

public class WithoutTheKeywordWhichMustNotBeNamed {

    // we need to start from one less than 0
    private static final int START_INDEX = -1;

    public static final int indexOfMaximum(int[] array) {
        // this is a container
        List<Integer> result = new ArrayList<Integer>(Arrays.asList(START_INDEX,
                Integer.MIN_VALUE));
        try {
            recurseAwesomely(array, START_INDEX, result);
        } catch (Throwable t) {
        } finally {
            return result.get(0); // awesome
        }
    }

    private static Entry<Integer, Integer> recurseAwesomely(int[] array, int index,
            List<Integer> result) {
        for (; array[++index] > result.get(1); result.addAll(Arrays.asList(index,
                array[index]))) {
            result.clear();
        }
        return recurseAwesomely(array, index, result);
    }
}

The idea is to recurse continuously until we get a Throwable due to overflowing awesomeness. We use a List out of convenience to store our results across recursions ('container'). We also use our for loop in an unconventional yet awesome way, by incrementing during the comparison, and saving the results as the increment statement (which is run after the body is done). Therefore, when our condition is true, we only need to clear our results for saving. finally, we have our last index saved, so we can return to the caller from the result container. Last but not least, remember to leave an awesome comment for our private static final variable!

Overall, I think this is an awesome question, hence I am rewarding it in the direction of awesomeness it deserves!

(please reset your sarcasm meter back to whatever it was originally)


On a serious note

Please don't use exceptions to replace .., for a variety of reasons:

  • .. is simpler to write
  • .. is simpler to understand
  • .. treats a false condition normally as well, instead of making the JVM jump through error stacktraces
  • Generally, it's just horrible code smell

The lesson here is: Don't replace .. with exceptions. @janos's answer has already hit the nail on its head.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.