问:
Why not just make non-parameterized queries return an error?
SQL injection is a very serious security issue, in large part because it's so easy to get it wrong: the obvious, intuitive way to build a query incorporating user input leaves you vulnerable, and the Right Way to mitigate it requires you to know about parameterized queries and SQL injection first.

Seems to me that the obvious way to fix this would be to shut down the obvious (but wrong) option: fix the database engine so that any query received that uses hard-coded values in its WHERE clause instead of parameters returns a nice, descriptive error message instructing you to use parameters instead.  This would obviously need to have an opt-out option so that stuff like ad-hoc queries from administrative tools will still run easily, but it should be enabled by default.

Having this would shut down SQL injection cold, almost overnight, but as far as I know, no RDBMS actually does this.  Is there any good reason why not?

答:
TL;DR: You'd have to restrict all literals, not just the ones in WHERE clauses. For reasons why they don't, it allows the database to remain decoupled from other systems.

Firstly, your premise is flawed. You want to restrict only WHERE clauses, but that's not the only place user input can go. For example,

```<code>SELECT
    COUNT(CASE WHEN item_type = 'blender' THEN 1 END) as type1_count,
    COUNT(CASE WHEN item_type = 'television' THEN 1 END) AS type2_count)
FROM item
</code>```

This is equally vulnerable to SQL injection:

```<code>SELECT
    COUNT(CASE WHEN item_type = 'blender' THEN 1 END) FROM item; DROP TABLE user_info; SELECT CASE(WHEN item_type = 'blender' THEN 1 END) as type1_count,
    COUNT(CASE WHEN item_type = 'television' THEN 1 END) AS type2_count)
FROM item
</code>```

So you can't just restrict literals in the WHERE clause. You have to restrict all literals.

Now we're left with the question, "Why allow literals at all?" Keep this in mind: while relational databases are used underneath an application written in another language a large percentage of the time, there is no requirement that you must use application code to use the database. And here we have an answer: you need literals to write code. The only other alternative would be to require all code to be written in some language independent of the database. So having them gives you the ability to write "code" (SQL) directly in the database. This is a valuable decoupling, and it would be impossible without literals. (Try writing in your favorite language sometime without literals. I'm sure you can imagine how difficult this would be.)

As a common example, literals are often used in the population of list-of-value/look-up tables:

```<code>CREATE TABLE user_roles (role_id INTEGER, role_name VARCHAR(50));
INSERT INTO user_roles (1, 'normal');
INSERT INTO user_roles (2, 'admin');
INSERT INTO user_roles (3, 'banned');
</code>```

Without them, you would need to write code in another programming language just to populate this table. The ability to do so directly in SQL is valuable.

We're then left with one more question: why don't programming language client libraries do it then? And here we have a very simple answer: they would have re-implement the entire database parser for each supported version of the database. Why? Because there's no other way to guarantee you've found every literal. Regular expressions aren't enough. For example: this contains 4 separate literals in PostgreSQL:

