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

Заколюкин Степан #208

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

Conversation

StepanZakolukin
Copy link

No description provided.

Copy link

@w1jtoo w1jtoo left a comment

Choose a reason for hiding this comment

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

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

Конечно, за исключением GetValueOrThrow :)

  • по идее, везде, где у тебя используется Result у тебя должен быть тест на состояние Failed. Но это не обязательно, но хотелось бы)

</ItemGroup>

<ItemGroup>
<ProjectReference Include="D:\.NET_projects\fp\ErrorHandling\ErrorHandling.csproj" />
Copy link

Choose a reason for hiding this comment

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

У меня не сработает, да и почти у всех кроме тебя => даже запустить не получится

Copy link
Author

Choose a reason for hiding this comment

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

Поменял на относительный путь


public class TxtReader : IReader
{
public ImmutableHashSet<string> AvailableExtensions { get; } = ImmutableHashSet.Create<string>(".txt");
Copy link

Choose a reason for hiding this comment

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

nit: по смыслу скорее Supported. Available вроде типа "доступный" (как кабинка туалета), а "supported" типа поддержанный.

Copy link
Author

Choose a reason for hiding this comment

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

Переименовал

var fileExtension = Path.GetExtension(pathToFile);
if (!_readers.TryGetValue(fileExtension, out var reader))
return Result.Fail<Func<IEnumerable<string>>>($"Не найден подходящий {nameof(IReader)} для файла с расширением {fileExtension}");
if (!Path.Exists(pathToFile))
Copy link

Choose a reason for hiding this comment

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

У тебя здесь пара не логичных моментов:

  1. GetReader содержит в себе логику из любого IReader
  2. TxtReader.ReadTextByLine(...) кидает исключение

И это плохо. Представь, что у тебя будет низкоуровневое исключение, оно будет падать только в момент чтения файла (например закончили дескрипторы). Тогда твоя программа развалится с треском.
Аналогично, представь, что завтра у тебя появится чтение из сетевой папки, например, по FTP. Там вообще свой вагон и маленькая тележка исключительных ситуаций. И твой код будет очень сложно расширить.

Подумай, как исправить это

Copy link
Author

Choose a reason for hiding this comment

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

  • Добавил функцию для валидации чтения файла, которая возвращает ActionStatus
  • Избавился от исключений в TxtReader.ReadTextByLine(...)

Arguments = $"-ling {tempFile}",
}
};
process.Start();
Copy link

Choose a reason for hiding this comment

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

Вот в этой строчке скрывается куча исключений, на самом то деле. По хорошему, их бы тоже обработать.

Самая понятная из них, что есть mystem упал. Его же тоже программисты писали, могли где-нибудь ошибиться. Можно такой кейс обработать и, например, сообщить пользователю в UI, что литературная обработка не доступна.

Copy link

Choose a reason for hiding this comment

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

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

Copy link
Author

Choose a reason for hiding this comment

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

  • Добавил обработку исключений в работе mystem, читаю поток вывода ошибок процесса
  • Добавил таймаут 5 сек. на парсинг файла, если работает дольше возвращается ActionStatus с сообщением об ошибке

@@ -0,0 +1,7 @@
namespace TagCloud;

public interface ICrrectnessChecker
Copy link

Choose a reason for hiding this comment

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

опечатка

Copy link
Author

Choose a reason for hiding this comment

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

Снимок экрана 2025-01-30 122442
А яндекс переводчик так не считает

Copy link

Choose a reason for hiding this comment

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

Должно быть cOrrectness, у тебя crrectness :)

@@ -0,0 +1,13 @@
namespace TagCloud;

public abstract class CrrectnessChecker : ICrrectnessChecker
Copy link

Choose a reason for hiding this comment

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

А почему бы тогда сюда DTOшку сразу не положить? Я бы конечно отдельно сделал, без наследований (отдельно валидаторы, отдельно коробочки с данными). Но в твоём кейсе неплохо в таком месте сразу данные хранить

Copy link
Author

Choose a reason for hiding this comment

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

Переименовал на CrrectnessCheckerBase

{
var partOfSpeech = elem;
var initialization = () => new WordInfo(word, partOfSpeech, count);
initialization.Should().Throw<ArgumentException>();
Copy link

Choose a reason for hiding this comment

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

Мы же как раз от исключений отказываемся. Может Result должен быть?

Copy link
Author

Choose a reason for hiding this comment

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

Сделал конструктор WordInfo приватным, создание объекта теперь происходит через статический метод Create с возвращением в качестве результата Result

@@ -0,0 +1,17 @@
namespace ErrorHandling;

public struct ActionStatus(string error)
Copy link

Choose a reason for hiding this comment

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

А чем это отличается от условного Result без параметра ? Зачем оно нужно

Copy link
Author

Choose a reason for hiding this comment

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

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

Copy link

Choose a reason for hiding this comment

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

nit: лучше тогда класс расширение переименовать, ибо в нём даже название нигде не будет фигурировать

@@ -9,16 +9,10 @@ private None()
}
}

public struct Result<T>
public readonly struct Result<T>(string error, T value = default)
Copy link

Choose a reason for hiding this comment

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

А можешь раскрыть, зачем тут struct? Ещё и readonly) И чем это лучше record?

@@ -0,0 +1,17 @@
namespace ErrorHandling;

public struct ActionStatus(string error)
Copy link

Choose a reason for hiding this comment

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

nit: лучше тогда класс расширение переименовать, ибо в нём даже название нигде не будет фигурировать

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