问:
Accessing shared data without blocking in TPL
I am writing a class that contains data. It exposes methods that allow to query the data, while the data is also being updated from an external source (web service, for example).

All the methods expose tasks that are started on a worker thread using the default task scheduler. So the structure of the class is as follows:

```<code>public class A
{
    private object _myLock;

    public Task<int> GetSomeNumber(int aParameter)
    {
        return Task.Run(() =>
        {
            lock (_myLock)
            {
                int result = 0;
                // calculate the result...
                // ...
                return result;
            }
        });
    }

    public Task<string> GetSomeText(int aParameter)
    {
        return Task.Run(() =>
        {
            lock (_myLock)
            {
                string result = "";

                // calculate the result...
                // ...
                return result;
            }
        });
    }
}
</code>```

The methods may be called several multiple times, while the data itself is being updated, so the calculations that require the shared data are surrounded with a lock statement. The problem is that this code blocks the thread in which the task is run. Of course, these are not UI thread, so the UI remains responsive, but it does consume threads and keeps them blocked. I would prefer for the worker threads in the thread pool to remain as available as possible.

Is there a way, a best practice of some sort, that allows to write this code so that the shared data is thread safe and at the same time the tasks are not blocked? If instead of waiting for a lock, the tasks would need to wait for something else to finish (a task), I would use ContinueWith in order to create a continuation task and return it, so that it would be scheduled to run when the first task is completed. Is there a way to do the same with lock, so that the task is only scheduled when the lock is available?

Update
I have done some reading and found out about several possible options that allow for shared data sync. These include: SemaphoreSlim, AsyncLock, and ConcurrentExclusiveSchedulerPair.

I would love to see a recommendation for a best practice, of writing a service class that provides "read only" task methods that can run concurrently with a read lock, and "write" task methods that require write lock.

答:
If you expected more reads than writes a generally safe bet is ReaderWriterLockSlim which allows concurrent threads to read data, but only one thread may be a writer at a time.

You did mention concurrent lists and dictionaries, is there a reason that ConcurrentDictionary<,> doesn't work for this situation? I have found it to be quite performant and far less cumbersome to deal with in most situations.

For some performance critical solutions Interlocked.CompareExcgange works quite well, but this depends on your data that needs to be synchronized, CompareExchange works well with numeric types, but I would avoid reference based variables.


问:
Is it bad form to use the same variable name in different scopes?
Say you have some basic code where similar operations will take place in nearby lexical scopes. Take for example some simple pseudo code:

```<code>variable = "foo"
# Do something with variable
if (True) {
    variable = "bar"
    # Do something else with variable
}
for i in range 1..100 {
    variable = i
    # Do another thing with variable
}
</code>```

Say that in each scope, the variable is used for a distinct, but similar task and thus the name "variable" is appropriate in each case. What is the best practice in this case for naming? Should you use the name "variable" each time? Increment the name such as "variable1", "variable2", etc.? Or something else entirely?

答: If the variable in question represents the same thing for both functions, I can't see why it would be a problem. If you're arbitrarily using variable to mean "any variable within a function that can do anything" then yes, it is a problem. Name your variables in the context to which they are used.

ContentLicense: CC BY-SA 3.0


问:
What benefit is there to using recursive binary search over iterative binary search or vice versa?
In a recent assignment for my programming 2 class we tested the efficiency of searches by populating a java ArrayList with 13,040 strings. The sequential search was obviously slower than the binary searches due to the complexity difference and the amount of times the code actually has to loop through the code.

Iterative binary search and recursive binary search, however, had the same amount of comparisons. For example:

```<code>sequentialSearch(): 'some_word' found in ArrayList at index 13,020 - comparisons: 13,021
</code>```

The comparisons being how many times the computer actually checked if the user's "some_word" was equal to a value ArrayList.

```<code>iterativeBinarySearch(): 'some_word' found in ArrayList at index 13,020 - comparisons: 14
recursiveBinarySearch(): 'some_word' found in ArrayList at index 13,020 - comparisons: 14
</code>```

So if the comparisons of iterative and recursive are the same, in what situations would you choose one over the other? Is it simply personal taste or is there a specific reasoning for using a specific one?

答:
If your language processor (compiler or interpreter) properly implements tail recursion optimization, then there winds up being no difference between a properly-coded tail-recursive binary search and an iterative binary search.  The language processor will turn the recursive calls into simple loops.

At that point, choice of recursive vs. iterative formulation is pretty much a matter of personal and local preference.  Some people find recursive code easier to understand.  Some people are scared to death of recursion, or don't understand it, or have no clue about tail recursion optimization, and want explicitly iterative code everywhere.


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答:
If it were down to me, I wouldn't enforce or hint at the use of any particular style because, as programmers, we whould be able to read a symbol IfItIsInCamelCase or in_underscore_space or even in_SomeOtherStyle and understand what it means. Having to spend a tiny amount of time parsing the symbol is no great overhead in the big scheme of things.

Now, the main argument for a convention I guess is that you know upfront what the format of a function/variable name is and don't need to look it up - is it LoadXMLFile, loadXMLFile, LoadXmlFile, load_xml_file? Now, I would counter that argument by saying "Get an IDE that supports intellisense style auto completion!" (not always possible though).

In the end though, it doesn't really matter what style you use beacuse the compiler / interpreter doesn't really care. What is important is that the name is useful:

```<code>NumberOfPrisonersReleasedByAccident
manufacturer_name
distance_EarthToMoon
</code>```

Three different styles, but you know exactly what each one does.

ContentLicense: CC BY-SA 2.5

Body:
If it were down to me, I wouldn't enforce or hint at the use of any particular style because, as programmers, we whould be able to read a symbol IfItIsInCamelCase or in_underscore_space or even in_SomeOtherStyle and understand what it means. Having to spend a tiny amount of time parsing the symbol is no great overhead in the big scheme of things.

Now, the main argument for a convention I guess is that you know upfront what the format of a function/variable name is and don't need to look it up - is it LoadXMLFile, loadXMLFile, LoadXmlFile, load_xml_file? Now, I would counter that argument by saying "Get an IDE that supports intellisense style auto completion!" (not always possible though).

In the end though, it doesn't really matter what style you use beacuse the compiler / interpreter doesn't really care. What is important is that the name is useful:

NumberOfPrisonersReleasedByAccident
manufacturer_name
distance_EarthToMoon

Three different styles, but you know exactly what each one does.


问:
Is there a term for data being written not being immediately available to be read?
Here is a problem I've repeatedly observed over the years:

a thread writes to something (database record, LDAP entry, etc.)

very soon afterwards, the same thread tries to read the record it just wrote

it gets back the old version of the record, not the new version it just wrote.
(Or, the newly created record is reported as not existing.
Or, the just deleted record appears to still exist.)

Is there a standard term for this phenomenon?