SELECT $lit1$I'm a literal$lit1$||$lit2$I'm another literal $$ with nested string delimiters$$ $lit2$||'I''m ANOTHER literal'||$$I'm the last literal$$;
```

Trying to do that would be a maintenance nightmare, especially since valid syntax often changes between major releases of databases.

Body:
TL;DR: You'd have to restrict all literals, not just the ones in WHERE clauses. For reasons why they don't, it allows the database to remain decoupled from other systems.

Firstly, your premise is flawed. You want to restrict only WHERE clauses, but that's not the only place user input can go. For example,

SELECT
    COUNT(CASE WHEN item_type = 'blender' THEN 1 END) as type1_count,
    COUNT(CASE WHEN item_type = 'television' THEN 1 END) AS type2_count)
FROM item

This is equally vulnerable to SQL injection:

SELECT
    COUNT(CASE WHEN item_type = 'blender' THEN 1 END) FROM item; DROP TABLE user_info; SELECT CASE(WHEN item_type = 'blender' THEN 1 END) as type1_count,
    COUNT(CASE WHEN item_type = 'television' THEN 1 END) AS type2_count)
FROM item

So you can't just restrict literals in the WHERE clause. You have to restrict all literals.

Now we're left with the question, "Why allow literals at all?" Keep this in mind: while relational databases are used underneath an application written in another language a large percentage of the time, there is no requirement that you must use application code to use the database. And here we have an answer: you need literals to write code. The only other alternative would be to require all code to be written in some language independent of the database. So having them gives you the ability to write "code" (SQL) directly in the database. This is a valuable decoupling, and it would be impossible without literals. (Try writing in your favorite language sometime without literals. I'm sure you can imagine how difficult this would be.)

As a common example, literals are often used in the population of list-of-value/look-up tables:

CREATE TABLE user_roles (role_id INTEGER, role_name VARCHAR(50));
INSERT INTO user_roles (1, 'normal');
INSERT INTO user_roles (2, 'admin');
INSERT INTO user_roles (3, 'banned');

Without them, you would need to write code in another programming language just to populate this table. The ability to do so directly in SQL is valuable.

We're then left with one more question: why don't programming language client libraries do it then? And here we have a very simple answer: they would have re-implement the entire database parser for each supported version of the database. Why? Because there's no other way to guarantee you've found every literal. Regular expressions aren't enough. For example: this contains 4 separate literals in PostgreSQL:

SELECT $lit1$I'm a literal$lit1$||$lit2$I'm another literal $$ with nested string delimiters$$ $lit2$||'I''m ANOTHER literal'||$$I'm the last literal$$;

Trying to do that would be a maintenance nightmare, especially since valid syntax often changes between major releases of databases.


问:
Ways of embedding static data with python application
I have several projects on Python I am currently versioning with Git. I also have the input-output data that is gradually changing over the course of the project. I need to be able to re-run my pipeline later exactly in a way it was executed at a given time.

What would be the best way of doing it without inserting the source data into the git repository?

答:
I'd keep the data versioned separately.

I don't know what your gradual data change workflow is. You could use version control or just named directories, with some sort of de-duplication or plainly. VCSs are usually a poor choice for large binary data.

This way you can always check out the data independently of code, and check in code independently of the data.

ContentLicense: CC BY-SA 3.0


问:
Is there any practical way for a linked node structure to be immutable?
I decided to write a singly-linked list, and had the plan going in to make the internal linked node structure immutable.

I ran into a snag though. Say I have the following linked nodes (from previous add operations):

```<code>1 -> 2 -> 3 -> 4
</code>```

and say I want to append a 5.

To do this, since node 4 is immutable, I need to create a new copy of 4, but replace its next field with a new node containing a 5. The problem is now, 3 is referencing the old 4; the one without the appended 5. Now I need to copy 3, and replace its next field to reference the 4 copy, but now 2 is referencing the old 3...

Or in other words, to do an append, the entire list seems to need to be copied.

My questions:

Is my thinking correct? Is there any way to do an append without copying the entire structure?

Apparently "Effective Java" contains the reccomendation:

Classes should be immutable unless there's a very good reason to make them mutable...

Is this a good case for mutability?

I don't think this is a duplicate of the suggested answer since I'm not talking about the list itself; that obviously has to be mutable to conform to the interface (without doing something like keeping the new list internally and retrieving it via a getter. On second thought though, even that would require some mutation; it would just be kept to a minimum). I'm talking about whether or not the internals of the list must be immutable.

答:
If you have a singly linked list you will be working with the front if it more than you would with the back.

Functional languages like prolog and haskel provide easy ways to get the front element and the rest of the array. Appending to the back is a O(n) operation with copies each node.


答:
You are correct, appending requires copying the whole list if you are unwilling to mutate any nodes in-place. For we need to set the next pointer of the (now) second-to-last node, which in an immutable setting creates a new node, and then we need to set the next pointer of the third-to-last node, and so on.

I think the core problem here is not immutability, nor is the append operation ill-advised. Both are perfectly fine in their respective domains. Mixing them is bad: The natural (efficient) interface for an immutable list emphasized manipulation at the front of the list, but for mutable lists it is often more natural to build the list by successively appending the items from first to last.

Therefore I suggest that you make up your mind: Do you want an ephemeral interface or a persistent one? Do most operations produce a new list and leave an unmodified version accessible (persistent), or do you write code like this (ephemeral):

```<code>list.append(x);
list.prepend(y);
</code>```

Both choices are fine, but the implementation should mirror the interface: A persistent data structure benefits from immutable nodes, while an ephemeral one needs internal mutability to actually fulfill the performance promises it implicitly makes. java.util.List and other interfaces are ephemeral: Implementing them on an immutable list is inappropriate and in fact a performance hazard. Good algorithms on mutable data structures are often quite different from good algorithms on immutable data structures, so dressing up an immutable data structure as a mutable one (or vice versa) invites bad algorithms.

While a persistent list has some disadvantages (no efficient appending), this need not be a serious problem when programming functionally: Many algorithms can be formulated efficiently by shifting the mindset and using higher-order functions such as map or fold (to name two relatively primitive ones), or by prepending repeatedly. Furthermore, nobody is forcing you to use only this data structure: When others (ephemeral, or persistent but more sophisticated) are more appropriate, use them. I should also note that persistent lists have some advantages for other workloads: They share their tails, which can conserve memory.

Title: Is there any practical way for a linked node structure to be immutable?

Body:
I decided to write a singly-linked list, and had the plan going in to make the internal linked node structure immutable.

I ran into a snag though. Say I have the following linked nodes (from previous add operations):

```<code>1 -> 2 -> 3 -> 4
</code>```

and say I want to append a 5.

To do this, since node 4 is immutable, I need to create a new copy of 4, but replace its next field with a new node containing a 5. The problem is now, 3 is referencing the old 4; the one without the appended 5. Now I need to copy 3, and replace its next field to reference the 4 copy, but now 2 is referencing the old 3...

Or in other words, to do an append, the entire list seems to need to be copied.

My questions:

Is my thinking correct? Is there any way to do an append without copying the entire structure?

Apparently "Effective Java" contains the reccomendation:

Classes should be immutable unless there's a very good reason to make them mutable...

Is this a good case for mutability?

I don't think this is a duplicate of the suggested answer since I'm not talking about the list itself; that obviously has to be mutable to conform to the interface (without doing something like keeping the new list internally and retrieving it via a getter. On second thought though, even that would require some mutation; it would just be kept to a minimum). I'm talking about whether or not the internals of the list must be immutable.

Body:
You are correct, appending requires copying the whole list if you are unwilling to mutate any nodes in-place. For we need to set the next pointer of the (now) second-to-last node, which in an immutable setting creates a new node, and then we need to set the next pointer of the third-to-last node, and so on.

I think the core problem here is not immutability, nor is the append operation ill-advised. Both are perfectly fine in their respective domains. Mixing them is bad: The natural (efficient) interface for an immutable list emphasized manipulation at the front of the list, but for mutable lists it is often more natural to build the list by successively appending the items from first to last.

Therefore I suggest that you make up your mind: Do you want an ephemeral interface or a persistent one? Do most operations produce a new list and leave an unmodified version accessible (persistent), or do you write code like this (ephemeral):

list.append(x);
list.prepend(y);

Both choices are fine, but the implementation should mirror the interface: A persistent data structure benefits from immutable nodes, while an ephemeral one needs internal mutability to actually fulfill the performance promises it implicitly makes. java.util.List and other interfaces are ephemeral: Implementing them on an immutable list is inappropriate and in fact a performance hazard. Good algorithms on mutable data structures are often quite different from good algorithms on immutable data structures, so dressing up an immutable data structure as a mutable one (or vice versa) invites bad algorithms.

While a persistent list has some disadvantages (no efficient appending), this need not be a serious problem when programming functionally: Many algorithms can be formulated efficiently by shifting the mindset and using higher-order functions such as map or fold (to name two relatively primitive ones), or by prepending repeatedly. Furthermore, nobody is forcing you to use only this data structure: When others (ephemeral, or persistent but more sophisticated) are more appropriate, use them. I should also note that persistent lists have some advantages for other workloads: They share their tails, which can conserve memory.


答:
With lists in functional languages, you nearly always work with a head and tail, the first element and the remainder of the list.  Prepending is much more common because, as you surmised, appending requires copying the entire list (or other lazy data structures that don't precisely resemble a linked list).

In imperative languages, appending is much more common, because it tends to feel more natural semantically, and you don't care about invalidating references to previous versions of the list.

As an example of why prepending doesn't require copying the entire list, consider you have:

```<code>2 -> 3 -> 4
</code>```

Prepending a 1 gives you:

```<code>1 -> 2 -> 3 -> 4
</code>```

But note that it doesn't matter if someone else is still holding a reference to 2 as the head of their list, because the list is immutable and the links only go one way.  There's no way to tell the 1 is even there if you only have a reference to 2.  Now, if you appended a 5 onto either list, you'd have to make a copy of the entire list, because otherwise it would appear on the other list as well.

Body:
With lists in functional languages, you nearly always work with a head and tail, the first element and the remainder of the list.  Prepending is much more common because, as you surmised, appending requires copying the entire list (or other lazy data structures that don't precisely resemble a linked list).

In imperative languages, appending is much more common, because it tends to feel more natural semantically, and you don't care about invalidating references to previous versions of the list.

As an example of why prepending doesn't require copying the entire list, consider you have:

2 -> 3 -> 4

Prepending a 1 gives you:

1 -> 2 -> 3 -> 4

But note that it doesn't matter if someone else is still holding a reference to 2 as the head of their list, because the list is immutable and the links only go one way.  There's no way to tell the 1 is even there if you only have a reference to 2.  Now, if you appended a 5 onto either list, you'd have to make a copy of the entire list, because otherwise it would appear on the other list as well.


问:
What strategy to follow while matching sql server datatypes in C# Code First approach while using Entity Framework
While matching SQL Server datatypes with C# Code First Approach in Entity Framework, what are specific points that we should keep in mind so that our C# datatype should match exactly our SQL Server datatype?

Specifically, while we have to match SQL Server datatype to C# datatype, let's say for particular datatype  hierarchyid, which exists in SQL Server but not in C#, how can we make it possible?

答:
EF isolates your code from concrete database. Each database has it's own features but EF's API is not so powerfull to express them all. Actually, from the client's side EF is a simple object storage.

So, if you want to manage such database features like specific datatypes, security checks, triggers, views... EF can't help with it. I haven't seen anything that can help you. You need to introduce a dependency to the sql server in your system.


答:
An approach which can sometimes be helpful would be to have two classes of list-holding objects--a forward-list object with a final reference to the first node in a forward-linked list and an initially-null non-final reference which (when non-null) identifies a reverse-list object holding the same items in the opposite order, and a reverse-list object with a final reference to the last item of a reverse-linked list and an initially-null non-final reference which (when non-null) identifies a forward-list object holding the same items in opposite order.

Prepending an item to a forward-list or appending an item to a reverse-list would merely require creating a new node which links to the node identified by the final reference and creating a new list object of the same type as the original, with a final reference to that new node.

Appending an item to a forward-list or prepending to a reverse-list would require having a list of the opposite type; the first time that is done with a particular list it should create a new object of the opposite type and store a reference; repeating the action should reuse the list.

Note that the external state of a list object will be considered the same whether its reference to an opposite-type list is null or identifies an opposite-order list.  There would be no need to make any variables final, even when using multi-threaded code, since every list object would have a final reference to a complete copy of its contents.

If code on one thread creates and cache a reversed copy of a list, and the field in which that copy is cached isn't volatile, it would be possible that code on another thread might not see the cached list, but the only adverse effect from that would be that the other thread would need to do extra work building another reversed copy of the list.  Because such action would at worst impair efficiency, but would not affect correctness, and because volatile variables create efficiency impairments of their own, it will often be better to have the variable be non-volatile and accept the possibility of occasional redundant operations.


问:
Where in an MVC web application should writing files locally go?
In my web application that uses an MVC framework which has different modules for models, views and controllers I talk to several databases and APIs. Those are implemented as individual models.

A lot of data gets entered by the user accross several different screens. That data goes into the session. Some of that data is meta information that validates the success of the process, and some of it is stuff that I want to keep. That data is supposed to be written to a file in the file system, and the path of that file with some meta-information is stored in a database. After that, a confirmation page will be displayed to the user.

I am now struggling with where to put the writing of the subset of the data that has accumulated in the session to the file in my specific format.

There are several thoughts I have on the matter. I am not sure which one is the most right.

It should be a View because it takes data that is already there in the user's session and presents it in a specific way – the file format (which is XML, but that is not relevant). Formatting and writing the file is implemented there.

Reasoning: The default HTML view that renders data as a website to the user's browser has the webserver's interface set as its STDOUT channel. Likewise would a JSON view that presents stuff in case an API call is made. If we write to a file, the STDOUT of the view that formats the file is set to a local file handle and we write there.

There should be a View to bring the data into my XML format, but a Model to write the data into the file.

Reasoning: Because after writing the file, another website will be displayed. Only one view can be at the end of the chain of things that do stuff in the lifetime of one request handling. But because data is being formatted, a view is appropriate. It just returns the formatted data rather than writing it to a sink (STDOUT).

It should be a Model, because it deals with data.

Reasoning: Models are data sources and data sinks. Although the source-part is absent here there is still a data sink. The fact that it needs to be formatted also is neglegible because if we'd talk to e.g. a RESTful API of some sort we would also first format the data to be either part of a GET request (which is very simple) or maybe a JSON representation as the body of a POST/PUT request.

The code that formats the data into XML is already built as a stand-alone class that is not tied to the webapp yet.

My question is this: Where in the application should I use that class and write the file to disk so I do not break the MVC pattern?

Example cases where this specific process would happen include:

a user feedback/survey form with multiple pages, like the Stack Overflow anual user survey,

an e-commerce order funnel,

back-office data entry that talks to a third party through a file-based API where the "sending" happens asynchronously at a later, unrelated time

答:
In a slight variation of JDT's answer...if I'm understanding all of it correctly, this is how I view it (pardon the pun):

View/Controller: Both part of the presentation concern.  The controller acts as the intermediary between the view and the model, affecting changes to the model (unless you have binding to the model from the view) and reflecting model state in the view.

Models: Implement the business rules/behavior or, at least, make use of objects that do.  The business rules are used when applying commands and queries to the application/session state and define the heart of the application's behavior.

Data: The application state needs to be persisted to be of any use, generally, so the models use a data layer to achieve that.

In this way, any mutation of the application state goes through the same layer of business rules to achieve consistency; the presentation wouldn't directly interact with the data.

I wouldn't have the controller directly being responsible for the persistence because if you were to switch out the presentation layer with another (where you don't have the controller, such as if it became a headless service), you've lost the piece that was doing the persistence for you.  By pushing it down to the business tier (in the models), you're free to change your presentation layer and still maintain your behavior.


答:
There's some datatype that's not supported by EF.

```<code>geography
geometry
hierarchyid
sql_variant
</code>```

http://thedatafarm.com/data-access/sql-server-2008-data-types-and-entity-framework-4/

I never use any of that type, but when using dapper I also come to this similar problem(processing image datatype), the easiest way to deal with this limitation is just to go back to old OLE DB.

Other than that you just use this as a reference,

Title: What strategy to follow while matching sql server datatypes in C# Code First approach while using Entity Framework

Body:
While matching SQL Server datatypes with C# Code First Approach in Entity Framework, what are specific points that we should keep in mind so that our C# datatype should match exactly our SQL Server datatype?

Specifically, while we have to match SQL Server datatype to C# datatype, let's say for particular datatype  hierarchyid, which exists in SQL Server but not in C#, how can we make it possible?

Body:
There's some datatype that's not supported by EF.

geography
geometry
hierarchyid
sql_variant

http://thedatafarm.com/data-access/sql-server-2008-data-types-and-entity-framework-4/

I never use any of that type, but when using dapper I also come to this similar problem(processing image datatype), the easiest way to deal with this limitation is just to go back to old OLE DB.

Other than that you just use this as a reference,


答:
As others have pointed out, you are correct that an immutable singly-linked list requires copying the entire list when performing an append operations.

Often you can use the workaround of implementing your algorithm in terms of cons (prepend) operations, and then reverse the final list once. This still needs to copy the list once, but the complexity overhead is linear in the length of the list, whereas by repeatedly using append you can easily get a quadratic complexity.

Difference lists (see e.g. here) are an interesting alternative. A difference list wraps a list and provides an append operation in constant time. You basically work with the wrapper as long as you need to append, and then convert back to a list when you are finished. This is somehow similar to what you do when you use a StringBuilder to construct a string, and at the end get the result as a String (immutable!) by calling toString. One difference is that a StringBuilder is mutable, but a difference list is immutable. Also, when you convert a difference list back to a list, you still have to construct the entire new list but, again, you only need to do this once.

It should be quite easy to implement an immutable DList class that provides a similar interface as Haskell's Data.DList.


问:
Lines of code that take on too much responsibility
Intuitively, I know that (in terms of a maintainable, understandable codebase) the following code is bad practice

```<code>var foo = fooFunc(barFunc(),wooFunc(chewFunc()));
</code>```

and might be better stated as

```<code>var bar = barFunc();
var chew = chewFunc();
var woo = wooFunc(chew);
var foo = fooFunc(bar, woo);
</code>```

This makes debugging easier, code more readable etc. etc...

Instead of personally spelling this out to co-developers, it might be better to lead them to an existing page that explains the perils of such a construct.

Is there an official term for this kind of anti-pattern?

答:
The code form you want is called A-normal form (ANF); it is not always more readable, but it might be more easily tranformable inside compilers, and is useful for precise garbage collection (hence, many compilers are transforming the source code into some intermediate ANF). See also SSA form.

I don't believe that ANF is always more readable; on the contrary, coding with nested side-effect free function calls is often more easy to understand IMHO. But that is a matter of opinion, and of course depends upon the context. YMMV.

Of course, things may be different if some of the functions have significant (e.g. global) side effects, in particular because many programming languages do not specify an order of argument evaluation.


问:
Immutable structures and deep composition hierarchy
I'm developing a GUI application, heavily working with graphics - you can think about it as a vector editor, for the sake of the example. It is very tempting to make all data structures immutable - so I could get undo/redo, copy/paste, and many other things almost without effort.

Fot the sake of simplicity, I will use the following example - application is used to edit polygonal shapes, so I have "Polygon" object, which is simply list of immutable points:

```<code>Scene -> Polygon -> Point
</code>```

And so I have only one mutable variable in my program - the one which holds current Scene object. The problem which I have starts when I try to implement point dragging - in mutable version, I simply grab a Point object and start modifying its coordinates. In immutable version - I am stuck. I could have stored indices of Polygon in current Scene, index of dragged point in Polygon, and replace it every time. But this approach does not scale - when composition levels go to 5 and further, boilerplate would become unbearable.

I'm sure this problem can be solved - after all, there is Haskell with completely immutable structures and IO monad. But I just cannot find how.

Can you give me a hint?

答:
I could have stored indices of Polygon in current Scene, index of dragged point in Polygon, and replace it every time. But this approach does not scale - when composition levels go to 5 and further, boilerplate would become unbearable.

You're absolutely right, this approach doesn't scale if you can't get around the boilerplate. Specifically, the boilerplate for creating a whole new Scene with a tiny subpart changed. However, many functional languages provide a construct for dealing with this sort of nested structure manipulation: lenses.

A lens is basically a getter and setter for immutable data. A lens has a focus on some small part of a larger structure. Given a lens, there are two things you can do with it - you can view the small part of a value of the larger structure, or you can set the small part of a value of a larger structure to a new value. For example, suppose you have a lens that focuses on the third item in a list:

```<code>thirdItemLens :: Lens [a] a
</code>```

That type means the larger structure is a list of things, and the small subpart is one of those things. Given this lens, you can view and set the third item in the list:

```<code>> view thirdItemLens [1, 2, 3, 4, 5]
3
> set thirdItemLens 100 [1, 2, 3, 4, 5]
[1, 2, 100, 4, 5]
</code>```

The reason lenses are useful is because they are values representing getters and setters, and you can abstract over them the same way you can other values. You can make functions that return lenses, for instance a listItemLens function which takes a number n and returns a lens viewing the nth item in a list. Additionally, lenses can be composed:

```<code>> firstLens = listItemLens 0
> thirdLens = listItemLens 2
> firstOfThirdLens = lensCompose firstLens thirdLens
> view firstOfThirdLens [[1, 2], [3, 4], [5, 6], [7, 8]]
5
> set firstOfThirdLens 100 [[1, 2], [3, 4], [5, 6], [7, 8]]
[[1, 2], [3, 4], [100, 6], [7, 8]]
</code>```

Each lens encapsulates behavior for traversing one level of the data structure. By combining them, you can eliminate the boilerplate for traversing multiple levels of complex structures. For instance, supposing you have a scenePolygonLens i that views the ith Polygon in a Scene, and a polygonPointLens n that views the nth Point in a Polygon, you can make a lens constructor for focusing on just the specific point you care about in an entire scene like so:

```<code>scenePointLens i n = lensCompose (polygonPointLens n) (scenePolygonLens i)
</code>```

Now suppose a user clicks point 3 of polygon 14 and moves it 10 pixels right. You can update your scene like so:

```<code>lens = scenePointLens 14 3
point = view lens currentScene
newPoint = movePoint 10 0 point
newScene = set lens newPoint currentScene
</code>```

This nicely contains all the boilerplate for traversing and updating a Scene inside lens, all you have to care about is what you want to change the point to. You can further abstract this with a lensTransform function that accepts a lens, a target, and a function for updating the view of the target through the lens:

```<code>lensTransform lens transformFunc target =
  current = view lens target
  new = transformFunc current
  set lens new target
