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

lisp: dynamic scope vs explicit parameter passing


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 ()
   (with-output-to-string (stream)
     (let ((*standard-output* stream))
   (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?


Actually you can bind *standard-output* directly:

(defun test-im-vs-ex-plicit ()
   (with-output-to-string (*standard-output*)   ; here
   (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
                 (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))

CL-USER 5 > (compile 'test)

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*

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

CL-USER 9 : 1 > :c 1

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...


React Flux dispatcher vs Node.js EventEmitter - scalable?

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...

XML pattern to JS regex

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, \[ \] \{ \} € @ # \- \(...

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

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,...

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

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...

Builder pattern where to apply [closed]

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...

Swift - Issue trying to access to Singleton object

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...

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

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...

Why there isn't library of 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?...

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

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...

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

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?

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...

Design Pattern for handling interrupt data

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...

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

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()...

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

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.

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

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: should deterministically create either AssetA or AssetB depending on some flag present in data Asset should also...

SQL Repeated Condition in Two Tables

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...

Sharing controller between views

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

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...

Should I used the Factory Method pattern?

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...

Flyweight pattern - Memory footprint

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...

Java immutability when defining members in a function called by constructor

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...

Java Design Issue: Enforce method call sequence

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...

Publisher in Pub/Sub should be Synchronous or Asynchronous?

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 extract business logic in this example

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...

Encapsulation with React child components

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...

DTOs with different granularity

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...

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

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 are line breaks allowed within Haskell expressions?

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...

Javascript chaining and passing arguments

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...

How to design abstract listener and its implementation?

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...

Domain Model with Event Sourcing

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...

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

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...

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

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...

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

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,...

How to Implement Singleton Pattern without Nullable

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...

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

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...

Using .size() vs const variable for loops

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)

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{...

Problems implementing ViewHolder pattern

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...

Segmentation fault in list of objects

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...

Advise on simplifying a PHP statement

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...

Send error from doNext block?

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];...

Singleton as performance upgrade in access to database

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...

Start programming without using advanced techniques? [on hold]

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...

Regular Expression differences between [] and ()

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? ...

reference data class member visitor pattern

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...

Design pattern for incremental code

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...

VIM - Reformatting indentation and braces

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...

undo / redo software pattern for split merge

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...

Where to apply domain level permissioning

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...