The most common cause of this phenomenon is with a replicated database (especially LDAP), in which the write and the read get routed to different nodes, and the write has not yet replicated to the read node. (But I'm looking for a term to refer to the phenomenon itself, not that specific cause of it.)

答:
This is called an eventually consistent system. Databases like Cassandra make good use of this model.

To understand why you might want an eventually consistent system, take a look at Brewer's Conjecture and Cap Theorem. It's a trade-off.


问:
Should I store my user claims in the JWT token?
I am using JWT tokens in HTTP headers to authenticate requests to a resource server.  The resource server and auth server are two separate worker roles on Azure.

I cannot makeup my mind as to whether I should store the claims in the token or attach them to the request/response some other way.  The Claims list affects rendering of client-side UI elements as well as access to data on the server.  For this reason I want to make sure that claims received by the server are authentic and validated before the request is processed.

Examples of claims are:  CanEditProductList, CanEditShopDescription, CanReadUserDetails.

The reasons I want to use the JWT token for them are:

Better protection against client-side editing of claims (i.e. hacking claims list).

No need to look up the claims on every request.

The reasons I don't want to use the JWT token:

The auth server then has to know the app-centric claims list.

The token becomes a single point of hack-entry.

I've read a few things saying that JWT tokens aren't intended for app-level data.

It seems to me that both have drawbacks, but I am leaning towards the inclusion of these claims into the token and just want to run this by people who have dealt with this before.

NOTE: I'll be using HTTPS for all API requests, so it seems to me that the token will be safe 'enough'.  I'm using AngularJS, C#, Web API 2 and MVC5.

答:
I store identifier claims only (userid, etc.) (encrypted) in my jwt.

Then when I get the token on the server (API) I can do a lookup server side (db,redis, or local network api call) and retrieve all the associations to the userid (apps,roles, etc.)

However if you want to stuff more unencrypted claims into the jwt just be careful with the size since it will likely be sent on each request, but make sure to encrypt sensitive claim data.

ContentLicense: CC BY-SA 4.0


问:
Better pattern than large if/else if/else for checking conditionals
I've got a fairly large set of booleans I'm checking in javascript, and then using them to alter the state of a layout in my React app. The whole thing is unwieldy, difficult to read, inelegant, and feels terribly amateurish. I was wondering if there was a better pattern for handling something like this.

Example code snippet (in coffeescript). Replaced object variables with ints for brevity:

```<code>setNeeded = _.contains(sessionInitialStates, codingSession.state)
sessionUpdating = codingSession.state is 'UPDATING'
sessionFailed = codingSession.state is 'FAILED'
setExtended = _.contains extStates, codingSession.state
setInReview = _.contains(reviewStates, controlSet.state) or
  _.contains(controlSetSyncStates, controlSet.state)
sessionIsTagging = _.contains tagStates, codingSession.state
sessionComplete = codingSession.state is 'COMPLETE'
sessionIsNew = _.isEmpty(codingSession.state) or
  codingSession.state is 'CREATED'

commError = controlSet.state is 'COMMUNICATION_ERROR'
if setNeeded and @props.creds
  someVar = 1

else if _.contains(sessionInitialStates, codingSession.state) and
    controlSet.state is 'PROCESSING_FAILED'
  someVar = 2

else if codingSession.state is 'CONTROL_SET_GENERATION' and
    controlSet.state is 'SELECTION_FAILED' and @props.creds
  someVar = 3

else if !sessionIsTagging or !sessionComplete
  if _.isEmpty @props.connector
    someVar = 4

  else if !@props.creds
    someVar = 5

  else if sessionFailed
    someVar = 6

  else if sessionIsNew
    someVar = 7

  else if sessionUpdating
    someVar = 8

  else if setInReview and !setExtended
    someVar = 9
</code>```

答:
When you notice large blocks of if/else, it usually means that your class or method is doing too much.

Instead of trying to rewrite the logic inside the method:

Ensure the method does one and one only thing.

Replace the class by multiple classes which inherit from a common one.

For practical examples, if you have an actual working piece of code but contains too much if/else statements, you may post it on CodeReview.SE.


答:
If the variable is something simple and clear, like i, count, sum, go ahead and reuse it.

If the variable is central to the method, like calculatedResult, or you are in a series of if/else blocks (or blocks all ending in return calculatedResult), reuse it.

But if the blocks are not mutually exclusive, and control flows from one to the other, it might be clearer to not reuse the same variable name.  For example, if you are doing a series of SQL queries, I might go  (Java-ish syntax)

```<code>if (theyCareAboutPeople) {
   peopleQuery = "SELECT * FROM people WHERE blah blah...";
   ResultSet people = mySqlDriver.execute(peopleQuery);
   // do something with people
}
if (theyCareAboutAges) {
   ageQuery = "SELECT * FROM ages WHERE blah blah...";
   ResultSet ages= mySqlDriver.execute(ageQuery );
   // do something with ages
}
</code>```

Note that I used meaningful names, like "peopleQuery" and "ages", instead of calling all the queries "query" and all the results "result".  IMO, this is slightly clearer, but YMMV.

Title: Is it bad form to use the same variable name in different scopes?

Body:
Say you have some basic code where similar operations will take place in nearby lexical scopes. Take for example some simple pseudo code:

```<code>variable = "foo"
# Do something with variable
if (True) {
    variable = "bar"
    # Do something else with variable
}
for i in range 1..100 {
    variable = i
    # Do another thing with variable
}
</code>```

Say that in each scope, the variable is used for a distinct, but similar task and thus the name "variable" is appropriate in each case. What is the best practice in this case for naming? Should you use the name "variable" each time? Increment the name such as "variable1", "variable2", etc.? Or something else entirely?

Body:
If the variable is something simple and clear, like i, count, sum, go ahead and reuse it.

If the variable is central to the method, like calculatedResult, or you are in a series of if/else blocks (or blocks all ending in return calculatedResult), reuse it.

But if the blocks are not mutually exclusive, and control flows from one to the other, it might be clearer to not reuse the same variable name.  For example, if you are doing a series of SQL queries, I might go  (Java-ish syntax)

if (theyCareAboutPeople) {
   peopleQuery = "SELECT * FROM people WHERE blah blah...";
   ResultSet people = mySqlDriver.execute(peopleQuery);
   // do something with people
}
if (theyCareAboutAges) {
   ageQuery = "SELECT * FROM ages WHERE blah blah...";
   ResultSet ages= mySqlDriver.execute(ageQuery );
   // do something with ages
}

Note that I used meaningful names, like "peopleQuery" and "ages", instead of calling all the queries "query" and all the results "result".  IMO, this is slightly clearer, but YMMV.


答:
There are two entirely different things at play here: variable reuse and variable name reuse (redeclaration.)  Your sample pseudocode does not make it clear which one of the two cases you are referring to, so I will mention both.

This is variable reuse:

```<code>int i = 5;
for( ;; )
{
    i = 3;
    ...
}
</code>```

This is variable name reuse:

```<code>int i = 5;
for( ;; )
{
    int i = 3;
    ...
}
</code>```

Variable reuse is very, very bad and it should be avoided at all costs because it leads to spaghetti code.  Code may one day be added after the for loop, expecting i to hold 5, and it may be very shocked to find out that it doesn't. People reading this code will assume that you are replacing the value of i in order to use the new value after the loop. Decent compilers will give you a "variable reuse" or "variable scope too broad" warning if you do this, but they may not always be able to detect it, (in the case of a for loop, they cannot, because you may be doing it intentionally,) so it is best to not push your luck.

Variable name reuse is perfectly fine, and as a matter of fact desirable under certain scenarios.  For example, variable name reuse guarantees that within the for loop you cannot accidentally refer to the outer scope i, because it has been redefined and therefore it is now inaccessible.  (Unfortunately C# does not like that, but most other languages have no problem with it.)

I would not answer "it is good or bad depending on what your peers say", because you may be asking this question on stackoverflow precisely in order to have arguments when discussing this matter with your peers.

Body:
There are two entirely different things at play here: variable reuse and variable name reuse (redeclaration.)  Your sample pseudocode does not make it clear which one of the two cases you are referring to, so I will mention both.

This is variable reuse:

int i = 5;
for( ;; )
{
    i = 3;
    ...
}

This is variable name reuse:

int i = 5;
for( ;; )
{
    int i = 3;
    ...
}

Variable reuse is very, very bad and it should be avoided at all costs because it leads to spaghetti code.  Code may one day be added after the for loop, expecting i to hold 5, and it may be very shocked to find out that it doesn't. People reading this code will assume that you are replacing the value of i in order to use the new value after the loop. Decent compilers will give you a "variable reuse" or "variable scope too broad" warning if you do this, but they may not always be able to detect it, (in the case of a for loop, they cannot, because you may be doing it intentionally,) so it is best to not push your luck.

Variable name reuse is perfectly fine, and as a matter of fact desirable under certain scenarios.  For example, variable name reuse guarantees that within the for loop you cannot accidentally refer to the outer scope i, because it has been redefined and therefore it is now inaccessible.  (Unfortunately C# does not like that, but most other languages have no problem with it.)

I would not answer "it is good or bad depending on what your peers say", because you may be asking this question on stackoverflow precisely in order to have arguments when discussing this matter with your peers.


问:
Where can I find design exercises to work on?
I feel it's important to continue practicing my problem-solving skills. Writing my own mini-projects is one way, but another is to try and solve problems posted online. It's easy to find interesting programming quizzes online that require applying clever algorithms to solve - Project Euler is one well-known example.

However, in a lot of real-life projects the design of the software - especially in the initial phases - has a large impact and at later stages it cannot be tweaked as easily as plain algorithms. In order to improve these skills, I'm looking for any collection of design problems.

When I say "design", I mean the abstract design of a software solution - for example what modules will there be and what are the dependencies between them, how data will flow in the program, what sort of data needs to be saved in the database, etc. Design problems are those problems that are critical to solve in the early stages of any project, but their solution is a whiteboard diagram without a single line of code.

Of course these sort of problems do not have a single correct solution, but I'll be especially happy with any place that also displays pros and cons of the typical solutions that might be used to approach the problem.

答: I've heard this sort of thing referred to as "programming katas." Kata is a martial arts term for a form or sequence of movements that is practiced over and over again to perfection. Do some searching for katas in your language of choice and I'll bet you'll turn up something. :)</p>


问:
With only backend development experience, how do I go into frontend development (js, html, css)?
Currently I am interning at a company as a "full stack" developer (Application developer on the job title) and I realize that I am having difficulties coping with frontend tasks. This is especially true when I am tasked with implementing a new frontend feature and I can see myself struggling to get the hang of frontend development philosophies and structure (where it feels like magic, I don't exactly see how HTML and javascript work in tandem and adding Angular.js makes it even more weird) as compared to backend (Having static typed languages (Java, C#), being able to find my way to see how is everything defined, and can easily traverse through the code).

Note* I am defining backend as everything after the REST curtain, code that is executed by the server and frontend as everything before the REST curtain, code that is for the web browser.

In the past, all my work and internships has been working with backend code, servers, databases, and files. For hackathons, I specifically do the backend architecture by myself while my teammates does the frontend coding.

With that being said, what would be the best approach to walk into frontend development with only backend experience? Language specific, what is the best way to understand how javascript and angularjs work with HTML and how do I traverse through such languages to find how everything is connected?

The justification behind this question is to seek ways to get started with understanding how Javascript, HTML, and CSS and its derivatives work so that I may have a better understanding of how it functions and how to traverse/program it. I have understanding of the basic JS syntax through web courses but not how is it integrated in web design.

答:
The short answer is to read a good book on Angular, read it again, and then practice coding, lots of it.  That said, if you've never worked with UI, it can be an interesting challenge, because you might be missing some fundamental conceptual information to help you put it all together.

What follows assumes that you know what an HTML tag is, and how a form element works.  If you don't, this is going to be a long haul.

Data Binding, or "how to get your dog to heel automatically"

Consider the following HTML:

```<code><span id="name"></span>
</code>```

Since you're a server specialist, I assume you know that, in addition to providing content like XML and JSON to a client, you can also provide an HTML page to a browser.  What if you could look up a value from the database, insert it into the middle of that span tag, and then output it to the browser?

```<code><span id="name">Rufus McGillicutty</span>
</code>```

That's probably the most basic form of data binding: filling a page's elements with content from a database.  And you don't even need to know Javascript or CSS to do it.  Javascript frameworks do data binding by manipulating the DOM, rather than pasting strings together server-side.

Forms, or "This is where you type your name."

If you have a

```<code><form></form>
</code>```

then you can obtain the values of any controls in that form when the user presses the SUBMIT button.  There are ways to bind those values to a data object, and now you have some data that you can insert into your database.

That's just CRUD, man.

Create, Read, Update, Delete.  Those are the operations you will need to support.  Well, those and things like "Place Order."  If you've done any significant server work, this should already be familiar to you.

It's all about the architecture

Hopefully you've heard acronyms like MVC and MVVM.  You should study those, not so much to understand the exact intricacies, but more to get the flavor of why these organizing principles work so well to build user interfaces that are useful and maintainable.

You should study, understand and know the following terms:

```<code>Model
View
ViewModel
Controller
Service Layer
Data Layer
</code>```

Note that Angular might not be the best frontend framework to learn first.  Knockout is probably more suitable in that regard, because it's simpler and the learning curve isn't quite so high.  You should also have at least a passing familiarity with jQuery.

Body:
The short answer is to read a good book on Angular, read it again, and then practice coding, lots of it.  That said, if you've never worked with UI, it can be an interesting challenge, because you might be missing some fundamental conceptual information to help you put it all together.

What follows assumes that you know what an HTML tag is, and how a form element works.  If you don't, this is going to be a long haul.

Data Binding, or "how to get your dog to heel automatically"

Consider the following HTML:

<span id="name"></span>

Since you're a server specialist, I assume you know that, in addition to providing content like XML and JSON to a client, you can also provide an HTML page to a browser.  What if you could look up a value from the database, insert it into the middle of that span tag, and then output it to the browser?

<span id="name">Rufus McGillicutty</span>

That's probably the most basic form of data binding: filling a page's elements with content from a database.  And you don't even need to know Javascript or CSS to do it.  Javascript frameworks do data binding by manipulating the DOM, rather than pasting strings together server-side.

Forms, or "This is where you type your name."

If you have a

<form></form>

then you can obtain the values of any controls in that form when the user presses the SUBMIT button.  There are ways to bind those values to a data object, and now you have some data that you can insert into your database.

That's just CRUD, man.

Create, Read, Update, Delete.  Those are the operations you will need to support.  Well, those and things like "Place Order."  If you've done any significant server work, this should already be familiar to you.

It's all about the architecture

Hopefully you've heard acronyms like MVC and MVVM.  You should study those, not so much to understand the exact intricacies, but more to get the flavor of why these organizing principles work so well to build user interfaces that are useful and maintainable.

You should study, understand and know the following terms:

Model
View
ViewModel
Controller
Service Layer
Data Layer

Note that Angular might not be the best frontend framework to learn first.  Knockout is probably more suitable in that regard, because it's simpler and the learning curve isn't quite so high.  You should also have at least a passing familiarity with jQuery.


答:
Reusing a variable is bad, because a compiler that would normally warn you about uninitialised variables etc. can't warn you, because at the time of the second use, the variable will be initialised.

Reusing a variable name is usually not a problem.

You may get compiler warnings if you create a variable with the same name as another variable in an outer scope. With good reason, because that is going to be confusing and error prone. Avoid it whether you get warnings or not.

You may have problems with a debugger that thinks there is a dozen variables with the same name and cannot tell you which one you are using right now. This is a problem of the debugger and should be fixed, but if you run into the situation, you may choose to write code that is more debugger friendly.


答:
After more research, I have created some pros/cons on each algorithm. It's easier to visualize in a table, but that is currently seemingly unsupported by markdown. However, I've separated these pros/cons into 6 categories (Structure, Control, Condition, Update, Speed, and Space).

Depending on the project at hand this should be able to determine the best algorithm to practice.

Iterative

Structure - Repetition

Control - Explicit use of loop

Condition - Entrance Condition

Update - It is controlled by counter and keeps updating a counter

Speed - It usually runs faster than recursive

Space - It usually takes less space than recursive.

Recursive

Structure - Selection

Control - Recursive call (i.e. recursive case). Data becomes smaller each time it is called.

Condition - Exit Condition (i.e. base case)

Update - It gradually approaches to base case. It keeps producing smaller versions at each call.

Speed - It usually runs slower than iterative

Space - It usually takes more space than iterative, called "call-stack".

Title: What benefit is there to using recursive binary search over iterative binary search or vice versa?

Body:
In a recent assignment for my programming 2 class we tested the efficiency of searches by populating a java ArrayList with 13,040 strings. The sequential search was obviously slower than the binary searches due to the complexity difference and the amount of times the code actually has to loop through the code.

Iterative binary search and recursive binary search, however, had the same amount of comparisons. For example:

```<code>sequentialSearch(): 'some_word' found in ArrayList at index 13,020 - comparisons: 13,021
</code>```

The comparisons being how many times the computer actually checked if the user's "some_word" was equal to a value ArrayList.

```<code>iterativeBinarySearch(): 'some_word' found in ArrayList at index 13,020 - comparisons: 14
recursiveBinarySearch(): 'some_word' found in ArrayList at index 13,020 - comparisons: 14
</code>```

So if the comparisons of iterative and recursive are the same, in what situations would you choose one over the other? Is it simply personal taste or is there a specific reasoning for using a specific one?


问:
Why are there so few C compilers?
C is one of the most widely-used languages in the world. It accounts for a huge proportion of existing code and continues to be used for a vast amount of new code. It's beloved by its users, it's so widely ported that being able to run C is to many the informal definition of a platform, and is praised by its fans for being a "small" language with a relatively clean set of features.

So where are all the compilers?

On the desktop, there are (realistically) two: GCC and Clang. Thinking about it for a few seconds you'll probably remember Intel exists as well. There are a handful of others, far too obscure for the average person to name and almost universally not bothering to support a recent language version (or often even a well-defined language subset, just "a subset"). Half of the members of this list are historical footnotes; most of the rest are very specialized and still don't actually implement the full language. Very few actually seem to be open-source.

Scheme and Forth - other small languages that are beloved by their fans for it - probably have more compilers than actual users. Even something like SML has more "serious" implementations to choose between than C. Whereas the announcement of a new (unfinished) C compiler aiming at verification actually sees some pretty negative responses, and veteran implementations struggle to get enough contributors to even catch up to C99.

Why? Is implementing C so hard? It isn't C++. Do users simply have a very skewed idea about what complexity group it falls in (i.e. that it actually is closer to C++ than Scheme)?

答:
So what is your target language?

SML compilers are often targeting C or something like LLVM (or as seen in your link, the JVM or JavaScript).

If you're compiling C, it's not because you're going to the JVM. You're going to something worse than C. Far worse. And then you get to duplicate that minor hell a bunch of times for all your target platforms.

And sure, C isn't C++, but I'd say that it's closer to C++ than Scheme. It does have its own subset of undefined behavior evilness (I'm looking at you size of built in types). And if you screw up that minutiae (or do it "correctly" but unexpectedly) then you have decades of existing code on vital systems that will tell you how terrible you are. If you screw up an SML compiler, it just won't work - and someone might notice. Someday.

OwnerDisplayName: anon

Title: Why are there so few C compilers?


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答: Writing too many lines of code without adequate tests.</p>

Title: What can slow a developer down?


问:
Is static going to make any difference in this code snippet
I have been to an interview and was asked this question - is there any difference adding or removing the static keyword in these classes?

I know what static means but my understanding of this point is weak.

```<code>class Program
{
    static void Main(string[] args)
    {
            aAsposeNew.MultipleInstancesProblem();
            Console.ReadLine();
    }
}

public static class aAsposeNew
{
    public static void MultipleInstancesProblem()
    {
            var task1 = Task.Run(() => CreateDocument("document1.pdf"));
            var task2 = Task.Run(() => CreateDocument("document2.pdf"));
            var task3 = Task.Run(() => CreateDocument("document3.pdf"));
    }

    public static void CreateDocument(string documentName)
    {
        var doc = new Document();
        doc.Pages.Add();

        var table = new Aspose.Pdf.Table();
        var row = table.Rows.Add();
        table.ColumnWidths = "600";
        var hf =
            new HtmlFragment(@"<ul>
                                 <li>Internal HR Meeting Outcome</li>
                                 <li>Internal HR Meeting Outcome January 2015</li>
                               </ul>");
        var cell = row.Cells.Add();
        cell.Paragraphs.Add(hf);
        doc.Pages[1].Paragraphs.Add(table);

        doc.Save(@"C:\Output\" + documentName);
    }
  }
</code>```

and without the static keyword:

```<code>class Program
{
    static void Main(string[] args)
    {
            aAsposeNew aAN = new aAsposeNew();
            aAN.MultipleInstancesProblem();
            Console.ReadLine();
    }
}

public class aAsposeNew
{
    public void MultipleInstancesProblem()
    {
            var task1 = Task.Run(() => CreateDocument("document1.pdf"));
            var task2 = Task.Run(() => CreateDocument("document2.pdf"));
            var task3 = Task.Run(() => CreateDocument("document3.pdf"));
    }

    public void CreateDocument(string documentName)
    {
        var doc = new Document();
        doc.Pages.Add();

        var table = new Aspose.Pdf.Table();
        var row = table.Rows.Add();
        table.ColumnWidths = "600";
        var hf =
            new HtmlFragment(@"<ul>
                                 <li>Internal HR Meeting Outcome</li>
                                 <li>Internal HR Meeting Outcome January 2015</li>
                               </ul>");
        var cell = row.Cells.Add();
        cell.Paragraphs.Add(hf);
        doc.Pages[1].Paragraphs.Add(table);

        doc.Save(@"C:\Output\" + documentName);
    }
  }
</code>```

答:
In this situation, as said, it will make no difference. In fact it would be a better practice to make the class static as the containing methods are static and there is no requirement to access any non-static instance members.

I use static class as a convenience to make it accessible for constants, exposing static methods to do independent units of work etc. A static class is loaded by the run time and lasts for the life of the app. Thus, we are guarenteed to always get the functionality we need without creating instances.


问:
How do you guarantee that your database context is disposed of properly when your lazy collection is no longer needed?
I'm looking for a best practices kind of answer here.

Given that best practices for interacting with classes that implement IDisposable is via the Using statement - What is the best practice for using EF lazy loading with MVC?

Example controller method:

```<code><HttpGet>
Public Function Schedule(ByVal id As Int64) As ActionResult

    Dim model As Schedule = Nothing
    Using database As dataContext = New dataContext
        model = (From s In database.Schedules Where s.ScheduleID = id Select s).FirstOrDefault
    End Using

    Return View(theSchedule)

End Function
</code>```

This example makes lazy loading not work because the database [dataContext] is disposed by time the model arrives in the View.

So I guess the question is:

What are best practices for using lazy loading in MVC?  How do you guarantee that your database context is disposed of properly and that you don't cause memory leaks?

答:
In general, you don't need to use Using statements with Entity Framework data contexts.  Lazy collections is one of the reasons why.  So your code would simply be:

```<code><HttpGet>
Public Function Schedule(ByVal id As Int64) As ActionResult

    Dim model As Schedule = Nothing
    Dim database As dataContext = New dataContext
    model = (From s In database.Schedules Where s.ScheduleID = id Select s).FirstOrDefault

    Return View(model)

End Function
</code>```

Data contexts in Entity Framework are designed to open and close connections as needed, and they dispose of themselves automatically when the data context object is no longer required.

The default behavior of DbContext is that the underlying connection is automatically opened any time is needed and closed when it is no longer needed. E.g. when you execute a query and iterate over query results using “foreach”, the call to IEnumerable.GetEnumerator() will cause the connection to be opened, and when later there are no more results available, “foreach” will take care of calling Dispose on the enumerator, which will close the connection.

The only time you would have to be careful about IDisposable is if you Override the data context's default behaviors.

Further Reading

Do I always have to call Dispose on DBContext?  Nope.

Managing DbContext the right way with Entity Framework 6: an in-depth guide

Body:
In general, you don't need to use Using statements with Entity Framework data contexts.  Lazy collections is one of the reasons why.  So your code would simply be:

<HttpGet>
Public Function Schedule(ByVal id As Int64) As ActionResult

    Dim model As Schedule = Nothing
    Dim database As dataContext = New dataContext
    model = (From s In database.Schedules Where s.ScheduleID = id Select s).FirstOrDefault

    Return View(model)

End Function

Data contexts in Entity Framework are designed to open and close connections as needed, and they dispose of themselves automatically when the data context object is no longer required.

The default behavior of DbContext is that the underlying connection is automatically opened any time is needed and closed when it is no longer needed. E.g. when you execute a query and iterate over query results using “foreach”, the call to IEnumerable.GetEnumerator() will cause the connection to be opened, and when later there are no more results available, “foreach” will take care of calling Dispose on the enumerator, which will close the connection.

The only time you would have to be careful about IDisposable is if you Override the data context's default behaviors.

Further Reading

Do I always have to call Dispose on DBContext?  Nope.

Managing DbContext the right way with Entity Framework 6: an in-depth guide


答:
I would probably start with basic HTML and CSS.

It's not hard when you already know how to program.

I would start by creating a personal project using HTML, CSS and Javascript.

Move on to jQuery if you get familiar with js.

I think the problem is that you are trying to achieve a lot at the same time.

With that said, there are many resources online nowadays, to learn basic front-end.

Title: With only backend development experience, how do I go into frontend development (js, html, css)?

Body:
Currently I am interning at a company as a "full stack" developer (Application developer on the job title) and I realize that I am having difficulties coping with frontend tasks. This is especially true when I am tasked with implementing a new frontend feature and I can see myself struggling to get the hang of frontend development philosophies and structure (where it feels like magic, I don't exactly see how HTML and javascript work in tandem and adding Angular.js makes it even more weird) as compared to backend (Having static typed languages (Java, C#), being able to find my way to see how is everything defined, and can easily traverse through the code).

Note* I am defining backend as everything after the REST curtain, code that is executed by the server and frontend as everything before the REST curtain, code that is for the web browser.

In the past, all my work and internships has been working with backend code, servers, databases, and files. For hackathons, I specifically do the backend architecture by myself while my teammates does the frontend coding.

With that being said, what would be the best approach to walk into frontend development with only backend experience? Language specific, what is the best way to understand how javascript and angularjs work with HTML and how do I traverse through such languages to find how everything is connected?

The justification behind this question is to seek ways to get started with understanding how Javascript, HTML, and CSS and its derivatives work so that I may have a better understanding of how it functions and how to traverse/program it. I have understanding of the basic JS syntax through web courses but not how is it integrated in web design.


答:
How did you start to be a backend developer? It must've felt very similar back then. Yet you managed it. I'm sure you'll do the same for frontend.

Here's how I'd suggest your learning:

Get to know html first. That should be very easy and quick.

Learn CSS. Not master it. Get familiar with majority of its properties (no problem if you don't master flexbox as long as you know it exists) and all CSS3 selector types (you should know exactly how they work for all of them)

Play a bit with #1 and #2

Learn DOM and understand how javascript works and interacts with it

Learn jQuery and async communication -  Ajax

Learn Javascript thoroughly like OOP in prototypes

learn Angular.

It should eventually all fall into place and be understandable.


答:
Today, you need a real C compiler to be an optimizing compiler, notably because C is no longer a language close to the hardware, because current processors are incredibly complex (out-of-order, pipelined, superscalar, with complex caches & TLB, hence needing instruction scheduling, etc...). Today's x86 processors are not like i386 processors of the previous century, even if both are able to run the same machine code. See the C is not a low level language (Your computer is not a fast PDP-11) paper by David Chisnall.

Few people are using naive non-optimizing C compilers like tinycc or nwcc, since they produce code which is several times slower than what optimizing compilers can give.

Coding an optimizing compiler is difficult. Notice that both GCC and Clang are optimizing some "source language-neutral" code representation (Gimple for GCC, LLVM for Clang). The complexity of a good C compiler is not in the parsing phase!

In particular, making a C++ compiler is not much harder than making a C compiler: parsing C++ and transforming it into some internal code representation is complex (because the C++ specification is complex), but is well understood, but the optimization parts are even more complex (inside GCC: the middle-end optimizations, source-language and target-processor neutral, form the majority of the compiler, with the rest being balanced between front-ends for several languages and back-ends for several processors). Hence most optimizing C compilers are also able to compile some other languages, like C++, Fortran, D, ... The C++ specific parts of GCC are about 20% of the compiler...

Also, C (or C++) is so widely used that people expect their code to be compilable even when it does not exactly follow the official standards, which do not define precisely enough the semantics of the language (so each compiler may have its own interpretation of it). Look also into the CompCert proved C compiler, and the Frama-C static analyzer, which care about more formal semantics of C.

And optimizations are a long-tail phenomenon: implementing a few simple optimizations is easy, but they won't make a compiler competitive! You need to implement a lot of different optimizations, and to organize and combine them cleverly, to get a real-world compiler that is competitive. In other words, a real-world optimizing compiler has to be a complex piece of software. BTW, both GCC and Clang/LLVM have several internal specialized C/C++ code generators. And both are huge beasts (several millions of source lines of code, with a growth rate of several percent each year) with a large developer community (a few hundred persons, working mostly full-time, or at least half-time).

Notice that there is no (to the best of my knowledge) multi-threaded C compiler, even if some parts of a compiler could be run in parallel (e.g. intra-procedural optimization, register allocation, instruction scheduling... ). And parallel build with make -j is not always enough (especially with LTO).

Also, it is difficult to get funded on coding a C compiler from scratch, and such an effort needs to last several years. Finally, most C or C++ compilers are free software today (there is no longer a market for new proprietary compilers sold by startups) or at least are monopolistic commodities (like Microsoft Visual C++), and being a free software is nearly required for compilers (because they need contributions from many different organizations).

I'd be delighted to get funding to work on a C compiler from scratch as free software, but I am not naive enough to believe that is possible today!

Title: Why are there so few C compilers?

Body:
C is one of the most widely-used languages in the world. It accounts for a huge proportion of existing code and continues to be used for a vast amount of new code. It's beloved by its users, it's so widely ported that being able to run C is to many the informal definition of a platform, and is praised by its fans for being a "small" language with a relatively clean set of features.

So where are all the compilers?

On the desktop, there are (realistically) two: GCC and Clang. Thinking about it for a few seconds you'll probably remember Intel exists as well. There are a handful of others, far too obscure for the average person to name and almost universally not bothering to support a recent language version (or often even a well-defined language subset, just "a subset"). Half of the members of this list are historical footnotes; most of the rest are very specialized and still don't actually implement the full language. Very few actually seem to be open-source.

Scheme and Forth - other small languages that are beloved by their fans for it - probably have more compilers than actual users. Even something like SML has more "serious" implementations to choose between than C. Whereas the announcement of a new (unfinished) C compiler aiming at verification actually sees some pretty negative responses, and veteran implementations struggle to get enough contributors to even catch up to C99.

Why? Is implementing C so hard? It isn't C++. Do users simply have a very skewed idea about what complexity group it falls in (i.e. that it actually is closer to C++ than Scheme)?


答:
I would like to contest your underlying assumption that there are only a small number of C implementations.

I don't even know C, I don't use C, I am not a member of the C community, and yet, even I know far more than the few compilers you mentioned.

First and foremost, there is the compiler which probably completely dwarfs both GCC and Clang on the desktop: Microsoft Visual C. Despite the inroads that both OSX and Linux have been making on the desktop, and the marketshare that iOS and Android have "stolen" away from former traditional desktop users, Windows is still the dominant desktop OS, and the majority of Windows desktop C programs are probably compiled using Microsoft tools.

Traditionally, every OS vendor and every chip vendor had their own compilers. Microsoft, as an OS vendor, has Microsoft Visual C. IBM, as both an OS vendor and a chip vendor, has XLC (which is the default system compiler for AIX, and the compiler with which both AIX and i/OS are compiled). Intel has their own compiler. Sun/Oracle have their own compiler in Sun Studio.

Then, there are the high-performance compiler vendors like PathScale and The Portland Group, whose compilers (and OpenMP libraries) are used for numbercrunching.

Digital Mars is also still in business. I believe Walter Bright has the unique distinction of being the only person on the planet who managed to create a production-quality C++ compiler (mostly) by himself.

Last but not least we have all the proprietary compilers for embedded microcontrollers. IIRC, there are more microcontrollers sold every year than desktop, mobile, server, workstation, and mainframe CPUs have been sold in the entire history of computing combined. So, those are definitely not niche products.

An honorary mention goes out to TruffleC, a C interpreter(!) running on the JVM(!) written using the Truffle AST interpreter framework that is only 7% slower than GCC and Clang (whichever is fastest on any given particular benchmark) across the Computer Languages Benchmark Game, and faster than both on microbenchmarks. Using TruffleC, the Truffle team was able to get their version of JRuby+Truffle to execute Ruby C extensions faster than the actual C Ruby implementation!

So, these are 6 implementations in addition to the ones you listed which I can name off the top of my head, without even knowing anything about C.

Title: Why are there so few C compilers?


问:
What does "host" mean in "... host driver" and "... host adapter"?
From How Linux Works, by Brian Ward, I saw "SCSI Host Adapter", "SATA Host Driver", "Disk Driver (sd)", "CD/DVD Driver (sr)", "USB Host Driver", and "USB Storage Driver".

What does "host" mean in the words?

Why isn't "guest" used?

what differences are between when "host" appears before "driver" and when it doesn't?

what differences are between when "host" appears before "adapter" and when it doesn't?

Thanks.

答:
A host adapter can, well, host attached devices. A host adapter knows how to detect, power on, hand-shake, initialize, and make available a simpler device using a pluggable interface such as SCSI, SATA, or USB. Host adapters usually know how to handle multiple attached devices, and route information between them and the rest of the computer.

The non-host devices do not know all these complications. They expect that a host adapter will take care of that, and just implement the simpler device-specific logic. A SATA disk cannot connect to another SATA disk and interact with it. A USB flash drive cannot connect to a USB mouse in a meaningful way. These devices are not hosts. (Note that e.g. SCSI and FireWire devices can actually talk to each other in meaningful ways without a help from a host adapter. The host adapter just orchestrates their interaction with the computer.)

Usually you don't call a USB mouse a 'guest', and a SATA disk, even less often. These devices can be seen as "permanently" attached, not traveling from one host to another. You could use a word like 'controller' instead of 'host', but it's longer and does not convey the entire meaning. E.g. network controllers are usually peers and act similarly. A host and an attached device are not peers, they play entirely different roles in the connection.


问:
What is a formal definition for an algorithm step?
Consider the following code to find the K th minimum element of an array:

```<code>FindKthMin(A[], k)
{
    A = Sort(A);
    return A[k];
}
</code>```

Could it be an algorithm without specifying the sort details?

Can we say algorithm has no meaning without specifying the instruction set (target machine and its basic instruction set)

For example in BubbleSort should we specify the Swap(..) or Add(..) details? I mean what are those atomic instructions which would stop us to go further?

Or what is a formal definition for an algorithm step? Is there any general mathematical definition for it (like functions or something)?

答:
When defining or talking about algorithmic complexity, you always have an (implicit) target abstract machine in mind (e.g. the RAM machine, the SECD machine, etc). Then the elementary steps are those of that target machine.

Bubble sort is O(n2) only with the assumption that compares are constant time. If you imagine sorting bignums it probably is no more the case (an individual compare is then probably proportional to the size of the compared numbers, i.e. to their logarithm)


答:
How about Code Kata. I've done a few of these, and they're fun to do, and challenging enough that there's always something to learn.

The comments for each of the kata typically have enough information to help answer anything you get stuck on.

Title: Where can I find design exercises to work on?

Body:
I feel it's important to continue practicing my problem-solving skills. Writing my own mini-projects is one way, but another is to try and solve problems posted online. It's easy to find interesting programming quizzes online that require applying clever algorithms to solve - Project Euler is one well-known example.

However, in a lot of real-life projects the design of the software - especially in the initial phases - has a large impact and at later stages it cannot be tweaked as easily as plain algorithms. In order to improve these skills, I'm looking for any collection of design problems.

When I say "design", I mean the abstract design of a software solution - for example what modules will there be and what are the dependencies between them, how data will flow in the program, what sort of data needs to be saved in the database, etc. Design problems are those problems that are critical to solve in the early stages of any project, but their solution is a whiteboard diagram without a single line of code.

Of course these sort of problems do not have a single correct solution, but I'll be especially happy with any place that also displays pros and cons of the typical solutions that might be used to approach the problem.


答: Note that at least in the case of SCSI, the correct term is Host Bus Adapter. And that's exactly what it does: SCSI devices are pretty intelligent and independent, so the SCSI HBA does actually not "control" the devices in the same sense that, say, a floppy disk controller (if you still remember floppies ;-) ) or a USB Host Controller does. A SCSI HBA literally does just that: it adapts from the SCSI bus to the Host Bus (e.g. PCIe) and vice versa.

Title: What does "host" mean in "... host driver" and "... host adapter"?

Body:
From How Linux Works, by Brian Ward, I saw "SCSI Host Adapter", "SATA Host Driver", "Disk Driver (sd)", "CD/DVD Driver (sr)", "USB Host Driver", and "USB Storage Driver".

What does "host" mean in the words?

Why isn't "guest" used?

what differences are between when "host" appears before "driver" and when it doesn't?

what differences are between when "host" appears before "adapter" and when it doesn't?

Thanks.


答:
It doesn't make sense to talk about the step complexity of an algorithm without defining what a "step" is first. Algorithmic complexity is always relative to a model of computation, whether that be transitions of a Turing Machine, reductions in λ-calculus, instructions of a Random Access Machine or the number of comparisons when talking about comparison-based sorts such as bubble sort, quick sort, merge sort, tim sort etc.

Note also that algorithms don't necessarily need to have "steps" at all. Analog algorithms are continuous, they don't have steps.

Title: What is a formal definition for an algorithm step?

Body:
Consider the following code to find the K th minimum element of an array:

```<code>FindKthMin(A[], k)
{
    A = Sort(A);
    return A[k];
}
</code>```

Could it be an algorithm without specifying the sort details?

Can we say algorithm has no meaning without specifying the instruction set (target machine and its basic instruction set)

For example in BubbleSort should we specify the Swap(..) or Add(..) details? I mean what are those atomic instructions which would stop us to go further?

Or what is a formal definition for an algorithm step? Is there any general mathematical definition for it (like functions or something)?


问:
Significance of '__name__ ' attribute in python
1)

Below python code,

```<code>>>> def f():
    return
</code>```

creates a function type object which has __name__ attribute with value 'f' which looks fine.

But,

2)

Below line of code,

```<code>>>> x = 1024
</code>```

creates  int type object but does not have __name__ attribute.

3)

lambda expressions in python also does not associate any unique name for a function type object.

```<code>>>> square = lambda x: x * x
>>> square.__name__
'<lambda>'
>>> summation = lambda x: x + 2
>>> summation.__name__
'<lambda>'
>>>
</code>```

For any program written using Functional paradigm, it  is considered an environment with name-object bindings in that environment.

So, Being functional paradigm programming beginner, How do I understand the significance of __name__ attribute? Why do I see such inconsistency in second and third case above in not maintaining __name__ attribute of an object?

答:
What inconsistency?

In the first case, you have a function. In the second case, you have a lambda expression, that is a function which has no name.

Python could have chosen one of those three approaches:

Returning None,

Returning an arbitrary string, such as <lambda>,

Raising an exception.

All three options are valid, given that the third one will result a try/except instead of an if/else. Python have chosen the second option. Why would you consider two others being more consistent?


问:
Is a makefile really needed
I have been programming in c/c++ for a while now, and I have never once used a makefile. I know that it is supposed to be useful when you are dealing with a large project, but I have always been able to compile, build and execute my program using only

```<code>gcc main.c -o run
</code>```

and if I am working with an external library (gtk+, for example) I make a simple bash script that looks like:

```<code>#!/bin/bash
echo compiling....
gcc main.c `pkg-config --cflags --libs gtk+-3.0` -o run
</code>```

So what I'm asking is do I need to learn how to make a makefile?

答:
Checkout the section on make in The Art of Unix Programming. It explains the motivation behind make and why we have tools that generate Makefiles.

To summarize, the creator of make had a time when he wasted time debugging a working program because he forgot to manually recompile an object code. Make is an automated tool that determines what files need to be recompiled based on timestamps and the dependencies between files. Make is crucial for multi-file projects. You need to learn how to write Makefile in order to declare the dependencies between the files. I recommend you to write medium-sized, manageable Makefiles before learning how to use tools that generate Makefiles.

Title: Is a makefile really needed


问:
Making an automotive system more 'modular' in terms of software?
I am working on an automotive project that we are supposed to make more modular. I am a software specialist and I have very little knowledge of automotive hardware. I don't have any requirements or details about the project other than "making it more modular/portable" and "think in terms of software not hardware". By making it more modular they mean that they want to be able to pick any car and replace its conventional battery or pump with a different type without having to redesign the entire system.

So far the only thing I have come up with is to separate the system into two layers with the first layer having the general code that can be reused in all cars and the second layer has code specific to each component. Of course I don't have the actual source code. I think I am required to produce a general software architecture that they can use for implementing all their systems. I don't have any other idea at the moment.

Any help, direction or source of information is appreciated.

EDIT: I am working with a few electrical engineers and they have some idea about cars. So I am not alone. But still we are lost as they want a modular system and want us to think more in terms of software to save their costs.

答:
I think that at the very least, they should tell you what are the minimal functions of each component. For instance, (I have no clue of car mechanics, so bear with the example), a pump might need to provide the following set of functions: CurrentPressure, MaximumOperatingPressure, MinimumOperatingPressure.

Assuming that all of the components can provide you with a similar set of API's, you could define a series of Interfaces, such as IPump, which would define the bare minimum functions a pump should provide.

This, in turn, would allow you to have some contracts against which you can write drivers, so that, regardless of make and model, you would always have the same set of functions available, where in each model then takes care to implement how are these values provided.

Your centralized code then, would only work in terms of these interfaces. So essentially, your code would not know, nor care for that matter, if you are working with Brand A Pump or Brand B Pump.

This proposal obviously assumes that there is a set of standards somewhere.


答:
Do you have a specific need for make?

Tools like make are all about automation - being able to repeat a process flawlessly, time after time, as efficiently as possible. Check out this thread on github regarding a JavaScript development framework and the potential choice of using make as the build tool:

https://github.com/ericelliott/cloverfield/issues/2#issuecomment-68798159

Whatever tool you choose, you should use it because you have a particular purpose in mind, not because you "should be doing it". You'll see in the github thread that the tooling discussion centers on identifying and meeting specific criteria that the developers want in a task runner.

Other answers in the thread suggest reasons to use make with C programming. Do those benefits sound like things you need?

If you choose to use make, I agree with SHiNKiROU, learn make yourself before you use tools to build Makefiles. I learned a little bit of make during the github discussion, and it was very enlightening.

Title: Is a makefile really needed

Body:
I have been programming in c/c++ for a while now, and I have never once used a makefile. I know that it is supposed to be useful when you are dealing with a large project, but I have always been able to compile, build and execute my program using only

```<code>gcc main.c -o run
</code>```

and if I am working with an external library (gtk+, for example) I make a simple bash script that looks like:

```<code>#!/bin/bash
echo compiling....
gcc main.c `pkg-config --cflags --libs gtk+-3.0` -o run
</code>```

So what I'm asking is do I need to learn how to make a makefile?


答:
How many compilers do you need?

If they have different feature sets, you create a portability problem. If they're commoditised you choose either the "default" (GCC, Clang or VS). If you care about the last 5% performance you have a benchmark-off.

If you're doing programming language work recreationally or for research purposes, it's likely to be in a more modern language. Hence the proliferation of toy compilers for Scheme and ML. Although OCaml seems to be getting some traction for non-toy non-academic uses.

Note this varies a lot by language. Java has essentially the Sun/Oracle toolchain and the GNU one. Python has various compilers none of which are really respected compared to the standard interpreter. Rust and Go have exactly one implementation each. C# has Microsoft and Mono.

Title: Why are there so few C compilers?


问:
Is it bad form to use the same variable name in different scopes?
Say you have some basic code where similar operations will take place in nearby lexical scopes. Take for example some simple pseudo code:

```<code>variable = "foo"
# Do something with variable
if (True) {
    variable = "bar"
    # Do something else with variable
}
for i in range 1..100 {
    variable = i
    # Do another thing with variable
}
</code>```

Say that in each scope, the variable is used for a distinct, but similar task and thus the name "variable" is appropriate in each case. What is the best practice in this case for naming? Should you use the name "variable" each time? Increment the name such as "variable1", "variable2", etc.? Or something else entirely?

答:
Specificity - don't use a variable named variable unless it refers to something specific, like variable timing on an engine. Just don't do it.

In a given context:

Do not re-use variable names in a given context for different purposes. In a function, don't make variable = 'foo' for use as a string then later in the function make variable a numerical index in a loop - that's bad practice and will return to bite you in a big way.

You can re-use variable names in a given context for the same generic purpose, but consider using a new variable to avoid confusion:

```<code>var i, j, myarray = [];
for( i = 0; i < 100; i++){
//
   mayarray.push[ i ];
}

for( j = 0; j < 1000; j++){
   // something with j
}
</code>```

You could technically re-use i for the second loop instead of using a new variable, j, but I would avoid re-use in this case because it can lead to confusion reading the code and could introduce bugs later on.

Outside the same context

We all re-use common variable names like i for loop indexes; that is good practice and improves readability as long as they are not in the same context.

If you are thinking about re-using a non-generic variable name, like partNumber, limit their re-use to places where they refer to the same logical thing in your code as other uses of the variable. Otherwise it can lead to confusion in your code.

Your application has a schema internally that shows the data you are manipulating. Map that schema to your variable names, use generic variable names for generic purposes, and be aware of your contexts for variable re-use.

Body:
Specificity - don't use a variable named variable unless it refers to something specific, like variable timing on an engine. Just don't do it.

In a given context:

Do not re-use variable names in a given context for different purposes. In a function, don't make variable = 'foo' for use as a string then later in the function make variable a numerical index in a loop - that's bad practice and will return to bite you in a big way.

You can re-use variable names in a given context for the same generic purpose, but consider using a new variable to avoid confusion:

var i, j, myarray = [];
for( i = 0; i < 100; i++){
//
   mayarray.push[ i ];
}

for( j = 0; j < 1000; j++){
   // something with j
}

You could technically re-use i for the second loop instead of using a new variable, j, but I would avoid re-use in this case because it can lead to confusion reading the code and could introduce bugs later on.

Outside the same context

We all re-use common variable names like i for loop indexes; that is good practice and improves readability as long as they are not in the same context.

If you are thinking about re-using a non-generic variable name, like partNumber, limit their re-use to places where they refer to the same logical thing in your code as other uses of the variable. Otherwise it can lead to confusion in your code.

Your application has a schema internally that shows the data you are manipulating. Map that schema to your variable names, use generic variable names for generic purposes, and be aware of your contexts for variable re-use.


问:
Which part of the code should rewind a file pointer?
If you had a function that took a handler to a file and then performed some actions that moved the pointer, would you expect it to put the pointer back when it was finished? Additionally, would you generally expect it to rewind to the start before it began its work?

```<code>def hash_contents(fp):
    original_pos = fp.tell()
    fp.seek(0)
    # do hashing / whatever
    fp.seek(original_pos)
</code>```

I've looked around a little to see what the most common assumptions are but I'm not sure what a good rule to follow is. For example, shutil.copyfileobj copies from whatever position the file started in and then consumes to the end.

What are the pros / cons and are there any standard rules of thumb to follow when designing these sort of functions?

This is actually a subquestion of something I was asking over at StackOverflow (Prefer BytesIO or bytes for internal interface in Python?) that really seems more suitable over here.

答: Changing the state of a file handle is such a heavy-weight side-effect that I would want it heavily documented in the interface precisely what the method does, and then it doesn't matter which way you decide.</p>


问:
Consuming a rest API that exposes nested objects
I have a series of nested objects, exposed over a REST API, like so:

```<code>class Categories
{
      int id;
      string name;
      List<Subcategories> subcategories;
}

class Subcategories
{
      int id;
      string name;
      List<Products> products;
}

class Products
{
     int id;
     string name;
     List<Models> models;
}
</code>```

These objects can be accessed over a REST API with the following end points

```<code>// get a list of categories
GET /categories

// get a category
GET /categories/:id

// Get subcategories for a product
GET /categories/:categoryId/subcategories

// Get a subcategory
GET //categories/:categoryId/:subcategoryId

//Get products under a subcategory
GET /categories/:categoryId/:subcategoryId/products

//Get a product
/categories/:categoryId/:subcategoryId/:productId

//Get models
/categories/:categoryId/:subcategoryId/:productId/models

Get a model under a product
/categories/:categoryId/:subcategoryId/:productId/:modelId
</code>```

What design pattern do I use to design a data access layer on the client side?
Please note that my  client only reads these objects, it doesn't write to them.
DAO? Repository? I am a bit confused between the two, not sure what would be applicable here.

答:
Why do you want them nested in your access layer? That API exposes plain objects, not trees of them as I can see.

So, you may build your internal API mimicking that one.

```<code>class Category {
    public static Category[] getList();
    public static Category getById($id);
    public static Subcategory[] getSubcategories($id);
    public void fetchDetails();
}

class Subcategory{
    public static Subcategory getById($id);
    public static Product[] getProducts($id);
    public void fetchDetails();
}
</code>```

I've declared some methods static, but just for clarity sake. In most cases static method on classes may prove testing hard.

In this example created objects are empty by default. fetchDetails() method fills them using REST API. This is to skip one API request when you want to fetch only children of a specific parent without fetching the whole parent first.

Well, as I said, it's only an example. Without the specific requirements of API consumers it's hard to suggest something really useful ;) And requirements tend to change ;)))

Body:
Why do you want them nested in your access layer? That API exposes plain objects, not trees of them as I can see.

So, you may build your internal API mimicking that one.

class Category {
    public static Category[] getList();
    public static Category getById($id);
    public static Subcategory[] getSubcategories($id);
    public void fetchDetails();
}

class Subcategory{
    public static Subcategory getById($id);
    public static Product[] getProducts($id);
    public void fetchDetails();
}

I've declared some methods static, but just for clarity sake. In most cases static method on classes may prove testing hard.

In this example created objects are empty by default. fetchDetails() method fills them using REST API. This is to skip one API request when you want to fetch only children of a specific parent without fetching the whole parent first.

Well, as I said, it's only an example. Without the specific requirements of API consumers it's hard to suggest something really useful ;) And requirements tend to change ;)))


问:
Agile. User stories, Tasks and Reporting
At the moment we are creating tasks based on (pointed) user stories. We then link the tasks to the user story in TFS and move them across the kanban board. Does this sound like a common approach? also how do we report on the tasks? Our velocity doesn't look good as the tasks aren't pointed. we might complete 2 out of 3 tasks in a sprint so how do we report on this?</p>

答: Ok. i think we've got a solution with the user stories.  I can understand how to break them down further now so that they still have value to the business. Part of our problem is tackling too much work at once.  This means we have very little velocity for a few sprints and then it jumps massively when everyones work is complete.  Our approach is to move tasks across the board that are all linked to a user story. We create the user story and tasks in TFS, the tasks are linked as children.  If the business needs to see progress in every sprint then you need to ensure your stories are manageable and maybe that the whole team works on a story to try and complete it in a sprint. if things are less relaxed then maybe you can let a user story run as long as the business can see the progress of the tasks.  Again its all about how it works for you. I think a key question is what the business needs to see and how often. Also, on the Kanban we list the task and the user story that it relates to on the same card.  I'm also thinking that once all tasks are complete in terms of Dev that the actual user story card is placed in the testing lane and the linked task cards are removed from the board.  If the product owner loads up the user story in TFS they will see the status of all the linked tasks.  For anyone interested, the type of work item we use in TFS for a user story is "Functional". When we want to add a task we load the user story and add child tasks as necessary.</p>


