Is there a way to write this if tree more elegantly?

if (position.x < 0) {
    position.x = 0;
if (position.y < 0) {
    position.y = 0;
if (position.x > 4800) {
    position.x = 4800;
if (position.y > 4800) {
    position.y = 4800;
  • \$\begingroup\$ You can refactor this into 2 methods and pass position.x and position.y as parameters. You can even do it in one method but this will require you to pass operator as parameter along with position.x or y and the value 0\4800. \$\endgroup\$ – Denis Apr 28 '16 at 6:29

Magic numbers

Without further context, 0 and 4800 seem to be magic numbers here. You may want to consider putting them as private static final fields so that they can be reused in an easier manner:

private static final int MIN = 0;
private static final int MAX = 4800;

Logic encapsulation via methods

There's nothing fundamentally wrong with your current approach. It's clear and concise enough (again, without further context), and if there's one minor improvement to make, it's to put this kind of validation into a method that returns what should be the value to update with:

private static int validate(int value, int min, int max) {
    return value < min ? min : value > max ? max : value;

If you are adverse to ternary operators for some reason, there's Math.min() and Math.max() to consider as well:

private static int validate(int value, int min, int max) {
    return Math.min(Math.max(value, min), max);

These 12 lines can thus be rewritten as such:

position.x = validate(position.x, MIN, MAX);
position.y = validate(position.y, MIN, MAX);
  • \$\begingroup\$ Thanks, where can I learn more about ternary operators? \$\endgroup\$ – CJL Apr 29 '16 at 2:52
  • \$\begingroup\$ @CJL there you go... \$\endgroup\$ – h.j.k. Apr 29 '16 at 3:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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