-
Notifications
You must be signed in to change notification settings - Fork 23
Виолетта Мамыкина, Адресная книга #5
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
base: master
Are you sure you want to change the base?
Conversation
| public static void main(String[] args) { | ||
| logger.debug("Logging example"); | ||
| System.out.println("Hello World!"); | ||
| public static class Address { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Имя класса и имя файла должны совпадать. Переименуйте, пожалуйста, файл.
| private int flat; | ||
|
|
||
| Address(String street, int house, int flat) { | ||
| this.street = street; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Передаваемые аргументы необходимо проверять на корректность, особенно если речь про публичные методы и конструкторы. Насколько это корректно, если house окажется равным -5?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если класс public, то и конструктор уместно сделать public.
| private static Map<Person, Address> addressBook = new LinkedHashMap<>(); | ||
|
|
||
| public addressBook(Map<Person, Address> myMap) { | ||
| this.addressBook = myMap; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
HashMap является изменяемым (mutable) типом, поэтому если кто-то извне случайно изменит myMap, то изменения отразятся и на addressBook. Чтобы избежать подобных сюрпризов, лучше создавать новый объект и заполнять его данными из myMap.
| } | ||
|
|
||
|
|
||
| public void addAddressBook(Person person, Address address) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
addAddressBook? Не очень подходящее название. Мы добавляем адресную книгу? Или человека с его адресом?
| public Address getAddress(Person person) throws IllegalAccessException { | ||
| if (addressBook.containsKey(person)) { | ||
| return addressBook.get(person); | ||
| } else throw new IllegalAccessException(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если ставите фигурные скобки около одной ветви if, то ставьте их и около другой, для симметричности и удобства чтения.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IllegalAccessException - не самый подходящий тип исключения (по смыслу). Есть варианты получше.
| Main.addressBook addressBook = createAddressBook(); | ||
| addressBook.changeAddressBook(((Main.Person) MyMap.keySet().toArray()[1]), new Main.Address("Харченко", 16, 540)); | ||
| addressBook.changeAddressBook((Main.Person) MyMap.keySet().toArray()[0], new Main.Address("Шателена", 18, 8)); | ||
| try { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не нужно ловить исключения в тестах. Если будет выброшено исключение, то система тестирования сама его поймает и сообщит о нем.
| return this.street; | ||
| } | ||
|
|
||
| public Integer getHouse() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Используйте примитивные типа (int) везде, где можно. Integer используется только там, где нельзя использовать int.
| return listOfPerson; | ||
| } | ||
|
|
||
| public List findOnHouse(String street, Integer house) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не забывайте указывать, какого типа данные хранит внутри себя List (с помощью обобщенных типов, generic types).
| public List findOnHouse(String street, Integer house) { | ||
| List<Person> listOfPerson = new ArrayList<>(); | ||
| for (Person person : addressBook.keySet()) { | ||
| if (addressBook.get(person).street == street && addressBook.get(person).house == house) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
См. findOnStreet
| private static final Logger logger = LogManager.getLogger(MainTest.class); | ||
| private static Map<Main.Person, Main.Address> MyMap = new LinkedHashMap<>(); | ||
|
|
||
| private static Main.addressBook createAddressBook() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Сделайте так, чтобы к классам можно было обращаться, не указывая Main.
| import java.util.Objects; | ||
|
|
||
| public class Address { | ||
| public String street; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если вы пишете геттеры, то поля делайте private, иначе смысла нет в геттерах.
| public class Address { | ||
| public String street; | ||
| public int house; | ||
| private int flat; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Поле private, но для него нет геттера. Что-то записали в объект, а прочитать это не можем.
|
|
||
| @Override | ||
| public String toString() { | ||
| return street + " " + house + " " + flat; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Адреса обычно пишут через запятую. указывая, где квартира, а где номер дома. Поищите, как пишут адреса.
| public class AddressBook implements AddressBookInterface{ | ||
| public Map<Person, Address> addressBook = new LinkedHashMap<>(); | ||
|
|
||
| public AddressBook() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если у вас только один конструктор и он пустой, то его можно не писать.
| } | ||
|
|
||
| public void addPersonWithAddress(Person person, Address address) { | ||
| addressBook.put(person, address); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
put молча перезапишет запись, если такой человек уже был ранее добавлен. Пусть метод выдает ошибку, когда мы пытаемся перезаписать адрес, для этого всё-таки есть отдельный метод
| import java.util.Objects; | ||
|
|
||
| public class Person { | ||
| public String name; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Напишите геттер, а поле сделайте private.
| } | ||
|
|
||
| public void changeAddress(Person person, Address address) { | ||
| if (addressBook.containsKey(person)) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Уместно сообщить об ошибке, если ничего не заменили.
| private int flat; | ||
|
|
||
| public Address(String street, int house, int flat) { | ||
| this.street = street; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Адрес тоже наверное стоит проверять, как минимум пустым он быть не может.
| private static final Logger logger = LogManager.getLogger(MainTest.class); | ||
| private static AddressBook createAddressBook() { | ||
| AddressBook addressBook = new AddressBook(); | ||
| addressBook.addPersonWithAddress(new Person("Дженжер"), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
С тестами всё хорошо, только не вижу тестов с некорректными данными. И вообще проверки некорректных ситуаций.
| if (house <= 0 || flat <= 0) throw new IllegalArgumentException(); | ||
| this.house = house; | ||
| this.flat = flat; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Задание несложное, так что давайте сделаем что-нибудь дополнительное, чтобы я со спокойной душой поставил вам 5. Как насчет того, чтобы сделать конструктор для Address, который бы считывал адрес из строки? Строку брать в каком-нибудь готовом формате, например, почтовом.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я давно вас не проверял, поэтому могу несколько дней подождать.
h31
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Исправьте замечание к toString и к тестам. Если всё будет в порядке с исправлениями, я готов поставить 5.
| } | ||
| try { | ||
| addressBook.addPersonWithAddress(new Person("Виноградный"), | ||
| new Address("наб.Фонтанки", -8, 359)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Как раз для случаев, когда нужно проверить, что при указанных входных данных метод выбрасывает исключение, создан тестовый метод assertThrows. Там, где исключения быть не должно, try лучше убрать.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не забудьте добавить тест для задания адреса из строки. С корректными и некорректными данными.
|
|
||
| public List<Person> findOnStreet(String street) { | ||
| List<Person> listOfPerson = new ArrayList<>(); | ||
| for (Map.Entry<Person, Address> mapSet : addressBook.entrySet()) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Речь была про mapSet, я бы назвал его addressBookEntry или addressBookRecord. Хотя имя метода тоже стало лучше, правильное изменение.
| @Override | ||
| public String toString() { | ||
| return street + " " + house + " " + flat; | ||
| return " ул. " + street + ", д. " + house + ", кв. " + flat; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Пробел в начале строки, двоеточие в Person.toString - это всё нужно перенести в более подходящие места.
| } | ||
|
|
||
| public Address(String address) { | ||
| if (address.matches("ул\\.\\s+.+,\\s+д\\.\\s+\\d+,\\s+кв\\.\\s+\\d+")) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Раз уж вы используете регулярку, есть смысл использовать группы для извлечения конкретных полей из строки.
|
Ставлю 5. |
No description provided.