</code>```

This takes a function and turns it into an "updater" on a complicated data structure, applying the function to only the view and using it to construct a new view. So going back to the scenario of moving the 3rd point of the 14th polygon to the right 10 pixels, that can be expressed in terms of lensTransform like so:

```<code>lens = scenePointLens 14 3
moveRightTen point = movePoint 10 0 point
newScene = lensTransform lens moveRightTen currentScene
</code>```

And that's all you need to update the whole scene. This is a very powerful idea and works very well when you have some nice functions for constructing lenses viewing the pieces of your data you care about.

However this is all pretty out-there stuff currently, even in the functional programming community. It's difficult to find good library support for working with lenses, and even more difficult to explain how they work and what the benefits are to your coworkers. Take this approach with a grain of salt.

Body:
I could have stored indices of Polygon in current Scene, index of dragged point in Polygon, and replace it every time. But this approach does not scale - when composition levels go to 5 and further, boilerplate would become unbearable.

You're absolutely right, this approach doesn't scale if you can't get around the boilerplate. Specifically, the boilerplate for creating a whole new Scene with a tiny subpart changed. However, many functional languages provide a construct for dealing with this sort of nested structure manipulation: lenses.

A lens is basically a getter and setter for immutable data. A lens has a focus on some small part of a larger structure. Given a lens, there are two things you can do with it - you can view the small part of a value of the larger structure, or you can set the small part of a value of a larger structure to a new value. For example, suppose you have a lens that focuses on the third item in a list:

thirdItemLens :: Lens [a] a

That type means the larger structure is a list of things, and the small subpart is one of those things. Given this lens, you can view and set the third item in the list:

> view thirdItemLens [1, 2, 3, 4, 5]
3
> set thirdItemLens 100 [1, 2, 3, 4, 5]
[1, 2, 100, 4, 5]

The reason lenses are useful is because they are values representing getters and setters, and you can abstract over them the same way you can other values. You can make functions that return lenses, for instance a listItemLens function which takes a number n and returns a lens viewing the nth item in a list. Additionally, lenses can be composed:

> firstLens = listItemLens 0
> thirdLens = listItemLens 2
> firstOfThirdLens = lensCompose firstLens thirdLens
> view firstOfThirdLens [[1, 2], [3, 4], [5, 6], [7, 8]]
5
> set firstOfThirdLens 100 [[1, 2], [3, 4], [5, 6], [7, 8]]
[[1, 2], [3, 4], [100, 6], [7, 8]]

Each lens encapsulates behavior for traversing one level of the data structure. By combining them, you can eliminate the boilerplate for traversing multiple levels of complex structures. For instance, supposing you have a scenePolygonLens i that views the ith Polygon in a Scene, and a polygonPointLens n that views the nth Point in a Polygon, you can make a lens constructor for focusing on just the specific point you care about in an entire scene like so:

scenePointLens i n = lensCompose (polygonPointLens n) (scenePolygonLens i)

Now suppose a user clicks point 3 of polygon 14 and moves it 10 pixels right. You can update your scene like so:

lens = scenePointLens 14 3
point = view lens currentScene
newPoint = movePoint 10 0 point
newScene = set lens newPoint currentScene

This nicely contains all the boilerplate for traversing and updating a Scene inside lens, all you have to care about is what you want to change the point to. You can further abstract this with a lensTransform function that accepts a lens, a target, and a function for updating the view of the target through the lens:

lensTransform lens transformFunc target =
  current = view lens target
  new = transformFunc current
  set lens new target

This takes a function and turns it into an "updater" on a complicated data structure, applying the function to only the view and using it to construct a new view. So going back to the scenario of moving the 3rd point of the 14th polygon to the right 10 pixels, that can be expressed in terms of lensTransform like so:

lens = scenePointLens 14 3
moveRightTen point = movePoint 10 0 point
newScene = lensTransform lens moveRightTen currentScene

And that's all you need to update the whole scene. This is a very powerful idea and works very well when you have some nice functions for constructing lenses viewing the pieces of your data you care about.

However this is all pretty out-there stuff currently, even in the functional programming community. It's difficult to find good library support for working with lenses, and even more difficult to explain how they work and what the benefits are to your coworkers. Take this approach with a grain of salt.


问:
Code Coverage or Test Brevity?
I've been writing a lot of unit tests lately and have become somewhat obsessed with code coverage. However, I'm struggling justifying going for 100% code coverage, when so many tests would be a redundant, and really clutter up my unit tests.

For example, imagine an customer endpoint of an API. The user posts a customer ID, their location and then some data. Looks like /api/customers/:locationId/:customerId.

Here's an example of a code coverage snippet from instanbul, I'm using Node.js:

The first miss, failing to update the customer, is something that should definitely be tested. But the last 2, failing to find location and customer, are present on nearly every endpoint. Am I really to pass in an incorrect location, and then an incorrect customer, for every one of the endpoints (create, update, delete, etc.)? Or should I just live with those not being covered?

答:
Test coverage is good. 100% test coverage is absolutely reachable without insane amounts of effort1, except of course for those this-can-never-happen-but-lets-check-for-it-nevertheless assertions.2

1. Assuming reasonably testable code.

2. However, increasing test coverage has diminishing returns. Not all code is worth covering by explicit tests.

Especially when talking about error handlers, these have to be covered by tests.3 The “happy path” will be implicitly tested by normal usage. But if things go wrong – you want to make sure things still go your way. It would be a shame if a silly little mistake would mean your error handling code would itself produce an error. Proper errors also make it easier for users of the API to figure out why their code isn't working – they are an important feature of your code.

3. Testing such errors is most important when the errors are supposed to be recoverable, because those errors are part of your business logic and API. This is in contrast to assertions that directly terminate the process and don't allow for further control flow.

In the context of a web API, checking all input can be crucially important for security – defensive programming should be the rule, not an accidental feature. Obviously, this validation needs to be tested!

Another tip: In your example, your code has an extraordinary amount of indentation. This can be a sign that your function should be split up into multiple smaller functions that can be tested separately. Closures are also difficult to test; using named functions increases testability. Also, long cascades of the form

if (a) {
  if (b) {
    if (c) {
      return happy_path;
    } else {
      throw error_c;
    }
  } else {
    throw error_b;
  }
} else {
  throw error_a;
}
```
<p>can be rewritten as</p>
<pre class="lang-cpp prettyprint-override"><code>if (!a) {
  throw error_a;
}

