mipt-java-2016 icon indicating copy to clipboard operation
mipt-java-2016 copied to clipboard

Calculator. Trotsiuk Vladislav g599

Open vladtrotsiuk opened this issue 8 years ago • 6 comments

vladtrotsiuk avatar Oct 16 '16 14:10 vladtrotsiuk

Здравствуйте!

"Придумай, как изменить интерфейс так, чтобы можно было бы и DataInputStream/DataOutputStream использовать, не только RandomAccessFile"

Я теперь использую DataInputStream/DataOutputStream, но теперь у меня валятся тесты с ошибкой java.lang.NullPointerException, хотя файл существует. Не могли ли Вы подсказать в чём ошибка? ( https://github.com/fediq/mipt-java-2016/pull/110)

2016-11-12 19:13 GMT+03:00 DanAnastasyev [email protected]:

@DanAnastasyev commented on this pull request.

In homework-g599-trotsiuk/pom.xml https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-8299930 :

@@ -25,6 +25,12 @@ 1.0.0 test

  •    <dependency>
    
  •        <groupId>ru.mipt.java2016</groupId>
    
  •        <artifactId>homework-tests</artifactId>
    
  •        <version>1.0.0</version>
    
  •    </dependency>
    

Убери это: просто перенеси классы с сериализацией Student в пакедж с тестами - тогда и не нужно будет зависимости трогать

In homework-g599-trotsiuk/src/main/java/ru/mipt/java2016/ homework/g599/trotsiuk/task2/DataBase.java https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-8299930 :

  •    try {
    
  •        dbFileName = Paths.get(path);
    
  •        data = new HashMap<>();
    
  •        dbFile = new File(path + File.separator + "storage.db" + ".lock");
    
  •        if (!dbFile.exists() && !dbFile.createNewFile()) {
    
  •            throw new FileNotFoundException("DataBase: Cannot create new database file");
    
  •        }
    
  •        this.serializerKey = serializerKey;
    
  •        this.serializerValue = serializerValue;
    
  •        File database = new File(path + File.separator + "storage.db");
    
  •        file = new RandomAccessFile(database, "rw");
    
  •        if (!database.createNewFile()) {
    

Ну ведь так и просится же выделить в отдельный метод чтение файла. Зачем писать такой длинный конструктор

In homework-g599-trotsiuk/src/main/java/ru/mipt/java2016/ homework/g599/trotsiuk/task2/DataBase.java https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-8299930 :

  •                }
    
  •            }
    
  •        }
    
  •    } catch (FileNotFoundException e) {
    
  •        e.printStackTrace();
    
  •    }
    
  • }
  • @Override
  • public V read(K key) {
  •    checkNotClosed();
    
  •    if (data.containsKey(key)) {
    
  •        return data.get(key);
    
  •    } else {
    
  •        return null;
    
  •    }
    

Ты можешь переписать этот if одной строчкой. Посмотри документацию Map К contains, remove это тоже относится

In homework-g599-trotsiuk/src/main/java/ru/mipt/java2016/ homework/g599/trotsiuk/task2/DataBase.java https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-8299930 :

  •        file = new RandomAccessFile(database, "rw");
    
  •        if (!database.createNewFile()) {
    
  •            if (file.length() > 0) {
    
  •                while (file.getFilePointer() < file.length()) {
    
  •                    K key = serializerKey.deserializeRead(file);
    
  •                    V value = serializerValue.deserializeRead(file);
    
  •                    if (data.containsKey(key)) {
    
  •                        throw new IOException("DataBase.readFromFile: Two same keys in database file");
    
  •                    }
    
  •                    data.put(key, value);
    
  •                }
    
  •            }
    
  •        }
    
  •    } catch (FileNotFoundException e) {
    
  •        e.printStackTrace();
    

А это нормально, что ты внутри блока кидаешь FileNotFoundException - и тут же его ловишь?

In homework-g599-trotsiuk/src/main/java/ru/mipt/java2016/ homework/g599/trotsiuk/task2/Serializer.java https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-8299930 :

@@ -0,0 +1,11 @@ +package ru.mipt.java2016.homework.g599.trotsiuk.task2;

+import java.io.IOException; +import java.io.RandomAccessFile; + +interface Serializer<K> { +

  • void serializeWrite(K value, RandomAccessFile dbFile) throws IOException;

Придумай, как изменить интерфейс так, чтобы можно было бы и DataInputStream/DataOutputStream использовать, не только RandomAccessFile

In homework-g599-trotsiuk/src/test/java/ru/mipt/java2016/ homework/g599/trotsiuk/task2/MyKeyValueStorageTest.java https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-8299930 :

+package ru.mipt.java2016.homework.g599.trotsiuk.task2;

+import ru.mipt.java2016.homework.base.task2.KeyValueStorage; +import ru.mipt.java2016.homework.tests.task2.AbstractSingleFileStorageTest; +import ru.mipt.java2016.homework.tests.task2.Student; +import ru.mipt.java2016.homework.tests.task2.StudentKey; + +import java.io.IOException; + +public class MyKeyValueStorageTest extends AbstractSingleFileStorageTest { +

  • @Override
  • protected KeyValueStorage<String, String> buildStringsStorage(String path) {
  •    try {
    
  •        return new DataBase<>(path, new SerializerString(), new SerializerString());
    
  •        } catch (IOException e) {
    

Поправь тут форматирование

In homework-g599-trotsiuk/src/main/java/ru/mipt/java2016/ homework/g599/trotsiuk/task2/DataBase.java https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-8299930 :

  •    if (data.containsKey(key)) {
    
  •        data.remove(key);
    
  •    }
    
  • }
  • @Override
  • public Iterator<K> readKeys() {
  •    checkNotClosed();
    
  •    return data.keySet().iterator();
    
  • }
  • @Override
  • public int size() {
  •    return data.size();
    

На закрытом хранилище (с data == null) NPE полетит...

In homework-g599-trotsiuk/src/main/java/ru/mipt/java2016/ homework/g599/trotsiuk/task2/DataBase.java https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-8299930 :

  • public int size() {
  •    return data.size();
    
  • }
  • @Override
  • public void close() throws IOException {
  •    try {
    
  •        file.setLength(0);
    
  •        file.seek(0);
    
  •        for (Map.Entry<K, V> current : data.entrySet()) {
    
  •            serializerKey.serializeWrite(current.getKey(), file);
    
  •            serializerValue.serializeWrite(current.getValue(), file);
    
  •        }
    
  •        file.close();
    
  •        Files.delete(dbFile.toPath());
    

Зачем?!

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-8299930, or mute the thread https://github.com/notifications/unsubscribe-auth/AVyOZm6iVzvPj-pNuGUi7pG5KjLkZJZcks5q9eW4gaJpZM4KX_Cc .

vladtrotsiuk avatar Dec 01 '16 18:12 vladtrotsiuk

Не, я хотел только изменения в интерфейсе. Смотри, ты можешь сделать так:

interface Serializer<K> {
    void serializeWrite(K value, DataOutput target)  throws IOException;
    K deserializeRead(DataInput source) throws IOException;
}

Этот интерфейс принимает не конкретные реализации - RandomAccessFile или DataInputStream/DataOutputStream - а интерфейсы, которые они реализуют. Тогда в своей базе данных ты можешь передавать в Serializer как RandomAccessFile, так и DataInputStream/DataOutputStream. А реализации интерфейса Serializer при этом не изменятся

DanAnastasyev avatar Dec 04 '16 11:12 DanAnastasyev

Исправил, но 4 теста все равно не проходят.

2016-12-04 14:30 GMT+03:00 DanAnastasyev [email protected]:

@DanAnastasyev commented on this pull request.

In homework-g599-trotsiuk/src/main/java/ru/mipt/java2016/ homework/g599/trotsiuk/task2/DataBase.java https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-11292878 :

 public DataBase(String path, Serializer<K> serializerKey, Serializer<V> serializerValue) throws IOException {
  •    try {
    
  •        dbFileName = Paths.get(path);
    
  •        data = new HashMap<>();
    

Ты не создаешь свой Map. Поэтому NullPointerException Можно прямо при объявлении переменной её инициализировать: private Map<K, V> data = new HashMap<>();

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/fediq/mipt-java-2016/pull/110#pullrequestreview-11292878, or mute the thread https://github.com/notifications/unsubscribe-auth/AVyOZkksGMpkQ-WyNLYjNt93mOq7UJHyks5rEqRCgaJpZM4KX_Cc .

vladtrotsiuk avatar Dec 19 '16 08:12 vladtrotsiuk

Здравствуйте! Я пофисил и отправил Вам задачи, у меня есть шанс получить за них какие-то баллы?

vladtrotsiuk avatar Dec 19 '16 23:12 vladtrotsiuk

Здравствуйте! Я пофисил и отправил Вам задачи, у меня есть шанс получить за них какие-то баллы?

А где пофисил-то? Ты же сам пишешь, что 4 теста не проходит то, что тут сейчас лежит

DanAnastasyev avatar Dec 20 '16 11:12 DanAnastasyev

https://github.com/fediq/mipt-java-2016/pull/110 переделал, теперь всё проходит Еду с Москвы, опаздываю

vladtrotsiuk avatar Dec 20 '16 13:12 vladtrotsiuk