问:
Avoiding lot of roles implementation in same object

Motivation

Let a project where...

... exists a lot different behaviors. For each behavior, there is an interface which has its possible actions. One object could perform a lot different behaviors.

Normally, a collaborator "A" only cares about interface "I" from a specific object.

So, how to avoid a object to implements lot of roles.

Example:

```<code>public class MyComplexObject implements Closeable, Reliable, Trustable, Treable, Moveable { ...}
</code>```

Why bother?

Composition solves the problem. But only partially. In Java, the target object will still have to delegate the problem calls for the target implementation. Although it is no-brain implementation, it is not comfortable when the list of roles is more than 5.

Inheritance (over interfaces) will not turn things better.

Let's assume 6 different interfaces (each interface with 5 methods). For now, let us simplify and imagine a default implementation for those interfaces. Now, assume that a set of more complex objects could implement one to six of those interfaces. It means 2^6= 64 different possible combinations. Also, long list of interface means a long list of internal methods.

It is clear that inheritance, using a BaseImplementation, does not make sense in this case.

Examples:

```<code>public class MyComplexObject1 implements Closeable, Reliable, Trustable, Treable, Moveable { ...}
public class MyComplexObject2 implements Reliable, Treable, Moveable { ...}
public class MyComplexObject3 implements Reliable, Trustable, Moveable { ...}
public class MyComplexObject4 implements Closeable, Trustable, Treable { ...}
</code>```

I am not asking for a silver bullet

"Being skeptical", "avoiding complexity" of course, those thing are good. However, too general. This problem is when long list of roles hurts. So this is a corner case scenario and not a mainstream problem.

What does not mean unrealistic scenario. There is a project that use an idea that could be used to solve that problem.

Netbeans, that has the concept of cookies

```<code>EditorCookie ec = activatedNodes[0].getLookup().lookup(EditorCookie.class);
</code>```

A cookie is a capability and cookies are a powerful feature of NetBeans. With a Java interface, your object's capabilities are fixed at compile time, while NetBeans cookies allow your object to behave dynamically because your object can expose capabilities, or not, based on its state.

https://platform.netbeans.org/tutorials/60/nbm-porting-basic.html

How cookies-like could be implemented

```<code>public class MyComplexObject {
    private Map<Class<?>, ?> adapters;

    public <T> T getAdapterIfApplicable(Class<T> t){
       return (T) adapters.get(t);
    }
    public MyComplexObject add(Class<T> aClass, T t){
       adapters(aClass, t);
       t.setTarget(this);
    }
...
}
...
public CloseableAdapter implements Adapter{
    void setTarget(Object target){
        this.target = target;
    }
}
...
new MyComplexObject().add(CloseableAdapter.class, aCloseAdapter);
</code>```

答:
It appears from the comments and edits that your concern is more about duplicating code in multiple implementation classes. That has nothing to do with how many interfaces are implemented.

Composite Pattern with Delegation

If the implementations of each interface is generic then they should be classes that are delegated to using the Composite Pattern. The adapter pattern is not the solution either way.

If A implements C then A is a C. To burden the calling code with this obfuscation of Adapter Pattern is a terrible API decision.

The question you are asking is not the correct one:

... how to avoid a object to implements a long list of interfaces.

I think you are seeing a problem that only exists to you. I have worked on hundreds of millions of lines of Java code since 1995. I have never seen the problem you seem to be concerned about.

The number of combinations of interfaces is not a practical issue. Never has been. If you have too many interfaces with to many methods then that is a design problem that needs to be fixed, your solution is not that fix.

You are adding a ridiculous amount of complexity for no apparent benefit:

implements means what is implementing that interface is a relationship, that is pretty tightly coupled and introducing Adapter pattern type indirection is going to bloat the codebase with more complexity and code to maintain and test, which is a good enough reason to not do that.

If this was a good approach it would have been done half a dozen times as an opensource library the 20 years that Java has been around.

This Adapter Pattern you are trying to use is not the correct approach, it will create a heavy burdensome API and be extremely brittle.

The work to use the API will be orders of magnitude more effort than maintaining naively duplicated code.


问:
Where to store configurable, global settings
As an example, let us say that I have an application with multiple users and multiple administrators.  I want the administrators to be able to configure sitewide session timeouts.  The code would check the settings for what the configured timeout is,and implement accordingly.

Is the ConfigurationManager class appropriate for this, or is there something else?  From what I read, I would need to use User rather than Application settings, because Application settings are readonly.  However, I dont want the ability for multiple user settings - just one settings.

EDIT: This is one single web application.

答:
ConfigurationManager is used to access the hierarchy of '.config' (machine, app and user) available to .NET applications. Modifying some values in some of these files may require some form of service restart, pool recycle or even a machine restart to get picked up.

Assuming you've already got code in place that can set the values you want, it sounds like you simply need to store this information wherever you store other data (your database for example) and simply have an administrator only page to modify the values.

ContentLicense: CC BY-SA 3.0


问:
Should I use a source-to-source or a traditional compiler in order to develop my own Programming Language?
I'm really interested in writing my own general-purpose high-level programming language, but I'm somewhat confused.

I know that Python and Ruby were written in C, which makes me wonder that if I want to write my 'own Python', is it preferable to use a source-to-source compiler in order to translate all the source code of my language to C, or should I target assembly language?

The point is, I know that I need to dig in Compiler Design and understand Lexical Analysis, and the whole process of parsing the code and generating tokens and an intermediate language and checking for syntax and semantic errors and then generating output code.

However, since I'm not an expert in low level / assembly programming, should I use a source-to-source compiler? What challenges might I face if I attempt to compile my language to assembly? What drawbacks might there be in using a source-to-source compiler? What domain specific facets of my situation should I consider when making this decision?

答:
I am going to focus on your core question, since other stuff has been answered elsewhere.

Should you target a higher level language or assembly?

Getting software done is hard. While making a new language can be pretty easy, you need to stick to simple stuff and avoid the stuff that is a pain to implement. Making your first language has the problem that you don't know what the "pain to implement" stuff is. And let's face it, you're not aiming making a new language that can only implement console based calculators - the interesting stuff is going to be non-trivial to implement.

So do yourself a favor and target a language that you already know. Making a new language and a functional compiler is hard enough without adding "learn assembly" to the list of tasks. By setting yourself up for success, you're more likely to have fun and learn from the endeavor.