if (!b) {
  throw error_b;
}

if (!c) {
  throw error_c;
}

return happy_path;
</code>```

These “guards” make the code more linear and in my experience both easier to understand and easier to test. In that example, you just need four tests to get 100% statement and branch coverage.

Title: Code Coverage or Test Brevity?

Body:
Test coverage is good. 100% test coverage is absolutely reachable without insane amounts of effort1, except of course for those this-can-never-happen-but-lets-check-for-it-nevertheless assertions.2

1. Assuming reasonably testable code.

2. However, increasing test coverage has diminishing returns. Not all code is worth covering by explicit tests.

Especially when talking about error handlers, these have to be covered by tests.3 The “happy path” will be implicitly tested by normal usage. But if things go wrong – you want to make sure things still go your way. It would be a shame if a silly little mistake would mean your error handling code would itself produce an error. Proper errors also make it easier for users of the API to figure out why their code isn't working – they are an important feature of your code.

3. Testing such errors is most important when the errors are supposed to be recoverable, because those errors are part of your business logic and API. This is in contrast to assertions that directly terminate the process and don't allow for further control flow.

In the context of a web API, checking all input can be crucially important for security – defensive programming should be the rule, not an accidental feature. Obviously, this validation needs to be tested!

Another tip: In your example, your code has an extraordinary amount of indentation. This can be a sign that your function should be split up into multiple smaller functions that can be tested separately. Closures are also difficult to test; using named functions increases testability. Also, long cascades of the form

if (a) {
  if (b) {
    if (c) {
      return happy_path;
    } else {
      throw error_c;
    }
  } else {
    throw error_b;
  }
} else {
  throw error_a;
}

can be rewritten as

if (!a) {
  throw error_a;
}

if (!b) {
  throw error_b;
}

if (!c) {
  throw error_c;
}

return happy_path;

These “guards” make the code more linear and in my experience both easier to understand and easier to test. In that example, you just need four tests to get 100% statement and branch coverage.

ContentLicense: CC BY-SA 4.0


问:
JIT compiler for C, C++, and the likes
Is there any just-in-time compiler out there for compiled languages, such as C and C++? (The first names that come to mind are Clang and LLVM! But I don't think they currently support it.)

Explanation:

I think the software could benefit from runtime profiling feedback and aggressively optimized recompilation of hotspots at runtime, even for compiled-to-machine languages like C and C++.

Profile-guided optimization does a similar job, but with the difference a JIT would be more flexible in different environments. In PGO you run your binary prior to releasing it. After you released it, it would use no environment/input feedbacks collected at runtime. So if the input pattern is changed, it is probe to performance penalty. But JIT works well even in that conditions.

However I think it is controversial wether the JIT compiling performance benefit outweights its own overhead.

答:
C++/CLI is jitted. Granted, C++/CLI is not C++ but it is pretty close. That said Microsoft's JIT doesn't do the super clever/cute kinds of runtime behavior based optimizations you're asking about, at least not to my knowledge. So this really doesn't help.

http://nestedvm.ibex.org/ turns MIPS into Java bytecode which would then be jitted. The problem with this approach from your question is that you throw away a lot of the useful information by the time it gets to the JIT.

Title: JIT compiler for C, C++, and the likes

ContentLicense: CC BY-SA 2.5


问:
Android: Pattern for checking requirements at startup?
My app's launcher activity checks a bunch of requirements like whether GPS is enabled, there's a network connection, the app has device administrator privileges, etc.  Some of these checks display dialogs or take the user to another activity to resolve the unsatisfied requirements.  I'm looking for a way of doing this that's easy to extend with more requirements and easy for others to read and understand.

My original solution was to perform the checks sequentially, each in its own method, with each method either taking remedial action or calling the next method in the sequence.  The sequence is started in onResume(), so upon returning from another activity it picks up with the first check that doesn't pass.  This got messy fast because some of the requirements are conditional.  For example, on Lollipop it checks if the app is the device owner, and whether it might be able to become the device owner.  If it can, it tells the user to run the appropriate adb shell command.  Naturally, this whole sequence of checks is skipped on KitKat.  So the chain of methods is actually more like a tangled braid.  It's hard to trace the logic of it or verify that each step eventually calls the next under all possible conditions.  I'm reluctant to make any changes to it, and I just wrote it myself a couple weeks ago.

My other idea was to number the steps (or associate them with the elements of an enum) and pass the last-completed step between activity instances.  But I anticipate this getting messy, too.

How would you structure this?

答:
I'm not sure this is the best solution, but this is what I ended up doing:

I put all my requirements checks in the onResume() of a headless fragment, and added it to my activity in onCreate(...).  If any of the requirements aren't met, the headless fragment displays dialog fragments that explain what it needs the user to do before taking them to the system settings.  When all the requirements are met, it calls a method on the activity.  (I may change this to broadcasting an event to completely decouple the fragment from the activity.)

This doesn't make the logic of the sequence of checks any less messy, but at least it moves all that code out of the activity, which makes both parts easier to navigate and understand.

Edit: Six months later, I refactored the above solution into something much more OO.

```<code>public interface Requirement {
    /**
     * Checks a system requirement and calls {@link
     * StartActivity#nextRequirement()} when it's satisfied.
     *
     * @param activity the current activity
     */
    void check(final StartActivity activity);
}
</code>```

A List<Requirement> is injected into the activity using Dagger2.  I can easily add more requirements, and their order is easy to see and change in the Dagger module.

```<code>@Inject List<Requirement> mRequirements;
private Iterator<Requirement> mRequirementsIterator;

void checkRequirements() {
    mRequirementsIterator = mRequirements.iterator();
    nextRequirement();
}

