design-patterns,coding-style,common-lisp,anti-patterns,dynamic-scope , lisp: dynamic scope vs explicit parameter passing


lisp: dynamic scope vs explicit parameter passing

Question:

Tag: design-patterns,coding-style,common-lisp,anti-patterns,dynamic-scope

I see two different patterns for "output" functions in (common) lisp:

(defun implicit ()
  (format t "Life? Don't talk to me about life!"))

(defun explicit (stream)
  (format stream "This will all end in tears."))

(defun test-im-vs-ex-plicit ()
  (values
   (with-output-to-string (stream)
     (let ((*standard-output* stream))
       (implicit)))
   (with-output-to-string (stream)
     (explicit stream))))

Is using dynamic scope like in implicit considered bad practice or is this a generally accepted use of dynamic scoping? Note that I'm assuming this is for e.g. a DSL to build complex output, like HTML, SVG, Latex or whatever and is not expected to do anything different apart from producing a printed representation.

Are there - apart from style - any important differences, e.g. with respect to performance, concurrency, or whatever?


Answer:

Actually you can bind *standard-output* directly:

(defun test-im-vs-ex-plicit ()
  (values
   (with-output-to-string (*standard-output*)   ; here
     (implicit))
   (with-output-to-string (stream)
     (explicit stream))))

There is no real simple answer. My advice:

Use stream variables, this makes debugging easier. They appear on the argument lists and are easier to spot in the backtrace. Otherwise you would need to see in the backtrace where there is a dynamic rebinding of a stream variable.

a) Nothing to pass?

(defun print-me (&optional (stream *standard-output*))
  ...)

b) One or more fixed arg:

(defun print-me-and-you (me you &optional (stream *standard-output*))
  ...)

c) One or more fixed args and multiple optional args:

(defun print-me (me
                 &key
                 (style  *standard-style*)
                 (font   *standard-font*)
                 (stream *standard-output*))
  ...)

Note also this:

Now assume (implicit) has an error and we get a break loop, a debugging repl. What's the value of standard-output in this break loop?

CL-USER 4 > (defun test ()
              (flet ((implicit ()
                       (write-line "foo")
                       (cerror "go on" "just a break")
                       (write-line "bar")))
                (with-output-to-string (stream)
                  (let ((*standard-output* stream))
                    (implicit)))))
TEST

CL-USER 5 > (compile 'test)
TEST
NIL
NIL

CL-USER 6 > (test)

Error: just a break
  1 (continue) go on
  2 (abort) Return to level 0.
  3 Return to top loop level 0.

Type :b for backtrace or :c <option number> to proceed.
Type :bug-form "<subject>" for a bug report template or :? for other options.

CL-USER 7 : 1 > *standard-output*
#<SYSTEM::STRING-OUTPUT-STREAM 40E06AD80B>

CL-USER 8 : 1 > (write-line "baz")
"baz"

CL-USER 9 : 1 > :c 1
"foo
baz
bar
"

Above is what you see in LispWorks or SBCL. Here you have access to the real program's binding, but using output functions during debugging will have effects on this stream.

In other implementations *standard-output* will be rebound to actual terminal io - for example in Clozure CL and CLISP.

If your program does not rebind *standard-output* there is less confusion in those cases. If I write code, I often think about what would be more useful in a REPL environment - which is different from languages, where there is less interactive debugging on REPLs and break loops...


Related:


Problems implementing ViewHolder pattern


android,design-patterns
I'm working on an android app from a book. I'm getting errors : "crimeHolder cannot be resolved" and I can't understand why.. public View getView(int poisition, View convertView , ViewGroup parent) { //If we weren't given a view, inflate one if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_crime, null); ViewHolder...

Javascript chaining and passing arguments


javascript,jquery,design-patterns
I have read a lots about chained functions in JavaScript, somehow I am really confused if it is possible to pass an argument across the chain. My main goal is to recreate a "jQuery like" behavior passing the first argument of a function when on chain. Here is a rough...

Design Pattern for handling interrupt data