问:
What is the value of encoders with decoders currently present
Can you tell me the value of using PHP encoder (ioncube, phpshield) with currently present service like decry.pt (http://www.decry.pt/) that can easily decode source codes.

I have tried decry.pt's free demo. Just drag & drop an encoded source and it will return the decoded one. It is so easy.

It seems the value of encoder can be easily be canceled.

答:
First, be aware that no software can ever be 100% protected from reverse engineering and decompilation, and sites such as the one you mention just illustrate this. They also illustrate that recreating code is hard to do because they tend not to work that well on applications as a whole if using all protection options that systems tend to provide, but regardless, providers of encoding systems should be evolving their technologies over time to move ahead of any progress that hackers have made. It's good practice to ensure that you're using the latest version of any protection tool when making a new major release.

You mentioned value, and in determining potential value of any DRM system, you need first to understand where your risks to revenue lie.  For example, are you seeking and likely to get most value by preventing someone who has no intention of purchasing getting a stolen copy of your application (or might doing so actually hurt revenue long term?), or is there more value from preventing the scenario of someone who is basically honest and happy to have paid to use code on one server, but who is now using it on several more without paying any extra when they tried it and found that it works because you did nothing to enforce a licensing policy? If we go for the latter and let's say your paying customer is a company, is that company paying hackers to try and break an application in order to work around a license going to make sense and be a smart business decision for them, or is it a business risk? Given that the results of breaking code are likely to be buggy, there will be no updates available and original bug fixes from the application providers, and there's a risk of legal action and loss of trust and therefore sales when publically exposed as crooks by the application provider or a bitter ex-employee, the smart choice is to be honest and lock in the benefits that doing so gives. Whilst there will be some exceptions to this, provided that an application is sensibly priced and is provided by a responsible company, in general end users shouldn't be interested in trying to "break" it even if they could.

So for many, that's essentially the answer here, with the biggest risk realistically not from hacker sites but in poor revenue protection from lack of licensing. What you must do as the application provider is ensure that you have a license policy that makes sound business sense and that you do something to enforce it, be it DRM or something else, otherwise you cannot complain when you lose revenue as a result.

Disclosure: I am associated with ionCube and ionCube 24.


答:
You should consider compiling to C (see this and that answers), or to some other languages (Java, Common Lisp, Ocaml, C++, or even a mix of Javascript & C - like HOP does... Notice that RefPerSys is generating C++ code, or in 2022 C code here). You could also compile to the textual representation of LLVM bytecode, or use the LLVM library as your backend, or (if having GCC 5 or better) use the libgccjit (to target GCC internal representations and profit from GCC optimizations). You could also choose some existing bytecode (e.g. JVM, Ocaml, Neko, Parrot, ...) and compile to it. And you might also use some JIT library like libjit, GNU lightning, asmjit etc...

Lexing & parsing are not the main work of a compiler or an interpreter. They are the simple parts. A compiler is mostly transforming (very often in several passes) some internal representations (in particular Abstract Syntax Trees, but not only them) of the source code that it is compiling. An interpreter is often transforming some internal representations, then traversing others (e.g. some bytecode, or some normalized AST). Play with GCC's -fdump-tree-all option, and perhaps with MELT (a Lisp-like DSL to inspect and/or transform GCC internal representations). The semantics of your programming language matters more than syntax.

An important part is memory management. Do you want a garbage collector (it is a core part of your semantics)? What about typing (static or dynamic) & type inference? Do you handle tail-calls? Do you want homoiconicity? metaprogramming? Do you want closures (they most often need a GC)? Consider Boehm's conservative GC, and/or read the GC handbook.

Bootstrapping compilers is important. See also this and the references I gave there. Read also this & that answers explaining technical & practical details (and should heal your headache about "Haskell written in Haskell", "Ocaml written in Ocaml", "MELT written in MELT", "CAIA written in CAIA", "GCC or Clang/LLVM written in C++").

Also, if you know none of them, play with Ocaml, or Common Lisp, or Haskell, or Scheme (see also SICP). Read Scott's book on Programming Language Pragmatics and Queinnec's book on Lisp In Small Pieces and Pitrat's book Artificial Beings, the conscience of a conscious machine (and blog here).

Be sure to make your language implementation some free software (on http://github.com/ you'll find many other language implementations - e.g. compilers or interpreters).

Title: Should I use a source-to-source or a traditional compiler in order to develop my own Programming Language?

Body:
I'm really interested in writing my own general-purpose high-level programming language, but I'm somewhat confused.

I know that Python and Ruby were written in C, which makes me wonder that if I want to write my 'own Python', is it preferable to use a source-to-source compiler in order to translate all the source code of my language to C, or should I target assembly language?

The point is, I know that I need to dig in Compiler Design and understand Lexical Analysis, and the whole process of parsing the code and generating tokens and an intermediate language and checking for syntax and semantic errors and then generating output code.

However, since I'm not an expert in low level / assembly programming, should I use a source-to-source compiler? What challenges might I face if I attempt to compile my language to assembly? What drawbacks might there be in using a source-to-source compiler? What domain specific facets of my situation should I consider when making this decision?

ContentLicense: CC BY-SA 4.0


问:
.NET solution dependency workflow for a small dev team
We have a team of 5 developers working on a product and are at a crossroads trying to determine a better way (if one exists) of managing development workflow and project dependencies.  We currently have two solutions, Core and Client.  Core references 8 projects as dependencies (not via NuGet).  Core is essentially an admin UI and REST API. Client, is a project template that will be replicated every time we have a new instance that needs to be customized. Client references 4 of the same projects that Core does.  Again, both are solutions (.sln's) and both directly reference dependency projects.

For local development, developers currently branch from two separate repos - one for each solution.  The developers' local environment must be set up so that the Client can properly call the REST API locally.  Local dev often requires changes to both Core and Client in order to test new features, etc.

Our issue is that at times our changes do not build on other developers' systems due to differing repo locations on the file system.  This causes issues with the path to projects in the solution files and creates a lot of unnecessary extra work and frustration.

We are considering moving to a NuGet workflow (local, Test, and Prod NuGet servers), but that seems like a lot of extra overhead for the payoff.  Can someone recommend a better solution for local, test, staging, prod development workflow for our small team?

答:
The repo location on the file system should not cause issues with the path to projects in the solution files. The latter should only depend on the locations of the working copies - maybe you mixed that up?

However, if I have to guess what's really going on, the solution to your problem is probably: relocate your projects so all references are relative paths to each other. So it should not matter where they are checked out on the file system as long as their relative location is the same. This must be true for your Core and your Client solution in combination. If you need to have different branches in parallel on a local workstation, have a local "root folder" for each branch, containing always both Core and Client solutions of that branch.


问:
Non-null alternative to Void (Java unit type)
I have a map-like type SmurfMap<K, V> which in certain contexts I use as a set-like SmurfMap<K, Void>.  Implementation details forbid the values of the map from being null, so I cannot actually use Void as a unit type.  Are there any non-null alternatives to Void in the JCL or Guava?

Types considered and not yet rejected:

new singleton enum Unit

Class<Void>

TypeToken<Void>

Object

EDIT SmurfMap<K, V> does not implement java.util.Map.  The datastructure backing a SmurfMap is terabytes to petabytes in size.

答:
Two alternative techniques to consider:

Use a type with the Void generic argument removed.  Instead of a Callable<Void>, use a Runnable.  Instead of a SmurfMap<K, Void>, use (or make) a SmurfSet<K>

Modify the clients to be null-friendly.  For example, I know of no good alternative to Future<Void>.  Guava's Futures.allAsList() returns an unmodifiable wrapped ArrayList, not an ImmutableList, quite possibly in part because a the null-hostile ImmutableList would prevent the method from being called with Future<Void>s.


答:
I did some professional work three years ago that used reflection to understand a .NET interface and provide some CIL glue to mangle it onto a base class.  It was an eye opener to  the level of additional work required.

Most software development, you focus on the success routes and if something unexpected happen you catch an exception. I found that the success route was less than 20% of the work.  The usual strategy of catching exceptions doesn't work, as the exceptions occur at run time, not when you are generating the code.  Instead you have to think of and check for any possible combination that could break your code, and then either support it, or fail the compilation.  This is very different from application development.

If you are wanting to create a new programming language, and want it to be adopted by others, your best bet is to find a problem that cannot currently be easily solved. If you create a new programming language that provides a clean and simple approach to solve a complex problem, then people with that problem have a good reason to adopt your language.


问:
What are standard directory layouts for source code, other libraries, build scripts, etc.?
I'm in the process of proposing a new standard directory layout that will be used across all the projects in our organization.  Projects can have compiled source code, setup scripts, build scripts, third-party libraries, database scripts, resources, web services, web sites, etc.

This is partly inspired by discovering Maven's standard layout.

Are there any other standard layouts that are generally accepted in the industry?

答:
As your question points out, project structures are often the result of the build toolset, and how the developers tools is designed to manage and organise code.  Maven has a strict layout, which enables it to provide a very structured build process. Visual Studio imposes a directory structure for within MVC web projects.  Erlang/OTP/rebar creates a very structured way in which projects are laid out.

Think about the tools you are using and if they imposer constraints on you, and then the needs of the humans on the project to classify and understand the project structure.

Finally, as its a standard it needs to be documented clearly, and most importantly, made easy for your fellow workers to implement.


答:
A classic problem - the simplest resolution is to do what everyone does, treat your Core product as a separate product, similar to how you'd treat an open source project you were reusing in your product.

For example, I use log4net in my product. I don't have a copy of their source, I only take the latest stable dll and use that directly, putting it in a '3rd party libs' directory that I know the location of. You can do this with your Client projects that use the dlls from your Core product.

If you are sharing source code between these projects then you're in a world of nuisance, I would combine the repos together in such a case, or put the shared code in a 3rd repo that both your main projects use. This isn't ideal but can work well - I've done such things with C/C++ projects in the past where a common /include directory was used, by building the dependant project it copies the source into this directory. Visual Studio's C# system isn't so friendly towards source code that is external to the project root though, so I wouldn't recommend this for C# (which is a shame that C# is so 'blunt-scissors' in this regard).

Title: .NET solution dependency workflow for a small dev team

Body:
We have a team of 5 developers working on a product and are at a crossroads trying to determine a better way (if one exists) of managing development workflow and project dependencies.  We currently have two solutions, Core and Client.  Core references 8 projects as dependencies (not via NuGet).  Core is essentially an admin UI and REST API. Client, is a project template that will be replicated every time we have a new instance that needs to be customized. Client references 4 of the same projects that Core does.  Again, both are solutions (.sln's) and both directly reference dependency projects.

For local development, developers currently branch from two separate repos - one for each solution.  The developers' local environment must be set up so that the Client can properly call the REST API locally.  Local dev often requires changes to both Core and Client in order to test new features, etc.

Our issue is that at times our changes do not build on other developers' systems due to differing repo locations on the file system.  This causes issues with the path to projects in the solution files and creates a lot of unnecessary extra work and frustration.

We are considering moving to a NuGet workflow (local, Test, and Prod NuGet servers), but that seems like a lot of extra overhead for the payoff.  Can someone recommend a better solution for local, test, staging, prod development workflow for our small team?


问:
const reference and const pointer. How do they work?
I read a post about how const storage works.

How does const storage work? (Item 2, Scott Myers Effective C++)

This says that each segment has separate section of write protected memory and const data goes there.

But what happens in case of references?
I want to understand three scenarios.

Global const reference.

const reference in method.

const reference in a class.

And for that matter pointers, I mean even though pointer can be stored in some write protected section, then how different versions of consts maintained.

such as

```<code>char x = 'z';
//following can not change the data of x, but ptr itself can change.
const char* ptr = &x;
char y = '9';
ptr = &y;
</code>```

above is allowed but following is not

```<code>char* const ptr1 = &x;
ptr1 = &y;
</code>```

How this is handled?

答:
When using the qualifier const as inthe case below:

```<code> const int value=67;
</code>```

We are telling the compiler that we promise not to change the value of the variable "value". As such the compiler will merely replace instances of "value" with the actual value we initialized it with.since the compiler replaces each instance of the variable with its actual value, we must initialize it.

```<code>  const int k; //error,must be initialized.
</code>```

when bounding such a value to a reference, the reference must have such a qualifier to ensure we do not modify the value bound to through the reference(lvalue reference).

```<code> const int& c1=value;
 c1=56; //error,we cannot modify it through the reference.
</code>```

but we can also bind a non-const value to a const reference...

```<code>int i=89;
const int& ic=i; //const lvalue-ref
int& ir=i;
ir=7; //ok.ir is not const
ic=67990; //error ic is const
</code>```

As for pointers:

```<code> const int val=90;
 int* valp=&val;//error the pointer is not const.
 const int* val2p=&val;//ok as they are both const
 *val2p =788;//error as it is a pointer to non-writable space
</code>```

However, a pointer to a const can be used to point to a non-const object.The idea is that pointers and references to const "think they point to or refer to const objects".

Unlike references, pointers are objects and can be made const. Meaning that a pointer can be made to point to a particular memory and not be allowed to point to another memory once initialized.

```<code> int* const x=&val;//it will point to that memory location only.
</code>```

The fact that "x" is itself a pointer does not say anything about the value it points to.

The other interesting case is the "constexpr" case:

```<code> constexpr int* i=nullptr; //it is the pointer that is const.not the value it points to
 constexpt const int* ii=&value; //both are const in this case.
</code>```

Body:
When using the qualifier const as inthe case below:

 const int value=67;

We are telling the compiler that we promise not to change the value of the variable "value". As such the compiler will merely replace instances of "value" with the actual value we initialized it with.since the compiler replaces each instance of the variable with its actual value, we must initialize it.

  const int k; //error,must be initialized.

when bounding such a value to a reference, the reference must have such a qualifier to ensure we do not modify the value bound to through the reference(lvalue reference).

 const int& c1=value;
 c1=56; //error,we cannot modify it through the reference.

but we can also bind a non-const value to a const reference...

int i=89;
const int& ic=i; //const lvalue-ref
int& ir=i;
ir=7; //ok.ir is not const
ic=67990; //error ic is const

As for pointers:

 const int val=90;
 int* valp=&val;//error the pointer is not const.
 const int* val2p=&val;//ok as they are both const
 *val2p =788;//error as it is a pointer to non-writable space

However, a pointer to a const can be used to point to a non-const object.The idea is that pointers and references to const "think they point to or refer to const objects".

Unlike references, pointers are objects and can be made const. Meaning that a pointer can be made to point to a particular memory and not be allowed to point to another memory once initialized.

 int* const x=&val;//it will point to that memory location only.

The fact that "x" is itself a pointer does not say anything about the value it points to.

The other interesting case is the "constexpr" case:

 constexpr int* i=nullptr; //it is the pointer that is const.not the value it points to
 constexpt const int* ii=&value; //both are const in this case.


问:
Design: Bridge Game
I'm making revisions to a Console version of contract bridge I made in Java. The source can be found here: Bridge

So most of the code is terrible and I've been trying make improvements wherever possible. The game runs but the design is bad.

It currently has three classes:
Card
Deck
BridgeConsole

All the game related code is in BridgeConsole but I've been told it's too long. So I'm considering separating some of the code in there. A GameState (renaming BridgeConsole to Main) class comes to mind but I'm not sure how to implement it. I've seen examples online where they have methods like init(), cleanup(), draw(), etc. but I'm not sure how the to properly implement it in my game. I'm also not sure where the methods I have to run the AI logic would go. Another possibility is instead of using ArrayList to hold the players hand, just create a Hand Class. Also removing all the static methods and variables I have in the BridgeConsole class.

I am looking for some suggestions or tips on good design for this particular project. I'm not satisfied by the being able to run the game, I'd for the code to be better so any help would appreciated.

答:
Despite being a god object, if you always feel that the code you're writing is suitable for the role of BridgeConsole, then the problem is with the name!  Rename it something more specific, and separate the other tasks into their respective classes.  It is easier said than done, so perhaps it would be simply easier to rewrite the class from scratch.  Before you do so, definitely keep a backup somewhere you can refer to!

Remove the class and then begin creating classes to perform the tasks that BridgeConsole did , but focused on the individual tasks.  Some component ideas include:

An EventBus class which only handles notifying listeners of events.  In this way, you can decouple many of the things BridgeConsole does and it would allow you to easily break it down into individual components.

Another trick you can use is to create a class which draws, or is responsible for printing the state onto the screen.  It shouldn't contain any logic other than what is required to show the current state on the screen.

A game state class (probably the most similar to your current BridgeConsole class) that only provides information related to the game state.

If the game state class is too large, consider creating also a Board state class which keeps track of the hands, cards played, this sort of thing.  The game state can instead focus on overall game state (for example, is the game started?  who are the players?  How many points does each player have?  Who won?).

If you've applied all these changes, and you still find yourself with a class that does too much, list out all the things that it does for you, and strongly consider dividing the class into components which perform each individual item in that list, much like you did for BridgeConsole.

And, if you find yourself pulling out your hair, consider simply rewriting the entire program.  It shouldnt' take you as long because you've already written it, plus you have working code to boot.  It would also teach you a valuable lesson on how to structure your code better.  The fact that you realize the problem with BridgeConsole only means you've grown as a developer since you've first made it, so your second attempt should surely fix many of the issues.

I hope that helps.  If you run into any difficulties, please mention them in the comments and I'll try to help.

Title: Design: Bridge Game


问:
Environment-aware Code
There are situations where the deployed environment (development, test, or production, for example) might dictate the outcome of certain actions.

For example, perhaps a successful "user registration" process will send a notification email to the new user.  Environment-specific actions:

Development:  Do not actually send the email.  Email logs will provide enough for developers.

Test:  Send all emails to some testEnvironment@domain.com inbox and not to the user's address.

Production:  Send the email to the user.

I have listed three possible solutions below.

CurrentEnvironment configuration value

One way of solving this, which I have seen a lot, is to have some configuration value (whether it be in some xml config file or in the database) such as CurrentEnvironment which specifies the current environment in which the system is deployed to.  This would require case/if checks in code to determine the desired action:

```<code>if(CurrentEnvironment == Environment.Test)
{
    // Send all emails to some testEnvironment@domain.com inbox.
}
else if(CurrentEnvironment == Environment.Production)
{
    // Send the email to the user.
}
</code>```

This is not a maintainable solution in my opinion.

Wipe all email addresses

Another method is to run a change script, once restoring a database, to do the following:

Remove all user email addresses (in development),

Replace all user email addresses with testEnvironment@domain.com (in test)

This is an extra step in the release process which, if missed, could have some dangerous results.  Additionally, this solution only fixes the email problem.  There are perhaps many other situations where the environment matters.

Config transformation

Another idea is to use web.config transformations.  This way the config can be different for different environments.  For example, we will have the following configs:

```<code> web.config
   web.Development.config
   web.Test.config
   web.Production.config
</code>```

The transformation can then use different "providers" or set certain attributes according to the environment.  For example, an overrideDeliveryAddress can be set in the web.Test.config:

```<code><EmailService>
  <providers>
    <add
      name="EmailServiceProvider"
      type="CustomProviders.EmailServiceProvider, CustomProviders"
      smtp="smtp.domain.com" password="xyz"
      overrideDeliveryAddress="testEnvironment@domain.com"
      enabled="true"
    />
 </providers>
</EmailService>
</code>```

This solution requires much more work, but is more maintainable and less invasive.  Code is now environment-oblivious.

What other ways can the above be achieved?  Should code EVER be environment aware?

答:
Code should not be environment aware, that's why we have configs. Also, you usually do not want to ship your code with development secrets (DB connection string, etc.). Or sometimes it is not desirable to give developers access to the production secrets.

Although it's a typical task in programming, to have separate configurations for different environments, we have no common solutions, tools or processes how to solve it. I prefer config copying or transformation, which you have mentioned.

Title: Environment-aware Code


问:
What are the time and space complexities of this recursive method that reverses a singly linked list?
What are the Time and Space complexities of this Java method that reverses a singly linked list (of length n)?

I'm more interested in knowing the reasoning behind the space complexity. Let me know if you'd like me to provide LinkedListNodeSingly and a convenience applet.

I believe both space and time complexities here are O(n). Time is O(n) since we go to the tail and work backwards through each of the n nodes.  I'm unsure if space is O(n) because even though we create new_head for each frame, we happen to point it to an existing node (starting in the base case) and just pass that up. So, though we create n references, they all point to the same location which holds one value.  So, is space O(1) even in the case where we perform LinkedListNodeSingly new_head = null; and 'return new_head'?

```<code>/**
 * Inspired by: http://www.programmerinterview.com/index.php/data-structures/reverse-a-linked-list/
 *
 * Time: O(n), at least I think so, since it is recursive, going through each node once for list of size n
 * Space: O(1), if we don't use a return val, but since we do, each frame would create new_head once, for O(n)
 */
public static LinkedListNodeSingly reverseUsingRecursion(LinkedListNodeSingly node) {
    if(node == null)
        return null;

    LinkedListNodeSingly new_head = null;

    //base case, where we swap the head (very first node) with the tail (very last node)
    if(node.next == null) {
        new_head = node; //node is tail here
        return new_head; //don't need a return overall, really
    }

    //don't need a return overall, really
    new_head = reverseUsingRecursion(node.next);

    /* This next line is key.  It is better understood with an example.
     * For list 1 2 3 4, we refer to each node by the data, e.g.: node 4 is the last (tail) node.
     * Going over the call stack:
     *  1. base case reached after 4th call to reverseUsingRecursion: return new_head == node 4
     *  2. returning from base case, we're at node 3's frame:
     *      2.1 We want node 4 to point back to node 3.
     *          Since node3.next == 4, node3.next.next = node3 sets node4.next to node3
     *      2.2 Since we want node3 to no longer to point to node4, we do node3.next = null.
     *          This breaks the previous direction of the singly list list between these two nodes.
     *          Q: Would we swap here if we were reversing a doubly linked list?
     *      2.3 We return the new head, node 4, all the way up to the first frame (to the first call to reverseUsingRecursion)
     *      2.4 At each return, we restore the frame for the previous node (e.g., point node3 to node2, after pointing node4 to node3, etc...)
     */
    node.next.next = node;
    node.next = null;

    return new_head;
}
</code>```

答:
Your code doesn't allocate any objects, nevertheless it has O(n) space complexity. Whenever you call your method, the implementation will set up a call stack frame. At the least, this includes the return address, but in this case you will also need stack space for the parameters and any local variables. Even if a variable points only to null or to existing objects, we need some space to hold the pointer itself.

This is completely language independent, and it is not possible to recurse without using a bit of memory to remember where you should continue once you're finished (the one exception is a “tail call”, which is not present in your example, and which Java does not currently optimize away).

Let's look at this simplified example:

```<code>void countUpTo(int n) {
   if (n > 0)
       countUpTo(n - 1);
   System.out.println(n);
}
</code>```

Obviously there are no allocations. Nevertheless, we are dealing with O(n) space complexity. Let's execute countUpTo(5):

countUpTo(5)

countUpTo(4)

countUpTo(3)

countUpTo(2)

countUpTo(1)

countUpTo(0)

println(0)

println(1)

println(2)

println(3)

println(4)

println(5)

Each level needs to remember to which outer level it must return. So when we are at countUpTo(3), we have to remember the following three levels:

main

countUpTo(5)

countUpTo(4)

Therefore, after println(3), we return to the countUpTo(4) context, which executes println(4) and then continues with the countUpTo(5) context.

When we are at countUpTo(0), we have to remember the following five levels:

main

countUpTo(5)

countUpTo(4)

countUpTo(3)

countUpTo(2)

countUpTo(1)

And remembering this stack needs space.

So when a function has a recursion depth of n, we can immediately say that it must at least have a space and time complexity of O(n).

Body:
Your code doesn't allocate any objects, nevertheless it has O(n) space complexity. Whenever you call your method, the implementation will set up a call stack frame. At the least, this includes the return address, but in this case you will also need stack space for the parameters and any local variables. Even if a variable points only to null or to existing objects, we need some space to hold the pointer itself.

This is completely language independent, and it is not possible to recurse without using a bit of memory to remember where you should continue once you're finished (the one exception is a “tail call”, which is not present in your example, and which Java does not currently optimize away).

Let's look at this simplified example:

void countUpTo(int n) {
   if (n > 0)
       countUpTo(n - 1);
   System.out.println(n);
}

Obviously there are no allocations. Nevertheless, we are dealing with O(n) space complexity. Let's execute countUpTo(5):

countUpTo(5)

countUpTo(4)

countUpTo(3)

countUpTo(2)

countUpTo(1)

countUpTo(0)

println(0)

println(1)

println(2)

println(3)

println(4)

println(5)

Each level needs to remember to which outer level it must return. So when we are at countUpTo(3), we have to remember the following three levels:

main

countUpTo(5)

countUpTo(4)

Therefore, after println(3), we return to the countUpTo(4) context, which executes println(4) and then continues with the countUpTo(5) context.

When we are at countUpTo(0), we have to remember the following five levels:

main

countUpTo(5)

countUpTo(4)

countUpTo(3)

countUpTo(2)

countUpTo(1)

And remembering this stack needs space.

So when a function has a recursion depth of n, we can immediately say that it must at least have a space and time complexity of O(n).


答:
If you translate whatever you have to C, then you have a working system wherever a C compiler is available. Which is basically everywhere. You don't have to worry about different processors, different operating systems, and all the rest.

You may instead compile to C++, which today is almost as common as C, and gives you the advantage that you can hide work that you need to do in a class instead of having to repeat yourself. Important if your language has objects that cannot be translated to C or C++ primitives.


答: If you target LLVM, you still need to preprocess and actually compile the input, but output can then be in any of the outputs LLVM allows, be it assembly or JavaScript.</p>


问:
Best Practice: Should error messages be handled by the API or by the App?
I am designing an application that interacts with a RESTful API.

When returning error messages like Unable to sign up user

Should the error message be generated by the app? or by the API? I am looking for best practices.

答:
The API should do whatever it can to give the application the necessary information how to proceed. But for the user, the message is most likely: </p>

```<code>None - for things like updates, prefetch etc. or where retrying helps.
Tell them "it didn't work".
Tell them "it didn't work, it might work later".
Tell them "it didn't work, here's what you can do to fix it"
Tell them "it didn't work, give this cryptic information to the help desk".
</code>```

<p>But it's up to the application to decide there, based on the situation and the information from the server. The server cannot know what a suitable message for the user would be. </p>

Body:
The API should do whatever it can to give the application the necessary information how to proceed. But for the user, the message is most likely:

None - for things like updates, prefetch etc. or where retrying helps.
Tell them "it didn't work".
Tell them "it didn't work, it might work later".
Tell them "it didn't work, here's what you can do to fix it"
Tell them "it didn't work, give this cryptic information to the help desk".

But it's up to the application to decide there, based on the situation and the information from the server. The server cannot know what a suitable message for the user would be.


问:
What's the best way to handle Windows API errors in response to system messages or when I have nowhere to return them to?
This is going to be a really stupid question and I hope it's fine for Stack Exchange at all, let alone just this part of it...

Right now, my custom Table control uses panic() functions that print an error on screen and DebugBreak() when a Windows API error occurs.

This is obviously an issue, but I'm not completely sure how to go about fixing it without effectively ignoring errors entirely. Keyword "effectively": even if I catch errors, if I can't do anything with them (be it forward the error to the user or to something else) it doesn't really count if I check for them.

Now for user-initiated functions (like tableAddColumn in my control) this isn't really an issue: just return the error information as a return value to the function.

My question is: what's the best way to handle Windows API errors in response to things where I can't obviously just return error information somehow. For instance, what if one of the drawing functions that I call in response to WM_PAINT fails? None of the system-provided messages provide functionality to return the API error to the system; they all just tell you to return zero if you handled the message.

I was thinking of creating a WM_NOTIFY notification tableErrorOccurred that gets sent to the control's parent when an API error occurs. However, I'm not sure how that would interact with the accessibility code. Windows accessible code is all COM, so I can freely return API errors via the HRESULT returns. Should those count toward the notification, or not? (Especially since the notification can and will return more information than just the HRESULT.)

I'm not sure whatever options there are, other than discounting the possibility of an error when all error conditions are made impossible. My current policy is to only check for an error when a function explicitly says it returns an error and how (for example, SendMessage(), EndPaint(), and SetScrollInfo() don't), and to ignore any commentary on which errors can be returned, in case the list of possible errors for whatever reason changes in the future. Am I wrong in this particular scenario: that is, would the error returns be guaranteed to never change and thus functions that only return errors on invalid parameters guaranteed to never fail with known valid parameters?

Some people have told me or talked about another Raymond Chen adage, "don't check for errors you don't know how to handle". Maybe someone can tell me that I'm misinterpreting this statement or something to that extent? Especially after the second link: it asks about what you would do with the error. I know what I want to do with these API errors: send them up to the thing that issued my own API request, just like every other API request in (almost) every other API ever! Is there a difference between doing this and "handling" the error? (You can tell that as I write more and more of this question, I am getting less and less sure of what my own opinion is, or whether any of this even IS a problem...)

The most common cases are calling GetClientRect(), which I could just save in my data structure if I can guarantee there are no cases in which the return value can change without a WM_WINDOWPOSCHANGED, and getting the height of the currently selected text font, which I can't save without sacrificing DPI independence (I deliberately get it every time to avoid the risk of crossing a DPI change boundary should a user program enable DPI awareness). The files util.h and coord.h have more info, but scroll.h and draw.h have the most API calls as far as I know.

The bits of the wine source code that I've seen don't check for errors. That's the only bit of information I have to say at this point. I'm not going to doubt that wine is a quality piece of software with a lot of effort put into it, but it seems odd to me that it does work well without explicit error checks on every API call...

I really don't want to rant about things here, so apologies in advance if this paragraph (and the previous) doesn't seem to go anywhere: It would be easier if I could return errors up to the system, or from SendMessage() (with the LRESULT as an out parameter, like COM method calls do). I don't really know. My experience with other GUI toolkits is that in most cases the only errors are incorrect parameters, but that really seems suspiciously optimistic to me. My main programming language for non-GUI stuff right now is Go, where errors are so fundamental that they're handled throughout both the standard library and user libraries (and have always been this way, without changes over time), and thus we know to carry errors up through the call chain; this reflects my own idea of error handling (and vice versa, to some extent).

So if anyone has any advice from the real world, that would be great, especially as I am close to finishing this and splitting out from the github project linked into something general purpose. Thanks.

EDIT 1 March 2015

I don't know why I forgot to paste this earlier but this is what some people on IRC said the day I posted this

```<code>[Sunday, February 15, 2015] [06:09:44 PM] <Rena>        andlabs, I think by "don't check for errors you can't handle" they mean just ignore them entirely.
[Sunday, February 15, 2015] [06:09:59 PM] <Rena>        I mean I can't really think of a sane thing to do if WM_PAINT is failing
[Sunday, February 15, 2015] [06:10:39 PM] <Rena>        sometimes there's nothing you can do but let it break
[Sunday, February 15, 2015] [06:19:17 PM] <andlabs>     Rena: yes, and that just goes against /everyhting/ I've been taugh tand everyone has been teaching everytone else!
[Sunday, February 15, 2015] [06:19:23 PM] <andlabs>     that's why I'm [expletive] confused!
[Sunday, February 15, 2015] [06:20:54 PM] <andlabs>     Rena: point that out anyway :S
[Sunday, February 15, 2015] [06:21:09 PM] <devin>       nobody ever tries to catch std::bad_alloc in C++ because if you've even reached the point where that's being thrown under normal circumstances then you're probably [expletive] and should just let the ship sink anyway
[Sunday, February 15, 2015] [06:21:37 PM] <Rena>        well things like, what are you even going to do if drawing something fails? it's not a huge issue and there's probably nothing you can do about it.
[Sunday, February 15, 2015] [06:21:49 PM] <Rena>        probably it means the system is running out of GDI memory or something
[Sunday, February 15, 2015] [06:22:47 PM] <andlabs>     Rena: right, at least in the case of WM_PAINT
[Sunday, February 15, 2015] [06:23:09 PM] <Rena>        if it's like memory allocation failed in some tool, it'd be a good idea to handle that by throwing up an "out of memory" message and/or trying to save the current file to a scratch file somewhere, instead of just crashing and losing work
[Sunday, February 15, 2015] [06:23:43 PM] <andlabs>     right
[Sunday, February 15, 2015] [06:23:59 PM] <andlabs>     ...actually I'll have to keep a note of that
[Sunday, February 15, 2015] [06:24:23 PM] <andlabs>     the other situations in which a reallocation would fail is
[Sunday, February 15, 2015] [06:24:25 PM] <andlabs>     a) heap corruption
[Sunday, February 15, 2015] [06:24:30 PM] <andlabs>     in which case you actually ARE [expletive]
[Sunday, February 15, 2015] [06:24:40 PM] <andlabs>     b) passing a pointer to something that isn't part of the realloc heap
[Sunday, February 15, 2015] [06:24:51 PM] <andlabs>     c) passing an obviously bad size like -4
[Sunday, February 15, 2015] [06:38:02 PM] <andlabs>     Rena, devin - yeah :/
[Sunday, February 15, 2015] [06:38:07 PM] <andlabs>     I figure that much :S
</code>```

This comment on a pseudo-related question I posted on Stack Overflow (about a specific scenario) explains my state of mind as well.

答:
There are programming errors, and so-called error messages depending on something outside your application.

As an example: If my code tries to open a file and receives an error message, there wasn't really an error: The OS just informs me that for some reason the file could not be opened. Assuming that the OS was correct, this isn't an error, but one of the possible outcomes of trying to open a file. If my code is good, it will react to this error message properly.

Now another example: I create a file and write to it, I close it, and I reopen it. I expect that opening the file never fails. I have no code to handle that failure. In that case, if opening the file ever fails, that shows there is a programming error; I made a wrong assumption.

Windows Paint method fails: I was 100% sure it couldn't fail. So the failure is either a programming error in Paint () or my programming error (my code was based on an incorrect assumption). Anyway, it's a programming error.

With programming errors, you have two choices: Pray that they don't happen, or gracefully crash your program. With error messages, you have two choices: Detect them and handle them correctly, or turn them into "programming errors" which means you pray they don't happen, or you gracefully crash your program.

("Gracefully" means that the crash should not leave permanent damage, and should not lead to major loss of work. The latter assumes that work has been stored from time to time to recover after a crash).


问:
What is the difference between an abstract method and an interface

An interface requires implementation of the specified functions in a class that implements the interface.

An abstract function from an abstract class requires implementation in a class that extends the abstract class.

They are essentially the same things, and I don't really see the difference. I've had a look at similar questions, and the answers still don't make much sense.

Can someone explain all the differences in-depth, and practical examples of when you would use either?

答:
An abstract method is one method. An abstract class can contain several methods, and so can an interface.
The difference between those two is that an abstract class can have implementations for some of its methods, while an interface doesn't have any implementations.

(Usually. Java now allows default implementations even in interfaces, but try not to let that confuse you. Java is a bit of a special case, where the main difference between interfaces and abstract classes is that you can inherit only once, but can implement any number of times. Other languages with multiple inheritance don't have that limitation.)


答:
TL;DR: Interface is description, abstract class is (unfinished) implementation; with all consequences.

As already said, we should compare comparable things, so an abstract class (with all methods abstract) vs. interface.

An abstract class is a real class (albeit not instantiable, but usable as a superclass). So it is already materialized (abstract) skeleton of implementation. An implementation with holes to fill, so to speak.

Interface, on the other hand, is just a description of a contract. The difference is, interfaces are much more flexible to work with. A very typical example would immediately appear in any language with only single inheritance: your implementation class may conform to many interfaces at once, but you can only inherit from one class, not from many (no matter if they are abstract or not).

Title: What is the difference between an abstract method and an interface

Body:
An interface requires implementation of the specified functions in a class that implements the interface.

An abstract function from an abstract class requires implementation in a class that extends the abstract class.

They are essentially the same things, and I don't really see the difference. I've had a look at similar questions, and the answers still don't make much sense.

Can someone explain all the differences in-depth, and practical examples of when you would use either?


问:
What would be the best way to implement priority based programming without adding too much of if-else processing logic
We need to add priority based programming in our application using java programming language. For example, there are three priorities that a phone can have: A1, A2 and A3. Also there can be three different types of phone numbers like home (H), office(O) and mobile(M). There have to be default priorities like:

M - A1

H - A2

O - A3

Now the priorities will also change based on user preferences. For example, if O comes with priority A1, M and H will change to A2 and A3.

What will be the best way to implement this logic without adding too much of if-else processing logic in the code?

答:
It seems to me that priority is not a property of a number type if priority is determined based on the priorities of the other number types, so I think the best approach would be to place the number types in a List.

In other words, you have a List of Lists.  The outer List determines the priority of the numbers contained within while the inner List contains the numbers themselves.

Suppose the position 0 in your outer list corresponds to priority A1, position 1 corresponds to priority A2, and position 2 corresponds to priority A3.  If you add more priorities later, you can add more, but suffice to say that the number of priorities corresponds to the number of possible number types.

Suppose the user wishes to change the priority of those of A1 to A3.  Well according to our List, we'd simply need to remove the first list of numbers and append it to the end.  The second item in the list now is the first and the third is now the second.  The priority of each number therefore is determined by its position in the list, so you know the priority of a number based on which list you retrieved it from.

I hope that's clear.  If not, let me know and I'll try to clarify in my answer.


问:
How to check or assess debugging skills of a person?
What kind of skills determine a person that is capable of debugging code with ease? Some time ago my friend carried out an interview with a relatively good programmer. The programmer got hired. He could write good code, understood the frameworks and design patterns. The thing he was missing was - debugging skills. He could not debug at all and finding problems with his or someone else's code was huge pain for him.

Since then we are thinking about how we can assess or estimate a person's debugging skills.

So the first question is: what skills determine if a person can effectively debug software?

And the second: how to test those skills during the interview?

答:
I would ask a couple of technology agnostic questions like the following:

Take me through all steps you take to identify root cause and fix a bug (defect)

How would you use the Call Stack while debugging a multi threading
app

This works really well specially in phone interviews as you only need the person to give you a convincing answer that shows how he really things while troubleshooting a problem.


问:
Taking strong, static typing to an extreme?
It is common in strong, static typing to use different types even for variables with simple, primitive types to ease static analysis and indicate intent to the programmer. A color and a point in 3D space might both be represented by an array of 3 floats, but given different type names. In C, a lot of common types are simply typedef'd ints.

I'm wondering: just how far is it practical to take this? If you're writing a function that takes a float between 0 and 1 (perhaps it represents a probability distribution) do you create a separate type? What about a function that must take a non-zero integer? Would it be reasonable to create a type nonZeroInt, not for the purposes of encapsulation, but simply for type-safety?

You can take this arbitrarily far, encoding all preconditions of functions into the type system. For example, you could define a "primeNumber" type for the input to a function that only takes a prime. A function which must take two integers with no common factors could be changed to take one argument of type "coprimePair."

The two hypothetical functions above would presumably be part of a library that includes functions to generate prime numbers and coprime pairs, and return them with the appropriate type. If I wanted to call a function in that library that requires a prime number, and I didn't get it from the included prime-generating function, I'd have to explicitly cast an int, essentially forcing me do a reality check and ask myself, "Am I certain that this variable will always be prime?"

My specific question is this: How far is this philosophy ever successfully taken in practice? Are there programming languages, or well-respected programming texts, that encourage a philosophy that says: every function that cannot accommodate the entire range of any existing type as its input, and return a meaningful result for all possible inputs, should instead define a new type?

答:
Here's how it's done in haskell:

```<code>data Prime = Prime Int
primeFromInt :: Int -> Maybe Prime
primeFromInt a | isPrime a = Just (Prime a)
primeFromInt _ = Nothing
</code>```

Note that it'll still allow claiming that an int is a prime:

```<code>Prime 10
</code>```

Even though 10 is not prime, compiler simply cannot detect this problem. Instead if you write it another way

```<code>primeFromInt 10
</code>```

This will nicely reject the 10 and give us nothing.

Body:
Here's how it's done in haskell:

data Prime = Prime Int
primeFromInt :: Int -> Maybe Prime
primeFromInt a | isPrime a = Just (Prime a)
primeFromInt _ = Nothing

Note that it'll still allow claiming that an int is a prime:

Prime 10

Even though 10 is not prime, compiler simply cannot detect this problem. Instead if you write it another way

primeFromInt 10

This will nicely reject the 10 and give us nothing.


问:
REST - Recommendation route: POST or GET?
I'm building an api route which will pull data from our server. This data is sorted in an arbitrary (changing and unknown to the client manner), and will never return the same data more than once.

I'm currently thinking POST /resource/recommendation is the cleanest signature for this, but i'd like to hear others' thoughts.

答:
Use GET.

The fact that the data changes each time a client accesses it is not a reason not to use GET. You are not POSTing any data to the web server, you are merely GETting the current state of the resource. That state may be constantly changing, for example GET /currenttime.html will constantly change each time you request it. There isn't anything in the HTTP spec that says that a client should expect that a resource does not change between GETs. The server can update the resource what ever way it sees fit, either internally or due to other clients updating the resource. A client should never assume that a resource has not changed since it last got its state.

It is though a reason to use an ETag in the response header to let the client (and any caching in between) know what the server has changed the resource since the client last accessed it. A client can compare the ETags to know that the resource has changed.

http://en.wikipedia.org/wiki/HTTP_ETag


问:
How do you avoid getters and setters?
I'm having something of a hard time with designing classes in an oo way. I've read that objects expose their behavior, not their data; therefore, rather than using getter/setters to modify data, the methods of a given class should be "verbs" or actions operating on the object. For example, in an 'Account' object, we would have the methods Withdraw() and Deposit() rather than setAmount() etc. See: Why getter and setter methods are evil.

So for example, given a Customer class that keeps alot of information about the customer, e.g. Name, DOB, Tel, Address etc., how would one avoid getter/setters for getting and setting all those attributes? What 'Behavior' type method can one write to populate all that data?

答:
The issue of having getters and setters can be a matter of the fact that a class may be used in the business logic in one way but you may also have helper classes to serialize / deserialize the data from a database or file or other persistent storage.

Due to the fact there are many ways to store / retrieve your data and you want to decouple the data objects from the way they are stored, the encapsulation can be "compromised" by either making these members public, or making them accessible through getters and setters which is almost as bad as making them public.

There are various ways around this. One way is to make the data available to a "friend". Although friendship is not inherited, this can be overcome by whatever serializer requesting the information from the friend, i.e. the base serializer "forwarding" the information.

Your class could have a generic "fromMetadata" or "toMetadata" method. From-metadata constructs an object so may well be a constructor. If it is dynamically typed language, metadata is pretty standard to such a language and probably is the primary way to construct such objects.

If your language is C++ specifically, one way around this is to have a public "struct" of data and then for your class to have an instance of this "struct" as a member and in fact all the data you are going to store / retrieve to be stored in it. You can then easily write "wrappers" to read/write your data in multiple formats.

If your language is C# or Java which don't have "structs" then you can do similarly but your struct is now a secondary class. There is no real concept of "ownership" of the data or const-ness so if you give out an instance of the class containing your data and it's all public, whatever gets hold can modify it. You could "clone" it although this can be expensive. Alternatively you could make this class have private data but use accessors. That gives users of your class a roundabout way to get to the data but it isn't the direct interface with your class and is really a detail in storing the data of the class which is a use-case too.

Title: How do you avoid getters and setters?


问:
Will object reuse optimize this often-called function?
Suppose I have a function that I need to call a lot, maybe a few thousand times on every mouse down or mouse move. It uses an instance of a function (class), called Transform:

```<code>function func1(a, b, c) {
  var t = new Transform();
  t.rotate(a);
  t.scale(b, c);
  return t.m[0];
}
</code>```

So I'm creating thousands of new transforms as I call this func1 lots.

What if, instead of creating new Transform()s every time, I created a small system to allocate extra transforms only as they are needed, and re-use them:

```<code>window.Util = {
  _CachedTransforms: [],
  tempTransform: function() {
    var arr = Util._CachedTransforms;
    var temp = arr.pop();
    if (temp === undefined) return new Transform();
    return temp;
  },
  freeTransform: function(temp) {
    Util._CachedTransforms.push(temp);
  }
}
</code>```

Then instead I could call func2:

```<code>function func2(a, b, c) {
  var t = Util.tempTransform();
  t.reset();
  t.rotate(a);
  t.scale(b, c);
  var result = t.m[0];
  Util.freeTransform(t);
  return result;
}
</code>```

Using func2 several thousand times, new Transform is only ever called once. This might suggest a benefit, but the numbers from jsperf don't seem to suggest any.

If you want to see these two functions in action as well as the Transform class, take a look at jsperf: http://jsperf.com/transforms

And especially: http://jsperf.com/transforms/2

To simulate it occuring lots during an event, my jsperf test does:

```<code>var a;
for (var i = 0; i < 4000; i++) {
  a += func1(1, i, 3); // vs func2
}
</code>```

There may be better ways to test if this is advantageous or not. Am I missing something?

More broadly, is object reuse like this still a good idea in this scenario, or ever?

答:
Considering as Javascript is single-threaded, there is no use in keeping an array of multiple instances, since there can only be one Transform object in use at a given time. Furthermore, since your usage of the tranform object is synchronous, there is no need to lock/free the instance. So in effect, you only need one instance, which can be made global, sparing you additional function calls.

```<code>function func2(a, b, c) {
  var t = Window.transformSingleton;
  t.reset();
  t.rotate(a);
  t.scale(b, c);
  var result = t.m[0];
  return result;
}
</code>```

Another option would be to pass the transform object as a parameter to func2. In Javascript object arguments gets passed as references, so you are still using a single object.

OwnerDisplayName: Simon Sarris

Body:
Considering as Javascript is single-threaded, there is no use in keeping an array of multiple instances, since there can only be one Transform object in use at a given time. Furthermore, since your usage of the tranform object is synchronous, there is no need to lock/free the instance. So in effect, you only need one instance, which can be made global, sparing you additional function calls.

function func2(a, b, c) {
  var t = Window.transformSingleton;
  t.reset();
  t.rotate(a);
  t.scale(b, c);
  var result = t.m[0];
  return result;
}

Another option would be to pass the transform object as a parameter to func2. In Javascript object arguments gets passed as references, so you are still using a single object.


问:
Is it good that testers are competing to see who opens more bugs?
I'm a software developer. There is a team of testers who follow and run test cases written by the analyst, but also perform exploratory testing. It seems like the testers have been competing to see who opens more bugs, and I've noticed that the quality of bug reports has decreased. Instead of testing functionality and reporting bugs related to the operation of the software, the testers have been submitting bugs about screen enhancements, usability, or stupid bugs.

Is this good for the project? If not, how can I (as a software developer), try to change the thinking and attitudes of the team of testers?

Another problem is because the deadline is estimated and cannot change, so as the deadline nears, the testers will be scrambling to finish their test cases, and this will cause the quality of the tests decrease. This will cause legitimate bugs to be in the final product received by the client.

OBS: This competition is not a practice of the company! It is a competition between only the testers organized by them, and without any prizes.

答: Finding bugs is their job. As long as they aren't making things less efficient (for instance, by opening a bug for ech of 10 typos instead of one to cover several of them) this is encouraging them to do exactly what they're supposed to be doing, so I can't see much of a downside.</p>


问:
When is an object of real world a (computational) object in OOP world?
In an OOP design phase strategy,

Any physical/conceptual object of a system can be modeled(considered) as computational object in your OOP designed program based on below two conditions:

First case: That physical/conceptual object of a system must have it's local state and that state changes over time.

or

Second case: that physical/conceptual object of a system may or may not have it's local state but that same object must influence the state of other physical/conceptual object of a system through interactions.

Above two cases are also supported here, which says:  Viewing objects as finite state machines

To illustrate above two cases, below is the object model diagram and class diagram of coin flipping game.

class Coin and class Player type objects, have local state coinOption, as mentioned in  first case. class CoinGame type object has no local state but influence the state of other objects(of type Player and Coin), as mentioned in second case.

As per second case, class CoinGame type object influences the state of other objects of type Player and Coin through below interactions, but class CoinGame type object itself does not have local state on it's own.

So, class CoinGame does not maintain any local state and has composite relation with Player and Coin, as per below java code.

```<code>public class CoinGame {

        Player[] players = new Player[2];

        Coin theCoin = new Coin();

        CoinGame(String player1Name, String player2Name){

            players[0] = new Player(player1Name);
            players[1] = new Player(player2Name);

        }
       .....
}
</code>```

Here is the complete code in java.
Above two cases are valid, when you select objects from real world.
Is my understanding correct?

答:
In SICP § 1.1.2, it says:

A critical aspect of a programming language is the means it provides for using names to refer to computational objects. We say that the name identifies a variable whose value is the object.

So a computational object is simply that which is pointed to by a variable.  It can be an object, a first-class function, or even a number.  That's all you need to have a computational object.

As to your first two assertions, that an object can model changes through time by changing its state and/or passing messages around to other objects, those two assertions are both true.


问:
Using parameters in automatic integration tests
I am trying to automate integration testing in our team, and I am wondering if making tests with parameters is good or bad design.

My problem is that the integration tests should run some perl scripts from our codebase that work with database and compare the data in database before and after the test. I would like to set a flag for all automated tests to revert the database changes, so different tests will not interact with each other. But I also want to disable the flag on purpose, so I will be able to manually check the data so the test does not overwrite them back immediately after finishing.

Is there some cleaner/more common solution for this? I know about database and data mocking, but I can not use that.

答:
When we speak of running tests with parameters, what we commonly mean is running a bunch of tests with A=5, immediately followed by running the same bunch of tests with A=6, and so on, all of this together constituting a single test run.

What you seem to need instead, is to run all your tests just once, but with a specific configuration, which may change from run to run.

So, all you need to do is have each one of your tests read a certain configuration file at start up, telling it whether it should revert, erase, etc.


答:
I do not think it's good that they make a contest out of finding the most bugs. While it is true that their job is to find bugs, their job is not "find the most bugs". Their goal isn't to find the most, their goal is to help improve the quality of the software. Rewarding them for finding more bugs is about the same as rewarding a programmer for writing the most lines of code, rather than the highest quality code.

Turning it into a game gives them an incentive to focus on finding many shallow bugs, rather than finding the most critical bugs. As you mention in your edit, this is exactly what is happening in your organization.

One could argue that any bug they find is fair game, and that all bugs need to be discovered. However, given that your team likely has limited resources, would you rather have a tester focus several hours or days probing deeply into your system trying to find really big bugs, or spend several hours or days skipping through the app looking for typographical errors and small errors in the alignment of objects on a page?

If the company really wants to make a game out of it, give the developers the power to add points to a bug. "stupid bugs" get negative points, hard to find bugs with well written reports get multiple points. This then moves the incentive from "find the most" to "be the best at doing your job". However, this isn't recommended either, because a programmer and QA analyst could work together to artificially pad their numbers.

Bottom line: don't make a game out of finding bugs. Find ways in your organization to reward good work and leave it at that. Gamification rewards people for reaching a goal. You don't want a QA analyst to have the goal of "find the most bugs", you want their goal to be "improve the quality of the software". Those two goals are not the same.

Title: Is it good that testers are competing to see who opens more bugs?

Body:
I'm a software developer. There is a team of testers who follow and run test cases written by the analyst, but also perform exploratory testing. It seems like the testers have been competing to see who opens more bugs, and I've noticed that the quality of bug reports has decreased. Instead of testing functionality and reporting bugs related to the operation of the software, the testers have been submitting bugs about screen enhancements, usability, or stupid bugs.

Is this good for the project? If not, how can I (as a software developer), try to change the thinking and attitudes of the team of testers?

Another problem is because the deadline is estimated and cannot change, so as the deadline nears, the testers will be scrambling to finish their test cases, and this will cause the quality of the tests decrease. This will cause legitimate bugs to be in the final product received by the client.

OBS: This competition is not a practice of the company! It is a competition between only the testers organized by them, and without any prizes.


答:
I am going to disagree a bit with the other answers.  "Finding bugs" for a tester is a bit like "writing code" is for a developer.  The raw amount is meaningless.  The job of the tester is to find as many of the bugs that exist that they can, not to find the most bugs.  If tester A finds 5 of the 10 bugs in a high quality component and tester B finds 58 of the 263 bugs in a low quality component, then tester A is the better tester.

You want developers writing the minimum amount of code to solve a particular problem, and you want a tester writing up the minimum number of reports that correctly describe broken behavior.  Competing to find the most defects is like competing to write the most lines of code.  It is far too easy to slip into gaming the system to be useful.

If you want to have testers to compete, it should be more directly based on what they are there to do, which is to validate that the software works as described.  So perhaps have people compete to see who can write the most accepted test cases, or even better, write the the set of test cases that cover the most code.

The better measure of developer productivity is the number of tasks complete times task complexity.  The better measure of tester productivity is the number of test cases executed times test case complexity.  You want to maximize that, not bugs found.


答:
Is my understanding correct?

No, since immutable objects (like strings in Java or C#, or tuples in Python), do not change their state over time, nevertheless they are perfectly valid examples for (computational) objects in any kind of OOP definition I know. However, those kind of objects can influence the state of other objects through interactions.

Just because objects can have a mutable state, it is not mandatory for them to have one for beeing a "valid object in the OOP sense".

Title: When is an object of real world a (computational) object in OOP world?

Body:
In an OOP design phase strategy,

Any physical/conceptual object of a system can be modeled(considered) as computational object in your OOP designed program based on below two conditions:

First case: That physical/conceptual object of a system must have it's local state and that state changes over time.

or

Second case: that physical/conceptual object of a system may or may not have it's local state but that same object must influence the state of other physical/conceptual object of a system through interactions.

Above two cases are also supported here, which says:  Viewing objects as finite state machines

To illustrate above two cases, below is the object model diagram and class diagram of coin flipping game.

class Coin and class Player type objects, have local state coinOption, as mentioned in  first case. class CoinGame type object has no local state but influence the state of other objects(of type Player and Coin), as mentioned in second case.

As per second case, class CoinGame type object influences the state of other objects of type Player and Coin through below interactions, but class CoinGame type object itself does not have local state on it's own.

So, class CoinGame does not maintain any local state and has composite relation with Player and Coin, as per below java code.

```<code>public class CoinGame {

        Player[] players = new Player[2];

        Coin theCoin = new Coin();

        CoinGame(String player1Name, String player2Name){

            players[0] = new Player(player1Name);
            players[1] = new Player(player2Name);

        }
       .....
}
</code>```

Here is the complete code in java.
Above two cases are valid, when you select objects from real world.
Is my understanding correct?


问:
What is the most efficient way to find a set of locations within a radius of a certain point?
Imagine a dataset of all the restaurants in the US (similar to Yelp, etc), how would you return a set of restaurants within a certain range of a particular zip code.  (Assuming you have already a function, distanceBetweenZipCodes, which figures out the distance for you.)

The brute force method would be

```<code>For each restaurant in restaurantsInUSA
  if(distanceBetweenZipCodes(restaurant.zipcode, user.zipcode) < walkingDistance)
    save restaurant
</code>```

However, it seems fairly inefficient to include New York restaurants in the search if the user is in California.  But, it is possible that a restaurant is located close to a state line so segmenting the data by state would be problematic.  You get the same problem if trying to segment by counties, cities or any other administrative boundary.

What would be the most appropriate way to segment the data to avoid having to check each and every record for all searches?

答: Calculate the distances between zip codes once and cache them. Keep the restaurants list sorted by the distance to the user. Enumerating the restaurants starting from the smallest distance you can detect the point when the restaurants go out of walking range - at that point you can ignore the rest and break the loop.</p>


问:
If I have a method that needs verification in order to proceed, do I call it inside the method or before?
This has been bothering me. This is more of a pragmatic problem than technical. Imagine I have a SaveOrderChanges method which, as its name implies, will save the order changes when the user submits the modified order.

But, before saving the order, I need to verify if the order submitted is actually from the current user, so I proceed to do a simple verification in the DB. I have a special method that works with this situation which I've called "VerifyOrder()".

The true question is if the SaveOrderChanges() method should include the call to that method, or should the other method be called before SaveOrderChanges() is called

imagine I have some method like this:

Do I make it like this :

```<code>public bool SaveOrderChanges(Order order)
{
  VerifyOrder(order); //Verify that the order is from the actual user
  //Some Code Logic in here
}
</code>```

Or like this:

```<code>if(VerifyOrder(order))
{
  SaveOrderChanges(order);
}
</code>```

答:
You should choose the latter.

In making my decision, I decided to look at this from the maintenance programmer's perspective. Here's how I'd see each case:

VerifyOrder(order) is inside SaveOrderChanges(Order order) so the verification is part of what SaveOrderChanges() does. You need to verify in order to save.

VerifyOrder(order) needs to be valid in order to run SaveOrderChanges(Order order), so the verification is not part of what SaveOrderChanges(Order order) does. Any changes to SaveOrderChanges() does not have to include VerifyOrder().

It's all a matter of semantics. By placing the verification inside the function, you are saying that the function does the verification. If you need the verification done beforehand, make sure it is not part of the function to keep separation of concerns.

Additionally, let's consider the case where you go with (1) and the verification fails. The execution will exit the verification function and still be inside SaveOrderChanges() (as your code is written). This is begging for bugs you don't want.


问:
Efficiently extracting data from pdf with a template system?
basically allow a user to label specific text in a pdf file. Use the label information to create a template, which a script uses to extract text from specific pdf.

What would be a good pattern to use in such situation? For example, maybe the script that uses the templates might work for a group of well formatted pdfs but not so with badly formatted pdfs. To optimize for those latter cases, you end up modifying the script which in turn ends up breaking other previously working pdfs. So you fix the script until it finally works on all the pdfs but only the ones you've seen and have been able to create templates for. You hope that eventually you will reach a script that will handle largely varying type of pdfs. It feels like a cat and mouse game and I'm thinking maybe there's a better way to go about doing this.

The other issue that comes up is how to organize code in such scenario. But more importantly, I'm looking for advice on how to tackle the difficult problem of extracting data from pdf using a template based system (or is template system not efficient here?).

答:
This depends a great deal on the nature of the PDFs you accept as input. If you have control over the format of the PDF you're accepting, you can very easily extract the data you need; on the other hand, if you agree to accept any valid PDF at all, your task will be much harder.

A loose hierarchy of options that PDFs can provide:

PDF forms are designed for the scenario you describe; several toolkits and web services are available for extracting info from PDF forms

Structured PDF is a more general way for tagging specific pieces of information in a PDF

Even without forms or tags, several toolkits allow you to extract text from a PDF, unless...

The PDF only contains images of pages of text, in which case your only hope is an OCR system


答:
The first one; SaveOrderChanges should call VerifyOrder.  Otherwise, some future coder will call SaveOrderChanges without calling VerifyOrder.  An alternative that still prevents such an error is to call VerifyOrder outside SaveOrderChanges, but for both methods to be private.

I am assuming that SaveOrderChanges has a precondition that VerifyOrder will succeed; it is being called to detect bugs rather than as part of processing the order.  Under this assumption, it is (probably) the responsibility of the caller to only call SaveOrderChanges on valid orders; ideally a failed call to VerifyOrder indicates a bug in the caller's code.

Title: If I have a method that needs verification in order to proceed, do I call it inside the method or before?

Body:
This has been bothering me. This is more of a pragmatic problem than technical. Imagine I have a SaveOrderChanges method which, as its name implies, will save the order changes when the user submits the modified order.

But, before saving the order, I need to verify if the order submitted is actually from the current user, so I proceed to do a simple verification in the DB. I have a special method that works with this situation which I've called "VerifyOrder()".

The true question is if the SaveOrderChanges() method should include the call to that method, or should the other method be called before SaveOrderChanges() is called

imagine I have some method like this:

Do I make it like this :

```<code>public bool SaveOrderChanges(Order order)
{
  VerifyOrder(order); //Verify that the order is from the actual user
  //Some Code Logic in here
}
</code>```

Or like this:

```<code>if(VerifyOrder(order))
{
  SaveOrderChanges(order);
}
</code>```


答: If you can really screw up the state of your data by saving an invalid order then something needs to do verification. Either the datastore needs to blow up and reject the transaction, or some code needs to check the validity of the order. I would not expose a public API that allows saving an order if it can result in data corruption. </p>


答: If computing the verification is not expensive, I would verify before calling the method, and assert that verification passes inside the method. This ensures will catch programming errors sooner, and allows callers to handle the else case however they want.</p>


问:
What is language-agnosticism and why is it called that?
When is something language agnostic? Why is it called that?</p>

答:
When a solution is called "language-agnostic" you are literally saying that your solution "doesn't know about" languages, meaning its universal or independent from language specifics (paradigms, language idioms, etc).

For example, design patterns are language-agnostic, because the way they are described the specific implementation doesn't matter as long it sticks to the whole or a subset of the pattern (v.gr. some design patterns can be implemented without OOP).

UML is language-agnostic, BPMN is language-agnostic, ERM is language-agnostic. An algorithm in pseudo-code is language agnostic...

Anything that is meant to be programmed but not described in a specific language can be called language-agnostic.


问:
Storing values in SQL whose types are determined in runtime
I have come across a need of storing runtime determined values in a SQL database.

For example, there is a GUI where a user can add new editable fields. So the user adds a field Name, chooses the value type String and fills in the value Arthur.
Then the user adds a new field Money, chooses the value type Decimal and fills in the value 10.05.

As seen above, the user is able to add any fields with any value types.

My idea is to have a SQL table schema as follow:

FieldName (varchar) - eg. 'Money' or 'IsAlive'

FieldType (varchar) - eg 'Decimal' or 'Boolean'

FieldValue (varchar) - eg. '10.5' or '1'

This would mean that I can store any pre-defined data type in the table whether it's a string, boolean or long.

The problem is that I am not sure it's the best approach to cast those values to string and then cast again when reading from the table.

Another option would be to have a column of each type but that sounds even worse.

Does my approach to cast everything to string sounds sensible or should I try something else?

答:
It all boils down to whether these extra fields will need to be searchable, as well as whether you are going to have few rows (hundreds) or many rows (hundreds of thousands.)

You see, the string "1000" compares below the string "900", so any search for a number will have to be be implemented using a full table scan. Plus, obtaining rows sorted by a user defined numeric field will need to be implemented by loading all the rows into memory, converting the strings to numbers, and sorting the rows in memory by comparing the numbers.  Which is something you do not want to do if you have hundreds of thousands of records.

So:

If your user-defined fields are not going to need to be searchable, or if you are only going to have a few rows, (so full table scan is acceptable,) then casting to string should be fine. As a matter of fact, you do not even need to go with a name-type-value table, you can just add one long text field to one of your existing tables, and this text field can contain all your sub-fields together, encoded in XML or JSON.

However, if these user defined fields need to be searchable AND there is a possibility that you might have many rows, then this approach will not work.  What you can do in this case, is have a name-value table for all strings, a name-value table for all integers, a name-value table for all floats, etc.


问:
Design patterns for implementing optionally supported features
Here's the original problem. There are two classes: Protocol and, say, ProtocolUser (which actully uses the Protocol class instance). Now, I need to support multiple protocols, whose feature sets only partly intersect, doing similar but not equal things. I grouped the features into several interfaces. That is:

```<code>interface IA {}
interface IB {}
interface IC {}

interface IP {};
class P_AB : IP, IA, IB {}
class P_AC : IP, IA, IC {}
class P_BC : IP, IB,IC {}

class P_User
{
    IP m_p;

    ??? // needs to use m_p via IA, IB or IC, depending on which are supported
}
</code>```

And the most vexed part: the protocols are to be switched on-the-fly. Methods of P_User will have to choose which interfaces to operate on, depending on which will be supported by the call time.

The initial plan was to rely on is & as operators. But it does look suspiciously cumbersome. The only alternative I see is to invent some kind of "CanDoThis / CanDoThat" infrastructure, but that doesn't differ much from a plain is.

Are there any helpful patterns I'm unaware of?

答:
What you could do is a variation of an Abstract Factory. Something like this:

```<code>public class ProtocolFactory
{
    public IP _protocol;

    public ProtocolFactory(IP protocol)
    {
         _protocol = protocol;
    }

    public IA GetAService()
    {
         return _protocol as IA ?? new NoOpProtocol();
    }

    public IB GetBService()
    {
         return _protocol as IB ?? new NoOpProtocol();
    }

    // etc
}

public class NoOpProtocol : IA, IB, IC
{
     // Implement all interfaces as no-ops
}
</code>```

So now your calling code is

```<code>var factory = new ProtocolFactory(m_p);
factory.GetAService().DoStuff();
factory.GetBService().DoMore();
// etc
</code>```

This seems less cumbersome, keeps the soft-casting functionality in one place, but still allows you extensibility, with as many protocols as you like, each implementing as few or as many interfaces as you like.

Body:
What you could do is a variation of an Abstract Factory. Something like this:

public class ProtocolFactory
{
    public IP _protocol;

    public ProtocolFactory(IP protocol)
    {
         _protocol = protocol;
    }

    public IA GetAService()
    {
         return _protocol as IA ?? new NoOpProtocol();
    }

    public IB GetBService()
    {
         return _protocol as IB ?? new NoOpProtocol();
    }

    // etc
}

public class NoOpProtocol : IA, IB, IC
{
     // Implement all interfaces as no-ops
}

So now your calling code is

var factory = new ProtocolFactory(m_p);
factory.GetAService().DoStuff();
factory.GetBService().DoMore();
// etc

This seems less cumbersome, keeps the soft-casting functionality in one place, but still allows you extensibility, with as many protocols as you like, each implementing as few or as many interfaces as you like.


答:
The two cases/conditions, by my reading, clarify which real world and conceptual objects are meaningful candidates to model computational objects after; not whether an object or variable in-code is a computational object. And there's a large degree of subjectivity there -- it's all about whether you, the programmer, can recognize a meaningful state or interaction to model some code after.

Consider two objects:

A Cup: An attribute of a cup is its fullness, which can vary over time. We can therefore model a "computational" cup object, in that our cup object would store fullness values that can change [over time]. For instance, if we need needed a small, finite container to buffer our consumption of a resource, a cup could be a legitimate model.

Your cousin Ed: Doesn't do nothin'. Just sits, doesn't move. And never bothers nobody. Hence ... no particular value as a computational model.


答:
Based on my personal experiences, this is not a good thing.  It almost always leads to developers filing bugs that are duplicates, ridiculous, or completely invalid.  You'll typically see a lot of these appearing suddenly at the end of a month/quarter as testers rush to meet quotas.  About the only thing worse than this is when you also penalize developers based on the number of bugs found in their code.  Your test and development teams are working against each other at that point, and one can't succeed without making the other look bad.

You need to keep your focus on the user here.  A user has no idea how many bugs were filed during testing, all they see is the one that got through.  Users ultimately don't care if you file 20 bug reports or 20,000, as long as the software works when they get it.  A better metric for evaluating testers would be the number of bugs that were reported by users but that should have reasonably been caught by testers.

This is a lot harder to keep track of, though.  It's fairly easy to run a database query to see how many bug reports were filed by a specific person, which I suspect is the main reason why the "bugs filed" metric is used by so many people.


问:
"Hand written" recursive descent parser with "catch all" rule
I'm trying to write a (scannerless) recursive descent parser with a "catch all" rule for the following "Mustache template" grammar (simplified here):

```<code>       content : (variable_tag | section_tag | static)*
  variable_tag : mustache_open id mustache_close
   section_tag : mustache_open '#' id mustache_close
                 content mustache_open '/' id mustache_close
 mustache_open : '{{'
mustache_close : '}}'
            id : [a–zA–Z$_][a–zA–Z0–9$_]*
        static : .+  // "catch all"
</code>```

The static production would have to stop before the next matched production. And I can't come to a solution for this that would not break the grammar structure.

A valid input is:

```<code>You have just won {{value}} dollars!
{{#in_ca}}
Well, {{taxed_value}} dollars, after taxes.
{{/in_ca}}
</code>```

The output for that would be an abstract syntactic tree like:

```<code>                           +-------+
                           |Content|
                           +-------+
                               |
        +---------------+------+--------+--------------+
        |               |               |              |
+--------------+  +-----------+  +-------------+  +----------+
|Static        |  |VariableTag|  |Static       |  |SectionTag|
|"\nYou...won "|  |value      |  |" dollars"\n"|  |in_ca     |
+--------------+  +-----------+  +-------------+  +----------+
                                                       |
                                                   +-------+
                                                   |Content|
                                                   +-------+
                                                       |
                                    +-------------+----+--------------+
                                    |             |                   |
                              +----------+  +-----------+  +---------------------+
                              |Static    |  |VariableTag|  |Static               |
                              |"\nWell, "|  |taxed_value|  |" dollars...taxes.\n"|
                              +----------+  +-----------+  +---------------------+
</code>```

Any reference to a implementation of a "catch all" rule for a recursive descent parser?

答:
For this particular grammar, I think you can just match until you see {{. Then push {{ back on the tokens to be read.

So I think the key here is just having the ability to push back onto the token list. Having a fixed buffer of tokens is generally good for error handling too, in LR parsers, but I wouldn't be surprised if it is useful in LL parsers as well.