preface

The original structure was to write if/else constantly, and then return it by satisfying the condition first. The code was hard to understand, and a lot of permissions were repeated.

Pre-refactoring code

Refactoring approach

  • The main reference to the permission dictionary, configuration type, rather than code separately write assignments, any required location can be reused, decoupled from the current
  • Introduce priority attributes without understanding logic through if/else precedence execution
  • Distinguish user permissions from service status. For complex service status, separate functions can be decoupled from the current use
  • The external function corresponding to the operation is also configured according to the property, optionally
  • By using filtering, all filtering operations are performed at once, eliminating unnecessary Boolean logic and logic or judgments
  • Decoupled render component functions, which can be customized according to the number of menus and business requirements, how to render the operation part

Mind mapping diagrams

Example of refactored code

/* * Determine whether playback can be performed. Complex permissions are defined as functions. In addition, other external conditions that need to be determined are recommended to encapsulate as an object */
const canPlay = (lessonState) = >{return profile[519] && lessonState === 5}

/* * buttons operate dictionaries and display buttons in the following order */
const optDict=[{
name:'Editing sessions'.key:1.fn:editFn,
priv:profile[519] {},name:'Recording return visit'.key:2.fn:playFn,
priv:canPlay()
},{
name:'Continuous course'.key:4.fn:delayFn,
priv:profile[533]}]/* * Filter method for permission judgment */
const optDictFiltered = (optDict) = > return optDict.filter(opt= > opt.priv)

const render = (optMenu) = >{
    let OPERATION = null;
    if(optMenu.length === 0) {return OPERATION
    }
    if(optMenu.length === 1) {let menu = optMenu[0]
        OPERATION = <button onClick={menu.fn}>{menu.name}</button>
        return OPERATION
    } else {
    let menu = optMenu[0];
    optMenu.unshift();
    let extraMenu = (
    <Menu>
    optMenu.map(item=><Menu.item key={item.key} >{item.name}</Menu.item)
    </Menu>
    );
         OPERATION = <dropdownbutton onClick={menu.fn} overlay={extraMenu}>
                {menu.name}</dropdownbutton>} return filtered (optDictFiltered(optDict))Copy the code

Original language finch link

www.yuque.com/robinson/fe…