c,design-patterns
I am developing a firmware application implemented in C, and I want to know what is a good design pattern for this kind of problem: In main loop, I will get interrupt when I received data from a device using UART communication I would send a AT command and wait...

variable global const “macros” in C++ and optimal design patterns


c++,design-patterns,mfc,const,global
I inherited some 10 year old code I have to complete. The code is in MFC (C++). There's a .h file where the custom data structures are written and some const variables are in there as Globals. Some of these are used for MS Office file extensions, of type CString,...

Should I used the Factory Method pattern?


design-patterns
I am developing an application that uses a combo box to select a version number. Depending on this selection a different subclass is to be instantiated and a method defined in the super class is to be called. I am having trouble deciding which pattern to use. Perhaps the Factory...

“One-time use methods” - looks better, but harder to read?


java,coding-style
I've got a constructor that has a LOT of setup to do, for a pretty complex object. Lots of this setup includes adding listeners to other objects within this one, so my constructor is full of the boilerplate anonymous inner class method descriptions. And since you NEED to implement them...

Builder pattern where to apply [closed]


java,design-patterns
Hi I have a doubt on builder design pattern.From the pluralsight videos I understood that this pattern is used to avoid the complexity of telescopic constructors in mutable classes. Some other sites explain it as a way to develop or construct complex object by keeping builder as a composition.I am...

Where are line breaks allowed within Haskell expressions?


haskell,coding-style
Background Most style guides recommend keeping line lengths to 79 characters or less. In Haskell, indentation rules mean that expressions frequently need to be broken up with new lines. Questions: Within expressions, where is it legal to place a new line? Is this documented somewhere? Extended question: I see GHC...

Segmentation fault in list of objects


c++,design-patterns,vector,segmentation-fault,copy-constructor
I didn't thought that this would be so hard, but I have the following program: In a multithreaded environment (using the ACE-Framework and OpenMP) I use the Observer pattern. In the init-routine of the Observer-controller-thread (ActiveObject) I create a vector of ConcreteObservers (for notifying them with their discrete job) like...

How to use constant powers of 2 readable in c++?


c++,binary,coding-style,constants,code-readability
I need several integer constants with 2^n and 2^n - 1 in my GNU c++ code. What is a good practise to keep the code readable? The code uses decimal values at the moment 4294967296 and 65536 which is hard to debug in future. 2^12 is not implemented in standard...

Domain Model with Event Sourcing


.net,design-patterns,cqrs,event-sourcing,event-driven-design
Silly question...but why do I need a Domain model at all if I use event sourcing. I have (an Event Bus of course) and Application Services with business operations that each send a Command after basic validation Command Handlers which receive Commands perform additional Command validation and publish Events Event...

Why there isn't library of design patterns?


java,oop,design-patterns
I'm new to design pattern subject. If design pattern are so great, why can't someone build a library of them so I don't have to create them in each application?...

Domain Driven Design for Rails App: Implementing a service in a basic example


ruby-on-rails,ruby,design-patterns,domain-driven-design,component-based
Two Models: An Owner and a Dog: owner.rb class Owner < ActiveRecord::Base has_one :dog end dog.rb class Dog < ActiveRecord::Base belongs_to :owner end And here is the schema: schema.rb ActiveRecord::Schema.define(version: 123) do create_table "dogs", force: true do |t| t.string "name" t.integer "energy" t.integer "owner_id" t.datetime "created_at" t.datetime "updated_at" end add_index...

undo / redo software pattern for split merge


design-patterns,software-engineering
I have a somewhat complex piece of genomics software where I allow undo and redo operations. If I have an element A, I can move it to A0, A1, A2, A3, etc. and move it around to any point in its history. This is easy. What I'm trying to figured...

Regular Expression differences between [] and ()


