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

add basic family tree #1

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

Conversation

alekseigrinko
Copy link

created packages and base classes

public FamilyTree() {
this.treeId = new Random().nextInt(10000);
this.humanList = new ArrayList<>();
System.out.println("Зарегистрировано семейно древо: " + this);
Copy link
Owner

Choose a reason for hiding this comment

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

В теле конструктора, цель которого создать объект класса, вы выводите информацию о всем объекте? То есть конструктор еще не отработал, но объект уже в печати? Это не логично

private String name;
private String surname;
private Gender gender;
private Human spouse;
Copy link
Owner

Choose a reason for hiding this comment

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

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

@alekseigrinko
Copy link
Author

add FileHandler

import java.io.*;

public class FileHandler implements Writable {
String path;
Copy link
Owner

Choose a reason for hiding this comment

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

private не забывайте

Comment on lines 108 to 109
if ((getHuman(getHuman(id).getSpouse().getId()).getSpouse() != null)
&& ((getHuman(getHuman(id).getSpouse().getId()).getSpouse().getId() == id))) {
Copy link
Owner

Choose a reason for hiding this comment

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

Код плохо читаем и непонятен. Стоит как то упростить или хотя бы разбить на приватные методы

Copy link
Owner

Choose a reason for hiding this comment

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

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

}

public List<Human> getHumanWithSortByName() {
return humanList.stream().sorted(new HumanComparatorByName()).collect(Collectors.toList());
Copy link
Owner

Choose a reason for hiding this comment

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

Зачем так сложно то? Разве запись humanList.sort(new HumanComparatorByName()) не проще?

Copy link
Author

Choose a reason for hiding this comment

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

хотел возвращать список, если делаю через humanList.sort, то он не возвращает значение


public void removeSpouse(long id) {
if (getElement(id).getSpouse() != null) {
Human spouse = (Human) getElement(id).getSpouse();
Copy link
Owner

Choose a reason for hiding this comment

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

После обобщения не должно быть упоминания класса Human, код должен быть описан с использованием параметра


public class TreeService<E extends Fundamental<E>> implements BaseFunctions<E>, SortFunctions<E> {

FamilyTree<E> familyTree;

Choose a reason for hiding this comment

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

private

@@ -0,0 +1,144 @@
package ru.gb.family_tree.service.tree_service;

Choose a reason for hiding this comment

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

Сервис это не отдельная сущность. Это тоже часть модели и соответственно должен лежать в пакете модели


public class BaseTerminal<E extends TreeService> implements Vew {

private CommandsService<Item> commandsService;

Choose a reason for hiding this comment

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

Паттерн mvp предполагает, что view никак не зависит от модели, но в вашем есть четкая зависимость. Вам не хватает презентера


import java.util.Scanner;

public class BaseTerminal<E extends TreeService> implements Vew {

Choose a reason for hiding this comment

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

Нет необходимости в дженериках

private CommandsService<Item> commandsService;
private Scanner scanner;

public BaseTerminal(Writable writable) {

Choose a reason for hiding this comment

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

writable также часть модели и view никак не должно от него зависеть

Comment on lines 25 to 40
if (command == 1) {
commandsService.doCommand("Активировать новое дерево");
} else if (command == 2) {
commandsService.doCommand("Добавить элемент дерева");
} else if (command == 3) {
commandsService.doCommand("Показать все элементы дерева");
} else if (command == 4) {
commandsService.doCommand("Сохранить изменения");
} else if (command == 5) {
commandsService.doCommand("Загрузить последние сохраненные изменения");
} else if (command == 0) {
System.out.println("Выход из меню.");
break;
} else {
System.out.println("Некорректная команда, попробуйте ещё раз.");
}

Choose a reason for hiding this comment

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

Нарушение второго принципа солид

Comment on lines 44 to 54
private void menu() {
System.out.println("--------------------------------------------");
System.out.println("Введите команду:");
System.out.println("1 - Активировать новое дерево");
System.out.println("2 - Добавить элемент дерева");
System.out.println("3 - Показать все элементы дерева");
System.out.println("4 - Сохранить изменения");
System.out.println("5 - Загрузить последние сохраненные изменения");
System.out.println("0 - Выход");
System.out.println("--------------------------------------------");
}

Choose a reason for hiding this comment

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

И это нарушение второго принципа солид

import java.util.List;
import java.util.stream.Collectors;

public class TreeService<E extends Fundamental<E>> implements BaseFunctions<E>, SortFunctions<E> {
Copy link
Owner

Choose a reason for hiding this comment

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

Много раз говорил, что не надо делать класс сервиса обобщенным...

e.setId(id);
familyTree.setElementId(id);
familyTree.getElementList().add(e);
System.out.println("В дерево добавлен: " + e);
Copy link
Owner

Choose a reason for hiding this comment

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

Работа с консолью должна выполняться View составляющей проекта

Copy link
Owner

Choose a reason for hiding this comment

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

нарушение первого принципа солид

Comment on lines +118 to +131
@Override
public List<E> SortByName() {
return familyTree.getElementList().stream().sorted(new ElementsComparatorByName<>()).collect(Collectors.toList());
}

@Override
public List<E> SortByBirthday() {
return familyTree.getElementList().stream().sorted(new ElementsComparatorByBirthday<>()).collect(Collectors.toList());
}

@Override
public List<E> SortByChildren() {
return familyTree.getElementList().stream().sorted(new ElementsComparatorByChildren<>()).collect(Collectors.toList());
}
Copy link
Owner

Choose a reason for hiding this comment

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

Методы и их описание должны быть в классе дерева, а отсюда только вызываться

Copy link
Owner

Choose a reason for hiding this comment

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

Сейчас это нарушение первого принципа солид

import java.time.format.DateTimeFormatter;
import java.util.*;

public class Controller<E extends Fundamental<E>> implements Functions {
Copy link
Owner

Choose a reason for hiding this comment

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

Презентер и контроллер используются в разных паттернах. В задании ожидалась реализация именно MVP паттерна


public class Controller<E extends Fundamental<E>> implements Functions {
private TreeService<E> treeService;
private Scanner scanner;
Copy link
Owner

Choose a reason for hiding this comment

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

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

private TreeService<E> treeService;
private Scanner scanner;
private DateTimeFormatter formatter;
private Writable writable;
Copy link
Owner

Choose a reason for hiding this comment

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

Writable это часть модели, а не презентера и не контроллера

Copy link
Owner

Choose a reason for hiding this comment

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

Именно сервис должен взаимодействовать с объектом Writable

Comment on lines +68 to +83
switch (commands) {
case NEW_TREE:
newTree();
break;
case ADD_ITEM:
addItem();
break;
case REMOVE_ITEM:
removeItem();
break;
case ADD_PARENTS:
addParents();
break;
case GET_PARENTS:
getParents();
break;
Copy link
Owner

Choose a reason for hiding this comment

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

свич кейс нарушает второй принцип солид

} else if (i == 2) {
gender = Gender.Female;
}
Item item = new Item(name, surname, birthday, gender);
Copy link
Owner

Choose a reason for hiding this comment

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

Создание объектов модели это работа модели, а не контроллера. Нарушен первый принцип

}

private void getItem() {
System.out.println("Введите ID элемента дерева, информацию по которому хотите получить: ");
Copy link
Owner

Choose a reason for hiding this comment

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

Работа с консолью это работа View

Comment on lines +67 to +71
private List<String> createCommands() {
List<String> list = new ArrayList<>();
list.addAll(this.controller.getCommands().values());
return list;
}
Copy link
Owner

Choose a reason for hiding this comment

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

То есть команды хранятся в контроллере, но пользоваться ими будет View? В этом есть смысл? Команды это по сути строчки либо кнопочки, которые находятся на UI и являются частью View

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