Skip to content

Conversation

@Violetta-Mamykina
Copy link

No description provided.

public static void main(String[] args) {
logger.debug("Logging example");
System.out.println("Hello World!");
public static class Address {
Copy link
Owner

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;
Copy link
Owner

Choose a reason for hiding this comment

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

Передаваемые аргументы необходимо проверять на корректность, особенно если речь про публичные методы и конструкторы. Насколько это корректно, если house окажется равным -5?

Copy link
Owner

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;
Copy link
Owner

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) {
Copy link
Owner

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();
Copy link
Owner

Choose a reason for hiding this comment

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

Если ставите фигурные скобки около одной ветви if, то ставьте их и около другой, для симметричности и удобства чтения.

Copy link
Owner

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 {
Copy link
Owner

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() {
Copy link
Owner

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) {
Copy link
Owner

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) {
Copy link
Owner

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() {
Copy link
Owner

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;
Copy link
Owner

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;
Copy link
Owner

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;
Copy link
Owner

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() {
Copy link
Owner

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);
Copy link
Owner

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;
Copy link
Owner

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)) {
Copy link
Owner

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;
Copy link
Owner

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("Дженжер"),
Copy link
Owner

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;
}
Copy link
Owner

Choose a reason for hiding this comment

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

Задание несложное, так что давайте сделаем что-нибудь дополнительное, чтобы я со спокойной душой поставил вам 5. Как насчет того, чтобы сделать конструктор для Address, который бы считывал адрес из строки? Строку брать в каком-нибудь готовом формате, например, почтовом.

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

@h31 h31 left a 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));
Copy link
Owner

Choose a reason for hiding this comment

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

Как раз для случаев, когда нужно проверить, что при указанных входных данных метод выбрасывает исключение, создан тестовый метод assertThrows. Там, где исключения быть не должно, try лучше убрать.

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<Person> findOnStreet(String street) {
List<Person> listOfPerson = new ArrayList<>();
for (Map.Entry<Person, Address> mapSet : addressBook.entrySet()) {
Copy link
Owner

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;
Copy link
Owner

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+")) {
Copy link
Owner

Choose a reason for hiding this comment

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

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

@h31
Copy link
Owner

h31 commented Mar 15, 2018

Ставлю 5.

@h31 h31 added the excellent Отлично label Mar 15, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

excellent Отлично

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants