Hello my dear developers
How do you feel today?
On this refactor I want to pay attention to a code smell called Feature envy, this smell is easy to spot because code outside a class uses data from a class for the application flow.
I have it in my sample when accession pieces position to find a given piece.
private bool TryFindPiece(Position position, out Piece piece)
{
if (!_pieces.Any(p => p.Position.Equals(position)))
{
piece = default(Piece);
return false;
}
...
}
Therefore let’s use the extract method refactor to have a IsAt method on piece
private bool TryFindPiece(Position position, out Piece piece)
{
if (!_pieces.Any(p => p.Position.Equals(position)))
{
piece = default(Piece);
return false;
}
...
}
private bool TryFindPiece(Position position, out Piece piece)
{
if (!_pieces.Any(p => p.IsAt(position)))
{
piece = default(Piece);
return false;
}
...
}
This follow the principal only talk to your friends and on this case Position is a friend of Piece. So if Piece is friends with Board, talking to Position would be talking to a friend of a friend.
I hope that this was as helpful for me as it was for you.
Happy coding and remember… there is life beyond coding 😄