77 lines
2.4 KiB
Go
77 lines
2.4 KiB
Go
package people
|
|
|
|
import (
|
|
"encoding/json"
|
|
)
|
|
|
|
// Person data representation.
|
|
//
|
|
// NOTE:
|
|
//
|
|
// The reason the people package was created is reusability.
|
|
//
|
|
// Personalities are used more often and are more general
|
|
// in applications than superheroes.
|
|
//
|
|
// # Some additional reflection:
|
|
//
|
|
// * Superheroes are a special case of people.
|
|
// * Normal persons are not superheros at all, but:
|
|
// - An ordinary person, over time, can gain superpowers
|
|
// - Do we need to handle them as no superhero?
|
|
// - A superhero can lose his superpowers.
|
|
// - But he was already using them, so does that mean he's no longer a superhero?
|
|
// - Batman, as example has, no superpowers, so he is not a DeeSee "superhero".
|
|
//
|
|
// Additional to think about, is that People, a man,
|
|
// can have many personalities(natural, juridical, fantasy, artistic, fake),
|
|
// also superheros can become transformation(magically) to another person(becomes additional personalities),
|
|
// so the person becomes more superpowers? (rhetorical question)
|
|
//
|
|
// .
|
|
// Anyway, to work anything about, there is a `Person` a struct which has a Method `IsSuperHero() bool.
|
|
type Person struct {
|
|
// Name of a Person
|
|
Name string `json:"name"`
|
|
|
|
// Identity of a Person.
|
|
// Sure, people can have many identities, fakes too.
|
|
// But at the time we handle only one-to-one person to identity relation
|
|
Identity *Identity `json:"identity"`
|
|
|
|
// SuperPowers list
|
|
SuperPowers *SuperPowers `json:"superpowers"`
|
|
|
|
// Birthday formatted as `YYYY-MM-DD` text string, there is no time zone and time.
|
|
// The format-Layout is defined in internal `birthdayLayout` constant
|
|
Birthday *Birthday `json:"birthday"`
|
|
}
|
|
|
|
// IsSuperHero the person?
|
|
func (p *Person) IsSuperHero() bool {
|
|
return p.SuperPowers != nil && len(*p.SuperPowers) > 0
|
|
}
|
|
|
|
// Has person the superpower?
|
|
// In other words: is the person a superhero at all?
|
|
func (p *Person) Has(power string) bool {
|
|
// The excessive use of the IsSuperHero() method is intentional, but for clarity,
|
|
// because it better describes what's going on.
|
|
//
|
|
// In the real world we deal with optimization of methods
|
|
// and of course it's better not to do so...
|
|
return p.IsSuperHero() && p.SuperPowers.Contains(power)
|
|
}
|
|
|
|
// Marshal marshals the person to JSON
|
|
func (p *Person) Marshal() ([]byte, error) {
|
|
return json.Marshal(p)
|
|
|
|
}
|
|
|
|
func Unmarshal(js string) (p *Person, err error) {
|
|
p = &Person{}
|
|
err = json.Unmarshal([]byte(js), p)
|
|
return
|
|
}
|