void nextRequirement() {
    if(mRequirementsIterator.hasNext()) {
        mRequirementsIterator.next().check(this);
    }
    else {
        onRequirementsSatisfied();
    }
}
</code>```

I call checkRequirements() from onResume().  Any dialog fragments displayed by a Requirement dismiss themselves in their own onPause(), since they will be displayed again if the requirement is still not met the next time the activity resumes.

Body:
I'm not sure this is the best solution, but this is what I ended up doing:

I put all my requirements checks in the onResume() of a headless fragment, and added it to my activity in onCreate(...).  If any of the requirements aren't met, the headless fragment displays dialog fragments that explain what it needs the user to do before taking them to the system settings.  When all the requirements are met, it calls a method on the activity.  (I may change this to broadcasting an event to completely decouple the fragment from the activity.)

This doesn't make the logic of the sequence of checks any less messy, but at least it moves all that code out of the activity, which makes both parts easier to navigate and understand.

Edit: Six months later, I refactored the above solution into something much more OO.

public interface Requirement {
    /**
     * Checks a system requirement and calls {@link
     * StartActivity#nextRequirement()} when it's satisfied.
     *
     * @param activity the current activity
     */
    void check(final StartActivity activity);
}

A List<Requirement> is injected into the activity using Dagger2.  I can easily add more requirements, and their order is easy to see and change in the Dagger module.

@Inject List<Requirement> mRequirements;
private Iterator<Requirement> mRequirementsIterator;

void checkRequirements() {
    mRequirementsIterator = mRequirements.iterator();
    nextRequirement();
}

void nextRequirement() {
    if(mRequirementsIterator.hasNext()) {
        mRequirementsIterator.next().check(this);
    }
    else {
        onRequirementsSatisfied();
    }
}

I call checkRequirements() from onResume().  Any dialog fragments displayed by a Requirement dismiss themselves in their own onPause(), since they will be displayed again if the requirement is still not met the next time the activity resumes.


问:
Do mocks violate the Open/Closed principle?
Some time ago I read, on a Stack Overflow answer that I can't find, a sentence that explained that you should test public APIs, and the author said that you should test interfaces. The author also explained that if a method implementation changed, you shouldn't need to modify the test case, as doing this would break the contract that make sure the system under test works. In other words, a test should fail if the method doesn't work, but not because the implementation changed.

This called to my attention when we talk about mocking. Since mocking relies heavily on expectation calls from system under test's dependencies, mocks are tightly coupled with the implementation rather than the interface.

While researching mock vs stub, several articles agree that stubs should be used instead of mocks, as they don't rely on expectations from dependencies, meaning the test need no knowledge of the underlying system under test implementation.

My questions would be:

Do mocks violate the open/closed principle?

Is there something missing in the argument in favor of stubs on the last paragraph, that make stubs not so great vs mocks?

If so, when would be a good use case to mock and when would be a good use case to use stubs?

答:
Note: I'm assuming you are defining Mock to mean "a class with no implementation, just something you can monitor" and Stub to be "partial mock, a.k.a. uses some of the real behavior of the implemented class", as per this Stack Overflow question.

I'm not sure why you think that the consensus is to use stubs, for example it's just the opposite in the Mockito Documentation

As usual you are going to read the partial mock warning: Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.

However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven & well-designed code.

That documentation says it better than I can. Using mocks allows you to just test that one particular class, and nothing else; if you need partial mocks to achieve the behavior you're looking for, you've probably done something wrong, are violating SRP, and so forth, and your code could stand a refactor. Mocks do not violate the open-closed principle, because they're only ever used in tests anyway, they're not real changes to that code. Usually they're generated on the fly anyway by a library like cglib.


答:
The Open/Closed principle is mostly about being able to change the behavior of a class without modifying it. Therefore, injecting a mocked component dependency inside a class under test does not violate it.

The problem with test doubles (mock/stub) is that you basically make arbitrary assumptions regarding how the class under test interacts with its environment. If those expectations are wrong, well, you're likely to have some problems once the code is deployed. If you can afford it, test your code within the same constraints than the one bounding your production environment. If you can't, make the least assumptions possible, and mock/stub only the peripherals of your system (database, authentication service, HTTP client, etc...).

The only valid reason why, IMHO, a double should be used, is when you need to record its interactions with the class under test, or when you need to provide fake data (which both techniques can do). Be careful however, abusing of it reflects a bad design, or a test that relies too much on the API under test implementation.

Title: Do mocks violate the Open/Closed principle?

Body:
Some time ago I read, on a Stack Overflow answer that I can't find, a sentence that explained that you should test public APIs, and the author said that you should test interfaces. The author also explained that if a method implementation changed, you shouldn't need to modify the test case, as doing this would break the contract that make sure the system under test works. In other words, a test should fail if the method doesn't work, but not because the implementation changed.

This called to my attention when we talk about mocking. Since mocking relies heavily on expectation calls from system under test's dependencies, mocks are tightly coupled with the implementation rather than the interface.

While researching mock vs stub, several articles agree that stubs should be used instead of mocks, as they don't rely on expectations from dependencies, meaning the test need no knowledge of the underlying system under test implementation.

My questions would be:

Do mocks violate the open/closed principle?

Is there something missing in the argument in favor of stubs on the last paragraph, that make stubs not so great vs mocks?

If so, when would be a good use case to mock and when would be a good use case to use stubs?


问:
is coding important?
Is coding important to be good at computer science? Should one implement the algorithm to know it well ?

I remember one cs professor's idiom that "I never code"

答:
As a Computer Science student i think that at first it's better to understand concepts that involve software development. Once you have learned the idea behind software and how does it interacts with a computer, then is time to start coding and dealing with specific implementation problems.

This is just like "Software Exceptions", at first you only deal with them because you did something that was not allowed to do. Then when you learn them, start doing the same with your code so to make it more verbose.

Well i think that people who dont care about concepts like those programmers who use Exceptions as a normal workflow in their applications. They know HOW but dont really get WHY.

Title: is coding important?


问:
Unifying two implementation through an interface
I have a simple object like this

```
  public class Book
    {
        public List Chapters { get; private set; }
        public TableOfContent BookTOC { get; set; }
        public string Identifier { get; private set; }
        public string Title { get; private set; }
        public string Publisher { get; set; }
        public string Rights { get; internal set; }
        public DateTime PublishingDate { get; internal set; }

        private IBookRepository _repository = null;

        public Book(IBookRepository bookRepository)
        {
            _repository = bookRepository;
        }

        public Book Load(string bookid)
        {
            //Load book from repository
        }

       public Chapter GetNextChapter(string chapterId)
        {
            //Load Chapter from repository
        }

    }
```

In this domain (actually anywhere in the world!), book has chapters and book has ToC. In our application, there would be two possible implementations of repository i.e. the book object may either be loaded from Xml or be loaded from database. These books are pretty large in size i.e. two-four hundred thousand chapters (This is all about book metadata, content is separate but out of question for now)

My problem is that when the book is loaded from database, I want to leverage database capabilities of querying and indexes etc. For example, in the GetNextChapter, when I am using database repository, I can locate just the specific chapter and find next of it. However in case of Xml, since I don't want to traverse xml over and over again, I would like to keep it loaded at one time initially and the cache it upstream so that I can find the next chapter just from the object itself. As you can see, these two implementations by nature are different, but at any given time we will be using only one of those. I am not able come up with a uniform interface of operations that both these implementations can follow. Let's say if I decide to have operation GetNextChapter implemented in both, then for database repository, I just need the chapter ID, whereas in the Xml repository, I need the whole book object or at least list of chapters (and even that has nothing to do with xml actually because that's just in memory filter).

Can anyone help in deciding how do I uniform these two through a single interface having two implementation? Or are they not meant to be uniformed via a single interface and deserve a separate way of implementation?

EDIT
To clarify further, if I add GetNextChapter method in the interface, Database implementation needs only the chapterID as parameter, whereas Xml implementation would need the book object. Similarly the LoadBook method will return full object (with chatpers and toc) for XMLImplementation (so that I don't have to traverse xml over and over) whereas it will only return partial object (without chapters and toc) in case of DatabaseImplementation (for obvious performance reasons).

So how will these two go against a single interface?

答:
This is a perfect example for an use of interface, or if you may, a public API. Within your Book domain, you are dependant on an implementation of IBookRepositoy, to whom you will interact with via it's public API (its public methods).

Now you just need to follow the Single Responsibility Principle and Separation of Concerns in order to achieve a good design. What you want here is to have multiple implementations of IBookRepository, that are not known to your Book domain object. You could say XMLBookRepository and DatabaseRepository would be your 2 different implementations.

That being said, the implementation used in both of this repositories should stay hidden from the Book domain, as it will interacting via the public API, the IBookRepository interface.

Once that's on the table, you need to implement both repository in the way they are needed. Note we are talking about 2 different implementations; this is because, as you yourself stated:

when I am using database repository, I can locate just the specific chapter and find next of it. However in case of Xml, since I don't want to traverse xml over and over again, I would like to keep it loaded at one time initially and the cache it upstream so that I can find the next chapter just from the object itself.

This is a clear indication that you need multiple implementation.


答:
It's not strictly Java, but I suggest you read this article on an immutable, but performant indexed persistent data structure written in Scala:

http://www.codecommit.com/blog/scala/implementing-persistent-vectors-in-scala

Since it's a Scala data structure, it can be used from Java too (with a bit more verbosity). It's based on a data structure available in Clojure, and I'm sure there's a more "native" Java library offering it as well.

Also, a note on constructing immutable data structures: what you usually want is some sort of "Builder", which allows you to "mutate" your "under-construction" data structure by appending elements to it (within a single thread); after you're done appending, you call a method on the "under-construction" object such as .build() or .result(), which "builds" the object, giving you an immutable data structure that you can then safely share.


问:
How to avoid using service location when using dependency injection?
I am trying to use dependency injection in a WPF application, and I really can't figure how to avoid using service location, which is considered to be an anti-pattern in many articles. I am using the MVVM Light framework.

Interface I
  Property N As Integer
End Interface
Class A
  Private _i As I
  Sub New(i As I)
    _i = i
  End Sub
  Sub DoWork()
    _i.N = 1
  End Sub
End Class
Class B
  Implements I
  Property N As Integer Implements I.N
End Class
Class C
  Sub DoSomething()
    REM IS THIS ANTI-PATTERN???
    Dim instanceA = SimpleIoc.Default.GetInstance(Of A)()
    instanceA.DoWork()
  End Sub
End Class
Module M
  Sub Main()
    SimpleIoc.Default.Register(Of A)()
    SimpleIoc.Default.Register(Of I, B)()
    Dim c As New C
    c.DoSomething()
  End Sub
End Module
```

