Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Неглубокий рефакторинг: принципы и основы рефакторинга

Неглубокий рефакторинг: принципы и основы рефакторинга

Презентация Дениса Ковалева (http://deeprefactoring.ru/speakers/denis-kovalev) о принципах и основах рефакторинга.

80eadbf0a221aaa4b764854df32fb781?s=128

Deep Refactoring

April 17, 2018
Tweet

Transcript

  1. НЕГЛУБОКИЙ РЕФАКТОРИНГ КОВАЛЕВ ДЕНИС

  2. REFACTORING GUIDE MARTIN FOWLER KENT BECK 2

  3. ЧТО ТАКОЕ РЕФАКТОРИНГ 3

  4. ЧТО ТАКОЕ РЕФАКТОРИНГ 4

  5. ЧТО ТАКОЕ РЕФАКТОРИНГ 5

  6. Any fool can write code that a computer can understand.

    Good programmers write code that humans can understand. Martin Fowler, 1999 ЗАЧЕМ НУЖЕН РЕФАКТОРИНГ 6
  7. ЗАЧЕМ НУЖЕН РЕФАКТОРИНГ ▸ Читаемость ▸ Расширяемость ▸ Тестируемость ЦЕЛИ

    РЕФАКТОРИНГА 7
  8. ПРИМЕР def get_home(person): return person.get('addr', dict()).get('home') person dict() -> addr

    dict() -> home def get_home(person): if 'addr' in person and 'home' in person['addr']: return person['addr']['home'] return None 8
  9. ▸ Extract Method ▸ Inline Method ▸ Extract Variable ▸

    Inline Temp ▸ Replace Temp with Query ▸ Split Temp Variable ▸ Remove Assignments to Parameters ▸ Replace Method with Method Object ▸ Substitute Algorithm ▸ Move Method ▸ Move Field ▸ Extract Class ▸ Inline Class ▸ Hide Delegate ▸ Remove Middle Man ▸ Introduce Foreign Method ▸ Introduce Local Extension ▸ Self Encapsulate Field ▸ Replace Data Value with Object ▸ Change Value to Reference ▸ Change Reference to Value ▸ Replace Array with Object ▸ Duplicate Observed Data ▸ Change Unidirectional Association to Bidirectional ▸ Replace Magic Number with Constant ▸ Encapsulate Field ▸ Encapsulate Collection ▸ +40 more… ТЕХНИКИ РЕФАКТОРИНГА 9
  10. CODE SMELL 10

  11. CODE SMELL 11 func getDiscount( basePrice, managerId, customerId, seasonDiscount, personalDiscount,

    priceTag, shopId, itemCategory, isItRaining, isCustomerHappy, areYouHappy, itemSize, customerSize, totalItemCount, someRandomFactor, doWeCheat, isPoliceAround )
  12. CODE SMELL [u for u in urls if is_blocked(u)] filter(is_blocked,

    urls) 12
  13. CODE SMELL 13 valid_users = filter( lambda d: d['attr'].get('verified'), map(

    lambda x: dict( id=x.id, attr=users_attr[x.id] ), filter(lambda x: x.age > 17, users) ) )
  14. LINUS TORVALDS, THE MIND BEHIND LINUX 14 remove_list_entry(entry) { prev

    = NULL; walk = head; while (walk != entry) { prev = walk; walk = walk->next; } if (!prev) head = entry->next; else prev->next = entry->next; } remove_list_entry(entry) { indirect = &head; while ((*indirect) != entry) indirect = &(*indirect)->next; *indirect = entry->next; } CODE TASTE
  15. CODE TASTE 15 for idx in index_list: if idx >

    99: if check(idx): do_method1() do_method2() do_method3() else: print(“check failed”) else: print(“too small”) УМЕНЬШЕНИЕ ВЛОЖЕННОСТИ ОСНОВНОГО КОДА for idx in index_list: if idx < 100: print(“too small”) continue if not check(idx): print(“check failed”) continue do_method1() do_method2() do_method3()
  16. CODE TASTE 16 УМЕНЬШЕНИЕ ВЛОЖЕННОСТИ ОСНОВНОГО КОДА for idx in

    index_list: if idx < 100: print(“too small”) continue if not check(idx): print(“check failed”) continue do_method1() do_method2() do_method3() def is_ok(idx): return idx > 99 and check(idx) for idx in index_list: if not is_ok(idx): continue do_method1() do_method2() do_method3()
  17. CODE TASTE 17 УМЕНЬШЕНИЕ ВЛОЖЕННОСТИ ОСНОВНОГО КОДА for idx in

    index_list: if not is_ok(idx): continue do_method1() do_method2() do_method3() for idx in filter(is_ok, index_list): do_method1() do_method2() do_method3()
  18. CODE TASTE 18 УМЕНЬШЕНИЕ ВЛОЖЕННОСТИ ОСНОВНОГО КОДА Public transport (also

    known as public transportation, public transit, or mass transit) is transport of passengers by group travel systems available for use by the general public, typically managed on a schedule, operated on established routes, and that charge a posted fee for each trip.[1][2][3] Examples of public transport include city buses, trolleybuses, trams (or light rail) and passenger trains, rapid transit (metro/subway/underground, etc.) and ferries. Public transport between cities is dominated by airlines, coaches, and intercity rail. High-speed rail networks are being developed in many parts of the world. A ferry is a merchant vessel used to carry passengers, and sometimes vehicles and cargo as well, across a body of water. Most ferries operate regular return services. A passenger ferry with many stops, such as in Venice, Italy, is sometimes called a water bus or water taxi. Ferries form a part of the public transport systems of many waterside cities and islands, allowing direct transit between points at a capital cost much lower than bridges or tunnels. However, ship connections of much larger distances (such as over long distances in water bodies like the Mediterranean Sea) may also be called ferry services, especially if they carry vehicles. Capital costs are fixed, one-time expenses incurred on the purchase of land, buildings, construction, and equipment used in the production of goods or in the rendering of services. In other words, it is the total cost needed to bring a project to a commercially operable status. Whether a particular cost is capital or not depend on many factors such as accounting, tax laws, and materiality.
  19. REFACTORING CODE USABILITY 19

  20. ШАГИ РЕФАКТОРИНГА ▸Tests ▸Refactoring 20

  21. КОГДА НЕЛЬЗЯ РЕФАКТОРИТЬ ▸Bugs ▸Deadline 21

  22. SOURCEMAKING.COM 22

  23. Bad programmers worry about the code. Good programmers worry about

    data structures and their relationships. Linus Torvalds, 2006 23
  24. СПАСИБО!