如何避免Java中的switch case?

问题描述 投票:0回答:1

我正在为JPA实体编写一个CRUD,我需要实现字段的更新。我在每个类的数组中都有一个可更新的字段名的列表,我要求用户输入他想更新的字段名和他想更新的属性值。我要求用户输入他想更新的字段名和他想更新的属性值。我验证输入的字段名对实体的上下文是否有效,然后,我需要根据属性名更新一些字段。我如何避免在这里使用switch case呢?"代码。

package com.kindgeek.monitoring.service;

import com.kindgeek.monitoring.entity.Person;
import com.kindgeek.monitoring.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PersonService {
    @Autowired
    private PersonRepository personRepository;

    public List<Person> findAll() {
        Iterable<Person> iterable = personRepository.findAll();
        List<Person> persons = new ArrayList<>();
        iterable.forEach(persons::add);
        return persons;
    }

    public Optional<Person> findById(Long id) {
        return personRepository.findById(id);
    }

    public Map<String, String> addPerson(Person person) {
        Map<String, String> response = new HashMap<String, String>() {
        };

        personRepository.save(person);
        return response;
    }
    public Map<String, String> updatePersonAttribute(String updateKey, String updateValue, Person person){
        switch (updateKey){
            case "": //Here I need to do updating
        }
    }
    public Map<String, String> updatePerson(HashMap<String, String> personUpdate, Long id) {
        Map<String, String> response = new HashMap<String, String>() {
        };

        Optional<Person> personOptional = personRepository.findById(id);
        if (personOptional.isPresent()) {
            Person person = personOptional.get();
            Set<String> updateKeys = personUpdate.keySet();
            for (String updateKey : updateKeys) {
                boolean keyValid = Arrays.asList(Person.modifiableAttributes).contains(updateKey);
                if (keyValid) {
                    String updateValue = personUpdate.get(updateKey);
                    HashMap<String, String> updateResponse = updatePersonAttribute(updateKey, updateValue, person);
                    response.putAll(updateResponse);

                }
            }
        } else {
            response.put("error", "true");
            response.put("errorText", String.format("Person with id %d is not found", id));
        }
        return response;
    }


    public Long count() {
        return personRepository.count();
    }

    public void deleteById(Long personId) {
        personRepository.deleteById(personId);
    }

}

P.S. 我想我需要一些像Trigger类的东西,以及像这样的签名的方法。updateAttribute(NameTrigger trigger, String newName). 但我不知道这是一个好的方法,如果是,我应该使用手动编写的类或不。

java switch-statement
1个回答
1
投票

这里是一个代码示例,以配合我的评论,使用查询 Map 来解析一个更新函数,用于给定的 updateKey:

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

class Scratch62323277 {

    static class MyProcessor {
        private Map<String, BiConsumer<Person, String>> processors = new HashMap<>();

        {
            processors.put("name", this::setName);
            processors.put("lastName", this::setLastName);
        }

        public void update(String key, String value, Person person) {
            //TODO: maybe nullcheck the map-get
            processors.get(key).accept(person, value);
        }

        private void setName(Person person, String value) {
            person.setName(value);
        }

        private void setLastName(Person person, String value) {
            // ignore null values (as an example)
            if (value == null) {
                return;
            }
            person.setName(value);
        }
    }

    static class Person {
        private String name;
        private String lastName;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    }
}

我建议你用一个枚举来表示键,并使用一个 EnumMap 因为它们的性能特点比 HashMap (完美的哈希一样,没有碰撞等。- 基本上只是一个索引数组的访问)

© www.soinside.com 2019 - 2024. All rights reserved.