Skip to content

Conversation

@spirinamayya
Copy link
Owner

No description provided.

Copy link
Collaborator

@DimaTrushin DimaTrushin left a comment

Choose a reason for hiding this comment

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

Есть несколько общих слов.

  1. добавить .gitignore
  2. убрать .DS_Store файл
  3. подключить clang-format для форматирования кода

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

Connection.cpp Outdated
_controller.ptr = &_model;
_view.subscribe(_controller.input());
_model.subscribe(_view.input());
} No newline at end of file
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не надо радовать пользователя гит репозитория "кирпичами". Делай пустую строку в конце каждого файла.

main.cpp Outdated
Comment on lines 7 to 9
MainWindow w;
Connection c(&w);
w.show();
Copy link
Collaborator

Choose a reason for hiding this comment

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

Вот это все выглядит как "кишки" единого объекта Application.
-Во-первых, у тебя раскиданы разные части по main, которые делают случайную работу, это нарушение уровня абстракции.

  • Во-вторых, я бы видел эту часть так. Надо создать объект application, который в себе содержит все нужные ресурсы и в своем конструкторе их инициализирует. Например так
class Application {
public:
private:
  Model model_;
  View view_;
  Controller controller_;
};

При этом MainWindow должна быть частью View или должна выдать View необходимые ресурсы для работы.

  • В-третьих, у тебя совсем не понятна роль Connection.
  • Функция show() должна бызываться в конструкторе view.

Connection.h Outdated
//~Connection();

private:
AVLTree _model;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не делай _ в начале имен. Дело в том, что имена начинающиеся с _ или __ зарезервированы по стандарту (в данном случае проблем нет, но очень легко ошибиться). Потому лучше сделать их в конце.

Connection.h Outdated

#include "Controller.h"

class Connection{
Copy link
Collaborator

Choose a reason for hiding this comment

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

Вот этот объект надо сделать Application, а MainWindow запихнуть во view.

Connection.h Outdated
#define COURSEPROJECT_CONNECTION_H

#include "Controller.h"

Copy link
Collaborator

Choose a reason for hiding this comment

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

Помести весь свой проект в namespace. Не пиши ничего в global namespace.

Model.h Outdated

// std::vector<Node*> root_;
Node* root_ = nullptr;
int Value;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Вот это что такое? Зачем в дереве какое-то value дополнительно? Кроме того, ты имена переменных пишешь то с большой то с маленькой буквы. Надо определиться и выбрать единый стиль.

Model.cpp Outdated
insertPort.notify();
}

void AVLTree::clearHelp(Node*& node)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Функции в cpp файле должны идти в том же порядке, в каком они объявлены в header-е. Иначе невозможно искать нужную функцию.

Model.cpp Outdated
Comment on lines 5 to 7
int l = 0, r = 0;
if(left != nullptr)
l = left->height;
Copy link
Collaborator

Choose a reason for hiding this comment

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

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

static int getHeight(const Node* node) {
  if (node == nullptr)
    return 0;
  return node->height;
}

И тогда можно будет просто написать

static int findMaxHeight(const Node* left, const Node* right) {
  return std::max(getHeight(left), getHeight(right));
}

Model.cpp Outdated


Node* AVLTree::insert(Node* node, int key)
{
Copy link
Collaborator

Choose a reason for hiding this comment

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

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

Model.cpp Outdated

if(root_== nullptr)
return;
insertPort.notify();
Copy link
Collaborator

Choose a reason for hiding this comment

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

Если я правильно понял, то у тебя нет анимации.

Copy link
Collaborator

@DimaTrushin DimaTrushin left a comment

Choose a reason for hiding this comment

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

В целом неплохо.
Потерян Model.h файл.
Еще есть несколько утечек во View.
И мне не нравится как задизайнен обход дерева, но видимо это надо так и оставить.

Controller.cpp Outdated
}

void Controller::action(const ViewData &data) {
if(data.operation == View::Operation::Add)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Я бы сделал switch по enum-у

Controller.cpp Outdated
else if(data.operation == View::Operation::Search)
model_->search(data.value);
else if(data.operation == View::Operation::Traversal && data.type == View::Type::InOrder)
model_->inOrder();
Copy link
Collaborator

Choose a reason for hiding this comment

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

А что это за команда у дерева? Это чисто для визуацилации или это какой-то запрос у дерева, который оно выполняет?

InfoTree.h Outdated
Info* copy(const Node* node);
void calcYCoord(const Node* node);

static constexpr int RADIUS = 40;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не пиши только большими буквами, так обычно пишут макросы, если нужны константы, то добавь k в начале, например kRadius или k_radius в зависимости от стиля. И можно _ в конце имени для единообразия.

InfoTree.cpp Outdated
}

void InfoTree::calcYCoord(const Node *rootGet) {
root_ = copy(rootGet);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Вынеси эту строчку в список инициализации в конструкторе

InfoTree::InfoTree() : root_(copy(rootGet)) {
  calcYCoord();
  calcXCoord();
}

Дело в том, что эта функция копирования не имеет отношения к вычислению координат, она строит дерево. Ее еще стоит переименовать в buildInfoTree или что-то такое.

Comment on lines +100 to +101
std::queue<Info *> que;
que.push(root);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Это ты от рекурсии избавлялась?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Не могу найти Model.h файл.

Model.cpp Outdated
port_.notify();
}

void AVLTree::inOrder() {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не лучшее решение. Вообще говоря, не понятно что такое эта операция для дерева.
Если это вопрос анимации, то это должно делаться на уровне InfoTree. А так что эта операция делает с деревом? Наверное сейчас уже лучше так и оставить, но в целом это ошибка дизайна.

Model.cpp Outdated
return cur;
}

void AVLTree::twoChildren(Node* node)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Вот это непонятная функция. У нее в названии нет глагола. Что она делает?

Model.cpp Outdated
node->rightCh = deleteNode(node->rightCh, cur->key);
}

Node* AVLTree::oneZeroChildren(Node* node)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Вот тут тоже не понятно, что функция делает, нет глагола.

</widget>
<pixmapfunction/>
<connections/>
</ui> No newline at end of file
Copy link
Collaborator

Choose a reason for hiding this comment

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

кирпич

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.

3 participants