Skip to content

Шептихин Вячеслав#225

Open
sheptikhinv wants to merge 18 commits intokontur-courses:masterfrom
sheptikhinv:master
Open

Шептихин Вячеслав#225
sheptikhinv wants to merge 18 commits intokontur-courses:masterfrom
sheptikhinv:master

Conversation

@sheptikhinv
Copy link
Copy Markdown

No description provided.

Copy link
Copy Markdown

@SquirrelLeonid SquirrelLeonid left a comment

Choose a reason for hiding this comment

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

К подходу с точки зрения result вопросов нет, но есть несколько небольших замечаний к коду


public class Client
{
[SuppressMessage("Interoperability", "CA1416:Проверка совместимости платформы")]
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше не подавлять сообщения таким образом, а в csproj явно указать платформу как net8.0-windows. Так ты четко сообщишь, что твой код не кроссплатформенный.

А так ты рискуешь в лучшем случае словить ошибки при компиляции под unix. В худшем - развалится в рантайме

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Подобные вхождения убрал, везде вписал net8.0-windows

Comment on lines +17 to +18
.AddVisualizationOptions(options.BackgroundColor, options.TextColor, options.FontSize,
options.OutputWidthPx, options.OutputHeightPx, options.FontFamily)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Небольшое отступление - некоторые моменты будут не по самой задаче с добавлением Result. но комментарии я по ним все же оставлю.

Можно подумать над тем, чтобы ввести промежуточный класс с опциями. В нем можно было бы провести группировку отдельных опций, которые управляют конкретной частью. В данном случае это могут быть VisualizationOptions.

.AddFileReaders()
.AddWordsFilter(options.FilterFilePath)
.AddWordsProcessor()
.AddCoordinateGenerators(options.OutputWidthPx ?? 100, options.OutputHeightPx ?? 100, options.AngleStepRadians)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Я бы не оставлял значения по умолчанию в логике инициализации контейнера.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Убрал центр из конструктора координатных генераторов

})
.Then(data => FileSaver.SaveFile(data.bitmap, data.output))
.Then(output => Console.WriteLine($"Visualization saved to file {output}"))
.OnFail(Console.WriteLine);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Тут вот не совсем прозрачно что выведется. Просто пустая строка?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Сделал более явный вывод ошибок, заменив на

error => Console.WriteLine(error);

{
var output = options.OutputFilePath ??
Path.Combine(Environment.CurrentDirectory,
$"TagsCloud_{DateTime.UtcNow:yyyy-MM-dd_HH-mm-ss}.png");
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Кажется здесь можно писать не строго .png, а выводить формат из bitmap (раз он приходит на вход)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Не совсем понял откуда взять формат у bitmap, формат изображения вычисляется в FileSaver на основе расширения пути создаваемого файла, а у битмапы не нашел никакого поля с форматом.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

У Bitmap есть поле RawFormat, а в нем хранится ImageFormat. Думаю можно оттуда взять

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Добавил метод для вычисления extension на основе ImageFormat, теперь беру его из Bitmap.RawFormat

Comment on lines +21 to +25
var bitmap = CalculateCloudBounds(wordLayouts).AsResult()
.Then(bounds => CreateBitmapForCloud(wordLayouts, visualizationOptions.ImageWidthPx,
visualizationOptions.ImageHeightPx, visualizationOptions.Padding, bounds))
.Then(bitmap => DrawWordsOnBitmap(bitmap, wordLayouts, visualizationOptions));
return bitmap;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Здесь хочу еще раз подсветить тебе момент владения объектом. Битмап возникает здесь и передается куда-то наружу. Здесь выходит неявная передача владения.

Вот тут я сошлюсь на комментарий про умный указатель.

Реализовывать его не нужно, но внимательнее с такими местами в будущем


if (bounds.Width > imageWidthPx.Value || bounds.Height > imageHeightPx.Value)
return Result.Fail<Bitmap>(
"Cloud bounds are larger than image size. Try to increase imageSize, or leave them empty for auto calculation");
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Тут кстати по разному можно трактовать. Для рисования это не то чтобы ошибка, потому что объекты вне границ изображения будут просто обрезаны

}
else
{
var cloudBounds = CalculateCloudBounds(wordLayouts);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно считать перед if, тогда внутри DrawWordsWithFixedSIze можно этот вызов убрать

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Вынес за if

foreach (var (word, frequency) in sortedWords)
{
var fontSize = CalculateFontSize(frequency, maxFrequency);
var wordSize = GetWordSize(word, fontSize, _visualizationOptions.FontFamily);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Здесь потенциально NullReferenceException, если _visualizationOptions не был задан

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Сделал string вместо string?, оказывается там и так все это время было значение по умолчанию внутри самого VisualizationOptions

Comment on lines +8 to +16
public static Result<string> SaveFile(Bitmap bitmap, string path)
{
var extension = Path.GetExtension(path).ToLower();
var imageFormat = extension.GetImageFormat();
if (!imageFormat.IsSuccess)
return Result.Fail<string>(imageFormat.Error);
bitmap.Save(path, imageFormat.Value);
return Result.Ok(path);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

С текущим подходом в этом методе должен быть безусловный вызов Dispose для bitmap

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Добавил .Dispose

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если вызов extension.GetImageFormat не будет успешным, то bitmap мы не освободим. Освобождать его надо в любом случае

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Стал собирать Result через условия, потом освобождать битмап, и только потом возвращать result

@SquirrelLeonid
Copy link
Copy Markdown

Задачу засчитываю на полный балл

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