Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Чечулин Антон #166

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Conversation

fearppen
Copy link

@fearppen fearppen commented Feb 4, 2024

Copy link

@MrTimeChip MrTimeChip left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В целом, неплохой код. Но видимо тебе уж слишком сильно понравился Result. :)
Стоит поправить его использование, следуя следующим правилам:

  1. Не хранить Result в полях класса
  2. Не возвращать перечисление Result (то есть, IEnumerable не надо) ((вообще, такое иногда можно, когда объекты Result это какие-то таски, треды или что-то подобное, что может сфейлиться. Но объект не может сфейлиться, фелится логика.))

pointsOnSpiral = pointCreator.GetPoints().GetEnumerator();
}

public IList<Rectangle> Rectangles { get => rectanglesInLayout; }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно чуть проще public IList<Rectangle> Rectangles => rectanglesInLayout;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ещё странно, что мы достали это поле наружу только ради тестов. Это не очень хорошая практика.

Comment on lines 24 to 25
public IEnumerable<Result<Point>> GetPoints()
{

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень странно возвращать IEnumerable<Result>
Нам чтобы узнать ошибку, которая произошла, надо пройтись по коллекции, после чего проход все равно дальше первого элемента не пойдет, и мы будем дальше прокидывать ошибку.
Кажется, лучше будет Result<IEnumerable>

Comment on lines 41 to 43
pointsOnSpiral.MoveNext();
if (!pointsOnSpiral.Current.IsSuccess)
return Result.Fail<Rectangle>(pointsOnSpiral.Current.Error);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Немного неочевидно, вытекает из того, что у нас IEnumerable

graphics = Graphics.FromHwnd(IntPtr.Zero);
}

public IEnumerable<Result<Tag>> GetTags()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Та же самая история, IEnumerable вместо Result

}
yield return new Tag(wordWithCount.Key,
fontSize,
rectangle.GetValueOrThrow(),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А почему тут GetValueOrThrow вместо просто Value?

Comment on lines 14 to 15
if (isMatch)
color = Color.FromName(settings.Color);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Немного странный подход к выбору из коллекции. Кажется, что объекты должны хранить в себе свое имя и совпадение должно проверяться вне объектов, а не изнутри.

Comment on lines 9 to 11
private readonly Result<Point> center;
private readonly Result<double> deltaAngle;
private readonly Result<double> deltaRadius;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Опять переборщил с Result.


public class BackgroundSettings
{
public Result<Color> BackgroundColor { get; }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тоже лишний Result.

Comment on lines +12 to +13
private readonly Result<IEnumerable<string>> words;
private readonly Result<HashSet<string>> boringWords;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В общем, по сути, мы никогда не должны хранить Result как поле. Мы либо получаем нужное значение и присваиваем его полю, либо кидаем ошибку. То есть Result у нас должен только возвращаться из методов, но никогда не должен быть активной частью внутренней логики. Это как вешать TryCatch на поля.


namespace TagsCloudVisualization.CommandLine;

public class CommandLineOptions

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По хорошему, все, что работает с командной строкой, должно лежать в отдельном проекте. Но раз уж прошлый наставник это допустил, то я не буду просить переделывать. :)

Copy link

@MrTimeChip MrTimeChip left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почти на месте, надо только исправить настройки. :)

Comment on lines 16 to 22
public Result<bool> Check()
{
if (Width <= 0)
return Result.Fail<bool>($"Width must be positive, but {Width}");
else if (Height <= 0)
return Result.Fail<bool>($"Height must be positive, but {Height}");
return Result.Ok(true);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не очень хорошо. В настройках должны лежать только корректные данные, ошибки надо прокидывать на моменте создания/присваивания полей. Либо ошибки кидать на моменте использования, потому что некоторые ошибки только в процессе работы программы становятся явными. И в любом случае - проверка корректности настроек вне настроек, а не в них.

Comment on lines 15 to 20
public Result<bool> Check()
{
if (Enum.IsDefined(typeof(KnownColor), BackgroundColor))
return Result.Ok(true);
return Result.Fail<bool>($"Can't find color with name {BackgroundColor} for background");
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

То же самое.

Comment on lines 42 to 51
public Result<bool> CheckForCorrectness()
{
var imageSettingsCheck = imageSettings.Check();
if (!imageSettingsCheck.IsSuccess)
return Result.Fail<bool>(imageSettingsCheck.Error);
var spiralSettingsCheck = spiralSettings.Check();
if (!spiralSettingsCheck.IsSuccess)
return Result.Fail<bool>(spiralSettingsCheck.Error);
return Result.Ok(true);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Уйдет, как поправишь настройки.

Comment on lines 29 to 31
var checkSettings = settings.Check();
if (!checkSettings.IsSuccess)
return Result.Fail<IList<Tag>>(checkSettings.Error);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Уйдет, как поправишь настройки.

Comment on lines 25 to 27
var isPointCreatorCorrect = pointCreator.CheckForCorrectness();
if (!isPointCreatorCorrect.IsSuccess)
return Result.Fail<Rectangle>(isPointCreatorCorrect.Error);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Уйдет, как поправишь настройки.

Comment on lines 16 to 23
public Result<bool> Check()
{
if (DeltaRadius <= 0)
return Result.Fail<bool>($"Delta radius must be positive, but {DeltaRadius}");
if (DeltaAngle <= 0)
return Result.Fail<bool>($"Delta angle must be positive, but {DeltaAngle}");
return Result.Ok(true);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

То же самое.

Comment on lines 32 to 43
public Result<bool> Check()
{
if (!IsCanGetFontFamily(FontFamily))
return Result.Fail<bool>($"Font with name {FontFamily} doesn't supported");
else if (MaxSize < MinSize)
return Result.Fail<bool>($"Max font size can't be less then min font size");
else if (MaxSize <= 0)
return Result.Fail<bool>($"Font sizes must be positive, but max size: {MaxSize}");
else if (MinSize <= 0)
return Result.Fail<bool>($"Font sizes must be positive, but min size: {MinSize}");
return Result.Ok(true);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

То же самое.

Comment on lines 16 to 23
public Result<bool> Check()
{
if (!File.Exists(PathToBoringWords))
return Result.Fail<bool>($"Cant't find file with this path {Path.GetFullPath(PathToBoringWords)}");
if (!File.Exists(PathToText))
return Result.Fail<bool>($"Cant't find file with this path {Path.GetFullPath(PathToText)}");
return Result.Ok(true);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

То же самое.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants