Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Code Optimization [java]

Name: Anonymous 2010-04-13 16:33

I'm working on a project that requires that I use processing. I am not too proficient with Java. I have written these retard-tier methods:


  color removeFromColor(int c, int subtraction)
  {
    for (int i = 16; i >= 0; i -= 8) {
      if ((c >> i & 0xFF) - subtraction > 0) {
        c |= (0 << i);
      } else {
        c -= (subtraction << i);
      }
    }
    return c;   
  }
 
  color addToColor(int c, int addition)
  {
    for (int i = 16; i >= 0; i -= 8) {
      if ((c >> i & 0xFF) + addition > 255) {
        c |= (255 << i);
      } else {
        c += (addition << i);
      }
    }
    return c;
  }


As you can perhaps guess, I would prefer if these methods were written as one private (factory?) method, with two wrapper methods for add and remove that modify the behavior of the main method. Unfortunately, I am not skilled enough to come up with an elegant solution. All of my design attempts thus far have resulted in overly-complicated, unnecessary bloat, or at least worse code than if I had just stuck to keeping two very-similar-yet-different methods.

Since in practice these are working just fine at the moment, I am asking this only out of curiosity. How would you optimize this? Or would you bother at all?

Name: Anonymous 2010-04-13 23:37

>>12
if((c >> i & 0xFF) + mod >  d)

Yeah, see, this is the thing. I accidentally let this logic be the same in both methods in the OP, because I had copy-pasted without fully undoing what I had done to the original code. It's corrected in  >>3. In add, I need to cap the value from increasing past 255, but in remove, I need to prevent it from decreasing past 0. So, in one case I need >, and the other, <.

Incidentally this is also the line that stumped me. I couldn't see a way around it aside from writing two separate if statements, which seemed like a clumsy solution.

color is just a processing "datatype"; it's really no different from an int and from my experience thus far can be used interchangeably, although for clarity the argument should be color (also corrected in >>3).

The method is private because the object as a whole is a shape, and this is a method used in both gradient and highlighting code, although you do make a good point in that it should probably be changing the state of the object.

As for the sign of the integer, this method is only being fed constants, but I appreciate your insight regardless. I guess there's no unsigned in Java?

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List