I have a pixel/location, we’ll call it 4,4 on a graph.
I’m attempting to refactor a function that checks to see if pixels around it, meet a certain criteria, in all 8 directions (diagonally, horizontally, and vertically), and if it meets that criteria, take a common action, that has a return value.
For instance:
int weight=0;
if (CheckWeight(new Point(4,4)) == true)
weight +=100;
if (CheckWeight(new Point(4,5)) == true)
weight +=10;
if (CheckWeight(new Point(4,3)) == true)
weight +=10;
if (CheckWeight(new Point(5,5)) == true)
weight +=10;
if (CheckWeight(new Point(3,3)) == true)
weight +=10;
if (CheckWeight(new Point(3,4)) == true)
weight +=10;
if (CheckWeight(new Point(5,4)) == true)
weight +=10;
if (CheckWeight(new Point(5,3)) == true)
weight +=10;
if (CheckWeight(new Point(3,5)) == true)
weight +=10;
Is there a good way to refactor these, so if I have to change certain things here, such as function I’m calling to check the weight, or condition I’m checking against, or weight increment, that I’m not duplicating my efforts 8 times?
I’ve had other programmers I know already suggest to just combine them under one check, which I obviously can’t do, cause it might meet 3 of these checks, and give me a weight of 30 this time, and 5 of these checks and give me a weight of 50 next time.
Edit: This routine will be run on 1920×1080 pixel maps, so several million times; performance could be a real issue involved in the refactoring.
A possible approach would be to refactor the common code to a for loop that would iterate through all points near the target one. Sample code follows:
You would need to implement the
GetNearestPointsFrommethod to return the correct points. By going this way you’re also encapsulating the logic for asserting the nearest points in a separate method, which I find more maintainable.Update:
Taking in consideration that you’re limited by performance constraints and you mention that you may need to change the
CheckWeightby another function, I would verify if wrapping theifchecks in a method that accepts aPredicate<Point>and a weight increment value would not affect performance too much. This way changing theCheckWeightmethod or the increment is performed only once. Sample code: