3 ms·
Interesting concept. Certainly struck a nerve with me. I've found one of the easiest ways to minimalize my code is to require less code. How? Better program
by edw519 18y ago
Interesting concept. Certainly struck a nerve with me.
I've found one of the easiest ways to minimalize my code is to require less code.
How? Better program design. Tighter structure, more efficient algorithms to accomplish to same thing. Reverse the order of two functions and suddenly that conditional is no longer necessary. Adding a parameter to a function may make it larger, but useful in more places. Only handle 90% of cases and send the outliers off to custom-land. You get the idea.
It then becomes a whole lot easier to minimalize 50 LOC than 100 LOC.
[EDIT: The timing of this post couldn't have been better. I struggled with some pretty complex code all day yesterday. I woke up at 5 a.m. and thought, "Just switch the order the functions are called." I did and it simplified beautifully, working perfectly, and eliminating about 50 LOC.]
- LogicHoleFlaw 18y agoOne of my most productive days was throwing away 1000 lines of code. --Ken Thompson
- AndyKelley 18y agoThis can also sometimes be achieved with math. For example, I was writing code that handled velocity and animation based on the arrow keys. The character had to change animations depending on 8 directions - nesw & diagonals. At first I had an ugly if-elseif statement handling all the keystates. But then I realized I could come up with a cool scheme to simplfy and beautify the code. I also needed to solve the problem of having a constant max-velocity that stayed the same even when going in a diagonal. //which direction to go dirX = 0; dirY = 0; if( keystate[SDLK_LEFT] ) dirX--; if( keystate[SDLK_RIGHT]) dirX++; if( keystate[SDLK_UP] ) dirY--; if( keystate[SDLK_DOWN]) dirY++; if( dirX == 0 && dirY == 0){ //stand still heroVelX = 0; heroVelY = 0; heroAnimation = heroStill[oldHeroDirIndex]; } else { //run in a direction angle = atan2(dirY,dirX); heroVelX = heroSpeed * cos(angle); heroVelY = heroSpeed * sin(angle); oldHeroDirIndex = (dirX+1)*3 + (dirY+1); heroAnimation = heroRunning[oldHeroDirIndex]; } //step to next frame in animation if( ++heroAnimation->curFrame >= heroAnimation->numFrames ) heroAnimation->curFrame = 0; heroX += heroVelX; heroY += heroVelY; -removes conflict from pressing left and right or up and down at the same time -uses a formula to calculate which animation to use, instead of using switch statement -uses a little bit of trig to keep max-speed constant Programming like this is very rewarding, if only for the feeling you get when it works. I guess this isn't really a big deal to any of you, but this sucker used to be 70 repetitive and buggy lines, rather than the pretty 29 it is now.