Skip to content

Шипицын Павел#275

Open
PavelMartinelli wants to merge 11 commits into
kontur-courses:masterfrom
PavelMartinelli:Tag_Cloud_1HW
Open

Шипицын Павел#275
PavelMartinelli wants to merge 11 commits into
kontur-courses:masterfrom
PavelMartinelli:Tag_Cloud_1HW

Conversation

@PavelMartinelli

Copy link
Copy Markdown


namespace TagsCloudVisualization;

public class CircularCloudLayouter

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Необходимо вынести интерфейс лейаутера

Comment on lines +75 to +109
private bool TryMoveTowardsCenterX(ref Rectangle rectangle)
{
var centerX = rectangle.X + rectangle.Width / 2;
var direction = Math.Sign(_center.X - centerX);

if (direction == 0)
return false;

var movedRectangle = rectangle;
movedRectangle.X += direction;

if (IntersectsWithAny(movedRectangle))
return false;

rectangle = movedRectangle;
return true;
}

private bool TryMoveTowardsCenterY(ref Rectangle rectangle)
{
var centerY = rectangle.Y + rectangle.Height / 2;
var direction = Math.Sign(_center.Y - centerY);

if (direction == 0)
return false;

var movedRectangle = rectangle;
movedRectangle.Y += direction;

if (IntersectsWithAny(movedRectangle))
return false;

rectangle = movedRectangle;
return true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Методы TryMoveTowardsCenterX и TryMoveTowardsCenterY очень похожи. Попробуй объединить их в один общий метод.

return true;
}

private IEnumerable<Point> GetSpiralPoints()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше вынести в отдельный PointsProvider


namespace TagsCloudVisualization;

public class GeneratorTagCloud

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Странное название. Лучше TagCloudGenerator

public class GeneratorTagCloud
{
private readonly TagCloudVisualizer _cloudVisualizer;
private readonly Func<Point, CircularCloudLayouter> _layouterFactory;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

_layouterFactory должна быть снаружи генератора.

Comment on lines +61 to +65
public string GenerateFileName(string fileName)
{
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
return $"{fileName}_{timestamp}.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.

Генерация имени файла - тоже не ответственность визуализатора.

Comment on lines +12 to +13
public string OutputFileName { get; set; }
public Size? ImageSize { get; set; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

{
center = new Point(100, 100);
layouter = new CircularCloudLayouter(center);
var dir = Directory.CreateDirectory($"../../../../TagsCloudVisualizationTests/test_results");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Такие относительные пути имеют шанс сломаться. Лучше использовать AppDomain.CurrentDomain.BaseDirectory. К тому же, после разделения ответственностей здесь не должно остаться логики, связанной с сохранением в файл и визуализацией. Поэтому на визуализатор нужно писать отдельные тесты.

for (var i = 0; i < 5; i++)
layouter.PutNextRectangle(new Size(45, 15));

var rectangles = layouter.PlacedRectangles.ToList();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

В текущей реализации лейаутера PlacedRectangles итак коллекция, поэтому дополнительно перечислять её в лист - бессмысленно.


var maxCount = quadrants.Max();
var minCount = quadrants.Min();
(maxCount <= minCount * 2).Should().BeTrue();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Что здесь проверяется? Не очевидно, почему это условие должно выполняться. Поэтому лучше вынести в отдельный тест.

@tripples25

Copy link
Copy Markdown
image sln не может подгрузить проекты

@tripples25

Copy link
Copy Markdown
image в csproj ничего не лежит по папкам, сложно ориентироваться в файлах

@tripples25

Copy link
Copy Markdown

Не могу прогнать тесты, из-за проблем с солюшеном

_minDimension = int.MaxValue;
}

public IReadOnlyList<Rectangle> PlacedRectangles => _placedRectangles.AsReadOnly();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Это свойство не нужно, PutNextRectangle возвращает прямоугольник. Обращений к нему быть не должно более

private readonly Point _center;
private readonly List<Rectangle> _placedRectangles;
private readonly ISpiralPointsProvider _pointsProvider;
private int _minDimension;

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.

Это поле нужно для адаптивного изменения плотности точек спирали: чем меньше прямоугольники, тем плотнее спираль; чем больше прямоугольники, тем реже точки.

if (rectangleSize.Width <= 0 || rectangleSize.Height <= 0)
throw new ArgumentException("Rectangle size must have positive dimensions");

UpdateMinDimension(rectangleSize);

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 (IntersectsWithAny(candidateRectangle))
continue;

CompactRectangle(ref candidateRectangle);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Рефы не следует использовать без веской на то причины. Здесь причины их использовать нет

Comment on lines +7 to +11
private const double AngleStep = 0.05;
private const double RadiusStepFactor = 0.05;

private double _currentRadius;
private double _currentAngle;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Почему эти поля не задаются через конструктор?


public interface IImageSaver
{
string GenerateFileName(string baseName);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Не используется в основном проекте, можно убрать


public interface IVisualizer
{
Bitmap CreateVisualization(IEnumerable<Rectangle> rectangles, Point center, TagCloudVisualizationConfig config);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Не используется


private bool IntersectsWithAny(Rectangle rectangle)
{
return _placedRectangles.Any(rect => rect.IntersectsWith(rectangle));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Может лучше начинать с конца проверять?

Comment on lines +71 to +73
var centerCoord = axis == Axis.X ? rectangle.X + rectangle.Width / 2 : rectangle.Y + rectangle.Height / 2;

var targetCoord = axis == Axis.X ? _center.X : _center.Y;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Кодстайл

for (var i = 0; i < 50; i++)
layouter.PutNextRectangle(new Size(45, 15));

const double minDensityRatio = 0.3;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Не маловато ли значение? По-хорошему должно быть больше 0.6-0.7. Попробуй тут большее количество прямоугольников расположить

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