问:
Why html entity names for characters like ¥ € ¢ © ®
It make sense to use entity names for describing  as per shown below code.

```<code><!doctype html>
<html>
    <head>
        <title> My First Webpage</title>
        <meta charset="utf-8" />
    </head>
    <body>
        <div>
            <a>
        </div>
    </body>
</html>
</code>```

As per this w3link,
I am not sure,

Why would I require entity names to specify/type characters like  ¥ € ¢ © ® , when the above code already supports utf-8

```<code>        <meta charset="utf-8" />
</code>```

standard where these characters are part of the  Unicode planes?

答: The simple answer is: you don't need HTML entities for anything other than "&" (ampersand), single/double quotes, "<" and ">". The other HTML entities are optional, not required.</p>


问:
What is the purpose of planning poker in a sprint?
Our business analyst and project leads tell us the client's requirement as Stories. Every Sprint planning, we (developers) are asked to play planning poker.

They asked all of us to consider the 'Complexity' rather than 'Effort'. We are really confused and we are wasting time on our meetings. One developer raised a question, 'What should we really want to consider? Is it about the code/DDL change that we have to do in this requirement (time estimation) or is it about whether or not we have understood the requirement?'

But what do they (business analyst & project leads) really mean by 'understand the requirement' and 'raise a card'?

