Refactor remove long method& primitive obession

This commit is contained in:
abdelrahmanassem 2024-12-27 13:57:09 +02:00
parent 1aa1311497
commit 902a9f3057

View file

@ -1,18 +1,3 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.owner; package org.springframework.samples.petclinic.owner;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -22,16 +7,10 @@ import org.springframework.stereotype.Component;
import java.text.ParseException; import java.text.ParseException;
import java.util.Collection; import java.util.Collection;
import java.util.Locale; import java.util.Locale;
import java.util.Optional;
/** /**
* Instructs Spring MVC on how to parse and print elements of type 'PetType'. Starting * Formatter to parse and print 'PetType' elements.
* from Spring 3.0, Formatters have come as an improvement in comparison to legacy
* PropertyEditors. See the following links for more details: - The Spring ref doc:
* https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#format
*
* @author Mark Fisher
* @author Juergen Hoeller
* @author Michael Isvy
*/ */
@Component @Component
public class PetTypeFormatter implements Formatter<PetType> { public class PetTypeFormatter implements Formatter<PetType> {
@ -50,13 +29,20 @@ public class PetTypeFormatter implements Formatter<PetType> {
@Override @Override
public PetType parse(String text, Locale locale) throws ParseException { public PetType parse(String text, Locale locale) throws ParseException {
Collection<PetType> findPetTypes = this.owners.findPetTypes(); Optional<PetType> petType = findPetTypeByName(text);
for (PetType type : findPetTypes) { return petType.orElseThrow(() -> new ParseException("PetType not found: " + text, 0));
if (type.getName().equals(text)) {
return type;
}
}
throw new ParseException("type not found: " + text, 0);
} }
/**
* Helper method to find a PetType by its name.
* @param name the name of the pet type to search for
* @return an Optional containing the PetType if found, or an empty Optional
*/
private Optional<PetType> findPetTypeByName(String name) {
return this.owners.findPetTypes()
.stream()
.filter(petType -> petType.getName().equalsIgnoreCase(name))
.findFirst();
} }
}