Recap - Employee Hierarchy
Part of the Object Oriented Programming section of Coddy's GO journey — lesson 40 of 107.
Challenge
EasyLet's build an employee hierarchy system for a company that demonstrates how composition elegantly models real-world organizational structures. You'll create a base employee type that specialized roles can extend with their own unique behaviors.
You'll organize your code across three files:
employee.go: Create the foundation with anEmployeestruct containingID,Name, andBaseSalary(float64) fields. Give it two methods:Info() stringthat returns[ID] [Name]CalculateBonus() float64that returns 10% of the base salary
roles.go: Create two specialized employee types that embedEmployee:Managerwith aTeamSizefield (int)—managers get a higher bonus: 20% of base salary plus $100 per team member. Shadow theCalculateBonusmethod to implement this.Developerwith aLanguagefield (string)—developers keep the standard bonus but shadow theInfomethod to append their programming language:[ID] [Name] ([Language])
main.go: Read employee details from input, create one Manager and one Developer, then display each employee's info and calculated bonus.
The following inputs will be provided:
- Line 1: Manager ID
- Line 2: Manager name
- Line 3: Manager base salary (float64)
- Line 4: Manager team size (integer)
- Line 5: Developer ID
- Line 6: Developer name
- Line 7: Developer base salary (float64)
- Line 8: Developer programming language
For each employee, print their info followed by their bonus on the next line. Format bonuses with two decimal places.
For example, given M001, Sarah Chen, 80000, 5, D001, Alex Rivera, 65000, and Go, your output should be:
M001 Sarah Chen
16500.00
D001 Alex Rivera (Go)
6500.00Notice how the Manager's bonus calculation (20% of 80000 + 5×100 = 16500) differs from the Developer's standard 10% bonus, while the Developer customizes how their info is displayed. Both types still have access to the embedded Employee fields and can call the original methods when needed.
Try it yourself
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
// Read Manager details
managerID, _ := reader.ReadString('\n')
managerID = strings.TrimSpace(managerID)
managerName, _ := reader.ReadString('\n')
managerName = strings.TrimSpace(managerName)
managerSalaryStr, _ := reader.ReadString('\n')
managerSalary, _ := strconv.ParseFloat(strings.TrimSpace(managerSalaryStr), 64)
teamSizeStr, _ := reader.ReadString('\n')
teamSize, _ := strconv.Atoi(strings.TrimSpace(teamSizeStr))
// Read Developer details
devID, _ := reader.ReadString('\n')
devID = strings.TrimSpace(devID)
devName, _ := reader.ReadString('\n')
devName = strings.TrimSpace(devName)
devSalaryStr, _ := reader.ReadString('\n')
devSalary, _ := strconv.ParseFloat(strings.TrimSpace(devSalaryStr), 64)
devLanguage, _ := reader.ReadString('\n')
devLanguage = strings.TrimSpace(devLanguage)
// TODO: Create a Manager using the read values
// Hint: Use composition - Manager embeds Employee
// TODO: Create a Developer using the read values
// Hint: Use composition - Developer embeds Employee
// TODO: Print manager info and bonus (bonus formatted to 2 decimal places)
// Use fmt.Printf with "%.2f" for formatting
// TODO: Print developer info and bonus (bonus formatted to 2 decimal places)
}
All lessons in Object Oriented Programming
1Fundamentals of Go OOP
External FilesGo Workspace & ModulesPackages & ImportsExported vs Unexported NamesIntroduction to OOP in GoStructs as ClassesDefining Methods on StructsPointer vs Value ReceiversStruct InitializationConstructor FunctionsRecap - Simple Calculator4Interfaces
Introduction to InterfacesImplicit ImplementationInterface as ContractEmpty Interface (any)Type AssertionType SwitchInterface CompositionStringer & Error InterfacesRecap - Shape Calculator7Encapsulation
Exported vs Unexported FieldsPackage-Level EncapsulationGetter & Setter MethodsInformation Hiding in GoRecap - Student Records10Generics (Go 1.18+)
Introduction to GenericsType ParametersType ConstraintsGeneric StructsGeneric Methods WorkaroundRecap - Generic Collection2Types & Structs Deep Dive
Basic & Composite TypesCustom Type DefinitionsStruct TagsAnonymous StructsNested StructsZero Values & DefaultsRecap - Contact Book5Composition Over Inheritance
Why Go Has No InheritanceStruct Embedding BasicsMethod PromotionEmbedding Multiple StructsEmbedding vs AggregationShadowing Embedded MethodsRecap - Employee Hierarchy8Error Handling & OOP
The error InterfaceCustom Error TypesError Wrapping (fmt.Errorf)Sentinel Errorserrors.Is() and errors.As()Panic, Defer, and RecoverRecap - File Parser3Pointers & Memory
Pointer Basics in GoPointers to StructsPass by Value vs ReferenceThe new() FunctionGarbage Collection in GoRecap - Linked List Builder6Polymorphism in Go
Polymorphism via InterfacesDuck Typing in GoInterface Satisfaction RulesPolymorphic CollectionsDependency InjectionRecap - Payment Processor9Concurrency & OOP
Goroutines BasicsChannels & CommunicationBuffered vs Unbuffered ChanSelect Statementsync.Mutex & sync.RWMutexsync.WaitGroupThread-Safe Struct DesignRecap - Worker Pool