Skip to content

Conversation

@ILFirV-V
Copy link

@ILFirV-V ILFirV-V commented Dec 9, 2024

@@ -0,0 +1,239 @@
using System.Globalization;
using FluentAssertions;

Choose a reason for hiding this comment

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

Привет) давай сначала общие рекомендации:

Содержание коммитов должно быть атомарным. Один коммит - одно логическое изменение. Например, в коммите Add. Решение 4 домашней работы добавлено вообще все: и первое задание, и второе, и тесты, и создание проектов под тест. Аналогично и во втором коммите - что такое рефакторинг? Без чтения кода мне неочевидно, какие были произведены изменения)
Предлагаю обсудить, какие есть плюсы и минусы у такого подхода

Прямо сейчас что-либо делать с коммитами не надо. Это рекомендации на будущее

Copy link
Author

Choose a reason for hiding this comment

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

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

Лучше несколько маленьких коммитов, чем один большой. Спасибо за рекомендацию

</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0"/>

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 PrintingConfig<TOwner> Using(Func<TPropType, string> print)
{
ArgumentNullException.ThrowIfNull(print);

Choose a reason for hiding this comment

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

Правда ли такая проверка нужна?

Copy link
Author

@ILFirV-V ILFirV-V Dec 11, 2024

Choose a reason for hiding this comment

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

Да, это проверка нужна чтобы отлавливать некорректные случаи при конфигурировании и не падать во время сериализации (после изменений в коде, до этого свойство было nullable и были проверки в других местах, можно было вместо этой проверки игнорировать null и не выбрасывать исключение)

Choose a reason for hiding this comment

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

А наличия <Nullable>enable</Nullable> не достаточно?

Copy link
Author

Choose a reason for hiding this comment

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

Думаю достаточно. Поправил

ArgumentNullException.ThrowIfNull(print);
Serializer = printObject =>
{
if (printObject is not TPropType propertyObject)

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.

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

Choose a reason for hiding this comment

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

Обычно, если в коде требуются проверки на корректность типа, то это жирный маркер, что что-то не так с архитектурой приложения. Вполне возможно, что все корректно и так действительно нужно, но примерно в 90% ситуаций это можно поправить переосмыслением подхода

Copy link
Author

Choose a reason for hiding this comment

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

Поправил


namespace ObjectPrinting.Configurations;

public class PropertyPrintingConfig<TOwner, TPropType>(PrintingConfig<TOwner> printingConfig)

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.

Мы можем добавить красивый Extension метод только для строки благодаря этому классу. Интерфейсы нужны для хранения настроек конфигурации в коллекции

.Using(x => $"{x} years")
.PrintToString(testObject);

printedString.Should().Contain($"{testObject.TestInt} years");

Choose a reason for hiding this comment

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

Тест не проверяет, что объект корректно сериализовался. Он лишь проверяет, что в тексте есть некоторая строка 10 years

Copy link
Author

Choose a reason for hiding this comment

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

Переписал с использованием Verify.NUnit

.UsingCommonCulture(culture)
.PrintToString(testObject);

printedString.Should().ContainAll(testDouble.ToString(culture), testFloat.ToString(culture));

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.

Переписал с использованием Verify.NUnit

var printedString = ObjectPrinter.For<PrintingTestObject>()
.PrintToString(testObject);

printedString.Should().Contain("circular reference");

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.

Переписал с использованием Verify.NUnit

var printedString = ObjectPrinter.For<PrintingTestObject>()
.PrintToString(testObject);

printedString.Should().ContainAll("Item1", "Item2", "Item3");

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.

Переписал с использованием Verify.NUnit

using ObjectPrinting.Extensions;
using ObjectPrinting.Tests.TestObjects;

namespace ObjectPrinting.Tests

Choose a reason for hiding this comment

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

  1. Тесты должны проверять всю строку целиком, а не ее части
  2. Нет теста на одновременный набор всех требований. Вдруг все вместе они не работают корректно?
  3. Тесты не покрывают все примитивные и другие типы. Аналогично по другим видам требований - по ним проверяется лишь один кейс, тогда как нужно доказать, что работает хотя бы для большинства

Copy link
Author

Choose a reason for hiding this comment

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

Переписал с использованием Verify.NUnit, добавил тестов

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