id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
8,100 | interpreter pattern the composite pattern defines both composite ( non-terminalsclasses and leaf ( terminalsclasses that can be used to construct composite componentsuch as special rule class leaf(object)def __init__(self*args**kwargs)pass def component_function(self)print("leaf"class composite(object)def __init__(self*args**kwargs)self children [def component_function(self)for child in childrenchild component_function(def add(selfchild)self children append(childdef remove(selfchild)self children remove(childin less dynamic languagesyou would have also had to define super class that would be inherited by both the composite and the leaf classesbut since python uses duck typingwe are once again saved from creating unnecessary boilerplate code internal dsl implementation using the composite pattern let us consider an implementation of the first rule for discounts from the restaurant in the beginning of this as some rudimentary internal dsl class tab(object)def __init__(selfcustomer)self items [self discounts [self customer customer |
8,101 | interpreter pattern def calculate_cost(self)return sum( cost for in self itemsdef calculate_discount(self)return sum( for in self discountsclass item(object)def __init__(selfnameitem_typecost)self name name self item_type item_type self cost cost class itemtype(object)def __init__(selfname)self name name class customer(object)def __init__(selfcustomer_typename)self customer_type customer_type self name name def is_a(selfcustomer_type)return self customer_type =customer_type class discount(object)def __init__(selfamount)self amount amount class customertype(object)def __init__(selfcustomer_type)self customer_type customer_type class rule(object)def __init__(selftab)self tab tab self conditions [self discounts [def add_condition(selftest_value)self conditions append(test_value |
8,102 | interpreter pattern def add_percentage_discount(selfitem_typepercent)if item_type ="any item" lambda xtrue elsef lambda xx item_type =item_type items_to_discount [item for item in self tab items if (item)for item in items_to_discountdiscount discount(item cost (percent/ )self discounts append(discountdef apply(self)if all(self conditions)return sum( amount for in self discountsreturn if __name__ ="__main__"member customertype("member"member_customer customer(member"john"tab tab(member_customerpizza itemtype("pizza"burger itemtype("burger"drink itemtype("drink"tab items append(item("margarita"pizza )tab items append(item("cheddar melt"burger )tab items append(item("latte"drink )rule rule(tabrule add_condition(tab customer is_a(member)rule add_percentage_discount("any item" tab discounts appendrule apply( |
8,103 | interpreter pattern print"calculated cost{}\ndiscount applied{}\ {}discount appliedformattab calculate_cost()tab calculate_discount() tab calculate_discount(tab calculate_cost(now that we have single rule workingusing objects that result in some form of readable codelet' return to the implementation of the dsl using the composite pattern conditions can be set of conjuncted conditionsa set of disjuncted conditionsor single boolean expression class andconditions(object)def __init__(self)self conditions [def evaluate(selftab)return all( evaluate(tabfor in self conditionsdef add(selfcondition)self conditions append(conditiondef remove(selfcondition)self conditions remove(conditionclass orconditions(object)def __init__(self)self conditions [def evaluate(selftab)return any( evaluate(tabfor in self conditionsdef add(selfcondition)self conditions append(conditiondef remove(selfcondition)self conditions remove(condition |
8,104 | interpreter pattern class condition(object)def __init__(selfcondition_function)self test condition_function def evaluate(selftab)return self test(tabclass discounts(object)def __init__(self)self children [def calculate(selftab)return sum( calculate(tabfor in self childrendef add(selfchild)self children append(childdef remove(selfchild)self children remove(childclass discount(object)def __init__(selftest_functiondiscount_function)self test test_function self discount discount_function def calculate(selftab)return sum(self discount(itemfor item in tab items if self test(item)class rule(object)def __init__(selftab)self tab tab self conditions andconditions(self discounts discounts(def add_conditions(selfconditions)self conditions add(conditionsdef add_discount(selftest_functiondiscount_function)discount discount(test_functiondiscount_functionself discounts add(discount |
8,105 | interpreter pattern def apply(self)if self conditions evaluate(self tab)return self discounts calculate(self tabreturn implementing the interpreter pattern two types of people use softwarethose who are satisfied with the offering out of the box and those who are willing to tinker and tweak to make the software fit their needs more perfectly the interpreter pattern is interesting only to the people in this second group since they are the people who will be willing to invest the time needed to learn how to use the dsl to make the software fit their needs back in the restaurantone owner will be happy with some basic templates for specialslike two-for-one offerwhile another restaurant owner will want to tweak and expand his offers we can now generalize the basic implementation for the dsl we did previously to create way of solving these problems in the future every expression type gets class (as before)and every class has an interpret method class and an object to store the global context will also be needed this context is passed to the interpret function of the next object in the interpretation stream assume that parsing already took place the interpreter recursively traverses the container object until the answer to the problem is reached class nonterminal(object)def __init__(selfexpression)self expression expression def interpret(self)self expression interpret(class terminal(object)def interpret(self)pass |
8,106 | interpreter pattern finallythe interpreter pattern can be used to decide if certain tab qualifies for any specials firstthe tab and item classes are definedfollowed by the classes needed for the grammar thensome sentences in the grammar are implemented and tested using test tabs note that we hard code the types in this example so the code can be runusuallythose are the types of things you would like to store in some file or database import datetime class rule(object)def __init__(selfconditionsdiscounts)self conditions conditions self discounts discounts def evaluate(selftab)if self conditions evaluate(tab)return self discounts calculate(tabreturn class conditions(object)def __init__(selfexpression)self expression expression def evaluate(selftab)return self expression evaluate(tabclass and(object)def __init__(selfexpression expression )self expression expression self expression expression def evaluate(selftab)return self expression evaluate(taband self expression evaluate(tabclass or(object)def __init__(selfexpression expression )self expression expression self expression expression |
8,107 | interpreter pattern def evaluate(selftab)return self expression evaluate(tabor self expression evaluate(tabclass percentagediscount(object)def __init__(selfitem_typepercentage)self item_type item_type self percentage percentage def calculate(selftab)return (sum([ cost for in tab items if item_type =self item_type]self percentage class cheapestfree(object)def __init__(selfitem_type)self item_type item_type def calculate(selftab)tryreturn min([ cost for in tab items if item_type =self item_type]exceptreturn class todayis(object)def __init__(selfday_of_week)self day_of_week day_of_week def evaluate(selftab)return datetime datetime today(weekday(=self day_of_week name class timeisbetween(object)def __init__(selffrom_timeto_time)self from_time from_time self to_time to_time def evaluate(selftab)hour_now datetime datetime today(hour minute_now datetime datetime today(minute |
8,108 | interpreter pattern from_hourfrom_minute [int(xfor in self from_time split(":")to_hourto_minute [int(xfor in self to_time split(":")hour_in_range from_hour <hour_now to_hour begin_edge hour_now =from_hour and minute_now from_minute end_edge hour_now =to_hour and minute_now to_minute return any(hour_in_rangebegin_edgeend_edgeclass todayisaweekday(object)def __init__(self)pass def evaluate(selftab)week_days "monday""tuesday""wednesday""thursday""friday"return datetime datetime today(weekday(in week_days class todayisaweekedday(object)def __init__(self)pass def evaluate(selftab)weekend_days "saturday""sunday"return datetime datetime today(weekday(in weekend_days class dayoftheweek(object)def __init__(selfname)self name name |
8,109 | interpreter pattern class itemisa(object)def __init__(selfitem_type)self item_type item_type def evaluate(selfitem)return self item_type =item item_type class numberofitemsoftype(object)def __init__(selfnumber_of_itemsitem_type)self number number_of_items self item_type item_type def evaluate(selftab)return len([ for in tab items if item_type =self item_type]=self number class customerisa(object)def __init__(selfcustomer_type)self customer_type customer_type def evaluate(selftab)return tab customer customer_type =self customer_type class tab(object)def __init__(selfcustomer)self items [self discounts [self customer customer def calculate_cost(self)return sum( cost for in self itemsdef calculate_discount(self)return sum( for in self discountsclass item(object)def __init__(selfnameitem_typecost)self name name self item_type item_type self cost cost |
8,110 | interpreter pattern class itemtype(object)def __init__(selfname)self name name class customer(object)def __init__(selfcustomer_typename)self customer_type customer_type self name name class customertype(object)def __init__(selfcustomer_type)self customer_type customer_type member customertype("member"pizza itemtype("pizza"burger itemtype("burger"drink itemtype("drink"monday dayoftheweek("monday"def setup_demo_tab()member_customer customer(member"john"tab tab(member_customertab items append(item("margarita"pizza )tab items append(item("cheddar melt"burger )tab items append(item("hawaian"pizza )tab items append(item("latte"drink )tab items append(item("club"pizza )return tab if __name__ ="__main__"tab setup_demo_tab(rules [members always get off their total tab rules append |
8,111 | interpreter pattern rulecustomerisa(member)percentagediscount("any_item" during happy hourwhich happens from : to : weekdaysall drinks are less rules appendruleand(timeisbetween(" : "" : ")todayisaweekday())percentagediscount(drink mondays are buy one get one free burger nights rules appendruleand(todayis(monday)numberofitemsoftype(burger ))cheapestfree(burgerfor rule in rulestab discounts append(rule evaluate(tab)print"calculated cost{}\ndiscount applied{}\nformattab calculate_cost()tab calculate_discount(in this you saw two ways of interpreting grammar and internal dsl we looked at the composite patternthen used it to interpret rule for specials in restaurant thenwe built on that ideatogether with the general interpreter patternto develop more complete interpreter to test conditions and calculate what discounts apply essentially you worked through the whole process from getting business requirements to defining the problem in terms of dsl and then implementing the dsl in code |
8,112 | interpreter pattern parting shots wherever you are on your programming journeydecide right now that you will do the hard work needed to become better you do this by working on programming projects and doing programming challenges one such challenge by jeff bay can be found in thought works anthologypublished by the pragmatic programmers attempt non-trivial project (one that will require more than , lines of code to solveby following these rules only one level of indentation is allowed per methodthus no if statements in loops or nesting you're not allowed to use the keyword else all primitive types and strings must be wrapped in objects-specifically for the use they are put to collections are first classand as such require their own objects don' abbreviate names if names are too longyou are probably doing more than one thing in method or class--don' do that only one object operator allowed per lineso object method(is okbut object attribute method(is not keep your entities small (packages objectsclasses linesmethods lines no class may have more than two instance variables you are not allowed to use getterssettersor access properties directly exercises follow the same thought process we used when defining dsl for the restaurant to define dsl that you can implement in your own to-do list application this dsl should allow your program to pick up cues like "every wednesday and translate them to recurring tasks also add awareness of date and some other indicators of time relative to some other date or time |
8,113 | interpreter pattern implement your dsl from the previous exercise in python so it can interpret to-do items and extract the necessary characteristics build basic to-do list application using one of the popular python web frameworks and have it interpret to-do' using your dsl interpreter find some interesting improvements or expansions to make the to-do list application something you can use on daily basis |
8,114 | iterator pattern the wheels of the bus go round and roundround and roundround and round data structures and algorithms form an integral part of the software design and development process oftendifferent data structures have different usesand using the right data structure for specific problem might mean lot less work and lot more efficiency choosing the correct data structure and matching it with the relevant algorithm will improve your solution since data structures have different implementationswe are tempted to implement the algorithms that operate on them differently for instanceif we were to consider binary tree that looks something like thisclass node(object)def __init__(selfdata)self data data self left none self right none traversing the elements of the tree to make sure you visit each one might look something like thisclass node(object)def __init__(selfdata)self data data self left none self right none def tree_traverse(node)if node left is not nonetree_traverse(node left(cwessel badenhorst badenhorstpractical python design patterns |
8,115 | iterator pattern print(node dataif node right is not nonetree_traverse(node rightif __name__ ="__main__"root node(" am the root"root left node("first left child"root right node("first right child"root left right node("right child of first left child of root"tree_traverse(rootcontrast this to when you want to traverse simple listlst [ for in range(len(lst))print(lst[ ] know used the for loop in way that is not considered pythonicbut if you come from / +or java backgroundthis will look familiar do this because want to illustrate how you could traverse list and binary tree and how they are distinctly different processes that produce similar result alexander stepanovadvocate of generic programming and as the primary designer and implementer of the +standard template libraryspent lot of time thinking about the techniques of generic programmingwhere the code is written in terms of algorithms that operate on data types to be defined at some future time he married ideas from pure mathematics and algebra with computer science and concluded that most algorithms can be defined in relation to an algebraic data type called containers by decoupling the algorithm from the specific type and implementation of containeryou become free to describe the algorithm without paying any attention to the actual implementation details of the specific type of container the result of this decoupling is more generalmore reusable code we want to be able to traverse collection without worrying about whether we are dealing with list or binary tree or some other collection to do thiswe want to create an interface that collection data type can inheritwhich would allow it to generalize the action of traversing the contents of the collection we do this by using the following components |
8,116 | iterator pattern firstwe define an interface that defines function that gets the next item in the collectionand another function to alert some external function that there are no more elements left in the collection to return secondwe define some sort of object that can use the interface to traverse the collection this object is called an iterator following the traditional approachwe can implement this idea as followsclassic_iter py import abc class iterator(metaclass=abc abcmeta)@abc abstractmethod def has_next(self)pass @abc abstractmethod def next(self)pass class container(metaclass=abc abcmeta)@abc abstractmethod def getiterator(self)pass class mylistiterator(iterator)def __init__(selfmy_list)self index self list my_list list def has_next(self)return self index len(self listdef next(self)self index + return self list[self index class mylist(container)def __init__(self*args)self list list(args |
8,117 | iterator pattern def getiterator(self)return mylistiterator(selfif __name__ ="__main__"my_list mylist( my_iterator my_list getiterator(while my_iterator has_next()print(my_iterator next()this prints out the following result this idea of traversing some collection is so widespread that it has name--the iterator pattern ython internal implementation of the iterator pattern as you have probably guessed by nowpython makes implementing the iterator pattern extremely simple in factyou have used iterators already in this book the way for loops are implemented in python uses the iterator pattern takefor instancethis for loopfor in range( )print(ithis is analogous to the iterator pattern implementation we saw in the previous section this convenience in python is accomplished by defining an iterator protocol that is used to create objects that are iterable and then returning some object that knows how to iterate over these iterable objects |
8,118 | iterator pattern python uses two specific method calls and one raised exception to provide the iterator functionality throughout the language the first method of an iterable is the __iter__(methodwhich returns an iterator object nexta __next__(method must be provided by the iterator objectit is used to return the next element in the iterable lastlywhen all the elements have been iterated overthe iterator raises stopiteration exception we often see the iterable collection in python return an instance of itselfgiven that the class in question also implements the __next__(method and raises the stopiteration exception an iterator similar to the classic implementation we looked at before might look something like thisclass mylist(object)def __init__(self*args)self list list(argsself index def __iter__(self)return self def __next__(self)tryself index + return self list[self index except indexerrorraise stopiteration(if __name__ ="__main__"my_list mylist( for in my_listprint(ithis timeyou will notice that we used the python for loop to iterate over the elements in the listwhich is only possible because our mylist class has the functions required by the python iterator protocol |
8,119 | iterator pattern if we were to implement the binary tree we saw at the beginning of this as python iterableit would be implemented as followsbin_tree_iterator py class node(object)def __init__(selfdata)self data data self left none self right none class mytree(object)def __init__(selfroot)self root root def add_node(selfnode)current self root while trueif node data <current dataif current left is nonecurrent left node return elsecurrent current left elseif current right is nonecurrent right node return elsecurrent current right def __iter__(self)if self root is noneself stack [elseself stack [self rootcurrent self root |
8,120 | iterator pattern while current left is not nonecurrent current left self stack append(currentreturn self def __next__(self)if len(self stack< raise stopiteration while len(self stack current self stack pop(data current data if current right is not nonecurrent current right self stack append(currentwhile current left is not nonecurrent current left self stack append(currentreturn data raise stopiteration if __name__ ="__main__"tree mytree(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )for in treeprint( |
8,121 | iterator pattern we keep the node class exactly as we defined it earlieronly now we have added container classnamely mytree this class implements the iterator protocoland as such can be used in normal python for loopas we have seen in the list iterator we also included convenience function that allows us to build binary tree by simply calling the add_node method on the tree instance of mytree this allows us to forget about how exactly the tree is implemented the process of inserting new node into the tree simply involves looking at the current node and going left if the node to be added' data value is less than or equal to that of the current node in the tree we keep doing this until an empty spot is foundand the new node is placed at this empty spot to traverse the treewe keep stack of nodesthen we start pushing repeatedlymoving left and pushing the current node onto the stack this happens until there are no more left children thenwe pop the top node from the stack and check if it has right child if it doesthe right child gets pushed onto the stackalong with the leftmost branch of the tree from that node we then return the value of the node popped from the stack the stack is maintained as an instance variable of the tree objectand as such we are able to continue where we left off every time the __next__(method is called this results in an ordered sequence being printedas follows we could use existing python functions and constructs to interface with the binary treelike for loops and max and sum functions just for funlook at how easy it is to use these constructs with completely custom data type you have seen that for loops work as expectednowwe will use the same code as we did in bin_tree_iterator pybut we will add max and sum call to the last if statement as suchonly the if statement is included in the code snippet |
8,122 | iterator pattern if __name__ ="__main__"tree mytree(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )for in treeprint(iprint("maximum value{}format(max(tree))print("total of values{}format(sum(tree))as you would expectthe results are as follows maximum value total of values the algorithms for each of these constructs were implemented completely decoupled of the data types that would later use them interestingly enoughyou can create list object that is iterable using list comprehension (which is almost like shorthand for creating iterable objectsas aboveonly the if statement is changedso once again will only include the code for the if and the code needed to transform the tree into list |
8,123 | iterator pattern if __name__ ="__main__"tree mytree(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )print([ for in tree]resulting in an ordered list of values [ list comprehensions are fairly simple to understand they take function or operation and map it to an iterable you could also add some sort of conditional statement after the iteration to exclude certain elements let' alter the comprehension we just looked at to now ignore all multiples of once again list comprehension with an if ! if __name__ ="__main__"tree mytree(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )tree add_node(node( )print([ for in tree if ! ]as you would hopethe is not included in the final list[ |
8,124 | iterator pattern itertools ' sure you are convinced of the usefulness of iterators by now soi will add quick mention of the itertools package included in the standard library it contains number of functions that allow you to combine and manipulate iterators in some interesting ways these building blocks have been taken from the world of functional programming and languages like haskell and reimagined in pythonic way for an extensive list of thesedo yourself favor and read the documentation for the itertools library to introduce you to the libraryi just want to mention three functions the first is chain()which allows you to chain multiple iterators one after the other import itertools print(list(itertools chain([ ]range( , )"the quick and the slow"))this iterates over every value in each of the three iterables and converts them all to single list that is printedas follows[ ' '' '' ''' '' '' '' '' ''' '' '' ''' '' '' ''' '' '' '' 'nextwe have the infinite iterator cycle()which allows you to create an iterator that will keep cycling over the elements passed to it indefinitely import itertools cycler itertools cycle([ ]print(cycler __next__()print(cycler __next__()print(cycler __next__()print(cycler __next__()print(cycler __next__()print(cycler __next__()print(cycler __next__()print(cycler __next__() |
8,125 | iterator pattern every time the cycler reaches the last elementit just starts back at the beginning the third and final function you can look at is zip_longest()which combines set of iterables and returns their matched elements on each iteration zip_longest example import itertools list [ list [' '' '' 'zipped itertools zip_longest(list list print(list(zipped)the result is set of pairs where the first pair contains the first elements of both liststhe second pair contains the second elements of both listsand so on [( ' ')( ' ')( ' ')there are many other interesting things you can do with iteratorsand many of them will help you find simple solutions for tricky problems as is probably the case with most libraries included in the python standard libraryit is worth your effort to explore and master the itertools package generator functions before we begin exploring generator expressionslet' write quick script to demonstrate what they do |
8,126 | iterator pattern gen_ func py def gen_squares( ) while nyield * print("next " + if __name__ ="__main__" gen_squares( print( __next__()print( __next__()print( __next__()print( __next__()print( __next__()the result you get from requesting next is the next squareas you can see here next next next next traceback (most recent call last)file "gen_func py"line in print( __next__()stopiteration there are couple of interesting things you will observe from the outputthe first of which is that every time you call the function the output changes the second thing you should note is that the function starts executing from just below the yield statement and continues until it hits the yield again |
8,127 | iterator pattern when the interpreter encounters the yield statementit keeps record of the current state of the function and returns the value that is yielded once the next value is requested via the __next__(methodthe internal state is loaded and the function continues from where it left off generators are great way to simplify the creation of iterators since generator is function that produces sequence of results and follows the interface for collections that can be iterated over as per the python implementation of the iterator pattern in the case of generator functionthe python internals take care of the iterator protocol for you when generator function is calledit returns generator object but does not begin any execution until the __next__(method is called the first time at that timethe function starts executing and runs until the yield is reached once the generator reaches its endit raises the same exception as iterators do the generator returned by the generator function is also an iterator generator expression much like we used list comprehensions as shorthand to create iteratorsthere is special shorthand for generators called generator expressions look at the example generator expression that follows it is simply an alternative for the generator function we defined earlier ( * for in range( )generator expressions can be used as arguments to certain functions that consume iteratorslike the max(functions print(max(( * for in range( )))this prints the number with pythonwe can drop the parentheses around generator if there is only one argument in the calling function print(max( * for in range( ))this is little bit neater |
8,128 | iterator pattern parting shots iterators and generators will help you do lot of heavy lifting as you explore the world of pythonand getting comfortable using them will help you code faster they also extend your code into the realm of functional programmingwhere you are more focused on defining what the program must do rather than how it must be done speaking of coding fasterhere are couple of tips to improve your development speed learn to touch type it is like being able to read and write if you are going to do something every daylearning to do that as effectively as possible is major force multiplier study and master your editor or ide of choicewhether that be vimemacspycharmor whatever else you useand make sure to learn all the shortcuts eliminate distractionsas every time you need to switch contextyou will take up to minutes to find your groove again not worth it make sure your tests run fast the slower your tests arethe greater the temptation is to skip them every moment spent searching online for an answer or example is coding and thinking time gone to wasteso learn the fieldmaster the languageand reduce your time on forums pay down technical debt as if your life depended on it--your happiness sure does exercises implement fibonacci sequence iterable using both generator and regular iterator create binary tree iterator using generator functions |
8,129 | observer pattern you knownortoni've been watching you --eddie murphydelirious if you did the object calisthenics exercise from you would have noticed how difficult it is to reduce the number of lines used in certain methods this is especially difficult if the object is too tightly coupled with number of other objectsi one object relies too much on its knowledge of the internals of the other objects as suchmethods have too much detail that is not strictly related to the method in question maybe this seems bit vague at the moment allow me to clarify say you have system where users are able to complete challengesand upon completion they are awarded pointsgain general experience pointsand also earn skills points for the skills used to complete the task every task needs to be evaluated and scored where relevant take moment and think about how you would implement such system once you have written down the basic architecturelook at the example that follows what we want is some way to keep track of the user credits earned and spentthe amount of experience the user has accumulated up until this pointas well as the scores that count toward earning specific badges or achievements you could think of this system as either some sort of habit-building challenge app or any rpg ever created task_completer py class task(object)def __init__(selfuser_type)self user user self _type _type (cwessel badenhorst badenhorstpractical python design patterns |
8,130 | observer pattern def complete(self)self user add_experience( self user wallet increase_balance( for badge in self user badgesif self _type =badge _typebadge add_points( class user(object)def __init__(selfwallet)self wallet wallet self badges [self experience def add_experience(selfamount)self experience +amount def __str__(self)return "wallet\ {}\nexperience\ {}\nbadges +\ {} ++++++++++++++++formatself walletself experience"\njoin(str(xfor in self badges]class wallet(object)def __init__(self)self amount def increase_balance(selfamount)self amount +amount def decrease_balance(selfamount)self amount -amount def __str__(self)return str(self amount |
8,131 | observer pattern class badge(object)def __init__(selfname_type)self points self name name self _type _type self awarded false def add_points(selfamount)self points +amount if self points self awarded true def __str__(self)if self awardedaward_string "earnedelseaward_string "unearnedreturn "{}{[{}]formatself nameaward_stringself points def main()wallet wallet(user user(walletuser badges append(badge("fun badge" )user badges append(badge("bravery badge" )user badges append(badge("missing badge" )tasks [task(user )task(user )task(user )for task in taskstask complete(print(userif __name__ ="__main__"main( |
8,132 | observer pattern in the outputwe can see the relevant values added to the walletexperienceand badgeswith the right badge being awarded once the threshold is cleared wallet experience badges fun badgeearned [ bravery badgeunearned [ missing badgeunearned [ +++++++++++++++this very basic implementation has fairly complex set of calculations to perform whenever task is completed in the preceding codewe have fairly well-implemented architecturebut the evaluation function is still clunkyand ' sure you already get that feeling that this is code you would not like to work on once you got it working also think that it would not be any fun to write tests for this method any additions to the system would mean altering this methodforcing even more calculations and evaluations to take place as we stated earlierthis is symptom of having tightly coupled system the task object must know about every points object in order for it to be able to assign the correct points or credits to the correct sub-system we want to remove the evaluation of every rule from the main part of the task complete method and place more responsibility with the sub-systems so they handle data alterations based on their own rules and not those of some foresight object to do thiswe take the first step toward more decoupled systemas seen heretask_semi_decoupled py class task(object)def __init__(selfuser_type)self user user self _type _type def complete(self)self user complete_task(selfself user wallet complete_task(selffor badge in self user badgesbadge complete_task(self |
8,133 | observer pattern class user(object)def __init__(selfwallet)self wallet wallet self badges [self experience def add_experience(selfamount)self experience +amount def complete_task(selftask)self add_experience( def __str__(self)return "wallet\ {}\nexperience\ {}\nbadges +\ {} ++++++++++++++++formatself walletself experience"\njoin(str(xfor in self badges]class wallet(object)def __init__(self)self amount def increase_balance(selfamount)self amount +amount def decrease_balance(selfamount)self amount -amount def complete_task(selftask)self increase_balance( def __str__(self)return str(self amount |
8,134 | observer pattern class badge(object)def __init__(selfname_type)self points self name name self _type _type self awarded false def add_points(selfamount)self points +amount if self points self awarded true def complete_task(selftask)if task _type =self _typeself add_points( def __str__(self)if self awardedaward_string "earnedelseaward_string "unearnedreturn "{}{[{}]formatself nameaward_stringself points def main()wallet wallet(user user(walletuser badges append(badge("fun badge" )user badges append(badge("bravery badge" )user badges append(badge("missing badge" ) |
8,135 | observer pattern tasks [task(user )task(user )task(user )for task in taskstask complete(print(userif __name__ ="__main__"main(this results in the same output as before this is already much better solution the evaluation now takes place in the objects where they are relevantwhich is closer to the rules contained in the objects callisthenics exercise hope little light went on for you in terms of the value of practicing these types of code callisthenics and how it serves to make you better programmer it still bothers me that the task handler is changed whenever new type of badge or credit or alert or whatever else you can think of is added to the system what would be ideal is if there were some sort of hooking mechanism that would not only allow you to register new sub-systems and then dynamically have their evaluations done as neededbut also free you from the requirement to make any alterations to the main task system the concept of callback functions is quite useful for achieving this new level of dynamics we will add generic callback functions to collection that will be run whenever task is completed now the system is more dynamicas these systems can be added at runtime the objects in the system will be decoupled even more task_with_callbacks py class task(object)def __init__(selfuser_type)self user user self _type _type self callbacks self userself user walletself callbacks extend(self user badgesdef complete(self)for item in self callbacksitem complete_task(self |
8,136 | observer pattern class user(object)def __init__(selfwallet)self wallet wallet self badges [self experience def add_experience(selfamount)self experience +amount def complete_task(selftask)self add_experience( def __str__(self)return "wallet\ {}\nexperience\ {}\nbadges +\ {}\ ++++++++++++++++formatself walletself experience"\njoin(str(xfor in self badges]class wallet(object)def __init__(self)self amount def increase_balance(selfamount)self amount +amount def decrease_balance(selfamount)self amount -amount def complete_task(selftask)self increase_balance( def __str__(self)return str(self amount |
8,137 | observer pattern class badge(object)def __init__(selfname_type)self points self name name self _type _type self awarded false def add_points(selfamount)self points +amount if self points self awarded true def complete_task(selftask)if task _type =self _typeself add_points( def __str__(self)if self awardedaward_string "earnedelseaward_string "unearnedreturn "{}{[{}]formatself nameaward_stringself points def main()wallet wallet(user user(walletuser badges append(badge("fun badge" )user badges append(badge("bravery badge" )user badges append(badge("missing badge" ) |
8,138 | observer pattern tasks [task(user )task(user )task(user )for task in taskstask complete(print(userif __name__ ="__main__"main(now you have list of objects to be called back when the task is completedand the task need not know anything more about the objects in the callbacks list other than that they have complete_task(method that takes the task that just completed as parameter whenever you want to dynamically decouple the source of call from the called codethis is the way to go this problem is another one of those very common problemsso common that this is another design pattern--the observer pattern if you take step back from the problem we are looking at and just think of the observer pattern in general termsit will look something like this there are two types of objects in the patternan observable classwhich can be watched by other classesand an observer classwhich will be alerted whenever an observable object the two classes are connected to undergoes change in the original gang of four bookthe observer design pattern is defined as followsa software design pattern in which an objectcalled the subjectmaintains list of its dependentscalled observersand notifies them automatically of any state changesusually by calling one of their methods it is mainly used to implement distributed event handling systems [gammae helmr johnsonr vlissidesj design patternselements of reusable object-oriented software publisheraddison-wesley in codeit looks like thisimport abc class observer(object)__metaclass__ abc abcmeta @abc abstractmethod def update(selfobserved)pass |
8,139 | observer pattern class concreteobserver(observer)def update(selfobserved)print("observingobservedclass observable(object)def __init__(self)self observers set(def register(selfobserver)self observers add(observerdef unregister(selfobserver)self observers discard(observerdef unregister_all(self)self observers set(def update_all(self)for observer in self observersobserver update(selfthe use of the abstract base class results in java-like interface that forces the observers to implement the update(method as we have seen beforethere is no need for the abstract base classbecause of python' dynamic natureand as such the preceding code can be replaced by more pythonic versionclass concreteobserver(object)def update(selfobserved)print("observingobservedclass observable(object)def __init__(self)self observers set(def register(selfobserver)self observers add(observer |
8,140 | observer pattern def unregister(selfobserver)self observers discard(observerdef unregister_all(self)self observers set(def update_all(self)for observer in self observersobserver update(selfin the preceding codethe observable keeps record of all the objects observing it in list called observersand whenever relevant changes happen in the observableit simply runs the update(method for each observer you will notice this every time the update(function is called with the observable object passed as parameter this is the general way of doing itbut any parametersor even no parameterscan be passed to the observersand the code will still adhere to the observer pattern if we were able to send different parameters to different objectsthat would be really interestingsince we would greatly increase the efficiency of the calls if we no longer needed to pass the whole object that has undergone changes let' use python' dynamic nature to make our observer pattern even better for thiswe will return to our user task system general_observer py class concreteobserver(object)def update(selfobserved)print("observing{}format(observed)class observable(object)def __init__(self)self callbacks set(def register(selfcallback)self callbacks add(callbackdef unregister(selfcallback)self callbacks discard(callback |
8,141 | observer pattern def unregister_all(self)self callbacks set(def update_all(self)for callback in self callbackscallback(selfdef main()observed observable(observer concreteobserver(observed register(lambda xobserver update( )observed update_all(if __name__ ="__main__"main(although there are many ways to string up the actions that can take place once the state of an observable changesthese are two concrete examples to build on sometimesyou might find that you would prefer the rest of the system be updated at specific time and not whenever the object changes to facilitate this requirementwe will add changed flag in protected variable (rememberpython does not explicitly block access to this variableit is more matter of convention)which can be set and unset as needed the timed function will then only process the change and alert the observers of the observable object at the desired time you could use any implementation of the observer pattern combined with the flag in the example that followsi used the functional observer as an exerciseimplement the flag for changed on the example with the object set of observers import time class concreteobserver(object)def update(selfobserved)print("observing{}format(observed) |
8,142 | observer pattern class observable(object)def __init__(self)self callbacks set(self changed false def register(selfcallback)self callbacks add(callbackdef unregister(selfcallback)self callbacks discard(callbackdef unregister_all(self)self callbacks set(def poll_for_change(self)if self changedself update_all def update_all(self)for callback in self callbackscallback(selfdef main()observed observable(observer concreteobserver(observed register(lambda xobserver update( )while truetime sleep( observed poll_for_change(if __name__ ="__main__"main(the problems that the observer pattern solves are those where group of objects has to respond to the change of state in some other object and do so without causing more coupling inside the system in this sensethe observer pattern is concerned with the management of events or responding to change of state in some sort of network of objects |
8,143 | observer pattern mentioned couplingso let me clarify what is meant when we talk about coupling generallywhen we talk about the level of coupling between objectswe refer to the degree of knowledge that one object needs with regard to other objects that it interacts with the more loosely objects are coupledthe less knowledge they have about each otherand the more flexible the object-oriented system is loosely coupled systems have fewer interdependencies between objects and as such are easier to update and maintain by decreasing the coupling between objectsyou further reduce the risk that changing something in one part of the code will have unintended consequences in some other part of the code since objects do not rely on each otherunit testing and troubleshooting become easier to do other good places to use the observer pattern include the traditional model-viewcontroller design patternwhich you will encounter later in the bookas well as textual description of data that needs to be updated whenever the underlying data changes as rulewhenever you have publish-subscribe relationship between single object (the observableand set of observersyou have good candidate for the observer pattern some other examples of this type of architecture are the many different types of feeds you find onlinelike newsfeedsatomrssand podcasts with all of thesethe publisher does not care who the subscribers areand thus you have natural separation of concern the observer pattern will make it easy to add or remove subscribers at runtime by increasing the level of decoupling between the subscribers and the publisher nowlet' use the pythonic implementation of the observer pattern to implement our tracking system from the beginning of the note how easy it is to add new classes to the code and how clean the processes of updating and changing any of the existing classes are class task(object)def __init__(selfuser_type)self observers set(self user user self _type _type def register(selfobserver)self observers add(observer |
8,144 | observer pattern def unregister(selfobserver)self observers discard(observerdef unregister_all(self)self observers set(def update_all(self)for observer in self observersobserver update(selfclass user(object)def __init__(selfwallet)self wallet wallet self badges [self experience def add_experience(selfamount)self experience +amount def update(selfobserved)self add_experience( def __str__(self)return "wallet\ {}\nexperience\ {}\nbadges +\ {}\ ++++++++++++++++formatself walletself experience"\njoin(str(xfor in self badges]class wallet(object)def __init__(self)self amount def increase_balance(selfamount)self amount +amount |
8,145 | observer pattern def decrease_balance(selfamount)self amount -amount def update(selfobserved)self increase_balance( def __str__(self)return str(self amountclass badge(object)def __init__(selfname_type)self points self name name self _type _type self awarded false def add_points(selfamount)self points +amount if self points self awarded true def update(selfobserved)if observed _type =self _typeself add_points( def __str__(self)if self awardedaward_string "earnedelseaward_string "unearnedreturn "{}{[{}]formatself nameaward_stringself points |
8,146 | observer pattern def main()wallet wallet(user user(walletbadges badge("fun badge" )badge("bravery badge" )badge("missing badge" user badges extend(badgestasks [task(user )task(user )task(user )for task in taskstask register(wallettask register(userfor badge in badgestask register(badgefor task in taskstask update_all(print(userif __name__ ="__main__"main(parting shots you should have clear understanding of the observer pattern by nowand also have feeling for how implementing this pattern in the real world allows you to build systems that are more robusteasier to maintainand joy to extend |
8,147 | observer pattern exercises use the observer pattern to model system where your observers can subscribe to stocks in stock market and make buy/sell decisions based on changes in the stock price implement the flag for changed on an example with the object set of observers |
8,148 | state pattern under pressure --queen"under pressurea very useful tool for thinking through software problems is the state diagram in state diagramyou construct graphwhere nodes represent the state of the system and edges are transitions between one node in the system and another state diagrams are useful because they let you think visually about the state of your system given certain inputs you are also guided to consider the ways in which your system transitions from one state to the next since we mentioned creating games earlier in this bookwe can model the player character as state machine the player might start out in the standing state pressing the left or right arrow keys might change the state to moving left or moving right the up arrow can then take the character from whatever state they're in into the jumping stateandsimilarlythe down button will take the character into the crouching state even though this is an incomplete exampleyou should begin to understand how we might use state diagram it also becomes clear that when the up arrow key is pressedthe character will jump up and then come back downif the key has not been releasedthe character will jump again releasing any key will take the character from whatever state it was in back to the standing state another example from more formal sphere would be looking at an atm machine simplified state machine for an atm machine might include the following stateswaiting accepting card accepting pin input validating pin (cwessel badenhorst badenhorstpractical python design patterns |
8,149 | state pattern rejecting pin getting transaction selection set of states for every part of every transaction finalizing transaction returning card printing slip dispensing slip specific system and user actions will cause the atm to move from one state to the next inserting card into the machine will cause the machine to transition from the waiting state to the accepting_card stateand so on once you have drawn up complete state diagram for systemyou will have fairly complete picture of what the system should be doing every step of the way you will also have clarity on how your system should be moving from one step to another all that remains is to translate your state diagram into code naive way to translate the diagram into runnable code is to create an object that represents the state machine the object will have an attribute for its statewhich will determine how it reacts to input if we were to code up the first example of the game characterit would look something like this window systems have issues with cursesbut that can be fixed by installing cygwinwhich gives you linux-like terminal that works well with the curses library curses to download cygwinhead to the main website at download the current dll version that matches your machine if you find you have to set up python againjust follow the steps under the linux section of the installation guide from the beginning of this book import time import curses def main()win curses initscr(curses noecho(win addstr( "press the keys to initiate actions"win addstr( "press to exit" |
8,150 | state pattern win addstr( ""win move( while truech win getch(if ch is not nonewin move( win deleteln(win addstr( ""if ch = break elif ch = print("running left"elif ch = print("running right"elif ch = print("jumping"elif ch = print("crouching"elseprint("standing"time sleep( if __name__ ="__main__"main(as an exerciseyou can expand upon this code using the pygame module from to create character that can run and jump on the screen instead of just printing out the action the character is currently taking it might be useful to look at the pygame documentation to see how to load sprite image from file (sprite sheetinstead of just drawing simple block on the screen by this timeyou know that the if statement we use to determine what to do with the input is problem it smells bad to your code sense since state diagrams are such useful representations of object-oriented systemsand the resulting state machines are widespreadyou can be sure that there is design pattern to clean up this code smell the design pattern you are looking for is the state pattern |
8,151 | state pattern state pattern on an abstract levelall object-oriented systems concern themselves with the actors in system and how the actions of each impact the other actors and the system as whole this is why state machine is so helpful in modeling the state of an object and the things that cause said object to react in object-oriented systemsthe state pattern is used to encapsulate behavior variations based on the internal state of an object this encapsulation solves the monolithic conditional statement we saw in our previous example this sounds greatbut how would this be accomplishedwhat you need is some sort of representation for the state itself sometimesyou may even want all the states to share some generic functionalitywhich will be coded into the state base class thenyou have to create concrete state class for every discrete state in your state machine each of these can have some sort of handler function to deal with input and cause transition of stateas well as function to complete the action required of that state in the following code snippetwe define an empty base class that the concrete state classes will be inherited from note thatas in previous python' duck-typing system allows you to drop the state class in this most basic implementation include the base class state in the snippet for clarity only the concrete states also lack action methodsas this implementation takes no actionand as such these methods would be empty class state(object)pass class concretestate (state)def __init__(selfstate_machine)self state_machine state_machine def switch_state(self)self state_machine state self state_machine state class concretestate (state)def __init__(selfstate_machine)self state_machine state_machine |
8,152 | state pattern def switch_state(self)self state_machine state self state_machine state class statemachine(object)def __init__(self)self state concretestate (selfself state concretestate (selfself state self state def switch(self)self state switch_state(def __str__(self)return str(self statedef main()state_machine statemachine(print(state_machinestate_machine switch(print(state_machineif __name__ ="__main__"main(from the resultyou can see where the switch happens from concretestate to concretestate the statemachine class represents the context of execution and provides single interface to the outside world as you progress down the path to becoming better programmeryou will find yourself spending more and more time thinking about how you can test certain code constructs state machines are no different sowhat can we test about state machine that the state machine initializes correctly that the action method for each concrete state class does what it should dolike return the correct value |
8,153 | state pattern thatfor given inputthe machine transitions to the correct subsequent state python includes very solid unit-testing frameworknot surprisingly called unittest to test our generic state machinewe could use the following codeimport unittest class genericstatepatterntest(unittest testcase)def setup(self)self state_machine statemachine(def teardown(self)pass def test_state_machine_initializes_correctly(self)self assertisinstance(self state_machine stateconcretestate def test_switch_from_state_ _to_state_ (self)self state_machine switch(self assertisinstance(self state_machine stateconcretestate def test_switch_from_state _to_state (self)self state_machine switch(self state_machine switch(self assertisinstance(self state_machine stateconcretestate if __name__ ='__main__'unittest main(play around with the options for asserts and see what other interesting tests you can come up with we will now return to the problem of the player character either running or walkingas we discussed in the beginning of this we will implement the same functionality from beforebut this time we will use the state pattern |
8,154 | state pattern import curses import time class state(object)def __init__(selfstate_machine)self state_machine state_machine def switch(selfin_key)if in_key in self state_machine mappingself state_machine state self state_machine mapping[in_keyelseself state_machine state self state_machine mapping["default"class standing(state)def __str__(self)return "standingclass runningleft(state)def __str__(self)return "running leftclass runningright(state)def __str__(self)return "running rightclass jumping(state)def __str__(self)return "jumpingclass crouching(state)def __str__(self)return "crouchingclass statemachine(object)def __init__(self)self standing standing(selfself running_left runningleft(selfself running_right runningright(self |
8,155 | state pattern self jumping jumping(selfself crouching crouching(selfself mapping " "self running_left" "self running_right" "self crouching" "self jumping"default"self standingself state self standing def action(selfin_key)self state switch(in_keydef __str__(self)return str(self statedef main()player statemachine(win curses initscr(curses noecho(win addstr( "press the keys to initiate actions"win addstr( "press to exit"win addstr( ""win move( while truech win getch(if ch is not nonewin move( win deleteln(win addstr( ""if ch = break |
8,156 | state pattern player action(chr(ch)print(player statetime sleep( if __name__ ="__main__"main(how do you feel about the altered codewhat do you like about itwhat have you learnedwhat do you think can be improvedi want to encourage you to begin looking at code online and asking yourself these questions you will often find you learn more from reading other people' code than from all the tutorials you could ever find online that is also the point where you take another big step forward in your learningwhen you begin to think critically about the code you find online rather than just copying it into your project and hoping for the best parting shots in this we discovered how closely we could link actual code in python to an abstract tool for solving multiple types of problemsnamely the state machine all state machines are composed of states and the transitions taking the machine from one state to another based on certain inputs usuallythe state machine will also execute some actions while in state before transitioning to another state we also looked at the actual code you could use to build your very own state machine in python here are some quick and simple ideas for constructing your own state machinebased solutions identify the states your machine can be insuch as running or walking orin the case of traffic lightredyellowand green identify the different inputs you expect for each state draw transition from the current state to the next state based on the input note the input on the transition line define the actions taken by the machine in each state abstract the shared actions into the base state class implement concrete classes for each state you identified |
8,157 | state pattern implement set of transition methods to deal with the expected inputs for every state implement the actions that need to be taken by the machine in every state rememberthese actions live in the concrete state class as well as in the base state class there you have it-- fully implemented state machine that has one-to-one relation to the abstract diagram solving the problem exercises expand on the simple state machine for the player character by using pygame to create visual version load sprite for the player and then model some basic physics for the jump action explore the different types of assert statements available to you as part of the python unittest library |
8,158 | strategy pattern move in silenceonly speak when it' time to say checkmate --unknown from time to timeyou might find yourself in position where you want to switch between different ways of solving problem you essentially want to be able to pick strategy at runtime and then run with it each strategy might have its own set of strengths and weaknesses suppose you want to reduce two values to single value assuming these values are numeric valuesyou have couple of options for reducing them as an exampleconsider using simple addition and subtraction as strategies for reducing the two numbers let' call them arg and arg simple solution would be something like thisdef reducer(arg arg strategy=none)if strategy ="addition"print(arg arg elif strategy ="subtraction"print(arg arg elseprint("strategy not implemented "def main()reducer( reducer( "addition"reducer( "subtraction"if __name__ ="__main__"main((cwessel badenhorst badenhorstpractical python design patterns |
8,159 | strategy pattern this solution results in the followingstrategy not implemented - this is what we want sadlywe suffer from the same problem we encountered in previous namely that whenever we want to add another strategy to the reducerwe have to add another elif statement to the function together with another block of code to handle that strategy this is surefire way to grow sprawling if statement we would much prefer more modular solution that would allow us to pass in new strategies on the fly without our having to alter the code that uses or executes the strategy as you have come to expect by nowwe have design pattern for that this design pattern is aptly named the strategy pattern because it allows us to write code that uses some strategyto be selected at runtimewithout knowing anything about the strategy other than that it follows some execution signature once againwe turn to an object to help us solve this problem we will also reach for the fact that python treats functions as first-class citizenswhich will make the implementation of this pattern much cleaner than the original implementation we will start with the traditional implementation of the strategy pattern class strategyexecutor(object)def __init__(selfstrategy=none)self strategy strategy def execute(selfarg arg )if self strategy is noneprint("strategy not implemented "elseself strategy execute(arg arg class additionstrategy(object)def execute(selfarg arg )print(arg arg class subtractionstrategy(object)def execute(selfarg arg )print(arg arg |
8,160 | strategy pattern def main()no_strategy strategyexecutor(addition_strategy strategyexecutor(additionstrategy()subtraction_strategy strategyexecutor(subtractionstrategy()no_strategy execute( addition_strategy execute( subtraction_strategy execute( if __name__ ="__main__"main(this again results in the required outputstrategy not implemented - at least we dealt with the sprawling if statement as well as the need to update the executor function every time we add another strategy this is good step in the right direction our system is little more decoupledand each part of the program only deals with the part of the execution it is concerned with without its worrying about the other elements in the system in the traditional implementationwe made use of duck typingas we have done many times in this book nowwe will use another powerful python tool for writing clean code--using functions as if they were any other value this means we can pass function to the executor class without first wrapping the function in class of its own this will not only greatly reduce the amount of code we have to write in the long runbut it will also make our code easier to read and easier to test since we can pass arguments to the functions and assert that they return the value we expect class strategyexecutor(object)def __init__(selffunc=none)if func is not noneself execute func def execute(self*args)print("strategy not implemented " |
8,161 | strategy pattern def strategy_addition(arg arg )print(arg arg def strategy_subtraction(arg arg )print(arg arg def main()no_strategy strategyexecutor(addition_strategy strategyexecutor(strategy_additionsubtraction_strategy strategyexecutor(strategy_subtractionno_strategy execute( addition_strategy execute( subtraction_strategy execute( if __name__ ="__main__"main(againwe get the required resultstrategy not implemented - since we are already passing around functionswe might as well take advantage of having first-class functions and abandon the executor object in our implementationleaving us with very elegant solution to the dynamic-strategy problem def executor(arg arg func=none)if func is noneprint("strategy not implemented "elsefunc(arg arg def strategy_addition(arg arg )print(arg arg def strategy_subtraction(arg arg )print(arg arg |
8,162 | strategy pattern def main()executor( executor( strategy_additionexecutor( strategy_subtractionif __name__ ="__main__"main(as beforeyou can see that the output matches the requirementstrategy not implemented - we created function that could take pair of arguments and strategy to reduce them at runtime multiplication or division strategyor any binary operation to reduce the two values to single valuecan be defined as function and passed to the reducer we do not run the risk of sprawling if growing in our executor and causing code rot to appear one thing that is bit bothersome about the preceding code snippet is the else statement in the executor we know that we will usually not be printing text in the terminal as the result of something happening inside our program it is way more likely that the code will return some value since the print statements are used to demonstrate the concepts we are dealing with in the strategy pattern in tangible manneri will implement the strategy patternusing print statement in the main function to simply print out the result of the executor this will allow us to use an early return to get rid of the dangling elseand thus clean up our code even more the cleaned-up version of our code now looks something like thisdef executor(arg arg func=none)if func is nonereturn "strategy not implemented return func(arg arg def strategy_addition(arg arg )return arg arg |
8,163 | strategy pattern def strategy_subtraction(arg arg )return arg arg def main()print(executor( )print(executor( strategy_addition)print(executor( strategy_subtraction)if __name__ ="__main__"main(once againwe test that the code results in the output we saw throughout this strategy not implemented - indeed it does now we have cleanclearand simple way to implement different strategies in the same context the executor function now also uses an early return to discard invalid stateswhich makes the function read more easily in terms of the actual execution of the optimal case happening on single level in the real worldyou might look at using different strategies for evaluating the stock market and making purchasing decisionsalternativelyyou might look at different pathfinding techniques and switch strategies there parting shots the broken windows theory works just as well in code as in real life never tolerate broken windows in your code broken windowsin case you were wonderingare those pieces of code that you know are not right and will not be easy to maintain or extend it is the type of code you really feel like slapping todo comment onthat you know you need to come back and fix but never will to become better coderyou need to take responsibility for the state of the codebase after you have had it in your careit should be bettercleanerand more maintainable than before next time you feel the temptation to leave to-do as booby trap for the poor developer who passes this way after youroll |
8,164 | strategy pattern up your sleeves and knock out that fix you had in mind the next poor coder who has to work on this code might just be youand then you will thank the coder who came before and cleaned things up little exercises see if you can implement maze generator that will print maze using "#and to represent walls and pathsrespectively before generating the mazehave the user pick one of three strategies use the strategy pattern to have the generator strategy passed to the maze generator then use that strategy to generate the maze |
8,165 | template method pattern success without duplication is merely future failure in disguise --randy gage in how to build multi-level money machinethe science of network marketing in lifeas in codingthere are patternssnippets of actions that you can repeat step by step and get the expected result in more complex situationsthe details of the unique steps may varybut the overall structure remains the same in lifeyou get to write standard operating procedures or devise rules of thumb (or mental modelsif that is how you rollwhen we write codewe turn to code reuse code reuse is the promised land that ushered in the almost ubiquitous obsession with object-oriented programming the dream is that you would follow the dry principle not only within specific projectbut also across multiple projectsbuilding up set of tools as you went along every project would not only make you better programmerbut would also result in another set of tools in your ever-growing arsenal some would argue that the content of this very book is violation of the dry principle since the existence of set of patterns that come up enough times to be codified and solved means that such problems should not need solving again complete code reuse has yet to be achievedas any programmer with more than couple of yearsworth of experience can testify the proliferation and constant reimagining of programming languages indicate that this is far from solved problem do not want to demoralizebut you need to be aware that we as developers need to be pragmaticand often we need to make decisions that do not fit the way the world should be being irritated with these decisions and desiring better solution is not problem unless it keeps you from doing the actual work that saidusing patterns like the strategy pattern allows us to improve the way we do things without needing to rewrite the whole program separation of concernas we have been talking about throughout this bookis yet another way of enabling less work to be done whenever things change-and things always change (cwessel badenhorst badenhorstpractical python design patterns |
8,166 | template method pattern what are we to do when we identify solid pattern of actions that need to be taken in variety of contextseach with its own nuancesfunctions are one form of recipe consider the pattern for calculating !where nn - where else nis solving this for the case where we could simply writefact_ that is fine if the only factorial you are ever going to be interested in is that of fivebut it is way more helpful to have general solution to the problemsuch as thisdef fact( )if return return fact( - def main()print(fact( )print(fact( )print(fact( )if __name__ ="__main__"main(what we see here is an illustration where specific set of steps leads to predictable result functions are really great at capturing this idea of an algorithm or set of steps leading to an expected result for some set of input values it does become more difficult when we begin to think about situations that might be more complicated than simply following predefined set of instructions another consideration is what you would do should you want to use the same steps in different wayor implement the steps using more efficient algorithm it might not be clear from the trivial case of the factorial functionso let' look at more involved example your point of sales system suddenly became popularand now customers want to have all kinds of funny things the chief of these requests is to interface with some third-party system they have been using forever to keep track of stock levels and pricing changes they are not interested in replacing the existing systembecause there are customers who are already using itso you have to do the integration |
8,167 | template method pattern you sit down and identify the steps needed to integrate with the remote system sync stock items between the point of sale and the third-party system send transactions to the third party this is simplified set of stepsbut it will serve us well enough in the world of simple functions we had beforewe could write code for each step in the process and place each step' code in separate functionseach of which could be called at the appropriate time see heredef sync_stock_items()print("running stock sync between local and remote system"print("retrieving remote stock items"print("updating local items"print("sending updates to third party"def send_transaction(transaction)print("send transaction{ ! }format(transaction)def main()sync_stock_items(send_transaction"id" "items""item_id" "amount_purchased" "value" ]if __name__ ="__main__"main( |
8,168 | template method pattern the result looks something like thisrunning stock sync between local and remote system retrieving remote stock items updating local items sending updates to third party send transaction{'items'[{'amount_purchased' 'item_id' 'value' }]'id' nextwe will evaluate the code in terms of what happens in the real world if there is one third-party system you need to integrate withthere will be others what if you are handed not one but two other third-party applications to integrate withyou could do the easy thing and create couple of sprawling if statements to direct traffic inside of the function to each of the three systems you need to cater toresulting in something like the incomplete code snippet that followswhich is included only to demonstrate the effect of the sprawling if on the neatness of the code def sync_stock_items(system)if system ="system "print("running stock sync between local and remote system "print("retrieving remote stock items from system "print("updating local items"print("sending updates to third party system "elif system ="system "print("running stock sync between local and remote system "print("retrieving remote stock items from system "print("updating local items"print("sending updates to third party system "elif system ="system "print("running stock sync between local and remote system "print("retrieving remote stock items from system "print("updating local items"print("sending updates to third party system "elseprint("no valid system" |
8,169 | template method pattern def send_transaction(transactionsystem)if system ="system "print("send transaction to system { ! }format(transaction)elif system ="system "print("send transaction to system { ! }format(transaction)elif system ="system "print("send transaction to system { ! }format(transaction)elseprint("no valid system"the test cases we included in the main function result in output similar to the one that follows just be aware that since dictionaries are not ordered in terms of their keysthe order of the items in the dictionary that is printed may vary from machine to machine what is important is that the overall structure remains the sameas do the values of the keys =========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system send transaction to system ({'items'[{'item_id' 'value' 'amount_purchased' }]'id' },=========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system send transaction to system ({'items'[{'item_id' 'value' 'amount_purchased' }]'id' },=========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system send transaction to system ({'items'[{'item_id' 'value' 'amount_purchased' }]'id' }, |
8,170 | template method pattern not only do you have to pass in the arguments needed to execute the specific functionalitybut also you have to pass around the name of the service relevant to the current user of the system it is also obvious from our previous discussions that this way of building system of any non-trivial scale will be disaster in the long run what options are leftsince this is book on design patternswe want to come up with solution that uses design patterns to solve the problem in question-- solution that is easy to maintainupdateand extend we want to be able to add new third-party providers without any alterations to the existing code we could try to implement the strategy pattern for each of the three functionsas followsdef sync_stock_items(strategy_func)strategy_func(def send_transaction(transactionstrategy_func)strategy_func(transactiondef stock_sync_strategy_system ()print("running stock sync between local and remote system "print("retrieving remote stock items from system "print("updating local items"print("sending updates to third party system "def stock_sync_strategy_system ()print("running stock sync between local and remote system "print("retrieving remote stock items from system "print("updating local items"print("sending updates to third party system "def stock_sync_strategy_system ()print("running stock sync between local and remote system "print("retrieving remote stock items from system "print("updating local items"print("sending updates to third party system "def send_transaction_strategy_system (transaction)print("send transaction to system { ! }format(transaction)def send_transaction_strategy_system (transaction)print("send transaction to system { ! }format(transaction) |
8,171 | template method pattern def send_transaction_strategy_system (transaction)print("send transaction to system { ! }format(transaction)def main()transaction "id" "items""item_id" "amount_purchased" "value" ]}print("="* sync_stock_items(stock_sync_strategy_system send_transactiontransactionsend_transaction_strategy_system print("="* sync_stock_items(stock_sync_strategy_system send_transactiontransactionsend_transaction_strategy_system print("="* sync_stock_items(stock_sync_strategy_system send_transactiontransactionsend_transaction_strategy_system if __name__ ="__main__"main( |
8,172 | template method pattern we have the same results with the test cases included in the main function as we had for the version using multiple if statements =========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system send transaction to system ({'items'[{'item_id' 'amount_purchased' 'value' }]'id' },=========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system send transaction to system ({'items'[{'item_id' 'amount_purchased' 'value' }]'id' },=========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system send transaction to system ({'items'[{'item_id' 'amount_purchased' 'value' }]'id' },two things bother me about this implementation the first is that the functions we are following are clearly steps in the same processandas suchthey should live in single entity instead of being scattered we also don' want to pass in strategy based on the system that is being targeted for every step of the wayas this is another violation of the dry principle insteadwhat we need to do is implement another design pattern called the template method pattern the template method does exactly what it says on the box it provides method template that can be followed to implement specific process step by stepand then that template can be used in many different scenarios by simply changing couple of details |
8,173 | template method pattern in the most general sensethe template method pattern will look something like this when implementedimport abc class templateabstractbaseclass(metaclass=abc abcmeta)def template_method(self)self _step_ (self _step_ (self _step_n(@abc abstractmethod def _step_ (self)pass @abc abstractmethod def _step_ (self)pass @abc abstractmethod def _step_ (self)pass class concreteimplementationclass(templateabstractbaseclass)def _step_ (self)pass def _step_ (self)pass def _step_ (self)pass this is the first instance where the use of python' abstract base class library is truly useful up until nowwe got away with ignoring the base classes that are so often used by otherless dynamic languages because we could rely on the duck-typing system with the template methodthings are little different the method used to execute the process is included in the abstract base class (abc)and all classes that inherit from this class are forced to implement the methods for each step in their own waybut all child classes will have the same execution method (unless it is overridden for some reason |
8,174 | template method pattern nowlet' use this idea to implement our third-party integrations using the template method pattern import abc class thirdpartyinteractiontemplate(metaclass=abc abcmeta)def sync_stock_items(self)self _sync_stock_items_step_ (self _sync_stock_items_step_ (self _sync_stock_items_step_ (self _sync_stock_items_step_ (def send_transaction(selftransaction)self _send_transaction(transaction@abc abstractmethod def _sync_stock_items_step_ (self)pass @abc abstractmethod def _sync_stock_items_step_ (self)pass @abc abstractmethod def _sync_stock_items_step_ (self)pass @abc abstractmethod def _sync_stock_items_step_ (self)pass @abc abstractmethod def _send_transaction(selftransaction)pass class system (thirdpartyinteractiontemplate)def _sync_stock_items_step_ (self)print("running stock sync between local and remote system "def _sync_stock_items_step_ (self)print("retrieving remote stock items from system "def _sync_stock_items_step_ (self)print("updating local items" |
8,175 | template method pattern def _sync_stock_items_step_ (self)print("sending updates to third party system "def _send_transaction(selftransaction)print("send transaction to system { ! }format(transaction)class system (thirdpartyinteractiontemplate)def _sync_stock_items_step_ (self)print("running stock sync between local and remote system "def _sync_stock_items_step_ (self)print("retrieving remote stock items from system "def _sync_stock_items_step_ (self)print("updating local items"def _sync_stock_items_step_ (self)print("sending updates to third party system "def _send_transaction(selftransaction)print("send transaction to system { ! }format(transaction)class system (thirdpartyinteractiontemplate)def _sync_stock_items_step_ (self)print("running stock sync between local and remote system "def _sync_stock_items_step_ (self)print("retrieving remote stock items from system "def _sync_stock_items_step_ (self)print("updating local items"def _sync_stock_items_step_ (self)print("sending updates to third party system "def _send_transaction(selftransaction)print("send transaction to system { ! }format(transaction) |
8,176 | template method pattern def main()transaction "id" "items""item_id" "amount_purchased" "value" ]}for in [system system system ]print("="* system (system sync_stock_items(system send_transaction(transactionif __name__ ="__main__"main(once againour test code results in the output we would hope for as in the previous sectionthe order of the key value pairs in the dictionaries returned by your implementation might be differentbut the structure and values will remain consistent =========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system send transaction to system ({'items'[{'amount_purchased' 'value' 'item_id' }]'id' },=========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system |
8,177 | template method pattern send transaction to system ({'items'[{'amount_purchased' 'value' 'item_id' }]'id' },=========running stock sync between local and remote system retrieving remote stock items from system updating local items sending updates to third party system send transaction to system ({'items'[{'amount_purchased' 'value' 'item_id' }]'id' },parting shots knowing which pattern to use whereand where to not rely on any of the patterns in this or any other bookis form of intuition as is the case with martial artsit is helpful to practice implementing these patterns wherever you find the opportunity when you implement thembe aware of what is working and what is not where are the patterns helping youand where are they hampering your progressyour goal is to develop feeling for the kinds of problems that specific pattern would solve using clear and known implementationand where the pattern would just get in the way since just mentioned knowledge and the need for experimentationi suggest you look at the documentation of your favorite editor and find out if it has some sort of snippet function that you could use to handle some of the boilerplate code you find yourself writing repeatedly this might include the preamble you use to start coding in new fileor the structure around the main(function this harkens back to the idea that if you are going to use tool every dayyou really need to master that tool being comfortable using snippetsand especially creating your ownis good place to gain an extra bit of leverage over your tools and remove some wasteful keystrokes exercises implement fourth systemand this time see what happens when you leave out one of the steps explore the challenges associated with trying to keep two systems in sync without being able to stop the whole world and tie everything together nicelyyou will need to look at race conditionsamong other things |
8,178 | template method pattern think of some other systems where you know what steps you need to takebut the specifics of what gets done in each of these steps differ from case to case implement basic template pattern-based system to model the situation you thought of in the previous exercise |
8,179 | visitor pattern want to believe -- -files since python can be found in many placesyou might one day want to do little bit of home automation get couple of single-board and micro computers and connect them to some hardware sensors and actuatorsand soon you have network of devicesall controlled by you each of these items in the network has its own functionalityand each performs different interactions like metering the light levels in the homeor checking the temperature you could encapsulate the functionality of each device as an object in virtual network that matches the physical wired networkthen treat the whole system like you would any other network of objects this will focus on that side of the implementationassuming all the elements have already been wired up and are modeled as objects in the system the network in our simulation will have the following componentsthermostat temperature regulator front door lock coffee machine bedroom lights kitchen lights clock suppose each object class has the functionality to check the status of the device it is connected to these return different values lights might return for "the lights are onand for "the lights are off,and an error message- when the lights controller (cwessel badenhorst badenhorstpractical python design patterns |
8,180 | visitor pattern cannot be reached the thermostat might return the actual temperature it is reading and none if it is offline the front door lock is similar to the lightswith being locked unlockedand - error the coffee machine has states for erroroffonbrewingwaitingand heating using integers from - to respectively the temperature regulator has states for heatingcoolingonoffand error the clock either returns none if the device is disconnected or the time as python time value the classes involved with concrete instances will look something like thisimport random class light(object)def __init__(self)pass def get_status(self)return random choice(range(- , )class thermostat(object)def __init__(self)pass def get_status(self)temp_range [ for in range(- )temp_range append(nonereturn random choice(temp_rangeclass temperatureregulator(object)def __init__(self)pass def get_status(self)return random choice(['heating''cooling''on''off''error']class doorlock(object)def __init__(self)pass def get_status(self)return random choice(range(- , ) |
8,181 | visitor pattern class coffeemachine(object)def _init_(self)pass def get_status(self)return random choice(range(- , )class clock(object)def __init__(self)pass def get_status(self)return "{}:{}format(random randrange( )random randrange( )def main()device_network thermostat()temperatureregulator()doorlock()coffeemachine()light()light()clock()for device in device_networkprint(device get_status()if __name__ ="__main__"main(the output is somewhat messy and looks like this off - - : |
8,182 | visitor pattern this is lot cleaner than the types of output you will encounter in the real worldbut this is good representation of the messy nature of real-world devices we now have simulation of network of devices we can move on to the parts we are really interested innamely doing something with these devices the first thing we are interested in is checking the status of the device attached to the object to determine if the device is online or not let' create flat collection containing the nodes in the network and then implement an is_online method to tell us if the device is online or not thenwe can look at each device in turn and ask if it is online or not we also added name parameter to each constructor so we can easily see what device we are currently dealing with import random class light(object)def __init__(selfname)self name name def get_status(self)return random choice(range(- , )def is_online(self)return self get_status(!- class thermostat(object)def __init__(selfname)self name name def get_status(self)temp_range [ for in range(- )temp_range append(nonereturn random choice(temp_rangedef is_online(self)return self get_status(is not none class temperatureregulator(object)def __init__(selfname)self name name |
8,183 | visitor pattern def get_status(self)return random choice(['heating''cooling''on''off''error']def is_online(self)return self get_status(!'errorclass doorlock(object)def __init__(selfname)self name name def get_status(self)return random choice(range(- , )def is_online(self)return self get_status(!- class coffeemachine(object)def __init__(selfname)self name name def get_status(self)return random choice(range(- , )def is_online(self)return self get_status(!- class clock(object)def __init__(selfname)self name name def get_status(self)return "{}:{}format(random randrange( )random randrange( )def is_online(self)return true |
8,184 | visitor pattern def main()device_network thermostat("general thermostat")temperatureregulator("thermal regulator")doorlock("front door lock")coffeemachine("coffee machine")light("bedroom light")light("kitchen light")clock("system clock")for device in device_networkprint("{is online\ {}format(device namedevice is_online())if __name__ ="__main__"main(since the simulated response is randomly generatedyou should not expect your output to be an exact match of the one given herebut the general shape of the output should hold general thermostat is onlinetrue thermal regulator is onlinetrue front door lock is onlinetrue coffee machine is onlinefalse bedroom light is onlinefalse kitchen light is onlinetrue system clock is onlinetrue we now want to add boot sequence to turn on all the devices and get them into their initial statelike setting the clock to : starting the coffee machineturning off all the lightsand turning on but not setting any settings on the temperature system we will leave the front door in the state that it is in since we are now becoming interested in the actual state of the systemwe will remove the get_status method and instead set status attribute to random value in the __init__(method |
8,185 | visitor pattern one other thing that you should note is that we now import the testcase class from the unittest librarywhich allows us to write tests to make sure thatafter applying the boot sequence to devicethat device is indeed in the state we expect it to be this is not an in-depth tutorial on unit testingbut will be good for you to see so you gain deeper level of comfort with the testing tools available in python import random import unittest class light(object)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(range(- , )def is_online(self)return self status !- def boot_up(self)self status class thermostat(object)def __init__(selfname)self name name self status self get_status(def get_status(self)temp_range [ for in range(- )temp_range append(nonereturn random choice(temp_rangedef is_online(self)return self status is not none def boot_up(self)pass |
8,186 | visitor pattern class temperatureregulator(object)def __init__(selfname)self name name self status self get_status(def get_status(self): return random choice(['heating''cooling''on''off''error']def is_online(self)return self status !'errordef boot_up(self)self status 'onclass doorlock(object)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(range(- , )def is_online(self)return self status !- def boot_up(self)pass class coffeemachine(object)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(range(- , )def is_online(self)return self status !- def boot_up(self)self status |
8,187 | visitor pattern class clock(object)def __init__(selfname)self name name self status self get_status(def get_status(self)return "{}:{}format(random randrange( )random randrange( )def is_online(self)return true def boot_up(self)self status " : class homeautomationboottests(unittest testcase)def setup(self)self thermostat thermostat("general thermostat"self thermal_regulator temperatureregulator("thermal regulator"self front_door_lock doorlock("front door lock"self coffee_machine coffeemachine("coffee machine"self bedroom_light light("bedroom light"self system_clock clock("system clock"def test_boot_thermostat_does_nothing_to_state(self)state_before self thermostat status self thermostat boot_up(self assertequal(state_beforeself thermostat statusdef test_boot_thermal_regulator_turns_it_on(self)self thermal_regulator boot_up(self assertequal(self thermal_regulator status'on'def test_boot_front_door_lock_does_nothing_to_state(self)state_before self front_door_lock status self front_door_lock boot_up(self assertequal(state_beforeself front_door_lock statusdef test_boot_coffee_machine_turns_it_on(self)self coffee_machine boot_up(self assertequal(self coffee_machine status |
8,188 | visitor pattern def test_boot_light_turns_it_off(self)self bedroom_light boot_up(self assertequal(self bedroom_light status def test_boot_system_clock_zeros_it(self)self system_clock boot_up(self assertequal(self system_clock status" : "if __name__ ="__main__"unittest main(setting the execution function for when the program is run from the command line to unittest main(tells python to look for instances of the unittest testcase class and then to run the tests in that class we set up six testsand the status after running the tests looks something like thisran tests in ok each of these had us implement functions we would expect of each functionbut how would the system look if we wanted to implement different profilessay person and person share the houseand they have different preferencessuch as time to get uptime to go to bedand what should happen in the morning or evening they also have different temperatures that they feel most comfortable with since they are friendly peoplethey have agreed on middle ground for when both of them are homebut when one or the other is home they would like to have the system settings set to their perfect configuration simple extension of the system we saw up to now would see an implementation like thisimport random import unittest class light(object)def __init__(selfname)self name name self status self get_status( |
8,189 | visitor pattern def get_status(self)return random choice(range(- , )def is_online(self)return self status !- def boot_up(self)self status def update_status(selfperson_ _homeperson_ _home)if person_ _homeif person_ _homeself status elseself status elif person_ _homeself status elseself status class thermostat(object)def __init__(selfname)self name name self status self get_status(def get_status(self)temp_range [ for in range(- )temp_range append(nonereturn random choice(temp_rangedef is_online(self)return self status is not none def boot_up(self)pass def update_status(selfperson_ _homeperson_ _home)pass |
8,190 | visitor pattern class temperatureregulator(object)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(['heating''cooling''on''off''error']def is_online(self)return self status !'errordef boot_up(self)self status 'ondef update_status(selfperson_ _homeperson_ _home)if person_ _homeif person_ _homeself status 'onelseself status 'heatingelif person_ _homeself status 'coolingelseself status 'offclass doorlock(object)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(range(- , )def is_online(self)return self status !- def boot_up(self)pass |
8,191 | visitor pattern def update_status(selfperson_ _homeperson_ _home)if person_ _homeself status elif person_ _homeself status elseself status class coffeemachine(object)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(range(- , )def is_online(self)return self status !- def boot_up(self)self status def update_status(selfperson_ _homeperson_ _home)if person_ _homeif person_ _homeself status elseself status elif person_ _homeself status elseself status class clock(object)def __init__(selfname)self name name self status self get_status( |
8,192 | visitor pattern def get_status(self)return "{}:{}format(random randrange( )random randrange( )def is_online(self)return true def boot_up(self)self status " : def update_status(selfperson_ _homeperson_ _home)if person_ _homeif person_ _homepass else" : elif person_ _home" : elsepass as an exercisewrite tests for these states where person and person are either there or not make sure you cover all the possible options in these tests this is an already messy implementationand you know we are going to do some cleanup we could implement the system using state machinebut implementing state machine for each device for each state of the inhabitancy of the house just seems wrongit is also lot of work without lot of value there has to be better way to get us therelet' consider what we want to do the visitor pattern once againwe are going to tease apart complex piece of functionality into more discrete partsthen abstract these parts in such way that the one does not need to be intimately familiar with the other this pattern of separation and isolation is one you will see over and over again as you spend time optimizingextendingand cleaning up existing systems |
8,193 | visitor pattern it is necessary to mention martin fowler' take on developing micro service-based architectures fowler posits that one first has to develop the monolith because at the outset you do not know which elements will coalesce to form good micro services and which can be kept separate as you work on and grow systema single object becomes network of objects when these networks become too complexyou refactorseparateand clean up the code in ways that would not make any sense at smaller scale this is another high-level instance of the you ain' gonna need it principle (yagni)which simply implores the developer to not build functionality or structures that will not be used this is much like the young developer who upon creating new object immediately proceeds to add createreadupdateand delete functionality even though the object can never be updated (or whatever business rule appliesimmediately abstracting any function or idea into some sort of meta class will leave lot of dead code in your systemcode that needs to be maintainedreasoned aboutdebuggedand testedbut never actually used new team members will need to slog through this code only to realize after the whole system is analyzed that it was waste of time and effort if this type of code proliferates the systemthe push for complete rewrite will become strongerand more time will be wasted if dead code is again implementedthe new developers will head straight into the same problem in shortdo not write code you are not going to use good rule of thumb is to wait until you have to do the same thing (or very similar thingthe third time before you abstract it the flip side of this rule is that as soon as you come across the same requirement or problem in your project the third timeyou should not proceed without abstracting the solutionso that whenever you next come across this situationyou will have solution ready to go you have now found balance with this in mindimagine that you have needed to alter objects twice to allow some function to be performed over the entire collection of objectsand now you have third algorithm you want to implement specific to the structure clearlyyou want to abstract the algorithms being implemented in terms of the data structure ideallyyou want to be able to dynamically add new algorithms and have them be executed relative to the same data structure without any alterations needing to be made to the classes that make up the elements of said data structure |
8,194 | visitor pattern look at the generic implementation of the visitor pattern and get feel for the code we will dig into the details after this code snippet import abc class visitable(object)def accept(selfvisitor)visitor visit(selfclass compositevisitable(visitable)def __init__(selfiterable)self iterable iterable def accept(selfvisitor)for element in self iterableelement accept(visitorvisitor visit(selfclass abstractvisitor(object)__metaclass__ abc abcmeta @abc abstractmethod def visit(selfelement)raise notimplementederror(" visitor needs to define visit method"class concretevisitable(visitable)def __init__(self)pass class concretevisitor(abstractvisitor)def visit(selfelement)pass we can now return to the example of our friends who are sharing house let' abstract the setting up of the system for each of them using the visitor pattern we will do this by creating visitor for each of the three potential configurations of people inside the houseand then we check who is home before visiting each device and setting it accordingly |
8,195 | visitor pattern import abc import random import unittest class visitable(object)def accept(selfvisitor)visitor visit(selfclass compositevisitable(visitable)def __init__(selfiterable)self iterable iterable def accept(selfvisitor)for element in self iterableelement accept(visitorvisitor visit(selfclass abstractvisitor(object)__metaclass__ abc abcmeta @abc abstractmethod def visit(selfelement)raise notimplementederror(" visitor need to define visit method"class light(visitable)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(range(- , )def is_online(self)return self status !- def boot_up(self)self status |
8,196 | visitor pattern class lightstatusupdatevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home def visit(selfelement)if self person_ _homeif self person_ _homeelement status elseelement status elif self person_ _homeelement status elseelement status class thermostat(visitable)def __init__(selfname)self name name self status self get_status(def get_status(self)temp_range [ for in range(- )temp_range append(nonereturn random choice(temp_rangedef is_online(self)return self status is not none def boot_up(self)pass class thermostatstatusupdatevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home def visit(selfelement)pass |
8,197 | visitor pattern class temperatureregulator(visitable)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(['heating''cooling''on''off''error']def is_online(self)return self status !'errordef boot_up(self)self status 'onclass temperatureregulatorstatusupdatevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home def visit(selfelement)if self person_ _homeif self person_ _homeelement status 'onelseelement status 'heatingelif self person_ _homeelement status 'coolingelseelement status 'offclass doorlock(visitable)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(range(- , ) |
8,198 | visitor pattern def is_online(self)return self status !- def boot_up(self)pass class doorlockstatusupdatevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home def visit(selfelement)if self person_ _homeelement status elif self person_ _homeelement status elseelement status class coffeemachine(visitable)def __init__(selfname)self name name self status self get_status(def get_status(self)return random choice(range(- , )def is_online(self)return self status !- def boot_up(self)self status class coffeemachinestatusupdatevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home |
8,199 | visitor pattern def visit(selfelement)if self person_ _homeif self person_ _homeelement status elseelement status elif self person_ _homeelement status elseelement status class clock(visitable)def __init__(selfname)self name name self status self get_status(def get_status(self)return "{}:{}format(random randrange( )random randrange( )def is_online(self)return true def boot_up(self)self status " : class clockstatusupdatevisitor(abstractvisitor)def __init__(selfperson_ _homeperson_ _home)self person_ _home person_ _home self person_ _home person_ _home def visit(selfelement)if self person_ _homeif self person_ _homepass else |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.