Plus, we have slicing meetings for individual scrum teams, where each developer gives an estimation of time for given task for each scrum team. So, what kind of thing are they really talking about in Planning Poker?

Can anyone explain this using an example? Try to differentiate what they are really talking about when they say 'Complexity' & 'Effort'.

答: Also user story pointing gives the business a heads up in terms of if anything needs re-negotiating. if you have a month to complete some work you scored as 100 then you might be in trouble.  it also gives you chance to break an epic story down into something smaller that still has value and can be completed in a sprint.</p>


答:
I would start by looking at existing standards in this area, like ARINC 653 and (especially) AUTOSAR.

Both of those are real-time component-based systems where components communicate by passing messages. That's more complex, but ultimately far more flexible, that the straightforward approach of using the modularity features of a specific programming language.

Title: Making an automotive system more 'modular' in terms of software?

Body:
I am working on an automotive project that we are supposed to make more modular. I am a software specialist and I have very little knowledge of automotive hardware. I don't have any requirements or details about the project other than "making it more modular/portable" and "think in terms of software not hardware". By making it more modular they mean that they want to be able to pick any car and replace its conventional battery or pump with a different type without having to redesign the entire system.

So far the only thing I have come up with is to separate the system into two layers with the first layer having the general code that can be reused in all cars and the second layer has code specific to each component. Of course I don't have the actual source code. I think I am required to produce a general software architecture that they can use for implementing all their systems. I don't have any other idea at the moment.

Any help, direction or source of information is appreciated.

EDIT: I am working with a few electrical engineers and they have some idea about cars. So I am not alone. But still we are lost as they want a modular system and want us to think more in terms of software to save their costs.


答:
Those entities were created in the first place for two reasons:

Originally, UTF-8 wasn't that ubiquitous: many HTML files were stored using other encodings which easily led to problems when you had to use special characters. By using HTML entities, you were sure they are displayed correctly, no matter what encoding you use.

Those entities make it easy to add them to a page without having to remember the Unicode identifier. What's faster among the following alternatives:

To type © in your favorite editor,

To type © or © (the second representation may not be supported in older browsers),

To type Alt+169,

To run charmap and search for the "©" character,

To open a random web page hoping it will contain the copyright symbol in its footer and copy-paste it.

Obviously, the third one is the fastest, and obviously, every developer remembers that 169 is the decimal representation of the Unicodde © symbol, as everyone remembers the codes corresponding to the quotes “”, mid-dots ·, and a few dozen or hundred of other useful symbols. The second alternative has the same issue.

Which keeps us with three other alternatives. The fourth one takes time. The fifth one may be a bit faster, but still not as fast as typing ©.

While the first reason may be a bit obsolete, the second reason is still valid. This being said, using Unicode characters instead of their HTML representations is a perfectly valid choice and has in turn two benefits:

Readability. If I don't know which code corresponds to which symbol, maintaining HTML full of HTML entities won't be easy.

Size. Shorter HTML means less bandwidth used. Very probably, it doesn't make too much difference, but still.

Title: Why html entity names for characters like ¥ € ¢ © ®

Body:
It make sense to use entity names for describing  as per shown below code.

```<code><!doctype html>
<html>
    <head>
        <title> My First Webpage</title>
        <meta charset="utf-8" />
    </head>
    <body>
        <div>
            <a>
        </div>
    </body>
</html>
</code>```

As per this w3link,
I am not sure,

Why would I require entity names to specify/type characters like  ¥ € ¢ © ® , when the above code already supports utf-8

```<code>        <meta charset="utf-8" />
</code>```

standard where these characters are part of the  Unicode planes?

Body:
Those entities were created in the first place for two reasons:

Originally, UTF-8 wasn't that ubiquitous: many HTML files were stored using other encodings which easily led to problems when you had to use special characters. By using HTML entities, you were sure they are displayed correctly, no matter what encoding you use.

Those entities make it easy to add them to a page without having to remember the Unicode identifier. What's faster among the following alternatives:

To type &copy; in your favorite editor,

To type &#169; or &#x00A9; (the second representation may not be supported in older browsers),

To type Alt+169,

To run charmap and search for the "©" character,

To open a random web page hoping it will contain the copyright symbol in its footer and copy-paste it.

Obviously, the third one is the fastest, and obviously, every developer remembers that 169 is the decimal representation of the Unicodde © symbol, as everyone remembers the codes corresponding to the quotes “”, mid-dots ·, and a few dozen or hundred of other useful symbols. The second alternative has the same issue.

Which keeps us with three other alternatives. The fourth one takes time. The fifth one may be a bit faster, but still not as fast as typing &copy;.

While the first reason may be a bit obsolete, the second reason is still valid. This being said, using Unicode characters instead of their HTML representations is a perfectly valid choice and has in turn two benefits:

Readability. If I don't know which code corresponds to which symbol, maintaining HTML full of HTML entities won't be easy.

Size. Shorter HTML means less bandwidth used. Very probably, it doesn't make too much difference, but still.


