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

Зубков Андрей #210

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

Conversation

HardreaM
Copy link

@HardreaM HardreaM commented Dec 3, 2023

No description provided.

Copy link

@razor2651 razor2651 left a comment

Choose a reason for hiding this comment

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

я не стал дублировать комментарии, например про ArgumentException, встречается несколько раз, поэтому пройдись по коду и посмотри встречаются ли еще где-то проблемы обозначенные в комментариях

}

[Test]
public void CircularCloudLayoter_RectanglesListEmpty_WhenCreated()

Choose a reason for hiding this comment

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

обычно ты видишь либо полное имя теста, которое строится как <NameSpace>.<ClassName>.<MethodName>.<Casename>
либо ты видишь граф на котором все вышеуказанные пункты так же являются отдельными нодами, поэтому у тебя тут появляется дублирование: CircularCloudLayouter
TagCloudTests.CircularCloudLayouterTests.CircularCloudLayoter_RectanglesListEmpty_WhenCreated

@@ -0,0 +1,46 @@
namespace TagCloudTests
{
[TestFixture]

Choose a reason for hiding this comment

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

тут это лишнее

{
if (rectangleSize.Height <= 0 || rectangleSize.Width <= 0)
{
throw new ArgumentException();

Choose a reason for hiding this comment

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

летит такой пользователь вертолета, и у него на экране вылетает ArgumentException, он не поймет чо произошло, упадет и разобьется

{
public class CircularCloudLayouter : ICircularCloudLayouter
{
private readonly Point center;

Choose a reason for hiding this comment

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

зачем это поле?

private readonly Point center;
private readonly SpiralGenerator spiral;
private IList<Rectangle> rectangles;
public IList<Rectangle> Rectangles => rectangles.ToList().AsReadOnly();

Choose a reason for hiding this comment

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

зачем AsReadOnly?

layouter.PutNextRectangle(new Size(50 + random.Next(0, 100), 50 + random.Next(0, 100)));
}

var bitmap = new Bitmap(1920, 1080);

Choose a reason for hiding this comment

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

какой кошмар, а у тебя тут нет подсказок IDE что здесь что-то не так?


namespace TagCloud;

public class CloudDrawer

Choose a reason for hiding this comment

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

этот класс явно не Drawer, он 'я-все-делаю-er', давай декомпозируем, drawer тут явно выделяется в отдельную сущность

layouter.PutNextRectangle(new Size(50 + random.Next(0, 100), 50 + random.Next(0, 100)));
}

var bitmap = new Bitmap(1920, 1080);

Choose a reason for hiding this comment

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

что будешь делать когда прямоугольники не войдут на картинку?

layouter.PutNextRectangle(new Size(50 + random.Next(0, 100), 50 + random.Next(0, 100)));
}

var bitmap = new Bitmap(1920, 1080);

Choose a reason for hiding this comment

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

у тебя несколько раз повторяются эти константы, захочешь изменить - придется руками искать все места где они находятся и менять руками

{
private const int Width = 1920;
private const int Height = 1080;
private SpiralGenerator spiral;

Choose a reason for hiding this comment

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

это не замечание, а скорее рекомендация
поле/переменную с сущностью которую тестят обычно называют sut (System Under Tests), это не правило, а скорее часто встречающийся подход
часто получается так что тестовый класс содержит в себе десятки других полей, когда ты называешь переменную/поле sut то визуально легко определить что в данном классе тестируется

{
this.center = center;
Rectangles = new List<Rectangle>();
spiral = new SpiralGenerator(center);

Choose a reason for hiding this comment

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

создавать зависимости руками в коде не является хорошей практикой, так у тебя cloudLayouter жестко начинает быть связан с конкретным spiralGenerator, а не с его публичным интерфейсом
классы должны зависеть от абстракций, давай будем работать с этой сущностью через абстракцию и принимать эту зависимость извне

rectangle.Offset(-vector.Item1, 0);
}

private void ShiftRectangleInYDirection(ref Rectangle rectangle, (int, int) vector)

Choose a reason for hiding this comment

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

у тебя тут два метода с оптимизацией укладки, но есть целый ворох проблем:

  1. сразу напрашивается вопрос о дублировании

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

  3. старайся не использовать неименованные таплы, на таком простом примере возможно спустя полгода ты и быстро восстановишь контекст что такое item1 и item2, но проще либо именовать значения в тапле, либо все таки выделять какие-то контракты, к тому же не очень понятно чем не подошел Point, те же (x, y), думаю в контексте координатной плоскости использование структуры Point для описания вектора с именем переменной vector вполне понятно

  4. кажется что проверки на центр и 0 нужны только для первого прямоугольника (но тут я может чего не понял), и выполняются лишний раз для всех остальных

  5. по сути у тебя сейчас получается очень жесткая неявная зависимость на генератор точек, если я реализую другую абстракцию, например: DinosaurPointGenerator - которая будет выдавать точки на плоскости в форме динозавра, то такая оптимизация все только сломает при подмене зависимости

  6. кажется что производительность этой оптимизации будет сильно зависеть от выбраного шага для генератора, а результат не сильно то и стоит того, взгляни на разницу с оптимизацией и без нее
    (справа с оптимизацией, слева - без)
    ну и не забывай что у нас тут нет задачи сделать строго оптимальную укладку
    image
    image


public static class CloudDrawer
{
public static Bitmap DrawTagCloud(CircularCloudLayouter layouter, int border = 10)

Choose a reason for hiding this comment

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

почему у тебя drawer получает зависимость в методе извне, а не данные?

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