id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
8,000 | builder pattern development process in the real world with some languageslike javayou can overload the constructor with many different options in terms of the parameters accepted and what is then constructed in turn alsonotice that the if conditional in the constructor __init__(could be defined more clearly ' sure you ... |
8,001 | builder pattern generic implementation of the builder pattern in python looks like thisform_builder py from abc import abcmetaabstractmethod class director(objectmetaclass=abcmeta)def __init__(self)self _builder none @abstractmethod def construct(self)pass def get_constructed_object(self)return self _builder constructe... |
8,002 | builder pattern using the builder patternwe can now redo our webform generator from abc import abcmetaabstractmethod class director(objectmetaclass=abcmeta)def __init__(self)self _builder none def set_builder(selfbuilder)self _builder builder @abstractmethod def construct(selffield_list)pass def get_constructed_object(... |
8,003 | builder pattern def __repr__(self)return "{}format("join(self field_list)class htmlformbuilder(abstractformbuilder)def __init__(self)self constructed_object htmlform(def add_text_field(selffield_dict)self constructed_object field_list append'{ }:formatfield_dict['label']field_dict['field_name'def add_checkbox(selfcheck... |
8,004 | builder pattern def construct(selffield_list)for field in field_listif field["field_type"="text_field"self _builder add_text_field(fieldelif field["field_type"="checkbox"self _builder add_checkbox(fieldelif field["field_type"="button"self _builder add_button(fieldif __name__ ="__main__"director formdirector(html_form_b... |
8,005 | builder pattern director construct(field_listwith open("form_file html"' 'as ff write"{ ! }formatdirector get_constructed_object(our new script can only build forms with text fieldscheckboxesand basic button you can add more field types as an exercise one of the concretebuilder classes has the logic needed for the crea... |
8,006 | builder pattern abstraction of the actual binary numbers in the machine with pythonwe have further level of abstraction in terms of objects and functions (even though also has functions and librariesexercises implement radio group generation function as part of your form builder extend the form builder to handle post-... |
8,007 | adapter pattern it is not the strongest of the species that survivesnor the most intelligent it is the one that is most adaptable to change --charles darwin sometimes you do not have the interface you would like to connect to there could be many reasons for thisbut in this we will concern ourselves with what we can do ... |
8,008 | adapter pattern nextyou implement an email sender as classsince by now you suspect that if you are going to build larger systems you will need to work in an object-oriented way the emailsender class handles the details of sending message to user users are stored in comma-separated values (csvfilewhich you load as neede... |
8,009 | adapter pattern for this to workyou might need some sort of email service set up on your operating system postfix is good free option should you need it before we continue with the examplei would like to introduce two design principles that you will see many times in this book these principles provide clear guide to wr... |
8,010 | adapter pattern existing system in the real worldthis can mean the difference between system that is stuck with cobol base and magnetic tape and one that moves with the times it also has the added bonus of allowing you to course correct more easily should you find that one or more design decisions you made early on wer... |
8,011 | adapter pattern if __name__ ="__main__"user_fetcher userfetcher('users csv'mailer mailer(mailer send'me@example com'[ ["email"for in user_fetcher fetch_users()]"this is your message""have good daycan you see how it might take bit of effort to get this rightbut how much easier it will be when we want to drop in postgres... |
8,012 | adapter pattern packages and tools available to you you need to extend code you wrote year ago in way that you never consideredwithout the luxury to go back and redo everything you did before every few weeks or monthsyou will realize that you are no longer the programmer you were before--you became better--but you stil... |
8,013 | adapter pattern in system where we have only two interfacesthis is not bad solutionbut by now you know that very rarely will it stay just the two systems what also tends to happen is that different parts of your program might make use of the same service suddenlyyou have multiple files that need to be altered to fit ev... |
8,014 | adapter pattern class clientobject()def __init__(selfwhat_i_want)self what_i_want what_i_want def do_something()self what_i_want required_function(if __name__ ="__main__"adaptee whatihave(adapter myadapter(adapteeclient clientobject(adapterclient do_something(adapters occur at all levels of complexity in pythonthe conc... |
8,015 | adapter pattern it implements required_function methodwhich returns the result of calling the provided_function_ (method of its wrapped whatihave object all other calls on the class are passed to its what_i_have instance via the ___getattr__(method you still only need to implement the interface you are adapting objecta... |
8,016 | adapter pattern the code does not look any differentother than having the default object instead of interfacesuperclass as parent class of the objectadapter class this means that we never have to define some super class to adapt one interface to another we followed the intent and spirit of the adapter pattern without a... |
8,017 | adapter pattern import csv import smtplib from email mime text import mimetext class mailer(object)def send(senderrecipientssubjectmessage)msg mimetext(messagemsg['subject'subject msg['from'sender msg['to'[recipientss smtplib smtp('localhost' send_message(recipients quit(class logger(object)def output(message)print("[l... |
8,018 | adapter pattern [ ["email"for in user_fetcher fetch_users()]"this is your message""have good dayyou may just as well use the logger class you developed in in the preceding examplethe logger class is just used as an example for every new interface you want to adaptyou need to write new adapterobject type class each of t... |
8,019 | adapter pattern the adapter pattern has the following elementstarget defines the domain-specific interface the client uses client uses objects that conform to the target interface adaptee the interface you have to alter because the object does not conform to the target adapter the code that changes what we have in the ... |
8,020 | decorator pattern time abides long enough for those who make use of it --leonardo da vinci as you become more experiencedyou will find yourself moving beyond the type of problems that can easily be solved with the most general programming constructs at such timeyou will realize you need different tool set this focuses ... |
8,021 | decorator pattern every system is differentbut you should get result shaped like the one here[time elapsed for - fibonacci number for we now extend our fibonacci code so we can request the number of elements in the fibonacci sequence we wish to retrieve we do this by encapsulating the fibonacci calculation in function ... |
8,022 | decorator pattern fib_ func_profile_me py import time def fib( )if return fibprev fib for num in range( )fibprevfib fibfib fibprev return fib def profile_me(fn)start_time time time(result (nend_time time time(print("[time elapsed for {}{}format(nend_time start_time)return result if __name__ ="__main__" print("fibonacci... |
8,023 | decorator pattern fibprev fib for num in range( )fibprevfib fibfib fibprev return fib def profile_me(fn)start_time time time(result (nend_time time time(print("[time elapsed for {}{}format(nend_time start_time)return result def get_profiled_function( )return lambda nprofile_me(fnif __name__ ="__main__" fib_profiled get... |
8,024 | decorator pattern the classic implementation of the decorator pattern does not use decorators in the sense that they are available in python once againwe will opt for the more pythonic implementation of the decorator patternand as such we will leverage the power of the built-in syntax for decorators in pythonusing the ... |
8,025 | decorator pattern the print statement inside the fib function is just there to show where the execution fits relative to the profiling decorator remove it once you see it in action so as to not influence the actual time taken for the calculation profiling decorator initiated inside fib [time elapsed for - fibonacci num... |
8,026 | decorator pattern def __call__(self*args)print("profilingdecorator called"start_time time time(result self (*argsend_time time time(print("[time elapsed for {}{}format(nend_time start_time)return result class tohtmldecorator(object)def __init__(selff)print("html wrapper initiated"self def __call__(self*args)print("toh... |
8,027 | decorator pattern this results in the following output when decorating functionbe careful to take note what the output type of the function you wrap is and also what the output type of the result of the decorator is more often than notyou want to keep the type consistent so functions using the undecorated function do n... |
8,028 | decorator pattern print("inside fib"if return fibprev fib for num in range( )fibprevfib fibfib fibprev return fib if __name__ ="__main__" print("fibonacci number for {}{}format(nfib( ))get ready for bit of mind bender the decorator function must return function to be used when the decorated function is called the retur... |
8,029 | decorator pattern retaining function __name__ and __doc__ attributes as noted beforeyou ideally do not want any function using your decorator to be changed in any waybut the way we implemented the wrapper function in the previous section caused the __name__ and __doc__ attributes of the function to change to that of t... |
8,030 | decorator pattern def dummy_decorator( )def wrap_f()print("function to be decorated" __name__print("nested wrapping function"wrap_f __name__return (wrap_f __name__ __name__ wrap_f __doc__ wrap_f __doc__ return wrap_f @dummy_decorator def do_nothing()print("inside do_nothing"if __name__ ="__main__"print("wrapped functio... |
8,031 | decorator pattern if __name__ ="__main__"print("wrapped function",do_nothing __name__do_nothing(what if we wanted to select the unit that the time should be printed inas in seconds rather than millisecondswe would have to find way to pass arguments to the decorator to do thiswe will use decorator factory firstwe create... |
8,032 | decorator pattern for num in range( )fibprevfib fibfib fibprev return fib if __name__ ="__main__" print("fibonacci number for {}{}format(nfib( ))nowlet' extend the code so we can pass in an option to display the elapsed time in either milliseconds or seconds import time from functools import wraps def profiling_decorat... |
8,033 | decorator pattern fibprev fib for num in range( )fibprevfib fibfib fibprev return fib if __name__ ="__main__" print("fibonacci number for {}{}format(nfib( ))as beforewhen the compiler reaches the \@profiling_decorator_with_unit it calls the functionwhich returns the decoratorwhich is then applied to the function being ... |
8,034 | decorator pattern the code we want should look something like this@profile_all_class_methods class domathstuff(object)def fib(self)@profiling_decorator def factorial(self)in essencewhat we want is class that looks exactly like the domathstuff class from the outsidewith the only difference being that every method call s... |
8,035 | decorator pattern uses this method to retrieve methods and attributes for an objectand by overriding this method we can add the decorator as we wanted since __getattribute__(returns methods and valueswe also need to check that the attribute requested is method class_profiler py import time def profiling_wrapper( )@wrap... |
8,036 | decorator pattern @profile_all_class_methods class domathstuff(object)def fib(self)@profiling_decorator def factorial(self)there you have ityou can now decorate both classes and functions it would be helpful to you if you download and read the flask source code (download form the official websiteuse of decorators to ha... |
8,037 | facade pattern the phantom of the opera is thereinside my mind --christine in this we will look at another way to hide the complexity of system from the users of that system all the moving parts should look like single entity to the outside world all systems are more complex than they seem at first glance takefor insta... |
8,038 | facade pattern it would not be hard to imagine an implementation of the process transaction that would work like thisimport datetime import random class invoice(object)def __init__(selfcustomer)self timestamp datetime datetime now(self number self generate_number(self lines [self total self tax self customer customer d... |
8,039 | facade pattern def generate_number(self)rand random randint( return "{}{}fomat(self timestamprandclass invoiceline(object)def __init__(selfline_item)turn line item into an invoice line containing the current price etc pass def save(self)save invoice line to persistent storage pass class receipt(object)def __init__(self... |
8,040 | facade pattern class customer(object)def __init__(self)pass @classmethod def fetch(clscustomer_code)fetch customer from persistent storage pass def save(self)save customer to persistent storage pass class loyaltyaccount(object)def __init__(self)pass @classmethod def fetch(clscustomer)fetch loyaltyaccount from persisten... |
8,041 | facade pattern invoice_line invoiceline(iteminvoice add_line(invoice_lineinvoice calculate(invoice save(loyalt_account loyaltyaccount fetch(customerloyalty_account calculate(invoiceloyalty_account save(receipt receipt(invoicepayment_typereceipt save(as you can seewhatever system is tasked with processing sale needs to ... |
8,042 | facade pattern this makes the code much cleaner and easier to read simple rule of thumb in object-oriented programming is that whenever you encounter an ugly or messy systemhide it in an object you can imagine that this problem of complex or ugly systems is one that regularly comes up in the life of programmerso you ca... |
8,043 | facade pattern what sets the facade pattern apart one key distinction with regards to the facade pattern is that the facade is used not just to encapsulate single object but also to provide wrapper that presents simplified interface to group of complex sub-systems that is easy to use without unneeded functions or comp... |
8,044 | facade pattern @staticmethod def make_invoice(customer_id)return invoice(customer fetch(customer_id)@staticmethod def make_customer()return customer(@staticmethod def make_item(item_barcode)return item(item_barcode@staticmethod def make_invoice_line(item)return invoiceline(item@staticmethod def make_receipt(invoicepaym... |
8,045 | facade pattern @staticmethod def fetch_receipts(invoice_id)return receipt(invoicepayment_type@staticmethod def fetch_loyalty_account(customer_id)return loyaltyaccount(customer@staticmethod def add_item(invoiceitem_barcodeamount_purchased)item item fetch(item_barcodeitem amount_in_stock amount_purchased item save(invoic... |
8,046 | facade pattern sale finalize(invoicesale generate_receipt(invoicepayment_typeas you can seenot lot has changed the code for sales results in single entry point to the more complex business system we now have limited set of functions to call via the facade that allows us to interact with the parts of the system we need ... |
8,047 | proxy pattern do you bite your thumb at ussir--abramromeo and juliet as programs growyou often find that there are functions that you call very often when these calculations are heavy or slowyour whole program suffers consider the following example for calculating the fibonacci sequence for number ndef fib( )if return ... |
8,048 | proxy pattern nowlet' see what effect memoization would have on our simple example case import time def fib( )if return return fib( fib( if __name__ ="__main__"start_time time time(fib_sequence [fib(xfor in range( , )end_time time time(print"calculating the list of {fibonacci numbers took {secondsformatlen(fib_sequenc... |
8,049 | proxy pattern import time def fib_cached (ncache)if return if in cachereturn cache[ncache[nfib_cached ( cachefib_cached ( cachereturn cache[nif __name__ ="__main__"cache {start_time time time(fib_sequence [fib_cached (xcachefor in range( )end_time time time(print"calculating the list of {fibonacci numbers took {second... |
8,050 | proxy pattern this is such good result that we want to create calculator object that does several mathematical series calculationsincluding calculating the fibonacci numbers see hereclass calculator(object)def fib_cached(selfncache)if return tryresult cache[nexceptcache[nfib_cached( cachefib_cached( cacheresult cache[n... |
8,051 | proxy pattern duck typing allows us to create such proxy by copying the object interface and then using the proxy class instead of the original class import time class rawcalculator(object)def fib(selfn)if return return self fib( self fib( def memoize(fn)__cache {def memoized(*args)key (fn __name__argsif key in __cache... |
8,052 | proxy pattern if __name__ ="__main__"calculator calculatorproxy(rawcalculator()start_time time time(fib_sequence [calculator fib(xfor in range( )end_time time time(print"calculating the list of {fibonacci numbers took {secondsformatlen(fib_sequence)end_time start_time must admitthis is not trivial piece of codebut let... |
8,053 | proxy pattern the memoize function takes regular old function as parameterthen it records the result of calling the received function if needed it calls the function and receives the newly calculated values before returning new function with the result saved if that value should be needed in future the final result is ... |
8,054 | proxy pattern protection proxy many programs have different user roles with different levels of access by placing proxy between the target object and the client objectyou can restrict access to information and methods on the target object parting shots you saw how proxy could take many formsfrom the cache proxy we de... |
8,055 | proxy pattern exercises add more functions to the rawcalculator class so it can create other sequences expand the calculatorproxy class to handle the new series-generation functions you added do they also use the memoize function out of the boxalter the __init__(function to iterate over the attributes of the target ob... |
8,056 | chain of responsibility pattern it wasn' me --shaggy"it wasn' meweb apps are complex beasts they need to interpret incoming requests and decide what should be done with them when you think about creating framework to help you build web apps more quicklyyou stand very real chance of drowning in the complexity and option... |
8,057 | chain of responsibility pattern most web frameworks create request object that is used throughout the system simple request object might look like thisclass request(object)def __init__(selfheadersurlbodygetpost)self headers self url self body self get self post at the momentyou have no extra functionality associated wi... |
8,058 | chain of responsibility pattern you could easily create user class that gets stored in database as an exerciselook at the sqlalchemy project (an sqlite database where you store basic user data make sure the user class has class function that finds user based on the user token fieldwhich is unique setting up wsgi serve... |
8,059 | chain of responsibility pattern in your command linewith the virtual environment activestart the serverwith hello_world_server py set as the application to handle requests uwsgi --http : --wsgi-file hello_world_server py if you point your browser to hello world in the window congratulationsyou have your very own web se... |
8,060 | chain of responsibility pattern right below the address baryou will see box with couple of tabs attached to it one of these tabs is authorization click it and select basic auth from the dropdown box now username and password fields are added to the interface postman allows you to enter the username and password in thes... |
8,061 | chain of responsibility pattern at index we will then send this to simple function that returns user objectwhich we just construct inline for the sake of this examplebut you are welcome to plug in your function that gets user from your local sqlite database user_aware_server py import base class user(object)def __init_... |
8,062 | chain of responsibility pattern in our examplewe created user based on the request this is clearly not correctbut the fact that we separated it into its own class allows us to take the code and change the get_verified_user method to get the user based on username we then verify that the password for that user is correc... |
8,063 | chain of responsibility pattern def application(envstart_response)authorization_header env["http_authorization"header_array authorization_header split(encoded_string header_array[ decoded_string base decode(encoded_stringdecode('utf- 'usernamepassword decoded_string split(":"user user get_verified_user(usernamepassword... |
8,064 | chain of responsibility pattern if we wanted to adhere to the single responsibility principle in the preceding examplewe would need piece of code to handle the user retrieval and another piece of code to validate that the user matches the password yet another piece of code would generate message based on the path of th... |
8,065 | chain of responsibility pattern what we want is to create some sort of way for us to make single call and then have the functions called dynamically class catchall(object)def __init__(self)self next_to_execute none def execute(self)print("end reached "class function class(object)def __init__(self)self next_to_execute c... |
8,066 | chain of responsibility pattern def main_function(head)head execute(if __name__ ="__main__"hd function class(current hd current next_to_execute function class(current current next_to_execute current next_to_execute function class(current current next_to_execute current next_to_execute function class(main_function(hdeve... |
8,067 | chain of responsibility pattern def function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']def main_function(input_string)if ' in input_stringinput_string function_ (input_stringif ' in input_stringinput_string function_ (input_stringif ' in input_stringinput_string function_ (input_stringif ' in i... |
8,068 | chain of responsibility pattern class function class(object)def __init__(self)self next_to_execute catchall(def execute(selfrequest)print(requestrequest "join([ for in request if !' ']self next_to_execute execute(requestclass function class(object)def __init__(self)self next_to_execute catchall(def execute(selfrequest)... |
8,069 | chain of responsibility pattern def main_function(headrequest)head execute(requestif __name__ ="__main__"hd function class(current hd current next_to_execute function class(current current next_to_execute current next_to_execute function class(current current next_to_execute current next_to_execute function class(main_... |
8,070 | chain of responsibility pattern to further illustrate this flexibilitywe extend the previous program so each class will only do something if it sees that the digit associated with the class name is in the request string class catchall(object)def __init__(self)self next_to_execute none def execute(selfrequest)print(requ... |
8,071 | chain of responsibility pattern def execute(selfrequest)if ' in requestprint("executing type function class with request [{}]format(request)request "join([ for in request if !' ']self next_to_execute execute(requestclass function class(object)def __init__(self)self next_to_execute catchall(def execute(selfrequest)if '... |
8,072 | chain of responsibility pattern note that this time we do not have any digits in the requestand as result the code for the instance of function class is not executed before the request is passed on to the instance of function class alsonote that we had no change in the code for the setup of the execution chain or in ma... |
8,073 | chain of responsibility pattern here is simple implementation of the chain of responsibility patternwith all of the extras stripped away all that is left is the general structure that we will be implementing on our web app class endhandler(object)def __init__(self)pass def handle_request(selfrequest)pass class handler ... |
8,074 | chain of responsibility pattern self name name self email email @classmethod def get_verified_user(clsusernamepassword)return userusernamepasswordusername"{}@demo comformat(usernameclass endhandler(object)def __init__(self)pass def handle_request(selfrequestresponse=none)return response encode('utf- 'class authorizatio... |
8,075 | chain of responsibility pattern def handle_request(selfrequestresponse=none)user user get_verified_user(request['username']request['password']request['user'user return self next_handler handle_request(requestresponseclass pathhandler(object)def __init__(self)self next_handler endhandler(def handle_request(selfrequestr... |
8,076 | chain of responsibility pattern class dispatcher(object)def __init__(selfhandlers=[])self handlers handlers def handle_request(selfrequest)for handler in self handlersrequest handler(requestreturn request the dispatcher class takes advantage of the fact that everything in python is an objectincluding functions since fu... |
8,077 | chain of responsibility pattern def function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']def function_ (in_string)print(in_stringreturn "join([ for in in_string if !' ']def main(request)dispatcher dispatcher(function_ function_ function_ function_ ]dispatcher handle_request(requestif __name__ ="_... |
8,078 | chain of responsibility pattern by the less frequently used handlers (use this only when the order of execution of the handlers does not matterwhen the order of the handlers has some sort of meaningyou could get some improved performance using ideas from the previous and caching the results of certain handled requests ... |
8,079 | command pattern 'll be back --terminator the robots are coming in this we are going to look at how we can control robot using python code for our purposeswe will be using the turtle module included in the python standard library this will allow us to handle commands like move forwardturn leftand turn right without the ... |
8,080 | command pattern the turtle is simple line-and-fill tool that helps to visualize what the robot is doing in the preceding codewe import the turtle library nextwe set the line color to blue and the background color to red thenwe tell the turtle to record the current point as the start of polygon that will be filled later... |
8,081 | command pattern def retreat() backward( def quit()screen bye(screen onkey(advance" "screen onkey(turn_left" "screen onkey(turn_right" "screen onkey(retreat" "screen onkey(quit"escape"screen listen(screen mainloop(what you are essentially doing is creating an interface with which to control the turtle in the real worldt... |
8,082 | command pattern with all the parameters needed to execute the methodas well as some target object that has the method this target object is called the receiver the receiver is an instance of class that can execute the method given the encapsulated information all of this relies on an object called an invoker that decid... |
8,083 | command pattern invoker invoker(invoker add_command(command invoker add_command(command invoker run(now you would be able to queue up commands to be executed even if the receiver were busy executing another command this is very useful concept in distributed systems where incoming commands need to be captured and handle... |
8,084 | command pattern class addcommand(object)def __init__(selfreceivervalue)self receiver receiver self value value def execute(self)self receiver add(self valuedef undo(self)self receiver subtract(self valueclass subtractcommand(object)def __init__(selfreceivervalue)self receiver receiver self value value def execute(self)... |
8,085 | command pattern def undo(self)self receiver multiply(self valueclass calculationinvoker(object)def __init__(self)self commands [self undo_stack [def add_new_command(selfcommand)self commands append(commanddef run(self)for command in self commandscommand execute(self undo_stack append(commanddef undo(self)undo_command s... |
8,086 | command pattern if __name__ ="__main__"acc accumulator( invoker calculationinvoker(invoker add_new_command(addcommand(acc )invoker add_new_command(subtractcommand(acc )invoker add_new_command(multiplycommand(acc )invoker add_new_command(dividecommand(acc )invoker run(print(accinvoker undo(invoker undo(invoker undo(invo... |
8,087 | command pattern command or the invoker to be clearthe command object does not execute anythingit is just container by implementing this patternwe have added layer of abstraction between the action to be executed and the object that invokes that action the added abstraction leads to better interaction between different ... |
8,088 | command pattern if __name__ ="__main__"invoker invoker(invoker add_command("function"text_writer"params"("command ""string "}invoker add_command("function"text_writer"params"("command ""string "}invoker run(for simple case like thisyou could just define lambda functionand you would not even have to write the function d... |
8,089 | command pattern "params"("command ""string "}invoker run(once the function you want to execute gets more complicatedyou have two options other than the method we used in the previous program you could just wrap the command' execute(function in lambdaletting you avoid creating class even though it is nifty trickyour cod... |
8,090 | interpreter pattern silvia broomewhat do you do when you can' sleeptobin kelleri stay awake --the interpreter sometimes it makes sense to not use python to describe problem or the solution to such problem when we need language geared toward specific problem domainwe turn to something called domain-specific language oma... |
8,091 | interpreter pattern this little bit of css code tells browser to render all the text inside the body tag of the web page that uses this css file in green the code needed by the browser to do this is lot more complex than this simple snippet of codeyet css is simple enough for most people to pick up in couple of hours h... |
8,092 | interpreter pattern @step( ' see the number (\ +)'def check_number(stepexpected)expected int(expectedassert world number =expected"got %dworld number def factorial(number)return - this code lets you define the outcome of the program in terms that non-technical person can understand and then maps those terms to actual c... |
8,093 | interpreter pattern in very informative talkneil greentechnical lead at icesuggested the following process for developing dsl understand your domain model your domain implement your domain if we were to follow neil' guidancewe would go talk to the restaurant owner we would try to learn how he or she expresses the rules... |
8,094 | interpreter pattern if tab customer is_member()for item in tab itemsitem price item price nowlook at the stark contrast between the previous code snippet and the definition of the same rules in simple dsl for defining specials if tab contains pizzas on wednesdays cheapest one is free every day from : to : drinks are le... |
8,095 | interpreter pattern able to use and maintain the system keep in mind that the use of dsl should aid the businessnot hamper itor it will discard the language in the long runif it ever adopts it in the first place we have considered the pros and cons of having dsl and decide to move forward with one for specifying rules ... |
8,096 | interpreter pattern drinks weekdays mondays burgers thursday ribs sunday pizzas we also identified the actions that could take placeget discount get discount get one free eat all you can finallywe recognized the key ideas as they relate to specials in the restaurantif customer is of certain type they always get fixed o... |
8,097 | interpreter pattern time_condition"today is "day_of_week "time is between "timeand "time "today is week day"today not week dayday_of_week"monday"tuesday"wednesday"thursday"friday"saturday"sundaytimehours":"minutes hourshour_tenshour_ones hour_tens" " hour_onesdigit minutesminute_tensminute_ones minute_tens" " " " " " m... |
8,098 | interpreter pattern we begin by creating just the stubs based on the grammar we defined earlierclass tab(object)pass class item(object)pass class customer(object)pass class discount(object)pass class rule(object)pass class customertype(object)pass class itemtype(object)pass class conditions(object)pass class condition(... |
8,099 | interpreter pattern class hourones(object)pass class minutes(object)pass class minutetens(object)pass class minuteones(object)pass class itemcondition(object)pass class number(object)pass class digit(object)pass class customercondition(object)pass not all of these classes will be needed in the final designand as such y... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.