Skip to content

Instantly share code, notes, and snippets.

@TeamDman
Last active January 9, 2021 20:22
Show Gist options
  • Save TeamDman/257711d371bac9bcc56e3badcd8bd721 to your computer and use it in GitHub Desktop.
Save TeamDman/257711d371bac9bcc56e3badcd8bd721 to your computer and use it in GitHub Desktop.
Java Tips
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class Tips {
private static final Scanner in = new Scanner(System.in);
private static final Random rand = new Random(System.currentTimeMillis());
// Never reassigned => should be final
public static void main(String[] args) {
/**
* Use editor features to fix indentation. Google them if you don't know the keyboard shortcuts
* IntelliJ: Ctrl+Alt+L
* Eclipse: Ctrl+A, Ctrl+I (select all, fix indentation for highlighted lines)
*
* Use proper naming convention
* TitleCase for Class names
* TitleCase for Enum names
* camelCase for field names
* camelCase for method names
*
* Use logical operators when comparing boolean expressions
* a & b is a bitwise operator. Only used with booleans to avoid short-circuit evaluation, which shouldn't be needed
* a | b is a bitwise operator. Only used with booleans to avoid short-circuit evaluation, which shouldn't be needed
* a && b is a logical operator. Use this one with booleans
* a || b is a logical operator. Use this one with booleans
*
* Code duplication should be avoided.
* If you find yourself copying a method and only changing 2 lines inside, you can probably make it one method
* to handle both scenarios.
* This doesn't mean that every time you perform a simple statement more than once it should be made a method.
* Simple methods that are only called once decrease readability
* Single line methods should probably be avoided
*
* String comparisons should use .equals or .equalsIgnoreCase
* Using the == operator on strings is bad and will cause headaches trying to debug your code
**/
String first = new String("a"), second = new String("a");
System.out.println(first == second); // false
System.out.println(first.equals(second)); // true
System.out.println(first.equalsIgnoreCase("A")); // true
// In this example, I created first and second explicitly calling the String constructor.
// This should generally be avoided, instead:
first = "a";
second = "a";
System.out.println(first == second); // true, optimizations make them both use the same object.
int value = 0;
value = value + 1;
// can be simplified to
value += 1;
// can be further simplified to
value++;
boolean isActive = false;
if (isActive)
isActive = false;
else
isActive = true;
// can be simplified to
isActive = !isActive;
// Input validation can be done very easily without try-catch statements
int input = -1; // set to invalid value so the loop condition is met
Scanner in = new Scanner(System.in);
while (input < 0 || input > 10) {
System.out.print("Enter a number from 0 to 10, inclusive: ");
input = in.nextInt();
}
System.out.printf("You entered %d\n", input);
// Case-insensitive validation is also simple
String option = "";
while (!option.equals("a") && !option.equals("b")) {
System.out.print("Enter either 'a' or 'b': ");
option = in.next().toLowerCase();
}
System.out.printf("You entered %s\n", option);
// printf isn't necessary, but it can improve readability and is worth learning.
// It can also be used to easily align console output
// https://kodejava.org/how-do-i-align-string-print-out-in-left-right-center-alignment/
// If you use the Scanner::nextInt() method to get a number, then attempt something like asking
// to hit enter to continue, it might seem like it doesn't wait
System.out.print("Enter a number: ");
in.nextInt(); // We don't care what it is. Don't make a variable if it's ignored
System.out.println("Press enter to continue");
in.nextLine();
System.out.println("Probably didn't wait.");
// The reason is, when you hit <enter> after putting a number, the scanner only removes the number from
// the buffer. When the scanner is asked for the nextLine(), it still sees the <enter> in the buffer.
// This can be 'fixed' by calling nextLine() twice, which is ugly.
// Better solution:
System.out.print("Enter a number: ");
in.nextInt();
System.out.println("Press enter to continue");
try {
while (true) {
if (System.in.read() == '\n')
break;
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Better.");
}
private boolean getValue() {
/**
* Method names involve verbs, since they are performing some action.
* ex. getName(), setName(), add(), remove()
*/
boolean a = true;
if (a == true)
return true;
// can be simplified to
if (a)
return true;
// can be further simplified to
return a;
}
private void performLoop() {
/**
* Using a flag/sentinel in conjunction with control statements like break; and continue; is fine
* However, doing something like:
* {
* flag = false;
* break;
* }
* is redundant and should be avoided.
*/
boolean flag = true;
while (flag) {
if (rand.nextInt(2) == 1) // some exit condition
flag = false;
}
// can instead be done as
while (true) {
if (rand.nextInt(2) == 1) // some exit condition
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment