问:
Indefinite loops where the first time is different
This isn't a serious problem or anything someone has asked me to do, just a seemingly simple thing that I came up with as a mental exercise but has stumped me and which I feel that I should know the answer to already. There may be a duplicate but I didn't manage to find one.

Suppose that someone asked you to write a piece of code that asks the user to enter a number and, every time the number they entered is not zero, says "Error" and asks again. When they enter zero it stops.

In other words, the code keeps asking for a number and repeats until zero is entered. In each iteration except the first one it also prints "Error".

The simplest way I can think of to do that would be something like the folloing pseudocode:

```<code>int number = 0;
do
{
    if(number != 0)
    {
        print("Error");
    }
    print("Enter number");
    number = getInput();
}while(number != 0);
</code>```

While that does what it's supposed to, I personally don't like that there's repeating code (you test number != 0 twice) -something that should generally be avoided. One way to avoid this would be something like this:

```<code>int number = 0;
while(true)
{
    print("Enter number");
    number = getInput();
    if(number == 0)
    {
        break;
    }
    else
    {
        print("Error");
    }
}
</code>```

But what I don't like in this one is "while(true)", another thing to avoid.

The only other way I can think of includes one more thing to avoid: labels and gotos:

```<code>    int number = 0;
    goto question;
error:
    print("Error");
question:
    print("Enter number");
    number = getInput();
    if(number != 0)
    {
        goto error;
    }
</code>```

Another solution would be to have an extra variable to test whether you should say "Error" or not but this is wasted memory.

Is there a way to do this without doing something that's generally thought of as a bad practice (repeating code, a theoretically endless loop or the use of goto)?

I understand that something like this would never be complex enough that the first way would be a problem (you'd generally call a function to validate input) but I'm curious to know if there's a way I haven't thought of.

答:
The following solution avoids repetition and separates the concerns of getting the input and validating it:</p>

```<code>do
{
  print "Enter number"
  number = getInput()
} while(!numberValid(number))

bool numberValid(number) {
  if (number == 0) {
    return true
  } else {
    print "Error!"
    return false
  }
}
</code>```

Body:
The following solution avoids repetition and separates the concerns of getting the input and validating it:

do
{
  print "Enter number"
  number = getInput()
} while(!numberValid(number))

bool numberValid(number) {
  if (number == 0) {
    return true
  } else {
    print "Error!"
    return false
  }
}


问:
Dealing with state problems in functional programming
I've learned how to program primarily from an OOP standpoint (like most of us, I'm sure), but I've spent a lot of time trying to learn how to solve problems the functional way. I have a good grasp on how to solve calculational problems with FP, but when it comes to more complicated problems I always find myself reverting to needing mutable objects. For example, if I'm writing a particle simulator, I will want particle "objects" with a mutable position to update. How are inherently "stateful" problems typically solved using functional programming techniques?</p>

答:
As noted by @KarlBielefeldt, the functional approach to such a problem is to view it as returning a new state from a previous state.  The functions themselves do not hold any information, so they will always update state m to state n.

I think you find this inefficient because you assume that the previous state has to be kept in memory while computing the new state.  Notice that the choice between writing a completely new state or re-writing the old one in place is an implementation detail from the point of view of a functional language.

For instance, say I have a list of a million integers, and want to increment the tenth by one unit.  Copying the entire list with a new number in its tenth position is wasteful, you are right; but it is only the conceptual way of describing the operation to the language compiler or interpreter.  The compiler or interpreter is free to take the first list and just overwrite the tenth position.

The advantage of describing the operation in this way is that the compiler can reason about the situation when many threads want to update the same list at different positions.  If the operation is described as "go to this position and overwrite what you find", then it is the programmer, not the compiler, who is in charge of making sure that overwrites do not collide.

With all that said, even in Haskell there is a State monad that helps to model situations where "keeping state" is a more intuitive solution for a problem.  But please also notice some problems that you find "inherently stateful, like writing to a database" have immutable solutions like Datomic.  This can be surprising until you understand it is a concept, not necessarily its realization.

ContentLicense: CC BY-SA 3.0


问:
Can decoupling hurt maintainability in certain situations?
Can the fact that the business logic is mapped to interfaces instead of implementations actually hinder the maintenance of the application in certain situations?

A naive example with the Java's Hibernate framework would be, that for example (provided I don't have the whole code-base in my head, the project structure is a mess and classes are named with arbitrary names) if I wish to see what's going on in a certain DAO, to see if it actually is doing what it's supposed to do, then instead of traversing backwards up the tree from the point where the data service is invoked (where the tree will end in an interface with no implementation details whatsoever apart from the signature) I have to for example go and look for a configuration XML file to see which class is mapped to said interface as the implementation before being able to access the actual implementation details.

Are there any situations where having loose coupling can actually hurt maintainability?

答: Trade offs are inherent in software design.  Decreasing coupling almost always makes it more difficult to find the concrete implementation your code eventually depends on.  We accept that cost because it makes it easier to change that implementation and test it in isolation, which minimizes the times we need to find the concrete implementation, and minimizes the ripple effects of any changes we make to it.  Don't fool yourself.  Just because a cost is worth paying doesn't mean it isn't there.</p>


答:
In Ruby I would consider this to be a guard clause and I would write it as either:

```<code>do_something if condition
</code>```

or

```<code>do_something unless condition
</code>```

I use these sparingly though.  If there is a lot of code (more than 2 statements or lines say) I prefer the traditional if then else construct.

The main time I use is is for short conditions so that I can write the single line:

```<code>procA if x=1
</code>```

instead of the 3 lines:

```<code>if x=1 then
  procA
end
</code>```

Title: Indefinite loops where the first time is different

Body:
This isn't a serious problem or anything someone has asked me to do, just a seemingly simple thing that I came up with as a mental exercise but has stumped me and which I feel that I should know the answer to already. There may be a duplicate but I didn't manage to find one.

Suppose that someone asked you to write a piece of code that asks the user to enter a number and, every time the number they entered is not zero, says "Error" and asks again. When they enter zero it stops.

In other words, the code keeps asking for a number and repeats until zero is entered. In each iteration except the first one it also prints "Error".

The simplest way I can think of to do that would be something like the folloing pseudocode:

```<code>int number = 0;
do
{
    if(number != 0)
    {
        print("Error");
    }
    print("Enter number");
    number = getInput();
}while(number != 0);
</code>```

While that does what it's supposed to, I personally don't like that there's repeating code (you test number != 0 twice) -something that should generally be avoided. One way to avoid this would be something like this:

```<code>int number = 0;
while(true)
{
    print("Enter number");
    number = getInput();
    if(number == 0)
    {
        break;
    }
    else
    {
        print("Error");
    }
}
</code>```

But what I don't like in this one is "while(true)", another thing to avoid.

The only other way I can think of includes one more thing to avoid: labels and gotos:

```<code>    int number = 0;
    goto question;
error:
    print("Error");
question:
    print("Enter number");
    number = getInput();
    if(number != 0)
    {
        goto error;
    }
</code>```

Another solution would be to have an extra variable to test whether you should say "Error" or not but this is wasted memory.

Is there a way to do this without doing something that's generally thought of as a bad practice (repeating code, a theoretically endless loop or the use of goto)?

I understand that something like this would never be complex enough that the first way would be a problem (you'd generally call a function to validate input) but I'm curious to know if there's a way I haven't thought of.

Body:
In Ruby I would consider this to be a guard clause and I would write it as either:

do_something if condition

or

do_something unless condition

I use these sparingly though.  If there is a lot of code (more than 2 statements or lines say) I prefer the traditional if then else construct.

The main time I use is is for short conditions so that I can write the single line:

procA if x=1

instead of the 3 lines:

if x=1 then
  procA
end


问:
Inspecting the model in a Rails application
I am learning some Ruby on Rails, and am a newbie. Most of my background is in ASP.net MVC on the back end.

As I play with a basic scaffold project, I wonder about this case: you jump into an established Rails project and want to get to know the model. Based on what I have seen so far (again, simple scaffold), the properties for a given class are not immediately revealed. I don't see property accessors on the model classes.

I do understand that this is because of the dynamic nature of Ruby and such things are not necessary or even perhaps desirable. Convention over code, I get that. (Am familiar with dynamic concepts, mostly via JS.)

But if I am somewhere off in a view, and want to quickly know whether the (eg) Person object has a MiddleName property, how would I find that out? I don't have to go into the migrations, do I?

答:
You can find the attributes of a model in schema.rb if you want the full list of attributes on a model, including association ids.  Alternatively, there are many ways to do it in the console, such as pp Model.instance or puts @instance.ai, which show the same thing.  However, that won't give you the methods available, since rails does a lot of work to extrapolate methods from attributes (for instance, setting a has_one :user does more than just include @instance.user).

If you want to look at your available methods on an object or model, you can use @instance.public_methods.  You can subtract out inherited methods as well, e.g. @instance.public_methods - Object.public_methods or @instance.public_methods - ActiveRecord::Base.public_methods.  You can also use .instance_methods on the class, for instance.

Finally, you may want to look at the annotate gem, which add comments to your models.  You have to rerun it after migrations but it might be what you're looking for

ContentLicense: CC BY-SA 2.5


问:
Why DbContext object shouldn't be referred in Service Layer?
I've been looking for some implementations of Service Layer and Controller interaction in blogs and in some open source projects. All of them seem to refer DbContext object in repository classes but avoided to use in service classes. Service classes essentially using a IQueryable<T> references of DbSet<T>. I want to know why this practice is good and why DbContext shouldn't have a reference in Service Layer.

答:
NOTE: I'm writing this answer as it would apply to a Programmers.SE question.

A big part of application design is abstraction i.e. hiding away lower-level details and providing a simple conceptual interface to consumers. A related principle is encapsulation - the internal details of an operation should remain within the component and should not leak into the outside world.

Typically, we would like to have all DB-related code in a single location. So we create a dedicated layer for it and encapsulate all DB logic in that layer. As far as the service layer is concerned, it does not know anything about how the data is retrieved. It just asks for some data from the data layer, "magically" gets it, and runs business logic on it.

This makes it very easy to change the DB logic. For example, swapping the underlying database with an equivalent one has negligible impact on other areas of the application. Because the service knows nothing about the DB, as long as it gets the same data back, it will continue working exactly as before.

Note that this also applies to other layers. The UI layer knows nothing of business logic. It talks in terms of domain-level abstractions and shows them to the consumer. How those domain objects are generated and manipulated is the job of the business layer and hidden within it.

OwnerDisplayName: nazmoonnoor

OwnerDisplayName: metacubed


问:
What is the one bit of computer science theory I should know?
Speaking as someone with an Electronic Engineering rather than Computer Science degree, what is the one bit of computer science I should know to make me a better real world programmer?

(By real world I mean something I'm going to use and benefit from in my day to day job as a programmer - for instance I'd suggest understanding database normalisation is of more practical use than understanding a quick sort for which there are lots of libraries).

答: The most important thing I learned in CS (and as a developer for many years and as an architect) is the ability to break a problem down based on volatility and not on function.  All good designs isolate and encapsulate volatility.  All good developers/architects do this intuitively even if they have not formalized it in their thinking.  A huge reason for project failure is the failure to break a problem down on the basis of volatility and encapsulate it.  A failure to encapsulate volatility inevitably leads to run away complexity and project failure.


问:
Best practices for caching search queries
I am trying to improve performance of my ASP.net Web Api by adding a data cache but I am not sure how exactly to go about it as it seems to be more complex than most caching scenarios. An example is I have a table of Locations and an api to retrieve locations via search, for an autocomplete.

```<code>/api/location/Londo
</code>```

and the query would be something like

```<code>SELECT * FROM Locations WHERE Name like 'Londo%'
</code>```

These locations change very infrequently so I would like to cache them to prevent trips to the database for no real reason and improve the response time.

Looking at caching options I am using the Windows Azure Appfabric system, the problem is it's just a key/value cache. Since I can only retrieve items based on keys I couldn't actually use it for this scenario as far as Im aware.

Is what I am trying to do bad use of a caching system? Should I try looking into NoSql DB which could possibly run as a cache for something like this to improve performance? Should I just cache the entire table/collection in a single key with a specific data structure which could assist with the searching and then do the search upon retrieval of the data?

答:
If you wrapped your query around an ORM like Hibernate, Eclipse link, etc then the ORM will do some caching for you locally in your RAM. You save the network IO latency.

When the request arrives at the SQL server, it will do another round of caching, saving you disk IO.

But then since the data changes so frequently, you need to think about other way to improve performance rather than caching.


问:
What is the origin of the negative term "legacy code"
Everyone talks about legacy code in software development and I have heard the term over the last ten years used to paint any codebase as being bad.

Where did this term, which has such powerful connotations to programmers alike originate?

I am sure there must be some book on software development that pioneered this term. I would love to locate the origin of the term "legacy code".

答:
Legacy code is based on the phrase of a legacy system that specifically applies to code.  According to Wikipedia it probably dates back to the 1970s and was in common usage in the 1980s.  It took off with the tech explosion of the 1990s.

This can be seen with Google's ngram viewer: legacy system,legacy code

Digging into this further, you can find documented uses of the term 'legacy system' in the 1970s.

The earliest example of 'legacy system' that google has is in a book on Proceedings of the Army Numerical Analysis and Computers Conference from 1978:

... well strutted and documented solution to a clearly defined problem is the legacy system operation needs to be understood and to change the existing system with confidence.

There is also an example of 'legacy system' being used outside of the technology industry in Clout: Womanpower and Politics grin 1976:

... in addition, she holds a seat as the third-ranking Democrat on the powerful Banking and Currency Committee - positions of power she has built up on her own, not via the legacy system.

Beyond these example which shows its use has extended beyond the pure software world, the specifics of where exactly the term originated are probably lost to the sands of time.  Given the military and political references, it may have originated with them (primarily the military and its jargon migration ("It seems likely that 'kluge' came to MIT via alumni of the many military electronics projects run in Cambridge during the war (many in MIT's venerable Building 20, which housed TMRC..."))


问:
How to Structure a Trinary state in DB and Application
How should I structure, in the DB especially, but also in the application, a trinary state?

For instance, I have user feedback records which need to be reviewed before they are presented to the general public.  This means a feedback reviewer must see the unreviewed feedback, then approve or reject them. I can think of a couple ways to represent this:

Two boolean flags: Seen/Unseen and Approved/Rejected.  This is the simplest and probably the smallest database solution (presumably boolean fields are simple bits).  The downside is that there are really only three states I care about (unseen/approved/rejected) and this creates four states, including one I don't care about (a record which is seen but not approved or rejected is essentially unseen).

String column in the DB with constants/enum in application.  Using Rating::APPROVED_STATE within the application and letting it equal whatever it wants in the DB.  This is a larger column in the db and I'm concerned about doing string comparisons whenever I need these records.  Perhaps mitigatable with an index?

Single boolean column, but allow nulls.  A true is approved, a false is rejected.  A null is unseen.  Not sure the pros/cons of this solution.

What are the rules I should use to guide my choice? I'm already thinking in terms of DB size and the cost of finding records based on state, as well as the readability of code the ends up using this structure.

答:
A simple integer column containing a status code would suit.  0 = un-reviewed, 1 = seen, 2 = approved, etc.  Its easy to query.  If you sort the codes in 'order', you can also easily pull back all rows below or above a certain state.

For display purposes, a second table containing the description of each code could be used if needed.


问:
Organization of DLL linked functions
This is a code organization question.

I got my basic code working but when I expand it, it will be terrible. I have a DLL which I don't have a .lib for. Therefore I have to use the whole LoadLibrary()/GetProcAddress() combo. It works great. But this DLL that I'm referencing has 100+ functions. My current process is:

1) Typedef a type for the function. E.g.: typedef short(_stdcall *type1)(void);

2) Assign a function name that I want to use such as type1 function_1;

3) Load the DLL, then do something like: function_1 = (type1)GetProcAddress(hinstLib, "_mangled_funcName@5");

Normally I would like to do all of my function definitions in a header file but because I have to use the load library function, its not that easy. The code will be a mess. Right now I'm doing (1) and (2) in a header file and was considering making a function in another .cpp file to do the load library and dump all of the (3)'s in there. I considered using a namespace for the functions so I can use them in the main function and not have to pass over to the other function.

Any other tips on how to organize this code? My goals are to be able to use function_1 as a regular function in the main code. If I have to a ref::function_1 that would be okay but I would prefer to avoid it. This code for all practical purposes is just plain C at the moment.

答: Create a compact meta format (AKA a DSL) for describing the function signatures and write a code generator which reads that meta-format and produces all of the needed headers and cpp files for the loadLibrary code. So you don't have to bother with the readability of the C or C++ code too much, just make sure your meta-format is well readable.</p>

Title: Organization of DLL linked functions


答:
Legacy code base usually refers not to a POS system, but rather any system that exists in a code base or system that is no longer used for new development.  For instance my team currently supports a few .net 1.1 and 2.0 applications that are considered legacy code.  If there comes a time where a modification is required they will be either rewritten or updated to use the latest frameworks and standards.  Until then we manage them as legacy applications that need to continue to function but no enhancements or code fixes are implemented.

There are also a few legacy systems that we do not support at all that were written in VB6 and Classic ASP.  We have no capacity, or directive to support or modify these systems but as long as they continue to run and have no needs for enhancements they will not likely be updated.  There is nothing particularly wrong with any of these systems.  They perform their jobs the way they are supposed to and aside from looking like an app from the mid to late 90's they have no major issues.

So legacy does not mean POS just a system that was created in an earlier technology or language that is not up to current standards.  Some legacy systems qualify as POS mostly because they lacked the development methodologies that exist to day that allow for managed code and the 15+ years of experience of the veteran web coders.

Title: What is the origin of the negative term "legacy code"

Body:
Everyone talks about legacy code in software development and I have heard the term over the last ten years used to paint any codebase as being bad.

Where did this term, which has such powerful connotations to programmers alike originate?

I am sure there must be some book on software development that pioneered this term. I would love to locate the origin of the term "legacy code".


答:
I'd separate the two behaviours
The first is getting a number for the user, the second is validating it and eventually re-asking it
So I'd go like this
<code>
int number = 0;
print "Enter number";
number = getInput();
while(number != 0) {
    print "Error!";
    number = getInput();
}
</code>
Maybe you could not like the double input line, but I think it's a nice trade off </p>

Body:
I'd separate the two behaviours
The first is getting a number for the user, the second is validating it and eventually re-asking it
So I'd go like this

int number = 0;
print "Enter number";
number = getInput();
while(number != 0) {
    print "Error!";
    number = getInput();
}

Maybe you could not like the double input line, but I think it's a nice trade off


问:
Improving the running time of Breadth First Search and Adjacency List creation
We are given an array of integers where all elements are between 0-9. have to start from the 1st position and reach end in minimum no of moves such that we can from an index i move 1 position back and forward i.e i-1 and i+1 and jump to any index having the same value as index i.

Time Limit : 1 second

Max input size : 100000

I have tried to solve this problem use a single source shortest path approach using Breadth First Search and though BFS itself is O(V+E) and runs in time the adjacency list creation takes O(n2) time and therefore overall complexity becomes O(n2). is there any way i can decrease the time complexity of adjacency list creation? or is there a better and more efficient way of solving the problem?

```<code>int main(){

    vector<int> v;
    string str;
    vector<int> sets[10];

    cin>>str;
    int in;
    for(int i=0;i<str.length();i++){
        in=str[i]-'0';
        v.push_back(in);
        sets[in].push_back(i);
    }

    int n=v.size();
    if(n==1){
        cout<<"0\n";
        return 0;
    }
    if(v[0]==v[n-1]){
        cout<<"1\n";
        return 0;
    }

    vector<int> adj[100001];
    for(int i=0;i<10;i++){
        for(int j=0;j<sets[i].size();j++){
            if(sets[i][j]>0)
                adj[sets[i][j]].push_back(sets[i][j]-1);
            if(sets[i][j]<n-1)
                adj[sets[i][j]].push_back(sets[i][j]+1);
            for(int k=j+1;k<sets[i].size();k++){
                if(abs(sets[i][j]-sets[i][k])!=1){
                    adj[sets[i][j]].push_back(sets[i][k]);
                    adj[sets[i][k]].push_back(sets[i][j]);
                }
            }
        }
    }

    queue<int> q;
    q.push(0);

    int dist[100001];
    bool visited[100001]={false};
    dist[0]=0;
    visited[0]=true;

    int c=0;
    while(!q.empty()){
        int dq=q.front();
        q.pop();
        c++;

        for(int i=0;i<adj[dq].size();i++){
            if(visited[adj[dq][i]]==false){
                dist[adj[dq][i]]=dist[dq]+1;
                visited[adj[dq][i]]=true;
                q.push(adj[dq][i]);
            }
        }

    }

    cout<<dist[n-1]<<"\n";

    return 0;
}
</code>```

答:
Key insight: there's no need to eagerly construct the adjacency list.  In fact, there's no need to ever construct the adjacency list; you just need a way to find the next nodes.  With this insight, we can construct an efficient version of the search.

Lazy edges

For any given node, finding indices i+1 and i-1 is trivial.  Finding nodes that have the same value merely requires a lookup in the sets datastructure you've already created.

The rest of your breadth first search still applies equally; you mark off nodes you've already seen to make sure you don't revisit them.

Grouped values

Note that there's really no reason to return to a value once you've left it.  Any path that reaches an X-valued index can reach any other X-valued index on the next step.  That means your maximum path is 19 (each value can occur at most twice for a 20 nodes i.e. 19 edges along the path).

However, it it also means you don't want the following to occur:

you're at index K with value X, and iterate over all other indices with value X, marking them as visited, and adding them to the queue

you eventually reach each one of those X-valued indices in the queue, and iterate over everything it can reach, i.e. all those other X's - even though they've all been visited, and you already know you're not going to add them to the queue.

So you're doing quadratic work (each instance of a value iterates over each instance of the same value) and it's obviously pointless to boot.  Once you process an X-valued index and thus visit all other X's, you know you'll never need to follow an X->X edge again.  Easy fix? Just empty the list of indices by that value once you've processed one.

This new algorithm is linear time:

reading the input is linear

building sets is linear (each index is inserted once)

each index can be "processed" (added to the queue) at most once, so that's linear.

each index can be "visited" (checking the visited array) at most three times: once by i-1, once by 1+1, and once by some other identically valued index.

If you really want, you can possibly shave off a bit of the constant factor here.  After all, the final path will pass through each value once (and when it does, touching one or two indexes for that value).  You can therefore construct a much, much smaller graph of how values can reach each other; solving that for the shortest paths is essentially free (at most 10 nodes, after all), and a shortest path through the indexes must be the shortest path through the values (proof left to reader, but note that any shortcut via i+1/i-1 costs at least a step, but can never win more than a step).  Then, when you solve the bigger graph of indices, you don't need to bother taking any steps that conflict with what you already know of the solution; i.e. don't enqueue any indices that have a value other than your own or the "next" value along any shortest path in the value graph. (In essence, this optimization is A*).

Similarly, you could segment your queue by value and distance, and skip processing the rest of the current value with greater distance once you've found a way to the next.

Such trickery is almost certainly not worth it, but hey, it's possible :-).

Coding Style:  I'd suggest naming your variables after what they represent.  Your code is a little hard to follow because it contains things like sets (of what? why? - oh it's a way to lookup indices having a value), and a queue q (again, what's this mean? oh it's the reachable set in order of distance).  Give meaningful concepts (that you repeat in the code) like adj[dq][i] a name.  It's the neighbor you're going to visit.  This algorithm is so simple, it's eventually clear, but there's no reason it shouldn't be clear right away.

TL;DR

Don't precompute edges, instead compute reachability when needed.

Empty the set of indices you use to compute value-to-value reachability after using it once to avoid quadratic behavior.

The result is O(N).


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答:
I think other people nicely point out how to deal with it in a professional manner.
I would like to say how to deal with the personal feeling like frustration, fear.

Bottom line is you will be FINE even if you do not resolve issues in timely manner.
Life goes on.

Sometimes, the schedule would be pushed. The project would be either successful of failed.
You may be fired and then have great job. You just never know.

Don't get me wrong.
It does't mean it is OK to let the problem be there.
All we can do is doing my best and let it go.

Sometimes, I think the frustration, fear not solving problem is my life as a average developer.


答:
A code generator script would be a very neat solution, you should investigate.

If you want to stick to C only, you could probably clean up the code a bit using a couple macros. Maybe one to declare the typedef and the variable in one go, similar to this:

```<code>#define FUNC_DECL(retType, name, param)\
     typedef retType (_stdcall * name##_f)(param);\
     name##_f name;
</code>```

And one to initialize the variable in a cleaner way:

```<code>#define FUNC_LOAD(name, lib)\
     name = (name##_f)GetProcAddress(lib);
</code>```

So you would now just need to add a FUNC_DECL(function_X) in the global scope of a C file
and call FUNC_LOAD(function_X, lib) in some initialization function.
You would still have to declare an extern statement in a header file however, if function_X is to be visible elsewhere. E.g.: extern function_X_f function_X;

Title: Organization of DLL linked functions

Body:
This is a code organization question.

I got my basic code working but when I expand it, it will be terrible. I have a DLL which I don't have a .lib for. Therefore I have to use the whole LoadLibrary()/GetProcAddress() combo. It works great. But this DLL that I'm referencing has 100+ functions. My current process is:

1) Typedef a type for the function. E.g.: typedef short(_stdcall *type1)(void);

2) Assign a function name that I want to use such as type1 function_1;

3) Load the DLL, then do something like: function_1 = (type1)GetProcAddress(hinstLib, "_mangled_funcName@5");

Normally I would like to do all of my function definitions in a header file but because I have to use the load library function, its not that easy. The code will be a mess. Right now I'm doing (1) and (2) in a header file and was considering making a function in another .cpp file to do the load library and dump all of the (3)'s in there. I considered using a namespace for the functions so I can use them in the main function and not have to pass over to the other function.

Any other tips on how to organize this code? My goals are to be able to use function_1 as a regular function in the main code. If I have to a ref::function_1 that would be okay but I would prefer to avoid it. This code for all practical purposes is just plain C at the moment.

Body:
A code generator script would be a very neat solution, you should investigate.

If you want to stick to C only, you could probably clean up the code a bit using a couple macros. Maybe one to declare the typedef and the variable in one go, similar to this:

#define FUNC_DECL(retType, name, param)\
     typedef retType (_stdcall * name##_f)(param);\
     name##_f name;

And one to initialize the variable in a cleaner way:

#define FUNC_LOAD(name, lib)\
     name = (name##_f)GetProcAddress(lib);

So you would now just need to add a FUNC_DECL(function_X) in the global scope of a C file
and call FUNC_LOAD(function_X, lib) in some initialization function.
You would still have to declare an extern statement in a header file however, if function_X is to be visible elsewhere. E.g.: extern function_X_f function_X;


问:
Multiple attribution in Python, JS, ...?
I accidentally discovered this a=b=c=d=e=f=2 in python(2.7)(and JavaScript a few minutes later) interpreter .

Is this a feature or just the way the interpreter works, if is a feature how it is called ?

Do other languages have this feature ?

答:
Assignments like these are OK for simple objects. For others, it can lead to undesirable side effects. In linked list the example below, in the line:

```<code>last = last.nxt = Item(2)
</code>```

We may expect that Item(1).nxt points to Item(2) and last points to Item(2)
However, we end up with a circular reference where Item(2).nxt points to itself.

For example:

```<code>class Item(object):
    def __init__(self, value):
        self.value = value
        self.nxt = None

    def __str__(self):
        return 'self: id(self): %d, value: %s, nxt: %d' % (id(self), \
                str(self.value), id(self.nxt))

 prev = last = Item(1)

 print prev
 >>> self: id(self): 140382915976272, value: 1, nxt: 9568656
 print last
 >>> self: id(self): 140382915976272, value: 1, nxt: 9568656
 print id(None)
 >>> 9568656

 last = last.nxt = Item(2)
 print prev
 >>> self: id(self): 140382915976272, value: 1, nxt: 9568656
 print last
 >>> self: id(self): 140382915975120, value: 2, nxt: 140382915975120
</code>```

Body:
Assignments like these are OK for simple objects. For others, it can lead to undesirable side effects. In linked list the example below, in the line:

last = last.nxt = Item(2)

We may expect that Item(1).nxt points to Item(2) and last points to Item(2)
However, we end up with a circular reference where Item(2).nxt points to itself.

For example:

class Item(object):
    def __init__(self, value):
        self.value = value
        self.nxt = None

    def __str__(self):
        return 'self: id(self): %d, value: %s, nxt: %d' % (id(self), \
                str(self.value), id(self.nxt))

 prev = last = Item(1)

 print prev
 >>> self: id(self): 140382915976272, value: 1, nxt: 9568656
 print last
 >>> self: id(self): 140382915976272, value: 1, nxt: 9568656
 print id(None)
 >>> 9568656

 last = last.nxt = Item(2)
 print prev
 >>> self: id(self): 140382915976272, value: 1, nxt: 9568656
 print last
 >>> self: id(self): 140382915975120, value: 2, nxt: 140382915975120


问:
Modern.IE VM license
Microsoft provides some VMs for testing purposes (advertised on Stack Overflow) and I'm trying to understand the license terms. The one I don't really understand is

1.b. You may use the software for testing purposes only. You may not  use the software for commercial purposes.

My thoughts:

Testing a website in several browsers on several different virtual machines seems a quite professional approach. I hardly believe many private developers would do that. Of course they should, but which private developer has the time to do so?

If that's really only available to private developers, what is the offer to companies doing the same thing? I am missing the advertisement for a paid service.

Is testing by a company considered a commercial purpose? Can I use the VMs within a company for testing or not?

答:
I can see where this would be confusing for a non-native speaker of English.

Microsoft sees three general environments:

Development

Test

Production

You may use the virtual machines for the middle environment, but not the first or third.

The production environment is presumably the one used to generate revenue (make money) or is the one used for commercial purposes.

So they are happy for you to test like crazy and for free, but when you develop1 or start trying to make money off of the product then they want to be paid for their product.

1 Develop in this case would be a bit difficult as the VMs don't contain any development tools.  You could install development tools on a VM, but you would be violating the terms of service.

Title: Modern.IE VM license


问:
What is decoupling and what development areas can it apply to?
I recently noticed decoupling as a topic in a question, and want to know what it is and where it can apply.

By "where can it apply", I mean:

Is it only relevant where compiled languages like C and Java are involved?

Should I know about / study it as a web developer?

答:
'Coupling' is a term that describes the relationship between two entities in a software system (usually classes).

When a class uses another class, or communicates with it, it's said to 'depend' on that other class, and so these classes are 'coupled'. At least one of them 'knows' about the other.

The idea is that we should try to keep the coupling between classes in our systems as 'loose' as possible: hence 'loose coupling' or sometimes 'decoupling' (although in English 'decoupling' would mean 'no coupling at all', people often use it to imply 'loose coupling' between entities).

So: what is loose-coupling versus strong coupling in practice, and why should we make entities loosely-coupled?

Coupling describes the degree of dependency between one entity to another entity. Often classes or objects.

When ClassA depends heavily on ClassB, the chances of ClassA being affected when ClassB is changed are high. This is strong coupling.

However if ClassA depends lightly on ClassB, than the chances of ClassA being affected in any way by a change in the code of ClassB, are low. This is loose coupling, or a 'decoupled' relationship.

Loose coupling is good because we don't want the components of our system to heavily depend on each other. We want to keep our system modular, where we can safely change one part without affecting the other.

When two parts are loosely coupled, they are more independent of each other and are less likely to break when the other changes.

For example, when building a car, you wouldn't want an internal change in the engine to break something in the steering wheel.

While this would never happen by accident when building a car, similar things happen to programmers all the time. Loose coupling is meant to reduce the risk of such things happening.

Strong coupling usually occurs when entity A knows too much about entity B. If entity A makes too many assumptions about how entity B operates or how it is built, then there is a high risk that a change in entity B will affect entity A. This is because one of its assumptions about entity B are now incorrect.

For example, imagine that as a driver, you would make certain assumptions about how the engine of your car works.

The day you buy a new car with an engine that works differently (or for some reason your engine was replaced), your previous assumptions would be incorrect. If you were code in a computer, you would now be incorrect code that doesn't work properly.

However, if all the assumptions that as a driver you made about cars is that: A- they have steering wheels and B- they have brake and gas pedals, then changes in the car won't affect you, as long as your few assumptions stay correct. This is loose coupling.

An important technique to achieve loose coupling is Encapsulation. The idea is that a class hides its internal details from other classes, and offers a strictly defined interface for other classes to communicate with it.

So for example, if you were defining a class Car, it's interface (public methods) would probably be drive(), stop(), steerLeft(), steerRight(), getSpeed(). These are the methods other objects can invoke on Car objects.

All of the other details of the Car class: how the engine works, kind of fuel it uses, etc. are hidden from other classes - to prevent them from knowing too much about Car.

The moment class A knows too much about class B: we have a strongly coupled relationship, where class A is too dependent on class B and a change in class B is likely to affect class A. Making the system hard to expand and maintain.

A relationship between two entities, where they know little about each other (only what's necessary) - is a loosely coupled, or decoupled relationship.

ContentLicense: CC BY-SA 4.0


问:
Is it possible to have a mutable type that is not garbage collected?
I'm wondering if such a thing can exist.  Can there be an object that is mutable but not  flagged as garbage collected ( specifically, tp_flags & Py_TPFLAGS_HAVE_GC )

I have a C++ struct-like object that I'm writing and I'd like to know if all of its members are immutable.  I'm thinking of checking for the Py_TPFLAGS_HAVE_GC flag to determine this.  If all members are immutable I want to speed up the deepcopy by doing a faster shallow copy, since I know members are immutable then it shouldn't have to go through an expensive deep copy.

Is this logically sound, or is there some mythical type that will blow me out of the water here.

答:
Firstly, any number of types created by extensions can not bother to implement GC, despite being mutable.

Secondly, a mutable type that doesn't contain other objects doesn't need to implement GC to avoid the creation of cycles. Thus you can't assume they will. For a specific example, see the array.array type.

Thirdly, just because an object is immutable doesn't mean it can't contain a mutable object. E.g., consider ([],).


答:
Since you want to follow best practices then using search engine like ElasticSearch or Solr. Not only they are fast and manage their own caches, they're also better equipped with different kinds of search methods.

Using/managing your own cache is a good idea too but I'd leave that as an optimisation rather than solution to your problem (searching) because it only gives you speed but not ease of searching.

For example, right now you only want to search location by user search string. If later you want to search location by geocode (because mobile clients can send their location) you will need to write your own solution if you want to use your DB. That kind of search is available from search engines. Other type of search that you might want to do is faceted search and there are more methods (like similar sounding string, etc.)

The hassle of going with using search engine is having to keep everything updated on both the database and the search engine. But it's a small price to pay.

Title: Best practices for caching search queries

Body:
I am trying to improve performance of my ASP.net Web Api by adding a data cache but I am not sure how exactly to go about it as it seems to be more complex than most caching scenarios. An example is I have a table of Locations and an api to retrieve locations via search, for an autocomplete.

```<code>/api/location/Londo
</code>```

and the query would be something like

```<code>SELECT * FROM Locations WHERE Name like 'Londo%'
</code>```

These locations change very infrequently so I would like to cache them to prevent trips to the database for no real reason and improve the response time.

Looking at caching options I am using the Windows Azure Appfabric system, the problem is it's just a key/value cache. Since I can only retrieve items based on keys I couldn't actually use it for this scenario as far as Im aware.

Is what I am trying to do bad use of a caching system? Should I try looking into NoSql DB which could possibly run as a cache for something like this to improve performance? Should I just cache the entire table/collection in a single key with a specific data structure which could assist with the searching and then do the search upon retrieval of the data?


答:
Decoupling is generally all about seeing whether or not two things need to closely work together or can be further made independent. Independence is great because it makes those things easy to change or use somewhere else. Decoupling can be applied in many areas, not only development, and this is especially true for temporal decoupling, which can even be applied in your daily life (to some extent). Also noting, there are many types of coupling in software development to consider, and not all will be covered in the answer. You will have to do your research.

Two things, A and B, are coupled if there's a dependency between them. If A depends on B, you can use B without taking A into consideration. If you want to use A, you will have to also carry B over, as A depends on it.

In software development, usually, you can't remove coupling between components completely. Decoupling in that context normally means loosening the existing coupling. That is, making sure each component knows as little as possible about the other components around it.

This is probably the most common type of coupling found in the wild:

```<code>//Inside a class meant to display info for a particular Facebook user.
void DisplayFriends(FacebookUser user, FacebookClient client)
{
     Friend[] = (Friend[])client.GetConnection().ExecuteCommandForResult("getFriends:" + user.Name);
     ...
}
</code>```

Here DisplayFriends is needlessly manually operating with the connection behind the Facebook client in order to get what it needs. DisplayFriends's class is coupled to both FacebookClient and Connection. If FacebookClient suddenly changes the kind of connection it uses, the app won't be able to get the Facebook friends anymore. We can remove the coupling between DisplayFriends' class and Connection by asking FacebookClient to provide what we need for us.

```<code>//Inside a class meant to display info for a particular Facebook user.
void DisplayFriends(FacebookUser user, FacebookClient client)
{
     Friend[] = client.GetFriends(user);
     ...
}
</code>```

Now we don't really care how FacebookClient gets our friends. All we really care about is the fact that it gets them. Any change brought to its internal behavior won't damage our own class.

This kind of decoupling can be easily achieved by following the Law of Demeter for functions, which says (quoting Wikipedia):

The Law of Demeter for functions requires that a method m of an object
  O may only invoke the methods of the following kinds of objects:

O itself

m's parameters

Any objects created/instantiated within m

O's direct component objects

A global variable, accessible by O, in the scope of m

Since I mentioned about temporal coupling in the beginning of the answer, I'm going to shortly describe it.

Temporal coupling is normally considered when designing applications that execute algorithms in parallel. Consider two executable units (be them actual instructions, methods, or whatever you wish to consider a unit to be), A and B. We say A is temporally coupled to B if B must be executed before A is executed. If A is not temporally coupled to B, A and B can be executed at the same time. Build your own example for this one: think of the usual things you do in your daily life. Are there any two things that you do one after the other, but you could do at the same time?

Finally, to answer your last bit:

Should I know about / study it as a web developer?

Yes. For example, one of the most popular design patterns for web development (MVC) is all about decoupling.

Title: What is decoupling and what development areas can it apply to?

Body:
I recently noticed decoupling as a topic in a question, and want to know what it is and where it can apply.

By "where can it apply", I mean:

Is it only relevant where compiled languages like C and Java are involved?

Should I know about / study it as a web developer?

Body:
Decoupling is generally all about seeing whether or not two things need to closely work together or can be further made independent. Independence is great because it makes those things easy to change or use somewhere else. Decoupling can be applied in many areas, not only development, and this is especially true for temporal decoupling, which can even be applied in your daily life (to some extent). Also noting, there are many types of coupling in software development to consider, and not all will be covered in the answer. You will have to do your research.

Two things, A and B, are coupled if there's a dependency between them. If A depends on B, you can use B without taking A into consideration. If you want to use A, you will have to also carry B over, as A depends on it.

In software development, usually, you can't remove coupling between components completely. Decoupling in that context normally means loosening the existing coupling. That is, making sure each component knows as little as possible about the other components around it.

This is probably the most common type of coupling found in the wild:

//Inside a class meant to display info for a particular Facebook user.
void DisplayFriends(FacebookUser user, FacebookClient client)
{
     Friend[] = (Friend[])client.GetConnection().ExecuteCommandForResult("getFriends:" + user.Name);
     ...
}

Here DisplayFriends is needlessly manually operating with the connection behind the Facebook client in order to get what it needs. DisplayFriends's class is coupled to both FacebookClient and Connection. If FacebookClient suddenly changes the kind of connection it uses, the app won't be able to get the Facebook friends anymore. We can remove the coupling between DisplayFriends' class and Connection by asking FacebookClient to provide what we need for us.

//Inside a class meant to display info for a particular Facebook user.
void DisplayFriends(FacebookUser user, FacebookClient client)
{
     Friend[] = client.GetFriends(user);
     ...
}

Now we don't really care how FacebookClient gets our friends. All we really care about is the fact that it gets them. Any change brought to its internal behavior won't damage our own class.

This kind of decoupling can be easily achieved by following the Law of Demeter for functions, which says (quoting Wikipedia):

The Law of Demeter for functions requires that a method m of an object
  O may only invoke the methods of the following kinds of objects:

O itself

m's parameters

Any objects created/instantiated within m

O's direct component objects

A global variable, accessible by O, in the scope of m

Since I mentioned about temporal coupling in the beginning of the answer, I'm going to shortly describe it.

Temporal coupling is normally considered when designing applications that execute algorithms in parallel. Consider two executable units (be them actual instructions, methods, or whatever you wish to consider a unit to be), A and B. We say A is temporally coupled to B if B must be executed before A is executed. If A is not temporally coupled to B, A and B can be executed at the same time. Build your own example for this one: think of the usual things you do in your daily life. Are there any two things that you do one after the other, but you could do at the same time?

Finally, to answer your last bit:

Should I know about / study it as a web developer?

Yes. For example, one of the most popular design patterns for web development (MVC) is all about decoupling.


问:
Should I ditch AJAX in client side web development when I've got a web-socket open?
I was thinking that maybe I should forget AJAX (HTTP) requests when I've got a web-socket open between client and server, but I decided I should ask here to check if this could be a bad practice for some reason that I'm not thinking of.

Once the socket is open, there's less syntax (often meaning simpler error handling) involved in passing information between client and server with Socket.io (just one example of a web-socket).

Is there some obvious situation where a web-socket (Socket.io for example) isn't going to be capable of handling a functionality that an AJAX request could do easily?

答:
If you simply want to remove AJAX in favor of Web Sockets, there must be one problem: what if the client doesn't support Web Sockets?

If, on the other hand, you keep AJAX requests if there is no active Web Sockets connection, and use Web Sockets otherwise, then it might make the architecture more difficult to follow. More code written means more code to maintain and more chances to have bugs.

The additional concerns I can think of:

If you have a lot of visitors, Web Sockets server may become quite unresponsive. Keeping AJAX and Web Sockets apart would mean that while notifications may be delayed, the web interface will still feel responsive.

Taking Stack Exchange as an example, I would hardly notice the Web Sockets delay if my answer is upvoted by somebody at 3:35:17.624 and I see this upvote in my browser only at 3:35:24.501. On the other hand, when I upvote a question and the AJAX request takes 7 seconds, I'll go and check whether my internet connection is ok.

Web Sockets connection takes time to open (two to four seconds on websites I've worked on, 1.5 s. on Stack Exchange). Freezing all AJAX for, say, two seconds every time the page is loaded may not be always acceptable UX-wise.

Finally, it strongly depends on the context and the actual AJAX requests. For example, I would easily imagine all AJAX queries on chat site being moved to Web Sockets (if this is the technology used for chatting there), since the essential features of the website rely any way on Web Sockets. On the other hand, moving AJAX queries to Web Sockets for an e-commerce website (where cart is managed through AJAX) would be really weird in a context where Web Sockets were previously used only for live customer support.


答: Automata Theory and FSM. :-)</p>

Title: What is the one bit of computer science theory I should know?

Body:
Speaking as someone with an Electronic Engineering rather than Computer Science degree, what is the one bit of computer science I should know to make me a better real world programmer?

(By real world I mean something I'm going to use and benefit from in my day to day job as a programmer - for instance I'd suggest understanding database normalisation is of more practical use than understanding a quick sort for which there are lots of libraries).

Body: Automata Theory and FSM. :-)


答: I think it's easy to see websockets as simply upgraded AJAX so the natural question is "Why not use websockets for everything?" While it's true you could use them for everything (more or less), it might be good to think about the original intent. AJAX was really good at grabbing resources asynchronously and doing something once complete. Then came COMET etc as a way to bypass the shortcomings of AJAX, etc. And then now we have websockets as the next step of that. But that doesn't change the fact that AJAX is great for asynchronously fetching resources - perhaps even plain old static files - and then closing. Websockets are great for persistent connections that need low latency.

Title: Should I ditch AJAX in client side web development when I've got a web-socket open?

Body:
I was thinking that maybe I should forget AJAX (HTTP) requests when I've got a web-socket open between client and server, but I decided I should ask here to check if this could be a bad practice for some reason that I'm not thinking of.

Once the socket is open, there's less syntax (often meaning simpler error handling) involved in passing information between client and server with Socket.io (just one example of a web-socket).

Is there some obvious situation where a web-socket (Socket.io for example) isn't going to be capable of handling a functionality that an AJAX request could do easily?


答: "Legacy code" is a term used by marketing people to pressure those whose code is old (but presumably works fine) into updating to the latest greatest (and probably more bug-ridden) software languages and techniques.  It is closely linked to "legacy system", which refers to old hardware and operating systems that work fine but don't conform to what is now "politically correct" (e.g. OpenVMS, IBM system). </p>


问:
blurry lines between web application context layer, service layer and data access layer in spring
I'll admit I'm a spring newbie, but you can correct me if I'm wrong, this one liner looks kinda fishy in a best practices sort of way:

```<code>@RepositoryRestResource(collectionResourceRel="people"...)
public interface PersonRepository
extends PagingAndSortingRepository<Person, Long>
</code>```

For those who are unaware, the following does many things: It is an interface definition that can be registered in an application context as a jpa repository, automagically hooking up all the default CRUD operations within a persistence context (that is externally configured). and also configures default controller/request-mapping/handler functionality at the namespace "/people" relative to your configured dispatcher servlet-mapping.

Here's my point. I just crossed 3 conceptual layers with one line of code! this feels against my seperation-of-concern instincts but i wanted to hear your opinion. And for the sake of being on a question and answer site, I would like to know whether there is a better way of seperating these different layers - Service, Data, Controllers - whilst maintaining as minimal configuration as possible

答:
I've never used that annotation myself, and I suspect its for entirely the reason you've described. Yes you have a totally valid concern there. At a minimal level, just use @Repository, @Service, @Controller with <context:component-scan base-package="your.base.package" />.  You can use generics at a DAO level if you want to create generic CRUD operations.

That annotation (I suspect), seems like it was designed to be used in Spring Security when trying to authenticate users using a REST call.

However I wouldn't be using that particular annotation in my application at all for exactly the reason you describe.


问:
Continuous Integration using Docker
One of the main advantages of Docker is the isolated environment it brings, and I want to leverage that advantage in my continuous integration workflow.

A "normal" CI workflow goes something like this:

Poll repository for changes

Pull from repository

Install dependencies

Run tests

In a Dockerized workflow, it would be something like this:

Poll repository for changes

Pull from repository

Build docker image

Run docker image as container

Run tests

Kill docker container

My problem is with the "run tests" step: since Docker is an isolated environment, intuitively I would like to treat it as one; this means the preferred method of communication are sockets. However, this only works well in certain situations (a webapp, for example). When testing different kind of services (for example, a background service that only communicated with a database), a different approach would be required.

What is the best way to approach this problem? Is it a problem with my application's design, and should I design it in a more TDD, service-oriented way that always listens on some socket? Or should I just give up on isolation, and do something like this:

Poll repository for changes

Pull from repository

Build docker image

Run docker image as container

Open SSH session into container

Run tests

Kill docker container

SSH'ing into the container seems like an ugly solution to me, since it requires deep knowledge of the contents of the container, and thus break the isolation.

I would love to hear SO's different approaches to this problem.

答:
You may invert the logic by moving test runner to the docker image:

Tests are run within the docker image, so they access the application like in any other context, and the presence of docker doesn't change anything.

Aggregating test results is where connection becomes an issue. The actual technology used will depend on your current infrastructure. It may as well be a message queue, a custom API or a direct access to the database.

Since it belongs to the process which runs inside a docker image to report the test results, and not to the central service to pull the results from the test runners, it means that again, the presence of docker image doesn't make any difference.

Title: Continuous Integration using Docker


问:
If immutable objects are good, why do people keep creating mutable objects?
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.

答:
Check this blog post: http://www.yegor256.com/2014/06/09/objects-should-be-immutable.html. It summarizes why immutable objects are better than mutable. Here is a short list of arguments:

immutable objects are simpler to construct, test, and use

truly immutable objects are always thread-safe

they help to avoid temporal coupling

their usage is side-effect free (no defensive copies)

identity mutability problem is avoided

they always have failure atomicity

they are much easier to cache

People are using mutable objects, as far as I understand, because they are still mixing OOP with imperative procedural programming.


答:
The "seek help" answers are definitely correct.  It is highly unlikely that you are the first person to ever encounter a particular problem.

But as a though experiment, what if there is no help?  What if you must solve the problem on your own?  The most important problem solving ability is the ability to identify and challenge your own assumptions.  If you can enumerate your assumptions about a problem one-by-one and eliminate each in turn, you will eventually come upon the errant assumption and new possibilities for a solution will open up as a result.

(By the way, this is also the best approach when you can't see an answer to a problem you get in a job interview.  Verbally list out your assumptions, and determine which one is wrong and then re-attack the problem.  Almost all "trick questions" are based upon natural yet faulty assumptions).

Title: What happens if you're unable to solve a problem?

Body:
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?


问:
What are the differences between a while loop and a for loop?
What are the differences between a while loop and a for loop? It seems to me that they are the same.</p>

答:
There is a fundamental difference between the two: with a for loop, you need to know beforehand how often the loop body will be executed. This is a major restriction, since there are many problems where you simply don't know that. Sometimes you don't even know whether or not that number is finite at all!

Consider, for example, a program asking the user to input a series of names. Say, a patient management system for a dentist. How would you know beforehand how many patients the dentist is going to enter? You don't! You can't write a for loop for that.


答:
The term legacy code dates to at least 1989 as used by Glenn Everhart in comp.sys.amiga:

(...by the way, yes, I do sometimes program in C also...but I find it easier
  to convert legacy code w/o changing its language...)

I found nothing verifiably earlier in Google Books.


问:
Prefer class members or passing arguments between internal methods?
Suppose within the private portion of a class there is a value which is utilized by multiple private methods.  Do people prefer having this defined as a member variable for the class or passing it as an argument to each of the methods - and why?

On one hand I could see an argument to be made that reducing state (ie member variables) in a class is generally a good thing, although if the same value is being repeatedly used throughout a class' methods it seems like that would be an ideal candidate for representation as state for the class to make the code visibly cleaner if nothing else.

Edit:

To clarify some of the comments/questions that were raised, I'm not talking about constants and this isn't relating to any particular case rather just a hypothetical that I was talking to some other people about.

Ignoring the OOP angle for a moment, the particular use case that I had in mind was the following (assume pass by reference just to make the pseudocode cleaner)

```<code>int x
doSomething(x)
doAnotherThing(x)
doYetAnotherThing(x)
doSomethingElse(x)
</code>```

So what I mean is that there's some variable that is common between multiple functions - in the case I had in mind it was due to chaining of smaller functions.  In an OOP system, if these were all methods of a class (say due to refactoring via extracting methods from a large method), that variable could be passed around them all or it could be a class member.

答:
Thanks for asking the question, I wanted to ask this also.

When I was thinking about this, there are some advantages in why to pass it as argument

it's easier to test -> easier to maintain (related to last point)

has no side effects

it's easier to understand

I clearly see your point for example - one is parsing Excel document (using POI library for example) and instead of passing row instance to every method that needs to work with that row, author has member variable currentRow and works with it.

I'd say there should be a name for this anti-pattern, is it? (not listed here)


答:
The other answers do a good job of describing what decoupling is. I wanted to discuss your final question.

Should I know about / study it as a web developer?

The answer is an emphatic yes. It doesn't matter what kind of developer you are. You could be a web developer or an embedded systems developer.

Let's say that you have a class that generates custom URLs that are placed on your web page. You might be tempted to have the class write the URLs directly to the page, placing them in the href of an a tag. This might seem simpler at first. But what happens when you need to make a change to put the links in a email and send them to a user? Your current code wouldn't work because your URL generator is tightly coupled to the web framework you are using.

The better option would be to have a URL generator class that returns the URL as a string. This could be used by your web code and it could also be used by your email code. It may seem like more work upfront to have decoupled code, but the effort pays for itself over time.

Having code that is modularized and decoupled will make your code more understandable, more testable, and more maintainable, no matter what programming domain you are working in.


问:
Who owns the copyright in a patch file?
I'm trying to determine OSS compliance for a body of source code, part of which includes sections from OpenEmbedded, and contains a lot of patch files, as they (seem to) try to adapt various tools.

In these patch files I find a range of copyright possibilities

the patch file removes a hunk of code from an original, hence 90% of the patch file itself is the original code, so the patch file is "derived" and the original copyright still applies

In betweenies

the patch file contains just a few lines of actual patching (or is primarily additions), and has a large number of lines as comment explaining why it is needed. Seems fair to assign the copyright in that file to the patch author, not the original

How should copyright be identified for the inbetweenies? What lines can be drawn?

The tool I am using is insisting on attribution per file, so I have been assessing a "ratio of contribution" for original/patch authors and picking one. Is that a reasonable/fair/legal approach?

Also: I have been applying the merger doctrine the context lines in a patch file (those lines around the actual change). Hence excluding them from "what ratio is original/patch?") and that tends to bias the ratio toward the patch author, not original author - is that fair?

答:
Copyrights can be claimed if you make an attribution that is substantial enough to be considered a work of its own, consisting of "original thought".

As a patch file typically contains two sets of source code (the original code and the code it will be replaced with), there will be multiple persons who can claim copyright on the various sections in the patch file. The original authors can claim copyright on the (substantial) portions of code that are being removed and the authors of the new code can claim copyright on that (if it is substantial enough).

For patch files that don't contain creative work (for example, mechanical replacements), those are not subject to copyright at all.

Title: Who owns the copyright in a patch file?


答:
Disclaimer: I do not know about that annotation so I will rest my answer in your definition.

When programming, we use layers because otherwise, when programming we risk running in a set of known problems. But if that line of code is all what you need to build all the functionality relative to a business object, you will not be programming it anymore, so you do not need to divide the code in layers (because there is no code to be divided).

If it does it all by itself, I would think of it more as Spring providing a "component" that is external to your application.

As an example, if you were using an LDAP client to manage your users and permissions, you would not worry that by using that client you are "crossing" conceptual layers. That is an issue "internal" to the LDAP client/server, and you just use the abstraction of the LDAP service.

Of course, before using it, you must decide if these business objects should be accessed directly. I also investigate how this "component" can interact with the rest of the application. At first glance, I can think of these issues:

Do you trust Spring to properly implement the component?

Does it support some kind of integration schema (maybe an observer model, so your business logic can know when an object is modified through the component)?

What would be the steps to take if you want to add, say, a Web UI that access the same data? Would you be able to hook up to the "CRUD methods", or would you have to replicate the functionality?

Title: blurry lines between web application context layer, service layer and data access layer in spring

Body:
I'll admit I'm a spring newbie, but you can correct me if I'm wrong, this one liner looks kinda fishy in a best practices sort of way:

```<code>@RepositoryRestResource(collectionResourceRel="people"...)
public interface PersonRepository
extends PagingAndSortingRepository<Person, Long>
</code>```

For those who are unaware, the following does many things: It is an interface definition that can be registered in an application context as a jpa repository, automagically hooking up all the default CRUD operations within a persistence context (that is externally configured). and also configures default controller/request-mapping/handler functionality at the namespace "/people" relative to your configured dispatcher servlet-mapping.

Here's my point. I just crossed 3 conceptual layers with one line of code! this feels against my seperation-of-concern instincts but i wanted to hear your opinion. And for the sake of being on a question and answer site, I would like to know whether there is a better way of seperating these different layers - Service, Data, Controllers - whilst maintaining as minimal configuration as possible


问:
Regex to String generation
Let's say that we have a regex and an index i.  If we suppose that the set of strings that match our regex are sorted in a lexicographical order, how could we get the i element of this list?

Edit : I added this simple example for more explanation:

input :

```<code>regex="[a-c]{1,2}";
index=4;
</code>```

In this case the ordered list of strings that this regex matches contains the following  elements:

```<code>a
aa
ab
ac
b
ba
bb
bc
c
ca
cb
cc
</code>```

output :

The 4th element, which is ac

ps: It's known that a given regex could match an infinite number of strings.  This shouldn't have an impact on the process of extracting the element in the given finite index.

答:
On their own, regexes are serving the purpose of answering the question: "Given this list of strings as input and this pattern, which subset mathces it?". It does not work backwards i.e. from this regex, start generating strings that match it.

Having said that, take a look at this: https://code.google.com/p/xeger/, that is supposed to do what you want to achieve (with some limitations as described in https://code.google.com/p/xeger/wiki/XegerLimitations).

If your regex is accepted, I guess the anwer to your question is pretty straightforward i.e. generate the list and take the item at index i

Title: Regex to String generation


问:
Use of pirated/cracked software for development
Disclaimer: I by no means condone the use of pirated software.

Have you ever witnessed the use of pirated software for development purposes? May be a company didn't have enough money to buy a piece of software and there were no free alternatives? May be a company wanted to try something out before buying and there were no trial licenses for that product. Whatever the circumstances, have you worked at a company where using pirated/cracked software was accepted? Were there any consequences to doing this?

答:
I worked at a company where there were several copies of a popular CAD program licensed using a keygen floating around, and the word processor, spreadsheet, and mail client programs for nearly the entire company were licensed under a single serial number.  The issue of the unlicensed software was escalated to the VP of the division, and I am unaware of who else was informed.

The problem was promptly tabled due to disbelief that any repercussions would be faced, and the sentiment "we don't have the financial capability to purchase the software at this point in time." About a year after I left the company there I read an article in the local newspaper how my previous employer had settled out of court with the BSA for a six-figure amount.

I think it all depends on the scale and intent of the piracy, morale of employees, and if the victim feels that litigation would recover enough money to make it worth their time.


问:
Designing communications for extensibility
I am working on the design stages of an application that will a) collect data from various sources (in my case that's scientific data from serial ports), keeping track of the age of the data, b) generate real-time statistics (e.g. running averages) c) display, record, and otherwise handle the data (and statistics).

I anticipate that I will be adding both data producers and consumers over time, and would like to design this application abstractly so that I will be able to trivially add functionality with a small amount of interface code. What I'm stumbling on is deciding what communication infrastructure I should use to handle the interfaces. In particular, how should I make the processed data and statistics available to multiple consumers?

Some things I've considered:

Writing to several named pipes (variable number). Each consumer reads from one of them.

Using FUSE to make a userspace filesystem where a read() returns the latest line of data even if another process has already read it.

Making a TCP server, and having consumers connect and request data individually.

Simply writing the consumers as part of the same program that aggregates the data.

So I would like to hear your all's advice on deciding how to interface these functions in the best way to keep them separate and allow room for extenstions.

答: That sounds like a job for a Publish/Subscribe architecture, AKA Reactive programming. Although the title may sound misleading, Enterprise Integration Patterns is an excellent guide in how to build such systems in the large.


问:
Is there an imperative language with a Haskell-like type system?
I've tried to learn Haskell a few times over the last few years, and, maybe because I know mainly scripting languages, the functional-ness of it has always bothered me (monads seem like a huge mess for doing lots of I/O). However, I think it's type system is perfect.

Reading through a guide to Haskell's types and typeclasses (like this), I don't really see a reason why they would require a functional language, and furthermore, they seem like they would be perfect for an industry-grade object-oriented language (like Java). This all begs the question: has anyone ever taken Haskell's typing system and made a imperative, OOP language with it?

If so, I want to use it.

答:
Depends on your definition of OOP, which of course is different from everyone else's. But for whatever it's worth, Standard ML has a module system that is more powerful than Haskell's - in Haskell you can only instantiate a type class once, whereas in SML I can order the integers by their traditional ordering, or by divisibility, or any number of other ways I like. SML isn't object-oriented, in the sense that it doesn't have built-in syntax sugar for objects, but it can still be done. But it's not purely functional either - it won't force you to separate side effects from pure code if you don't want to. OCaml and F# are SML dialects that do have an object system. F# in particular may interest you since it runs on .NET and interoperates with C#.

There's also Scala, which is more "industry-grade object-oriented language" and less SML-like, but still has features from SML-like languages like pattern matching and algebraic data types, and interoperates with Java. You might also be interested in Go, which is the language I'm least familiar with but if I recall correctly has structural subtyping (i.e. you don't declare interfaces up front, having the right interfaces is sufficient) like Standard ML's module system.


问:
Javascript Rookie Question: Define Variables Inline
I'm proficient with HTML and CSS but I'm still pretty shaky when it comes to Javascript. That said, I've been able to build a site using the Internet Archive Book Reader, which relies on reader.js

Here's a copy of one of my versions of reader.js https://gist.github.com/dylan-k/ed4efed2384e221d46cc

It's a good site, but I find I have to repeat things a lot. Basically, I have one copy of reader.js for every page/book featured on the site. It seems there must be a better way. I re-use the script, making copies, just so that I can change lines 28, 80, 83, 84.

Is there a way I could include just one copy of reader.js and then use a

答:
Absolutely!  Modifying javascript libraries is practically a time-honored tradition.

Take a look at one of the lines:

```<code>br.getPageURI = function(index, reduce, rotate) {
    // reduce and rotate are ignored in this simple implementation, but we
    // could e.g. look at reduce and load images from a different directory
    // or pass the information to an image server
    var leafStr = '000000';
    var imgStr = (index+1).toString();
    var re = new RegExp("0{"+imgStr.length+"}$");
    var url = '/exhibitions/bythebook/book8/W922/W922_'+leafStr.replace(re, imgStr) + '_sap.jpg';
    return url;
}
</code>```

A simple and unintrusive way to alter the URL would be to add a parameter.  Consider the following:

```<code>br.getPageURI = function(index, reduce, rotate, baseurl) {
    baseurl = baseurl|| '/exhibitions/bythebook/book8/W922/W922_';
    var leafStr = '000000';
    var imgStr = (index+1).toString();
    var re = new RegExp("0{"+imgStr.length+"}$");
    var url = baseurl + leafStr.replace(re, imgStr) + '_sap.jpg';
    return url;
}
</code>```

This means, replace the base URL with the parameter passed as the fourth parameter.  The first line is essentially a failsafe to ensure that it has a value if no fourth parameter is passed.  You can apply this modification immediately without causing problems elsewhere.  Whenever this method is called, provide the proper fourth parameter.

For lines 80, 83, and 84, you will need to be able to dynamically provide these parameters.  Since this is a static js file, you could either remove the section:

```<code>br.init();

$('#BRtoolbar').find('.read').hide();
$('#textSrch').hide();
$('#btnSrch').hide();
</code>```

And execute it yourself in a script after having included the javascript static file, altering parameters as you see fit:

```<code><script src="static.js"></script>
<script>
    br.bookTitle= 'Dynamic book title here ' + new Date();
    br.bookUrl  = 'http://thewalters.org/exhibitions/bythebook/book8/';

    br.init();

    $('#BRtoolbar').find('.read').hide();
    $('#textSrch').hide();
    $('#btnSrch').hide();
</script>
</code>```

Or, you could wrap the entire object in its own function and call it with the parameters to change:

```<code>// In static js
function MyBookReader(bookTitle, bookUrl) {
    br = new BookReader();

    ...

    br.bookTitle= bookTitle;
    br.bookUrl  = bookUrl;

    br.init();

    $('#BRtoolbar').find('.read').hide();
    $('#textSrch').hide();
    $('#btnSrch').hide();
}

// In script on page
MyBookReader('Tale of two cities', 'http://bookreader-url.com');
</code>```

Hope that helps.

Body:
Absolutely!  Modifying javascript libraries is practically a time-honored tradition.

Take a look at one of the lines:

br.getPageURI = function(index, reduce, rotate) {
    // reduce and rotate are ignored in this simple implementation, but we
    // could e.g. look at reduce and load images from a different directory
    // or pass the information to an image server
    var leafStr = '000000';
    var imgStr = (index+1).toString();
    var re = new RegExp("0{"+imgStr.length+"}$");
    var url = '/exhibitions/bythebook/book8/W922/W922_'+leafStr.replace(re, imgStr) + '_sap.jpg';
    return url;
}

A simple and unintrusive way to alter the URL would be to add a parameter.  Consider the following:

br.getPageURI = function(index, reduce, rotate, baseurl) {
    baseurl = baseurl|| '/exhibitions/bythebook/book8/W922/W922_';
    var leafStr = '000000';
    var imgStr = (index+1).toString();
    var re = new RegExp("0{"+imgStr.length+"}$");
    var url = baseurl + leafStr.replace(re, imgStr) + '_sap.jpg';
    return url;
}

This means, replace the base URL with the parameter passed as the fourth parameter.  The first line is essentially a failsafe to ensure that it has a value if no fourth parameter is passed.  You can apply this modification immediately without causing problems elsewhere.  Whenever this method is called, provide the proper fourth parameter.

For lines 80, 83, and 84, you will need to be able to dynamically provide these parameters.  Since this is a static js file, you could either remove the section:

br.init();

$('#BRtoolbar').find('.read').hide();
$('#textSrch').hide();
$('#btnSrch').hide();

And execute it yourself in a script after having included the javascript static file, altering parameters as you see fit:

<script src="static.js"></script>
<script>
    br.bookTitle= 'Dynamic book title here ' + new Date();
    br.bookUrl  = 'http://thewalters.org/exhibitions/bythebook/book8/';

    br.init();

    $('#BRtoolbar').find('.read').hide();
    $('#textSrch').hide();
    $('#btnSrch').hide();
</script>

Or, you could wrap the entire object in its own function and call it with the parameters to change:

// In static js
function MyBookReader(bookTitle, bookUrl) {
    br = new BookReader();

    ...

    br.bookTitle= bookTitle;
    br.bookUrl  = bookUrl;

    br.init();

    $('#BRtoolbar').find('.read').hide();
    $('#textSrch').hide();
    $('#btnSrch').hide();
}

// In script on page
MyBookReader('Tale of two cities', 'http://bookreader-url.com');

Hope that helps.


问:
Indefinite loops where the first time is different
This isn't a serious problem or anything someone has asked me to do, just a seemingly simple thing that I came up with as a mental exercise but has stumped me and which I feel that I should know the answer to already. There may be a duplicate but I didn't manage to find one.

Suppose that someone asked you to write a piece of code that asks the user to enter a number and, every time the number they entered is not zero, says "Error" and asks again. When they enter zero it stops.

In other words, the code keeps asking for a number and repeats until zero is entered. In each iteration except the first one it also prints "Error".

The simplest way I can think of to do that would be something like the folloing pseudocode:

```<code>int number = 0;
do
{
    if(number != 0)
    {
        print("Error");
    }
    print("Enter number");
    number = getInput();
}while(number != 0);
</code>```

While that does what it's supposed to, I personally don't like that there's repeating code (you test number != 0 twice) -something that should generally be avoided. One way to avoid this would be something like this:

```<code>int number = 0;
while(true)
{
    print("Enter number");
    number = getInput();
    if(number == 0)
    {
        break;
    }
    else
    {
        print("Error");
    }
}
</code>```

But what I don't like in this one is "while(true)", another thing to avoid.

The only other way I can think of includes one more thing to avoid: labels and gotos:

```<code>    int number = 0;
    goto question;
error:
    print("Error");
question:
    print("Enter number");
    number = getInput();
    if(number != 0)
    {
        goto error;
    }
</code>```

Another solution would be to have an extra variable to test whether you should say "Error" or not but this is wasted memory.

Is there a way to do this without doing something that's generally thought of as a bad practice (repeating code, a theoretically endless loop or the use of goto)?

I understand that something like this would never be complex enough that the first way would be a problem (you'd generally call a function to validate input) but I'm curious to know if there's a way I haven't thought of.

答:
You could do something like:</p>

```<code>int number;
while((number = solicitNumber()) != 0) {
    print("Error!");
}

...

int solicitNumber() {
    print("Enter number");
    return getInput();
}
</code>```

Body:
You could do something like:

int number;
while((number = solicitNumber()) != 0) {
    print("Error!");
}

...

int solicitNumber() {
    print("Enter number");
    return getInput();
}


问:
What is the one bit of computer science theory I should know?
Speaking as someone with an Electronic Engineering rather than Computer Science degree, what is the one bit of computer science I should know to make me a better real world programmer?

(By real world I mean something I'm going to use and benefit from in my day to day job as a programmer - for instance I'd suggest understanding database normalisation is of more practical use than understanding a quick sort for which there are lots of libraries).

答:
The Halting Problem

The fact that computer related problems exist that simply cannot be solved by a computer.


答:
A regular expression maps directly to a finite state machine.  Generating strings from the FSM is straightforward with a backtracking algorithm.  The example is for the regular expression /aa?b/</p>

```<code>(start) 0 -- a --> 1 -- a --> 2 -- b --> 3 (accepting and terminal)
                   |                     ^
                   |---------b ----------|

State   Previous char   Input char    Input string     History
  0        null                           --             []
                            a              a
  1        null                                        [{a,1}]
                            a              aa          [{a,1},{a,2}]
  2        null
                            b             aab          [{a,1},{a,2},{b,3}]
  3        null
         Accepting state, emit 'aab' as valid input
         Terminal state, backtrack
  2          b                             aa          [{a,1},{a,2}]
         No further valid inputs, backtrack
  1          a                             a           [{a,1}]
                            b              ab
  3        null                                        [{a,1},{b,3}]
         Accepting state, emit 'ab' as valid input
         Terminal state, backtrack
  1          b                             a           [{a,1}]
         No further valid inputs, backtrack
  0          a                             --          []
         No further valid inputs, stack empty, terminate
</code>```

Title: Regex to String generation

Body:
Let's say that we have a regex and an index i.  If we suppose that the set of strings that match our regex are sorted in a lexicographical order, how could we get the i element of this list?

Edit : I added this simple example for more explanation:

input :

```<code>regex="[a-c]{1,2}";
index=4;
</code>```

In this case the ordered list of strings that this regex matches contains the following  elements:

```<code>a
aa
ab
ac
b
ba
bb
bc
c
ca
cb
cc
</code>```

output :

The 4th element, which is ac

ps: It's known that a given regex could match an infinite number of strings.  This shouldn't have an impact on the process of extracting the element in the given finite index.

Body:
A regular expression maps directly to a finite state machine.  Generating strings from the FSM is straightforward with a backtracking algorithm.  The example is for the regular expression /aa?b/

(start) 0 -- a --> 1 -- a --> 2 -- b --> 3 (accepting and terminal)
                   |                     ^
                   |---------b ----------|

State   Previous char   Input char    Input string     History
  0        null                           --             []
                            a              a
  1        null                                        [{a,1}]
                            a              aa          [{a,1},{a,2}]
  2        null
                            b             aab          [{a,1},{a,2},{b,3}]
  3        null
         Accepting state, emit 'aab' as valid input
         Terminal state, backtrack
  2          b                             aa          [{a,1},{a,2}]
         No further valid inputs, backtrack
  1          a                             a           [{a,1}]
                            b              ab
  3        null                                        [{a,1},{b,3}]
         Accepting state, emit 'ab' as valid input
         Terminal state, backtrack
  1          b                             a           [{a,1}]
         No further valid inputs, backtrack
  0          a                             --          []
         No further valid inputs, stack empty, terminate


问:
How can I write byte[] to socket outputstream and specify the end of file?
I've googled 2 days straight and I can't find how to do this. I have an open stream between client and server, and client will send a JSON string (encrypted to bytes) to the server each 3 to 5 seconds.

How can I write to the Socket OutputStream so that I can read each JSON string in the server. I'm guessing I need to specify some kind of end of file or something, but can't find any info on how to achieve this.

答:
If you don't need the stream any more then you can close the stream when done.

Otherwise you will need to specify the length of the content explicitly by for example prefacing the json blob with its total length.

Otherwise you can send a ascii control byte like a null byte or ETX '\3' as a delimiter and detect it on the other end. This last one has the problem that you may overflow the input buffer before you get the entire stream or if someone sends malicious input.