Reputation: 1075
I am trying out the Spring Rest Service tutorial (https://spring.io/guides/gs/rest-service/) and made my own modifications to reverse a given name given in a REST Service call. I am struggling to identify which way of writing the ReverseString method is better OOP design. Here are two variation of my Name class and the corresponding ReverseString method inside.
public class Name {
private String name;
public Name(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
// Is this good OOP design?
public static Name ReverseName(Name myName){
myName.setName(new StringBuilder(myName.getName()).reverse().toString());
return myName;
}
}
--------OR-------------
public class Name {
private String name;
public Name(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public void ReverseName(){
this.setName(new StringBuilder(this.getName()).reverse().toString());
}
}
For added clarity here is my Spring controller Class:
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value ="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
@RequestMapping("/name")
public Name name(@RequestParam(value="reverse") String name){
Name myName = new Name(name);
myName.ReverseName();
return myName;
}
/**
// Other Option
@RequestMapping("/name")
public Name name(@RequestParam(value="reverse") String name){
return Name.ReverseName(new Name(name));
}
}
/**
}
Upvotes: 0
Views: 69
Reputation: 1254
They are functionally different. One modifies the internal state of the object, the other does not.
The first option is not OOP, but functional. The second modifies the internal state of the object, and is more OOP.
Which one is better is depending upon your requirements. OOP is just one way to handle a class of problems, and functional might be just fine.
Upvotes: 2