问:
How to deal with server-side and client-side naming conventions that clash?
I have a project that uses the underscore naming convention for the MySQL database and PHP scripts but uses camelCase for the javascript application (a common scenario I'm sure).

However, once JSON encoded objects are sent from the server-side to the client-side the javascript naming convention gets polluted with objects that have properties using the underscore naming convention!

The mismatch becomes apparent, for example, when a JSON object property is directly compared with a local variable e.g.

```<code>function matchCustomerByName(customer, firstName, lastName){
  if (customer.first_name === firstName && customer.last_name === lastName) {
     ...
  }
}
</code>```

Maybe its just me but I don't like the above naming style mismatch. My question is are they any standard/preferred/accepted ways of resolving the issue? Is it even an issue?

I'm tempted to use camelCase across the entire project (MySQL, PHP and javascript). The above function would then read:

```<code>function matchCustomerByName(customer, firstName, lastName){
  if (customer.firstName === firstName && customer.lastName === lastName) {
     ...
  }
}
</code>```

However, using camelCase for the MySQL database seems to go against common practice.

Perhaps I could convert between the two naming conventions at the PHP stage? Is there an easy (error proof) way of doing this?

答:
You should assume that the server-side dataobjects use their own conventions, and the client-side would have its own. When fetching/posting data, you can set up a model adapter to handle switching between the two. By doing it at this level, each side uses their own conventions that make sense in each's contexts.

After fetching your data from an ajax get, or whatever, you can pass it to an adapter function like so:

```<code>function adaptCustomerFromGET(json) {
  return {
    firstName: json.first_name,
    lastName: json.last_name,
    ...
  };
}

function adaptCustomerForPOST(model) {
  return {
    first_name: model.firstName,
    last_name: model.lastName,
    ...
  };
}
</code>```

Sure, it's another place to have to update when your model changes, but it's incredibly common to do this kind of thing, since whatever server-side API you're connecting to may have use very different conventions than you'd need client side, including the structure of the data itself; you may be getting a list from the server that you prefer to build a map out of for work client-side.

Body:
You should assume that the server-side dataobjects use their own conventions, and the client-side would have its own. When fetching/posting data, you can set up a model adapter to handle switching between the two. By doing it at this level, each side uses their own conventions that make sense in each's contexts.

After fetching your data from an ajax get, or whatever, you can pass it to an adapter function like so:

function adaptCustomerFromGET(json) {
  return {
    firstName: json.first_name,
    lastName: json.last_name,
    ...
  };
}

function adaptCustomerForPOST(model) {
  return {
    first_name: model.firstName,
    last_name: model.lastName,
    ...
  };
}

Sure, it's another place to have to update when your model changes, but it's incredibly common to do this kind of thing, since whatever server-side API you're connecting to may have use very different conventions than you'd need client side, including the structure of the data itself; you may be getting a list from the server that you prefer to build a map out of for work client-side.


答:
I think they've asked you to do the impossible.  We do something similar in our shop with industrial automation.  We frequently purchase mechanical presses and we retrofit them with our own control system.  We try very hard to make the user interface similar across all the presses, but internally they are sometimes similar and sometimes very different.  One press is equipped with hydraulic overloads, one has strain gauge-style tonnage monitoring while another has piezo-electric style tonnage monitoring.

Even among systems that every press has, like a press lubrication pump, the way they work are all generally different.

How do we handle these differences without insanity?  We don't.  The software for each press is about 90% custom.  We do have a "common library" of functions that we use across presses, such as an event logging system, but the events that are actually logged on each press are almost completely unique.  The common library contains standard logic for interfacing with an analog input card that we use across all the presses.

Each press has a main motor, but electrically these all work subtly differently, so we have custom logic for each.

In your example, can you make it so that you can replace a pump with a different model without having to make software changes?  I doubt it.  In fact the important thing is that you anticipate the need to change something when they do that, and you think about where these changes will be made.  Try to make it so these changes are limited to a single class or module.  What does the rest of the system care about that pump?  Does some other system need to know that pump is running before it can do its job?  Then your interface needs a Pump.Running property.  How you set that bit will probably have to change when they replace the pump, but at least the change should be localized.  You know that you'll need to log problems to the car-wide error reporting system, so you probably need an error reporting interface, and you should assume your Pump module will need to be injected with a reference to that interface in the constructor or initialization code.


问:
RESTful basic http atuhentication credentials
I am currently working on web application which has front-end, and back-end.
Back-end has RESTful architecture, or something that looks like RESTful to me (this is my first attempt to make something RESTful).

Few weeks ago I started to implement security for RESTful services.

I found out that there are few ways to that:

basic http authentication

Oauth 1.0

Oauth 2.0

After some reading and watching videos on the subject this is what bugs me:
With basic http authentication, front-end application sends username and password with every request.

Should those be the same end user credentials different for every user or should they be sort of "app credentials" for accessing services?

答:
When it comes to API authentication, those are the three most used models (in random order):

Credentials are sent with every response.

Credentials are sent once to generate an access key. The access key is then sent with every request.

Credentials are sent once, and then a session (relying on cookies) is used to avoid repetitive authentication. Since one of the properties of REST is that it is stateless, this shouldn't be considered as REST and won't be discussed in this answer.

The first one has a benefit of simplicity: you don't have to deal with the additional access key, its generation (it should use cryptographically secure pseudo-random number generator), its validation and its invalidation (how long should the client stay inactive for the key to become obsolete?).

The drawback, on the other hand, is the impact in terms of performance. Instead of verifying credentials once, you should verify them at every request, which also means that you probably cannot use PBKDF2 with a high number of rounds, since it will take too much CPU power and slow down the API tremendously).

Note that in the first case, you will be sending credentials through HTTP's Authorization header. In the second case, Authorization header should not be used to send the access key, since it's not its purpose. Including the access key in the URI seems to be a common practice, although it results in long, cryptic URIs and pollutes HTTP logs.

Should those be the same end user credentials different for every user or should they be sort of "app credentials" for accessing services?

You shouldn't use user password. If you do it, this means that you stored it, somehow, somewhere, in plain text, and that's a very, very bad practice.

There are two ways to use an API:

Per-user usage. This is often the case where the third-party API is accessed through JavaScript on client side. For instance, if your website allows a user to view the list of his friends from another website, the list being loaded through JavaScript by calling this other website API, you'll usually have a per-user usage.

In this case, there will be an association between the API account and the user account, so each user can access the API using a specific (randomly generated) client ID and the corresponding (cryptographically secure randomly generated) access key. The API should rely on the access key as its authentication means, but in any case should it receive or request the original user's password.

Per-application usage. This is often the case where you, and not your users, are using the third-party API. For instance, if you need to access some financial data, generate the reports and then sell those reports to the users (given that every paying user will have the same report), you're in this case.

Here, you'll have a single client ID and the corresponding access key. You'll need to store them securely on your server and under no circumstance share it with your clients.


问:
c++11 random: why different range of int and real?
In the c++11, we now have <random> to produce random number.
About uniform distributions, we have following int_distribution and double_distribution:

```<code>uniform_int_distribution-produces integer values evenly distributed across a range

uniform_real_distribution-produces real values evenly distributed across a range
</code>```

The first produces random integer values i, uniformly distributed on the closed interval [a, b], but the second, ie real one, produces random floating-point values i, uniformly distributed on the interval [a, b)

Question: why int and real distribution have different range, ie for one b] is inclusive but for another b) is exclusive?

If it is related with the algorithms behind, I would like to know what are they and where are the differences. Or preferences about it.

答:
Closed intervals "feel" more natural in a discrete setting.
Half-open intervals "feel" more natural in a continuous setting (well, they feel more natural even for rationals, but...).

I would be surprised by a "generates integer numbers" function that didn't use intervals if I gave it an explicit minimum and maximum, but I'm essentially OK with a single-argument one that takes rand(N) and gives me a result in [0, N-1], but if I give it rand(a, b) I actually want [a, b].


问:
Making backend service urls configurable
First of all, I will talk a little about the purpose of this question. We have several linux boxes on the same network on which different services are installed, some times these boxes are decommissioned and new boxes take its place. The services also need to be moved along with thoxe boxes. Now my internal web portal which is built in angular.js has to be be redeployed with the new set of hardcoded urls to access the services in the new boxes.

I am trying to get around this problem by creating a page that we could use to change the backend database and trigger the website to reload the url mappings from the DB. So in the event there is a box move the service urls can be picked up dynamically on changing the config. All the configuration is stored in a Database.

I havent figured out the triggering part yet. Is this the correct way of creating the setup, or am I doing it all wrong. With my limited knowledge in web dev this is all I could come up with.

Any pointers or reference docs would be very useful.

Thank You!

答:
Use CNAMEs in your internal DNS. Then you just point your url at e.g. http://foo-service.example.com/ and leave it there.

When you move the service from machine A to machine B, move the CNAME.


答:
Short answer:

Do the name to box resolution at the network tier, either setup a DNS server as the 'database' that holds the resolution table, or do it in the router. An easier approach might be to set up the routes in your web portal machine's hosts file. Depending on how you make the calls that might not need a redeploy.

Longer answer:

I you want to go for a bigger change then an approach used in the new 'cloud' way would be to have a state store keeping track of your network topology. So if each application was in a docker container and your network mapping (key = hostname to value = ip address ) was in say ZooKeeper then the 'triggers' can be ZooKeeper watchers that are capable of spinning up new docker conatiners when a new child node is created in your ZooKeeper registry.

PS.

There are other ways of storing the state than ZooKeeper.

If you don't want to use docker containers then you could use Virtual Machines.

Title: Making backend service urls configurable

Body:
First of all, I will talk a little about the purpose of this question. We have several linux boxes on the same network on which different services are installed, some times these boxes are decommissioned and new boxes take its place. The services also need to be moved along with thoxe boxes. Now my internal web portal which is built in angular.js has to be be redeployed with the new set of hardcoded urls to access the services in the new boxes.

I am trying to get around this problem by creating a page that we could use to change the backend database and trigger the website to reload the url mappings from the DB. So in the event there is a box move the service urls can be picked up dynamically on changing the config. All the configuration is stored in a Database.

I havent figured out the triggering part yet. Is this the correct way of creating the setup, or am I doing it all wrong. With my limited knowledge in web dev this is all I could come up with.

Any pointers or reference docs would be very useful.

Thank You!