When I need to use an instance of A in class C, is it an anti-pattern to use IoC container as service locator? Is there any other way to autoconstruct an instance of A with the required dependencies?

答:
First off, yes. Using an IoC that way is an anti-pattern. You've got a global variable in disguise there.

It is natural for dependencies to "bubble up" toward the entry point of the program and constructors grow in size. That's just the nature of the beast. However let's step back and ask ourselves a question.

Why do we want DI to begin with?

We want DI so we can easily fake dependencies for easier testing. They're for testing. These huge constructors never need to be called in production code.

You can use an IoC for this, but you don't have to. Ditch it if you want.

I might get creamed for this, but here goes nothing...

I picked this trick up from Working Effectively with Legacy Code by Michael Feathers, but let me be clear that I am kind of abusing the technique in order to shrink the size of the constructors that actually get called in production code.

Most often, the dependencies way up our chain don't change at runtime. They're effectively constant, but we still want the ability to fake those dependencies. Consider the following example. (Excuse my C# please)

```<code>public class Class1
{
    public Class1(Foo foo, Bar bar, Qux qux)
    {
        //...
    }
 }
</code>```

But in reality, our production code always uses the same values for all of our parameters. That's fine. Overload the ctor and create the new instances inside of it. (It's DI blasphemy, I know. Whatever. I don't care. It works.)

```<code>public class Class1
{
    public Class1(Foo foo, Bar bar, Qux qux)
    {
        //....
    }

    public Class1()
        :this(new Foo(), new Bar(), new Qux())
    {
        //...
    }
 }
</code>```

Now your production code calls the parameterless constructor and your tests call the real constructor. Problem solved. No fancy framework needed. Of course, there should be a way to accomplish the same thing with your IoC framework, but without knowing the details of what you're using, I can't say how. Unfortunately, VB.Net doesn't get the same love when it comes to frameworks as C#. Regardless, I thought you should see the "quick and dirty" way to do this. You can always switch to an IoC container later when your projects is of sufficient complexity to warrant it.

Body:
First off, yes. Using an IoC that way is an anti-pattern. You've got a global variable in disguise there.

It is natural for dependencies to "bubble up" toward the entry point of the program and constructors grow in size. That's just the nature of the beast. However let's step back and ask ourselves a question.

Why do we want DI to begin with?

We want DI so we can easily fake dependencies for easier testing. They're for testing. These huge constructors never need to be called in production code.

You can use an IoC for this, but you don't have to. Ditch it if you want.

I might get creamed for this, but here goes nothing...

I picked this trick up from Working Effectively with Legacy Code by Michael Feathers, but let me be clear that I am kind of abusing the technique in order to shrink the size of the constructors that actually get called in production code.

Most often, the dependencies way up our chain don't change at runtime. They're effectively constant, but we still want the ability to fake those dependencies. Consider the following example. (Excuse my C# please)

public class Class1
{
    public Class1(Foo foo, Bar bar, Qux qux)
    {
        //...
    }
 }

But in reality, our production code always uses the same values for all of our parameters. That's fine. Overload the ctor and create the new instances inside of it. (It's DI blasphemy, I know. Whatever. I don't care. It works.)

public class Class1
{
    public Class1(Foo foo, Bar bar, Qux qux)
    {
        //....
    }

    public Class1()
        :this(new Foo(), new Bar(), new Qux())
    {
        //...
    }
 }

Now your production code calls the parameterless constructor and your tests call the real constructor. Problem solved. No fancy framework needed. Of course, there should be a way to accomplish the same thing with your IoC framework, but without knowing the details of what you're using, I can't say how. Unfortunately, VB.Net doesn't get the same love when it comes to frameworks as C#. Regardless, I thought you should see the "quick and dirty" way to do this. You can always switch to an IoC container later when your projects is of sufficient complexity to warrant it.


答:
I think the issue may arise from the assumption that the only valid tests are those which meet the open/closed test.

It is easy to see that the only testing that should matter is that which tests the interface.  However, in reality, it is often more effective to test that interface by testing the inner workings.

For example, it is nearly impossible to test any negative requirement, such as "the implementation shall not throw any exceptions."  Consider a map interface being implemented with a hashmap.  You want to be certain that the hashmap meets the map interface, without throwing, even when it has to rehash things (which could get dicey).  You could test every combination of inputs to make sure they meet the interface requirements, but that could take longer than the heat death of the universe.  Instead, you break the encapsulation a bit, and develop mocks that interact more tightly, forcing the hashmap to do exactly the rehash needed to ensure the rehashing algorithm doesn't throw.

Tl/Dr: doing it "by the book" is nice, but when push comes to shove, having a product on your boss's desk by Friday is more useful than a by-the-book test suite which takes until the heat death of the universe to confirm conformance.


答:
I do not see why mocks would violate the open/closed principle.  If you could explain to us why you think they might, then we may be able to alleviate your concerns.

The only disadvantage of stubs that I can think of is that they  generally require more work to write than mocks, since each one of them is actually an alternative implementation of a dependent interface, so it generally has to provide a complete (or convincingly complete) implementation of the dependent interface.  To give you an extreme example, if your subsystem under test invokes an RDBMS, then a mock of the RDBMS would simply respond to specific queries known to be issued by the subsystem under test, yielding predetermined sets of test data.  On the other hand, an alternative implementation would be a full-blown in-memory RDBMS, possibly with the extra burden of having to emulate the quirks of the actual client-server RDBMS that you are using on production.  (Luckily, we have things like HSQLDB, so we can actually kind of do that, but still, it is a bit messy, especially since it mostly sticks to the SQL standard and does not bother emulating anyone's quirks.)

Good use cases for mocking are when the dependent interface is too complicated to write an alternative implementation for it, or if you are sure you will only write the mock once and never touch it again.  In these cases, go ahead and use a quick and dirty mock. Consequently, good use cases for stubs (alternative implementations) is pretty much everything else. Especially if you foresee engaging in a long-term relationship with the subsystem under test, definitely go with an alternative implementation which will be nice and clean, and will require maintenance only in the event that the interface changes, instead of requiring maintenance whenever the interface changes and whenever the implementation of the subsystem under test changes.

P.S. The person you are referring to could have been me, in one of my other testing-related answers here on programmers.stackexchange.com, for example this one.


问:
Linking kernel voids without CPU parse (Compute shaders)
Is it possible to parse data between compute shader voids without having to create a new buffer and cpu link (Using unity with C# interface).

For example I have a kernel with position data on a set of vector arrays.
I then want to adjust those positions after that kernel has sent them to my shader and rendered.

Edit:
Temporary solution:
Combined all data types to one int and dispatch to one kernal - this is an issue however , as I can't run efficient thread distribution - currently running 512 (1D).

答:
After a bit more research and gaining a greater understanding of GPU architecture (it really helps if you have an electronic/microprocessor studies background here).

Simple answer no: you cannot parse between kernals without CPU managment , which causes bottlenecking...and defeats the purpose of GPU calculations.

However you can run functions external to the main Kernal function as long they return a valid HLSL data type (so no GPU localised structs - use CGING file for that one.)

So thanks again stack exchange for pointing in the right direction : Alcohol.

E.g:
http://www.reedbeta.com/blog/2013/01/12/quick-and-easy-gpu-random-numbers-in-d3d11/


问:
Simplifying Some Probabilistic If-Then Spaghetti Code
I've got a fairly substantial code base that I'm trying to simplify. One section in particular deals with probabilistically creating objects. It currently uses hundreds of random number generator calls in if-then statements to achieve the desired result.

Example:

```<code>if rand(20) >= 2 then
    //Make Object A
if rand(20) >= 5 then
    //Make Object A
if rand(20) >= 14 then
    //Make Object A
if rand(20) >= 18 then
    //Make Object A

if rand(100) >= 25 then
    if rand(10) < 8 then
        //Make Object B
    elseif rand(10) < 8 then
        //Make Object C
    else
        //Make Object D
</code>```

My first idea is to use some kind of weighted statistical distribution to choose how many objects I need to make. However, I don't actually know if that would be an improvement in readability and maintainability. I probably wouldn't even know how to begin doing that with some of the bigger nested if-then trees, either.

The if-then trees fall into a few broad categories:

Make 0 to n of the same object

Make a single object, picked from several choices.

The above two combined (make 0 to n objects, with each one chosen from several possibilities)

Are there any easier ways that I can simplify code like this?

I just need to approximate the behavior in an easily readable and editable form.

答:
When I was faced with something like this a while back my solution:

All this information was stored as an external text file, loaded at program startup.  It was a collection of tables (all the symbolic resolution was done upon loading, no searching when it was called) with a list of the odds of that entry and either a list of entries or a pointer to another table.  Having everything in a human-editable text file made life much easier.  The loader also summed all the probabilities, if you extended a table in the future you didn't have to try to rebalance everything in a table to make it total to the same total (like your rand(20)).


问:
On Android and IOS does javascript run on inactive browser tabs?
In the design of a javascript based web app I was concerned if my app would run on inactive windows on Android and IOS since is basically a webapp wrapped by a native app.

Does anyone know how these two Operating Systems Manage running javascript on inactive tabs?

答:
For Windows Phone: tabs that are in the background are not given access to resources - so Javascript will not be running.

For android: The default browser does not allow this, but it is possible to install different browsers - so I can not say that this goes for every browser that you can install on the system. (I read that Opera does actually keep Javascript going on the background!) (EDIT: Chrome on android can play audio in the background since 2013). If I am not mistaken - your web-app could get put in the 'On-Pause' state and that would be why your javascript stops running. For more information on the android lifecycle, check out this graph: http://developer.android.com/images/activity_lifecycle.png)

iOS: Well it allows audio to be played from a web-app that does not have focus anymore.As for other events - I'm not sure and I do not have an iOS device at my disposal to test this right now - so someone else might want to correct me on this.

(EDIT: These things change every now and then of course - android especially has lots of different versions and the last I developed for was about a year ago - and it was a project  that ran on a version of almost three years ago.. WP I'm pretty confident about since I'm a WP user - and iOS should really be verified by someone else!)


答:
First things first, I would get a handle on the probabilities of any event occurring.  Get out a pen and paper, we'll do this by hand.

Make everything independent when you can.  For example, when you see the series of if's at the start:

```<code>if rand(20) >= 2 then
    //Make Object A
if rand(20) >= 5 then
    //Make another Object A
if rand(20) >= 14 then
    //Make a third Object A
if rand(20) >= 18 then
    //Make one last Object A
</code>```

We should recognize that these are 4 independent draws. Under each one, we have two possibilities: created an object A, or "did nothing."  Assign each a probability using ratios, so the first if statement's probability of making an object is 2/20.

Other sections will not allow you to treat them as independent draws because of the 'elseif' patterns.

```<code>if rand(100) >= 25 then
    if rand(10) < 8 then
        //Make Object B
    elseif rand(10) < 8 then
        //Make Object C
    else
        //Make Object D
</code>```

will require a tree to describe the probabilities

```<code>           X
          / \
p=25/100 /   \ p=75/100
   Do nothing X
             / \
   p=8/10   /   \  p=2/10
        Make B   X
                / \
        p=8/10 /   \ p=2/10
           Make C Make D
</code>```

Now so far this is just trying to get a handle on what has been written.  The next step is to try to simplify it.  The idea is that you can shuffle the rolls around, so long as the probabilities are the same.  For example, just with some multiplication I can see the probabilities of creating a B C or D.

```<code>           X
          / \
p=25/100 /   \ p=75/100
   Do nothing X
   (p=.25)   / \
   p=8/10   /   \  p=2/10
        Make B   X
  (p=.75*.8=.6) / \
        p=8/10 /   \ p=2/10
           Make C Make D
(p=.75*.2*.8=.12)  (p=.75*.2*.2=.03)
</code>```

Now, from looking at all of these probabilities, they can all be expressed as a rational ratio with 100 on the bottom  (.12 = 12/100; .03 = 3/100).  Accordingly, we can handle all of this with a single roll, which makes the logic a whole ton simpler.

```<code>roll = rand(100) -- a random roll from [0,100) is sufficient for the whole block
if roll < 60 then -- we'll hit this with a probability of .6
    // make object B
elseif roll < 72 then -- 72-60 = 12, so we'll hit this with a probability of .12
    // make object C
elseif roll < 75 -- 75-72 = 3, so we'll hit this with a probability of .03
    // make object D
else -- 100-75=25, so we'll hit this with a probability of .25
    -- do nothing.  This is the equivalent of not entering the
    -- outermost if statement, with a probability of .25.
end
</code>```

The other pattern I see here is that there are many independent draws which all create the same object.  You're right: it would be nice to simplify these.  You can use a joint probability table to join them.  For example, we can take the first two "make object A" cases.

```<code>                   Nothing(p=.3)              Make A (p=.7)  <-- second if
v--- first 'if'  +-------------------------+--------------------------+
Nothing(p=.15)   | Nothing (p=.3*.15=.045) | Make A (p=.7*.15=.105)   |
                 +-------------------------+--------------------------+
Make A (p=.85)   | Make A (p=.3*.85=.255)  | Make 2x A (p=.7*.85=.595 |
                 +-------------------------+--------------------------+
</code>```

You can apply this process as many times as you like, until you get a table containing the probability of getting 1A, 2A, 3A, or 4A.

When you are done with all of this, what you should see is a small number of draws, followed by a lookup from a few tables to determine the outcome based on those draws.  That should be enough to get a firm grasp on the probability spaghetti code.

From there, you could use some functional programming to make this cleaner.  You could build a table object which looks up a draw, and returns a function which will do the correct task for that slot in the table.  This has the advantage of being a very standard way to do probabilistic outcomes, so any future developer who looks at it will immediately recognize the random draw table and be comfortable with it.

Title: Simplifying Some Probabilistic If-Then Spaghetti Code

Body:
I've got a fairly substantial code base that I'm trying to simplify. One section in particular deals with probabilistically creating objects. It currently uses hundreds of random number generator calls in if-then statements to achieve the desired result.

Example:

```<code>if rand(20) >= 2 then
    //Make Object A
if rand(20) >= 5 then
    //Make Object A
if rand(20) >= 14 then
    //Make Object A
if rand(20) >= 18 then
    //Make Object A

if rand(100) >= 25 then
    if rand(10) < 8 then
        //Make Object B
    elseif rand(10) < 8 then
        //Make Object C
    else
        //Make Object D
</code>```

My first idea is to use some kind of weighted statistical distribution to choose how many objects I need to make. However, I don't actually know if that would be an improvement in readability and maintainability. I probably wouldn't even know how to begin doing that with some of the bigger nested if-then trees, either.

The if-then trees fall into a few broad categories:

Make 0 to n of the same object

Make a single object, picked from several choices.

The above two combined (make 0 to n objects, with each one chosen from several possibilities)

Are there any easier ways that I can simplify code like this?

I just need to approximate the behavior in an easily readable and editable form.

Body:
First things first, I would get a handle on the probabilities of any event occurring.  Get out a pen and paper, we'll do this by hand.

Make everything independent when you can.  For example, when you see the series of if's at the start:

if rand(20) >= 2 then
    //Make Object A
if rand(20) >= 5 then
    //Make another Object A
if rand(20) >= 14 then
    //Make a third Object A
if rand(20) >= 18 then
    //Make one last Object A

We should recognize that these are 4 independent draws. Under each one, we have two possibilities: created an object A, or "did nothing."  Assign each a probability using ratios, so the first if statement's probability of making an object is 2/20.

Other sections will not allow you to treat them as independent draws because of the 'elseif' patterns.

if rand(100) >= 25 then
    if rand(10) < 8 then
        //Make Object B
    elseif rand(10) < 8 then
        //Make Object C
    else
        //Make Object D

will require a tree to describe the probabilities

           X
          / \
p=25/100 /   \ p=75/100
   Do nothing X
             / \
   p=8/10   /   \  p=2/10
        Make B   X
                / \
        p=8/10 /   \ p=2/10
           Make C Make D

Now so far this is just trying to get a handle on what has been written.  The next step is to try to simplify it.  The idea is that you can shuffle the rolls around, so long as the probabilities are the same.  For example, just with some multiplication I can see the probabilities of creating a B C or D.

           X
          / \
p=25/100 /   \ p=75/100
   Do nothing X
   (p=.25)   / \
   p=8/10   /   \  p=2/10
        Make B   X
  (p=.75*.8=.6) / \
        p=8/10 /   \ p=2/10
           Make C Make D
(p=.75*.2*.8=.12)  (p=.75*.2*.2=.03)

Now, from looking at all of these probabilities, they can all be expressed as a rational ratio with 100 on the bottom  (.12 = 12/100; .03 = 3/100).  Accordingly, we can handle all of this with a single roll, which makes the logic a whole ton simpler.

roll = rand(100) -- a random roll from [0,100) is sufficient for the whole block
if roll < 60 then -- we'll hit this with a probability of .6
    // make object B
elseif roll < 72 then -- 72-60 = 12, so we'll hit this with a probability of .12
    // make object C
elseif roll < 75 -- 75-72 = 3, so we'll hit this with a probability of .03
    // make object D
else -- 100-75=25, so we'll hit this with a probability of .25
    -- do nothing.  This is the equivalent of not entering the
    -- outermost if statement, with a probability of .25.
end

The other pattern I see here is that there are many independent draws which all create the same object.  You're right: it would be nice to simplify these.  You can use a joint probability table to join them.  For example, we can take the first two "make object A" cases.

                   Nothing(p=.3)              Make A (p=.7)  <-- second if
v--- first 'if'  +-------------------------+--------------------------+
Nothing(p=.15)   | Nothing (p=.3*.15=.045) | Make A (p=.7*.15=.105)   |
                 +-------------------------+--------------------------+
Make A (p=.85)   | Make A (p=.3*.85=.255)  | Make 2x A (p=.7*.85=.595 |
                 +-------------------------+--------------------------+

You can apply this process as many times as you like, until you get a table containing the probability of getting 1A, 2A, 3A, or 4A.

When you are done with all of this, what you should see is a small number of draws, followed by a lookup from a few tables to determine the outcome based on those draws.  That should be enough to get a firm grasp on the probability spaghetti code.

From there, you could use some functional programming to make this cleaner.  You could build a table object which looks up a draw, and returns a function which will do the correct task for that slot in the table.  This has the advantage of being a very standard way to do probabilistic outcomes, so any future developer who looks at it will immediately recognize the random draw table and be comfortable with it.


问:
Demonstrate or Report a project to Client while freelancing
I have started freelancing for couple of weeks and have done few projects.

While doing it I found myself in risky situation when client ask progress and also want to see it done. which means I have to send them what work I done to the date. So they can know their project is on progress and will be completed on time.

But on the other end If I send them almost done project and if they think they don't need my help they could just leave the project without paying.

One thing I have been thinking is to ask for small Milestone payment before every regular progress. (What if they want update everyday?)

It is possible to have bug while project is on progress and they might refuse to pay subsequent milestone.

So..

How do you report and demonstrate project without risk of losing code (work done) before you are paid? (In situation where you are freelancing and client is at remote location)

答:
First of all I would recommend doing either up front payments (for small amounts, which I define < $1000) or milestone payments with clearly defined milestone, so you aren't worried about being paid and they aren't worried about you walking off with the money without doing any work.

Now it depends on what you are working on as to how to keep the client up to date.

Often it is good enough to send an email saying I've finished X and Y and have started on Z.

If you are doing a web project you can have a test server that has the latest progress running that they can look at.

You can also use something like Trello which gives them a visual on the tasks/features that you have done, are currently working on, and still pending.

Clear communication is necessary right from the word go. Agree on exactly what you will be delivering and when, and have it in writing. They will change their minds. That's natural, and as good customer service you should change what you are delivering to meet their needs, but the agreement will give you the leverage to actually get paid for what you have done, rather than having them say I didn't ask for that I'm not paying. This also requires you to be reliable and deliver things when you say you are going to. And as soon as you think you won't make that deadline, you need to say something and make them aware of the fact that it is taking longer than expected.


问:
OOP Principles in Customer and Account classes of a Bank
I am designing a Bank Application which deals with Customers having FD Accounts.

There are two approaches to this :

Approach 1

In this the customer has a list of accounts. The bank application will manage the accounts through the customers.

My mentor feels this is the correct approach. :-P

```<code>class Customer
{
     String name;
     Date   dob;
     .
     .

     Account[] accounts = new Account[5];
}

class Account
{
     int   accNo;
     float amount;
     .
     .
}
</code>```

Approach 2

In this approach each account has its associated customer reference stored. The Bank application will now manage the accounts and customers independently.

I feel this is the correct approach. :-)

```<code>class Customer
{
     String name;
     Date   dob;
     .
     .
}

class Account
{
     Customer customer;
     int   accNo;
     float amount;
     .
     .
}
</code>```

Now my issues are :

Ideally the bank application should worry more about the account than the customer. For example, the bank should have methods like
addAccount() : which will add account and create a customer implicitly if it is the first account of the customer and
deleteAccount() : which will delete the account and delete the customer implicitly if it is the last account.

There can be a use case in the future where an account can have multiple customers. So that can be accommodated easily in the second approach than the first.

Considering all this, please can you say which is a better Object Oriented Approach here?

Also how is this actually implemented in a real Bank?

答:
Oh Dear.

Your design is how bank applications were designed in the 1970s. Myself and several thousand professionals have spent decades undoing this design error to get systems looking more like option 1.

Banks deal with customers the account is just a mechanism for dealing with some of the customers money.

More importantly the stack of regulators who weigh down on any financial business are very interested in customers. They want to know about all the assets and liabilities of any individual or business; not the state of an single account. Failing to report all the accounts held by an individual, or, having more than one customer record for the same person, could get you fined or eventually lead to the loss of your banking licence.

As will deleting the customers data when an account is closed! You need to retain everything for several years.


问:
What prevents others from commerciallly redistributing open source software as-is?
Most, if not all, open source software licenses allow others to obtain a copy of the source code, edit, and redistribute both source and built versions of the software, edited or not. Also, more often than not, that includes commercial redistribution.

My question is: is there anything legally preventing someone, besides the original author, from simply taking the software and selling it as-is? or is it only disparaged by the fact that a free copy is available elsewhere? I just want to allow others to freely use and edit my software, even if it's for commercial use, but I don't want others selling exactly what I made.

Obviously there are other licenses like CC-NC and it's variants, but those generally are not used for software, and aren't open source due to the restrictions they place.

For example, if I wrote an open source Android game under the MIT license and some studio decides to put the game on the Play Store, without modification or my permission, and manage to sell thousands of copies, could I challenge them in court via some clause in the license I used or copyright law in general, and win?

答:
For example, if I wrote an open source Android game under the MIT license and some studio decides to put the game on the Play Store, without modification or my permission, and manage to sell thousands of copies, could I challenge them in court via some clause in the license I used or copyright law in general, and win?

No, you could not. By licensing it to them under the MIT license, you explicitly gave them permission to do this.

However, they are unlikely to be very successful with this, because you (and anyone else) could also put up the game for free. The free version(s) would compete with their identical paid version(s). Consumers have little reason to pay for something when they can also get it for free.

I just want to allow others to freely use and edit my software, even if it's for commercial use, but I don't want others selling exactly what I made.

Then you should not use an open source license, because selling for profit is one of the essential freedoms any open source license guarantees.

When you ask a lawyer to draft your license conditions (always let a lawyer write legal documents - laymen are not qualified for this), the question you need to answer is where exactly you draw the line how much someone needs to edit to be allowed to sell it. You don't want me to sell exactly what you did? So I change a single byte and now I can sell it? Do you want to decide on a case-by-case basis if a modification is different enough? Then you should not have a public license but instead negotiate a contract with every licensee individually.

Also, why exactly are you against people selling your unchanged work? You give it away for free, so you have no financial losses at all when someone decides to give someone money for a copy. So why exactly does this thought leave a bad aftertaste for you? Answering this question for yourself will also hold the key to what to tell your lawyer to write into your license conditions.


问:
Single import in a large file vs. multiple imports in smaller files. [Golang]
I'm sure the folks at Google worked long and hard to ensure the programmer wouldn't have to worry about details like this, but I'm curious.

In Go if I have multiple files in the same package, but they all import the same file, is this more or less efficient for the compiler than one large file with a single import? Or does it not matter in the slightest?

答:
It doesn't matter.

Parting a package into multiple source files is something for you, to organize your code better. But to the Go compiler it doesn't matter. If you have an unexported identifier in one source file, you can use that in the other source file (same package of course) without any notice (like import). What matters is that your package will have a dependency on the other package.

Note that it affects compilation efficiency in the slightest way: the compiler will have to process multiple files, create multiple internal data structures (required only for compilation), process the same sections (e.g. import) multiple times. But this should never affect your judgement to choose 1 file over multiple. Just some self made-up numbers to help understanding it: does it matter if your package with 1 source file compiles in 100 ms or it takes 100.1 ms if it is broken into 5 files? No, obviously.

Going further, compilation time should also not be a factor even if it is much bigger (like 1 sec vs 2 sec). Compilation time and run time efficiency are 2 different things, the latter is what should concern you.


问:
Program like NASA?: Margaret Hamilton's Three Primitive Control Structures
On slide 19 in a presentation Margaret Hamilton describes three primitive control structures. My goal is to reduce the probability of errors in my code by working with this "design framework". I am wondering if someone could explain to me how these structures work. Perhaps someone could point me to a simple implemented example in code.</p>

答:
Looking at the slide, its less a system of functions that returns multiple outputs and more a message passing system. If you write an object that can receive and return messages, it can return multiple outputs by simply returning multiple messages. In their case though, the messages that are returned are ordered, unlike most message-passing systems that are asynchronous, and the systems are built up in a strict tree structure. IT reminds me of a scenegraph.

Go look at message bus architectures for more information.


问:
How can variables be created at runtime?
Is it possible to define variables dynamically?

Last night I was writing some code (C and VB2010) and I ran into a problem related to defining variables in my program. The variables needed depend on the number of entries added by the user and the number of users. Even using dynamic memory allocation we have a size limit, but I wonder about this type of thing sometimes. We can define as many variables as we need (to a limit of course) when writing the code, but can't we define more at runtime?

For example: say your whole program is done and when user says 'x', this cannot be created as variable; rather we require a variable to store that x. Why cant we make x a variable at runtime? Can't we build a bridge between compile-time and runtime with some rules?

答:
It looks you are thinking of an interpreter. Then use classical techniques: write a parser which builds an abstract syntax tree then evaluates that AST in some environment (some map binding variables to values).

The variables in your interpreted language are not related to the variables of your interpreter code.

Read also about homoiconic languages

Better yet, dont write your own interpreter, but embed an existing one like GNU guile or Lua.

BTW you could generate C code at runtime, then compile it and dynamically load it (e.g. with dlopen on POSIX) as a plugin, see this & that