Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am currently working on a C# checkers game for a university project in program

ID: 645914 • Letter: I

Question

I am currently working on a C# checkers game for a university project in programming. But i have came to the point where i need to check whether a piece can be moved, or jump, but i feel like i'm using lots of code that isn't necessary to get true or false answers.

if (arrayX == 0)
{
    if (board.GetBoard(arrayX + 1, arrayY - 1).Piece == null)
    {
        return true;
    }
}
else if (arrayX == 7)
{
    if (board.GetBoard(arrayX - 1, arrayY - 1).Piece == null)
    {
        return true;
    }
}
For example, is there a more efficient way of doing these if statements? In the code i have more if statements branching off other if statements. So in summary, is there a way you can check loads of parameters, efficiently, without using loads of if statements branching off of one another?

Explanation / Answer

You may start by creating a method inside the Board class which makes your code slightly shorter:

public class Board()
{
public bool IsPieceMissing(x, y)
{
return this.GetBoard(x, y).Piece == null;
}
}

...

if (arrayX == 0)
{
if (board.IsPieceMissing(arrayX + 1, arrayY - 1))
{
return true;
}
}
else if (arrayX == 7)
{
if (board.IsPieceMissing(arrayX - 1, arrayY - 1))
{
return true;
}
}
The next thing is to work on the business logic, but for that, you need to provide a more global picture. What is the complete body of the method? Is it returning false at the end? Assuming it contains only the part you already provided and the return false; at the end, like this:

private bool DoSomething(arrayX, arrayY)
{
if (arrayX == 0)
{
if (board.IsPieceMissing(arrayX + 1, arrayY - 1))
{
return true;
}
}
else if (arrayX == 7)
{
if (board.IsPieceMissing(arrayX - 1, arrayY - 1))
{
return true;
}
}

return false;
}
you can return immediately instead of waiting until the end. The method becomes:

private bool DoSomething(arrayX, arrayY)
{
if (arrayX == 0)
{
return board.IsPieceMissing(arrayX + 1, arrayY - 1);
}
else if (arrayX == 7)
{
return board.IsPieceMissing(arrayX - 1, arrayY - 1);
}

return false;
}
Since the first condition now returns something anyway, you don't need the else:

private bool DoSomething(arrayX, arrayY)
{
if (arrayX == 0)
{
return board.IsPieceMissing(arrayX + 1, arrayY - 1);
}

if (arrayX == 7)
{
return board.IsPieceMissing(arrayX - 1, arrayY - 1);
}

return false;
}