I personally try to avoid deeply nested if/else. Or else in general, because I think it makes code more readable.
Especially when one of the branches is just an exit condition.
if exitCondition {
returnfalse
}
// long ass code execution
is way more readable than
if !exitCondition {
// long ass code execution
} else {
returnfalse
}
In a loop, you can just return the value instead of passing it to a “retVal” variable.
With those in mind, you could refactor HasPermissions to
func(r *RBAC) HasPermission(assignedRoles []string, requiredPermission string, visited map[string]bool) bool {
for _, assigned := range assignedRoles {
if visited[assigned] {
continue
}
role, ok := r.Roles[assigned]
if !ok {
//role does not exist, so skip itcontinue
}
for _, permission := range role.Permissions {
if permission.String() == requiredPermission {
//Permission has been found! Set permitted to true and bust out of the loopreturntrue
}
}
//check inherited rolesif permitted := r.HasPermission(role.Inherits, requiredPermission, visited); permitted {
returntrue
}
}
returnfalse
}
The same could be applied to LoadJSONFile and I think that really would approve the readability and maintainability of your code.
I personally try to avoid deeply nested if/else. Or else in general, because I think it makes code more readable. Especially when one of the branches is just an exit condition.
if exitCondition { return false } // long ass code execution
is way more readable than
if !exitCondition { // long ass code execution } else { return false }
In a loop, you can just return the value instead of passing it to a “retVal” variable.
With those in mind, you could refactor HasPermissions to
func (r *RBAC) HasPermission(assignedRoles []string, requiredPermission string, visited map[string]bool) bool { for _, assigned := range assignedRoles { if visited[assigned] { continue } role, ok := r.Roles[assigned] if !ok { //role does not exist, so skip it continue } for _, permission := range role.Permissions { if permission.String() == requiredPermission { //Permission has been found! Set permitted to true and bust out of the loop return true } } //check inherited roles if permitted := r.HasPermission(role.Inherits, requiredPermission, visited); permitted { return true } } return false }
The same could be applied to LoadJSONFile and I think that really would approve the readability and maintainability of your code.
edit: This refactor is not tested