Here is an example in Go:
package main
import (
"fmt"
"strconv"
"strings"
)
// Rectangle is the proper data structure
type Rectangle struct {
Height int
Width int
}
// Parse is the builder function, parsing the raw input from user
func Parse(raw string) *Rectangle {
l := strings.Split(raw, ",")
r := &Rectangle{
height: -1,
width: -1,
}
if l[0] == "r" {
r.height = convert(l[1])
r.width = convert(l[2])
return r
}
return nil
}
func convert(value string) int {
v, err := strconv.Atoi(value)
if err != nil {
return -1
}
return v
}
// client interaction
func main() {
r := Parse("r,5,10")
if r == nil {
fmt.Printf("r is nil\n")
return
}
fmt.Printf("height: %v, width: %v\n", r.Height, r.Width)
}
// Output:
// height: 5, width: 10
Notice that Parse
function's input takes a form of string consisting of 3 different data (r,5,10
). It then splits based on its available definition and then pass it to convert
for data conversion before assembling the proper data structure.
Once done, the client is able to interact using the proper data structure.