php,design-patterns,expression
How to understand about this Pattern? /^((?:\+?61)|0)(2((3[3789])|(4[0123456789])|(5[012356789])| (6[0123456789])|[789][0-9])|(3((3[234])|(4[012345789])|(5[0123456789])| (6[123457])|[789][0-9]))|(7(([23][0-9]|(4[0123456789]))|(5[234567])| (7[679])))|(8((2[56])|(5[123458])|(6[0123456789])|(7[0123456789])| (8[0123456789])|(9[0123456789]))))[0-9]{6}$/ How the square bracket[] and Parenthesis() differ from? ...

Design pattern for incremental code


java,design-patterns,code-design
According to the business logic, the output of one of the method is used as an input to another. The logic has linear flow. To emulate the behaviour, now there is a controller class which has everything. It is very messy, too much loc and hard to modify. Also the...

How to design abstract listener and its implementation?


design-patterns,design,template-method-pattern
I have decided to split my application into 3 separate modules - one "abstract" with almost all application logic (anyone looking at the code can tell WHAT it does), one "implementation" module with all specific implementation layers (like db, connections, etc) and one small "runtime" module that maps implementation with...

How to extract business logic in this example


design-patterns,logic,structure
The following method filters a data collection based on order statuses. Im wondering what would be the best way to extract the business logic held within about the order statuses. For example, say the order statuses were to change down the line i.e. ('in_transit', 'at_courier') then this method, and associated...

Swift - Issue trying to access to Singleton object


swift,design-patterns,ios8,singleton,apple
This is my first question on StackOverflow, I'll try to be specific. I am trying to implement the Singleton pattern on my app, without success so far. When I try to access to my Singleton, it seems that the program is not accessing the real singleton, but a copy of...

Send error from doNext block?


ios,objective-c,design-patterns,reactive-cocoa,overcoat
I'm using ReactiveCocoa and Overcoat/Mantle/AFNetworking to fetch data and authenticate a user from a RESTful API. This is the code in the login view controller that manages the login button and textfields for credentials: @weakify(self); self.loginButton.rac_command = [[RACCommand alloc] initWithEnabled:validCredentials signalBlock:^RACSignal *(id input) { @strongify(self); return [[PFUserManager sharedManager] logInUser:self.usernameTextField.text password:self.passwordTextField.text];...

Start programming without using advanced techniques? [on hold]


c#,coding-style
Can you start with coding programs without using advanced techniques, like Delegates or similar? Also is it wise to follow Single responsibility principle (each method has only one reason or purpose) as a beginner. Each method should have small number of code lines (like 10) is also one of coding...

How to force team members to comment using eclipse plugin or something else


eclipse,jenkins,eclipse-plugin,coding-style,build-automation
Currently, I am working in a new project and it was difficult for me to understand since there is no comment. I wonder if it is possible to force team members(including me) to add more comments. I would like to automate this ject in jenkins later if possible.

Java immutability when defining members in a function called by constructor


java,class,design-patterns,design,immutability
I have class like this: abstract class Parent { protected Parent(Raw rawData) { deserialize(rawData); } protected abstract void deserialize(Raw rawData); } class Child extends Parent { final byte firstByte; public Child(Raw rawdData) { super(rawData); } protected void deserialize(Raw rawData) { firstByte = rawData.getFirst(); } } So basically any child class...

How to override some property in the class under test during unit testing


c#,unit-testing,design-patterns
I have a class that I would like to test with Unit tests. It has some logic to look for some values in the local xml file, and if the value is not found it will read some external source (SqlServer DB). But during Unit testing I don't want this...

reference data class member visitor pattern


c++,design-patterns,reference
I have a container class that has a plain old datatype called DataStore. This data store will be passed to visitor.They share a single copy since any updated performed by the container are to be seen by visitor. class xyz { //Plain Old Datatype typedef struct DataStore { //add any...

Some doubts related this Swing MVC implementation. Opening a database connection should be a Controller task?


java,swing,design-patterns,model-view-controller,architecture
I am following a Java tutorial related to the implementation of the observer pattern (using Swing) and I have some doubts. My doubts are not related to the observer pattern but about the architecture of this tutorial application (that is based on something like an MVC logic) So it contains...

Does getInstance() denote a singleton according the singleton pattern?


java,design-patterns
Having worked with C# before, I have considered Calendar cal = Calendar.getInstance(); to be a singleton method according the GoF Singleton pattern (Wikipedia) and I wondered how to create two calendars, since Dateis somewhat deprecated. From the documentation Gets a calendar using the default time zone and locale. and the...

Encapsulation with React child components


coding-style,reactjs,encapsulation
How should one access state (just state, not the React State) of child components in React? I've built a small React UI. In it, at one point, I have a Component displaying a list of selected options and a button to allow them to be edited. Clicking the button opens...

React Flux dispatcher vs Node.js EventEmitter - scalable?


node.js,design-patterns,reactjs,flux,eventemitter
When you use Node's EventEmitter, you subscribe to a single event. Your callback is only executed when that specific event is fired up: eventBus.on('some-event', function(data){ // data is specific to 'some-event' }); In Flux, you register your store with the dispatcher, then your store gets called when every single event...

Advise on simplifying a PHP statement


php,joomla,coding-style
I am new to PHP and am coding a template file for a Joomla K2 item layout. I have an 'extra field' $extrafields[15] configured which outputs as "Yes", "No" or "". $extrafields[16] is a text string. I have this code, which works but would appriciate advice on how to simplify...

Singleton as performance upgrade in access to database


c#,asp.net,design-patterns
I'm writting a .NET application that implements different design patterns. I have an idea to write singleton + flyweight pattern example. Let's imagine I have remote database with Pizzas & ingredients. My idea is to: on app start I would download all Pizzas and Ingredients and keep them in flyweight...

Is there some kind of a design pattern that pushes for public statics methods?


php,design-patterns
I am wondering if there's a design pattern where every class has static public methods where you can just use them anywhere in the code. Is that kind of pattern considered safe if followed by some kind of known standard? Personally I use dependency injection, and the use of Namespaces,...

Sharing controller between views


python,design-patterns,model-view-controller
I have a frame which holds 2 views. I want to use a common controller for both of them but not instantiate 2 controllers. How do i achieve this? Singleton? Send the controller as an argument? Note, the controller will hold temporary data (bad idea?) that will be sent away...

Keeping track what the state parameters are


c#,design-patterns,flags,states
I'm refactoring software that is created by my predecessor. The software can communicate over the can-bus. At this moment all devices are hardcoded in the software and my job is to make every deviceType configurable. (Saved in serialized classes and creatable with a Model creator). With the software, the devices...

Using .size() vs const variable for loops


c++,vector,coding-style,const
I have a vector: vector<Body*> Bodies; And it contains pointers to Body objects that I have defined. I also have a unsigned int const that contains the number of bodyobjects I wish to have in bodies. unsigned int const NumParticles = 1000; I have populated Bodieswith NumParticles amount of Body...

How to return result while applying Command query separation (CQS)


c#,design-patterns,cqrs,command-query-separation
I am separating my query and command on service side like this: public class ProductCommandService{ void AddProduct(Product product); } public interface ProductQueryService{ Product GetProduct(Guid id); Product[] GetAllProducts(); } Command Query Separation accepts that a method should change state or return a result. There is no problem. public class ProductController: ApiController{...

“is not abstract and does not override abstract method java” using Decorator Pattern


java,design-patterns,override,decorator
public abstract class AdicionalesCpd extends Cpd{ public abstract int getCpu(); public abstract int getRam(); public abstract int getDisco(); public abstract String getCadena();} This my abstract class for the decorator pattern, and I have this problem when it compiles: **error: Cpu is not abstract and does not override abstract method getCadena()...

VIM - Reformatting indentation and braces


vim,coding-style,vim-plugin
When working with blocks of code in VIM, I'm able to easily re-indent blocks of code via selecting a region in visual mode (SHIFT+v), then just hit =. This re-tabs lines of code, uses the correct indentation depths, hard-tabs vs spaces, etc. I have a large set of functions I...

Segregating the read-only and read-write in Spring/J2EE Apps


mysql,jpa,design-patterns,architecture,spring-data
We using Spring, Spring-Data and JPA in our project. For production servers, we would like to setup database cluster such that all read queries are directed to one server and all write queries are directed to another server. This obviously will require some changes in the way the DAOs are...

Where to apply domain level permissioning


design-patterns,permissions,authorization,onion-architecture,hexagonal-architecture
Permissioning/Authorization (not Authentication) is a cross-cutting concern, I think. In an Onion Architecture or Hexagonal Architecture, where should permissioning be performed? Examples of permissioning required would be: Filtering data returned to the front end (UI, API, or otherwise) Validating that a business operation can be performed at all Ideally, via...

Flyweight pattern - Memory footprint


python,python-2.7,design-patterns,ubuntu-14.04,flyweight-pattern
I'm learning Python and I've thought it would be a nice excuse to refresh my pattern knowledge and in that case, the Flyweight pattern. I created two small programs, one that is not optimized and one is implementing the Flyweight pattern. For my tests purposes, I'm creating an army of...

DTOs with different granularity


java,spring,hibernate,design-patterns,dto
I'm on a project that uses the latest Spring+Hibernate for persistence and for implementing a REST API. The different tables in the database contain lots of records which are in turn pretty big as well. So, I've created a lot of DAOs to retrieve different levels of detail and their...

What is the proper way to use inheritance when combined with factory method?


oop,design-patterns
Given that I have 3 classes Asset, AssetA, AssetB what is the proper way to structure inheritance when using the factory method? Here is how I would like to use these classes: Asset.new(data) should deterministically create either AssetA or AssetB depending on some flag present in data Asset should also...

Converting ASP.NET MVC Standard application into N-Tier Application


c#,asp.net-mvc,design-patterns
I was working on a application for which i was using ASP.NET MVC. Then i came to know about n-tier architecture which i think gives more flexibility to the applications so i started converting my standard mvc project into n-tier. I also have role based views. Before asking this question...

XML pattern to JS regex


javascript,regex,xml,design-patterns
I have a form that generate an XML file validated by a XSD schema. In the XSD there are a lot of rules (pattern attribute). For example, pattern: [\p{L}\d\s\.,\[\]\{\}€@#\-\(\)/='\+:\?!&quot;%&amp;\*;&lt;&gt;]* documentation : type A : all letters, all numbers, space, dot, comma, \[ \] \{ \} € @ # \- \(...

Publisher in Pub/Sub should be Synchronous or Asynchronous?


javascript,design-patterns,javascript-events,anti-patterns
My view on mechanism: Pattern wise publisher should just publish an event and should not care about listeners / subscribers for that topic / event. In case of JavaScript, lot of frameworks for Pub / Sub publishes event in Sync manner for example : framework just maintains map of event...

How to Implement Singleton Pattern without Nullable


design-patterns,singleton,hhvm,hacklang
I am trying to implement the Singleton pattern in Hack. However, I keep running into issues with Nullable. <?hh //strict class Foo { private static Foo $foo; public function __construct() { // Do stuff here. } public static function theFoo(): Foo { if (null === self::$foo) { self::$foo = new...

Node.js and Q Promises: How can I hand over parameters in a cleaner way?


javascript,node.js,coding-style,promise,q
I have some code like this: function example(data){ asyncFnOne() .all([asyncFnTwo(), data]) .spread(asyncFnThree) .done(); }; It doesn't matter what those functions do. The problem I have is that I don't know how asyncFnThree can access both data from asyncFnTwo and from the function parameters. The way I solved the problem is...

Java Design Issue: Enforce method call sequence


java,oop,design-patterns
There is a question which was recently asked to me in an interview. Problem: There is a class meant to profile the execution time of the code. The class is like: Class StopWatch { long startTime; long stopTime; void start() {// set startTime} void stop() { // set stopTime} long...

SQL Repeated Condition in Two Tables


sql,variables,coding-style,condition
I am a beginner to SQL, and I am having trouble getting rid of repeated code. I have a condition "AccountId=20" that I use twice in a SQL query. The SQL looks something like: DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE AccountId=20); DELETE FROM Table_B WHERE...