问:
How can I encourage people to read error messages?
I was wondering if there are some good ways to encourage people to read error messages when the compilation fails.

People (especially) the junior ones usually ignore the error messages and just ask for help. I want them to be better and have run out of ideas. These are what I have tried.

I tell them to check error messages when compilation fails.

I sit and check the error messages with them.

When they ask me for help, I ask if they have checked the error or not.

Please let me know if you have similar experience and how you deal with it.

答:
"When the compilation fails"... in such cases, I'd go over to them as if to help with a brand new, difficult, requires-experience error... I'd go through the basic steps of "show me" and then I would read the error message that was displayed by the compiler, and if it really was a case of do-what-the-error-message-says, I'd put on my best "you are a child" face, ask them why they couldn't have read that themselves, then and walk away.

You can't really not help them when they ask, but you can be disparaging about it if they are wasting your time.


答:
Do not help right away. Make the junior colleague wait for at least 15 minutes, after one or two of this 15 minutes cycles, he/she will start to look at the issue on his own. Just don't say directly "wait 15 minutes", use something like "I'm busy, please let me finish x, then I help you".

If you help him immediately, this is the shortest path he has for the solution of the problem, then of course he will use this path. But, instead if you say, I will help you and solve the issue, but please, wait for 15 minutes before I can help you, during this time he will stare at the screen to see what he might try on this "wait time", he will probably look at the error messages on his own. :-)

If they do not start to look for the error for themselves, then you can say the person lacks of initiative or experience. If the problem is initiative, it is hard to solve. If it is experience after one or two analysis together, they should start to figure it out.

ContentLicense: CC BY-SA 3.0

Title: How can I encourage people to read error messages?

Body:
I was wondering if there are some good ways to encourage people to read error messages when the compilation fails.

People (especially) the junior ones usually ignore the error messages and just ask for help. I want them to be better and have run out of ideas. These are what I have tried.

I tell them to check error messages when compilation fails.

I sit and check the error messages with them.

When they ask me for help, I ask if they have checked the error or not.

Please let me know if you have similar experience and how you deal with it.


问:
Develop GUI and logic in a team the right way?
I am planning to start a small project with a friend. I will be developing the GUI using JavaFX in the MVC pattern and he will be responsible for the model/logic.

My question is: how can we achieve a save parallel developing, how do companies do that? Would we just write an interface for the model together, that specifies what functionality I will need in the controller and thus he has to implement?

Thx in advance.

答:
To your specific question in terms of code: A good idea would be to use the facade pattern to have a single point of access to the model from the controllers, so you can always call the facade and don't have to think about how his model logic will deal with the request internally, or which classes he will use. Furthermore, if MVC is done correctly the model, view and controllers will be swappable (as in, you could develop the view/controllers in javaFX but someone else can just use the same model and write android views/activities to call the logic). Meaning that you should not tell him what to provide from a controller point of view, but you should have your controller work with what the  model provides. Ofcourse, the model has to provide all the necesarry logic so here are some tips on how to achieve this in general.

To your question in general: If it's just you and a friend there are several things you can do to improve smooth development. Communication is important here, make sure you have predefined what you want to create and discuss some aspects of how this might be done.

Maybe create some user stories (http://en.wikipedia.org/wiki/User_story) or create a GUI mockup (each create a mockup, or you just create one) and discuss it. This will make you know what is required from a user point of view in the GUI, and he will see how your GUI handles this and will know which data will have to be provided by the model.

In addition you could try pair-programming, so he gets a feel for the view/controller code and you get a feel for the model code. Ofcourse you're not strictly developing apart anymore then, but rather together on some parts. Anyway, as it's only a two-man project and you both get along, this might be a fun and enriching experience.

Anyway, if you run into a problem where you think "Frick, I need this data but the facade doesn't expose it" you can just tell him that you need that bit of data and he can create a method in the facade that provides this. Sometimes requirements change or you have to do something you didn't think of before. That's software development though ^^


问:
Request content-type of HTTP errors
HTTP allows for multiple representations of a resource. The Accept header allows the client to choose the representation of the resource.

```<code>GET /foo/bar HTTP/1.1
Accept: application/pdf

GET /foo/bar HTTP/1.1
Accept: text/html

GET /foo/bar HTTP/1.1
Accept: image/svg+xml
</code>```

If the response is 200 OK, the entity is expected to be the resource as that content-type.

But in the spec (RFC 2616), there are a lot of references to entities that aren't resources: 201 Created, 202 Accepted, 409 Conflict, 5xx, etc.

For example, for a 403 Forbidden response:

The server understood the request, but is refusing to fulfill it...If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity.

But what is the type of the entity? An HTML page? JSON?

As I read the standard, the Accept header applies only to the resource entity. It would be odd to generate a PDF of why the server was in error, just because the request was for an application/pdf.

There is a way to have multiple representations of resources. Is there a standard mechanism to have multiple representations of errors? (In my case, there are clients that either use primarily JSON, or primarily XML.)

I realize I can always make a X-Paul-Conflict-Accept and the X-Paul-Create-Accept and the X-Paul-Forbidden-Accept headers; I was curious if there was a usual way of handling this.

答:
RFC2616 states: " Any response containing an entity-body MAY be subject to negotiation,  including error responses." This means that it is acceptable to use the Accept header for this purpose, but that the server is not required to do so (it may choose to ignore the browser's preferences for error messages).

Note that typically, a browser would not send a header that looks like your examples:the usual way of using the Accept header is to list all formats you are capable of understanding in order of preference, not just a single format. The application to error messages is more apparent in this case, as rather than requesting "application/pdf", the browser would be more likely to request "application/pdf, txt/html, text/plain", which the server is able to fulfill.

Title: Request content-type of HTTP errors


问:
Code First vs. Database First
When I design and create the software I work on, I typically design and create the back-end SQL tables first and then move on to the actual programming. The project I'm currently working on has me down right puzzled though. This is probably due to a lack of good, solid requirements, but there's unfortunately little I can do about that this time. It's a "just go make it happen" kind of situation.. but I digress.

I'm thinking of flipping my workflow on it's head and creating the UI and data model classes first in hopes that working that out will make it clear to me what my database schema will eventually look like. Is this a good idea? I'm nervous that I'll end up with a UI and still no idea of how to structure the db.

If anyone is curious, I'm using SQL Server as a backend and MS Access as a front end application. (Access isn't my choice either... so please don't hate on it too bad.)

答:
In general i think code comes after data because the code is going to manipulate the data.

If requirements are not clear you can create a data model of your interpretation of the requirements. Best is maybe to write down some requirements and send it to your employer, then they have something to shoot at.
Or create a gui first, it depend of the type of employer what works best :)

Title: Code First vs. Database First


答:
This is a bit of a behavior modification question, but needs to be addressed in a development team environment. Do your junior developers have to do support or any type of bug fixing?  Ask them how they feel when someone just tells them "I got an error" with no other information. We can avoid all the name-calling that probably goes on when they have to deal with stupid users.

When they tell you there is an error, ask them what the error message was. They can include it in an email or register in some sort of bug tracker/team information/wiki system. This way, others can look up a solution for this error message when it reoccurs.

You need to be diligent. Ask for the message. Ask if they looked up the message for previous solutions (Just like you tell your users.). You don't want to be perceived as not helping, so if it is a new problem, you should try to address it as conveniently as possible. Compliment those who contribute to the documentation of these errors.

As a team, you need to address the problems of interruptions. It may seem more convenient to just ask the person who knows the answer right away, but getting pulled away from your code create other problems and delays in the long run. The junior developers need to learn this.


问:
More efficient management of assets(image, documents) in a large web project
I am beginning to refactor a large, very old, messy project. One of the biggest issues is the lack of a central location on the filesystem for simple things like images, icons, documents, csv, etc.

The number of assets is on the scale of thousands, so I am looking for ways streamline management. Should I be looking into finding a CDN or some other kind of external storage and load/store the files that way?

Or should I continue to store files in the local file hierarchy? I would like to use a process that is easy to manage and common, so that there is little friction as the development team grows.

答:
There are a couple of ways to approach this, depending on your requirements and scale.

First of all though, I don't believe a CDN is appropriate in this case. A CDN is used for caching of static documents to provide faster delivery of those assets to end users. It's not relevant for centralised storage or management of files.

At the larger end of solutions are Digital Asset Management (DAM) systems, such as Adobe Bridge. These are specialised applications that allow management of assets for digital channels, and can be easily integrated to server your web app(s).

An easier solution is to roll your own, using blob storage within your database (or some other blob storage mechanism like Microsoft Azure Storage). This will allow you to work with a database and use ORM's in your code for managing the assets. It's also far more performant (and ACID safe) than reading from a file system.


问:
Why isn't software abstract on a grander scale?
Consider the following example:

The user wants a program to calculate a few fibonacci numbers.
Sounds easy enough. pseudocode:

```<code>stdout.write("How many fibonacci numbers do you want to calculate? ")
int count = int(stdin.readline())
while count>0:
    stdout.writeline(calculate_next_fibonacci_number())
    count--
</code>```

Even a very simple program like this is already flawed:

The program writes to stdout. That is not actually what the programmer intended, is it? The intention is to display a bunch of number to the user, not to write some text to stdout - there's no guarantee the user will ever see the text that's written to stdout.

Similarly, the user input is read from stdin, which is a text (or file, if you prefer) interface, when in reality, the program requires a number, not text. This seems fundamentally wrong.

Let's think about what we're trying to do more abstractly. We want to:

Calculate a bunch of numbers. How many is up to the user.

display the results to the user.

Why, then, don't we write code exactly like that?
(Most) programming languages provide this thing called a "function", which accepts parameters and uses them to do something. Does that not sound exactly like what we're trying to do?

```<code>void display_fibonacci_numbers(
        int number "how many fibonacci numbers to calculate"):

        Sequence<int> numbers
        while number>0:
            numbers.append(calculate_next_fibonacci_number())
            number--

        notify(numbers)

display_fibonacci_numbers()
</code>```

This code is, of course, incomplete - the notify function isn't implemented anywhere, and the user needs some way of inputting a number. I would imagine the user's operating system or desktop manager or whatever to take care of that - it could display a terminal, it could generate a GUI, it could tell the user do write the number into the air with his nose; either way it does not (should not) concern me, the programmer.

It is my belief that software should be more abstract.

A few more examples.

inter-process communication. How do you do it? Sockets? Signals? DBus? Files? The goal isn't to use sockets, signals or dbus, it's to communicate with another process. Why not something like Process.from_name("Music player").play_random_song()?

Downloading files. local_file.write(remote_file.read())? Why not download(url), which could, depending on the system configuration, start the download right away, but with a low priority so as not to slow down other downloads, or add it to the download queue to be downloaded later, or whatever?

File paths. Why on earth are file paths still strings (in most languages, at least)? Why do we have to deal with whether the path separator is / or \, whether it's ., .., or whatever? Why is there no FilePath class that takes care of this?

Going a step further, why not apply the duck-typing concept to modules? For example, in python, HTML is often parsed using the beautifulsoup module:

```<code>from bs4 import BeautifulSoup

page= BeautifulSoup(urlopen('http://test.at'))
</code>```

Again, the programmer's goal wasn't to use BeautifulSoup, but to parse HTML. Why, then, would he explicitly tell his code to use the BeautifulSoup module? What he really wants is to

```<code>import HTMLParser
page= HTMLParser.parse(urlopen('http://test.at'))
</code>```

Duck-typing for modules: Who cares what module it is as long as it does what I want?

Why is programming not like this? Am I overlooking something, something that makes all this impossible (or impractical)?

答:
You can buy a lot of pre made parts at the store, but there are still craftsman machinists that are needed to fabricate parts that do not exist. The abstractions are there, but not always for every environment. At some point, someone is going to need to flip a bit in a way that no abstraction in the form of a function is going to be available.

I'm going to use your file path string as an example:

File paths. Why on earth are file paths still strings (in most
  languages, at least)? Why do we have to deal with whether the path
  separator is / or \, whether it's ., .., or whatever? Why is there no
  FilePath class that takes care of this?

Sometimes these abstractions exist, but not in the programming language itself. Microsoft Windows, .NET Framework and the family of programming languages that use .NET and run on Windows has this capability. http://msdn.microsoft.com/en-us/library/system.io.path%28v=vs.110%29.aspx

It's not really part of the programming languages (VB.NET, C#, F#, etc.), but a framework. I see this .NET framework as an abstraction of all the Windows plumbing that is necessary and not really part of the logic or algorithms we need to create in our code. The programmer can chose to use this object from the .NET framework or create his own. Your argument seems like creating your own is a bad idea because there is something better that is more available, so why give the developer the choice? I'm not sure how you take that choice away. Prevent a file location string from ever being able to interact with the file system in any way shape or form? You can only program for Windows if you use the appropriate framework and family of languages? How do you get the URL from the web? Does it have to come in the form of a .NET IO object?


答:
The law of diminishing returns applies to abstraction just like anything else. Is it better to configure a device using jumper wires or DIP switches? Probably DIP switches, which are an abstraction over connecting jumper wires. Is it better to program in machine language or assembly language? The answer is almost certainly assembly language. It's difficult for me to think of some scenario where you wouldn't want to at least use an assembler to generate your machine language.

However, we're well beyond the mild abstractions I just suggested, and I would posit that many, maybe most, programmers are working at a level of abstraction beyond the point of diminishing returns already.

An example: I work with several PAAS systems that attempt to make the difficult task of integration with other systems more abstract and easier. I continually find myself wondering what's really going on beneath the clean-looking façade presented by such systems:

What does the word "blank value" in that checkbox label mean? Does it mean that the source row is present but the column value is null? Does it mean that the source row is absent? Does it mean both? Does this particular PAAS tool even have a concept of true / false / null? If so, which fields are nullable (and is this setting buried deep in a dialog somewhere, in an effort to make the user experience more abstract)?

When I select the "add records to target database" option, will this update records as well? I don't see an "update" option... so "add records" must do updates, too... right? (This may seem like a ridiculous example, but it's a real one. And yes, I did end up on Google trying to determine whether "add" really means "add/update" for one particular setting in one particular PAAS tool- is this your idea of a good developer experience?)

It's difficult to answer these questions, since all of that programmer stuff has been studiously hidden away, locked into black box implementations, etc., in the name of presenting an abstract user interface. I end up having a hard time even formulating the necessary questions (whether directed at Google or at tech support). I'm wondering about things like nullability and "upsert" operations, but my interlocutors are actively avoiding the use of such low-level technical terms. But these sorts of questions need to be answered to do integration...

And my last point hints at a possibility that, as we develop a more of a shared language of computing, we may be able to work at a more abstract level. If non-programmers (including GUI designers) would use standard terms like nullable, "upsert", foreign key, etc., then maybe a lot of things currently done using code could be done graphically, or in an otherwise more abstract manner. But when people say "add" instead of "upsert", because "upsert" is scary programmer language, well, I have to fall back on my old, low-level skills and tools to actually get the job done.

Title: Why isn't software abstract on a grander scale?

Body:
Consider the following example:

The user wants a program to calculate a few fibonacci numbers.
Sounds easy enough. pseudocode:

```<code>stdout.write("How many fibonacci numbers do you want to calculate? ")
int count = int(stdin.readline())
while count>0:
    stdout.writeline(calculate_next_fibonacci_number())
    count--
</code>```

Even a very simple program like this is already flawed:

The program writes to stdout. That is not actually what the programmer intended, is it? The intention is to display a bunch of number to the user, not to write some text to stdout - there's no guarantee the user will ever see the text that's written to stdout.

Similarly, the user input is read from stdin, which is a text (or file, if you prefer) interface, when in reality, the program requires a number, not text. This seems fundamentally wrong.

Let's think about what we're trying to do more abstractly. We want to:

Calculate a bunch of numbers. How many is up to the user.

display the results to the user.

Why, then, don't we write code exactly like that?
(Most) programming languages provide this thing called a "function", which accepts parameters and uses them to do something. Does that not sound exactly like what we're trying to do?

```<code>void display_fibonacci_numbers(
        int number "how many fibonacci numbers to calculate"):

        Sequence<int> numbers
        while number>0:
            numbers.append(calculate_next_fibonacci_number())
            number--

        notify(numbers)

display_fibonacci_numbers()
</code>```

This code is, of course, incomplete - the notify function isn't implemented anywhere, and the user needs some way of inputting a number. I would imagine the user's operating system or desktop manager or whatever to take care of that - it could display a terminal, it could generate a GUI, it could tell the user do write the number into the air with his nose; either way it does not (should not) concern me, the programmer.

It is my belief that software should be more abstract.

A few more examples.

inter-process communication. How do you do it? Sockets? Signals? DBus? Files? The goal isn't to use sockets, signals or dbus, it's to communicate with another process. Why not something like Process.from_name("Music player").play_random_song()?

Downloading files. local_file.write(remote_file.read())? Why not download(url), which could, depending on the system configuration, start the download right away, but with a low priority so as not to slow down other downloads, or add it to the download queue to be downloaded later, or whatever?

File paths. Why on earth are file paths still strings (in most languages, at least)? Why do we have to deal with whether the path separator is / or \, whether it's ., .., or whatever? Why is there no FilePath class that takes care of this?

Going a step further, why not apply the duck-typing concept to modules? For example, in python, HTML is often parsed using the beautifulsoup module:

```<code>from bs4 import BeautifulSoup

page= BeautifulSoup(urlopen('http://test.at'))
</code>```

Again, the programmer's goal wasn't to use BeautifulSoup, but to parse HTML. Why, then, would he explicitly tell his code to use the BeautifulSoup module? What he really wants is to

```<code>import HTMLParser
page= HTMLParser.parse(urlopen('http://test.at'))
</code>```

Duck-typing for modules: Who cares what module it is as long as it does what I want?

Why is programming not like this? Am I overlooking something, something that makes all this impossible (or impractical)?


问:
Decentralized Data Management - encapsulating databases into microservices
I've recently been taking a course on Software design and there was a recent discussion/recommendation about using a 'microservices' model where components of a service are separated into microservice sub-components that are as independent as possible.

One part that was mentioned was instead of following the very often seen model of having a single database that all the microservices talk to, you would have a separate database running for each of the microservices.

A better worded and more detailed explanation of this can be found here:
http://martinfowler.com/articles/microservices.html under the section
Decentralized Data Management

the most salient part saying this:

Microservices prefer letting each service manage its own database,
  either different instances of the same database technology, or
  entirely different database systems - an approach called Polyglot
  Persistence. You can use polyglot persistence in a monolith, but it
  appears more frequently with microservices.

Figure 4

I like this concept and, among many other things, see that as a strong improvement on maintenance and having projects with multiple people working on them. That said, I am by no means an experience software architect. Has anyone ever tried to implement it? What benefits and hurdles did you run into?

答:
I wholeheartedly agree with btilly's answer, but just wanted to add another positive for Microservices, that I think is an original inspiration behind it.

In a Microservices world, services are aligned to domains, and are managed by separate teams (one team may manage multiple services). This means that each team can release services entirely separately and independently of any other services (assuming correct versioning etc).

While that may seem like a trivial benefit, consider the opposite in a Monolithic world. Here, where one part of the application needs to be updated frequently, it will impact the entire project, and any other teams working on it. You will then need to introduce scheduling, reviews etc etc, and the whole process slows down.

So as to your choice, as well as considering your scaling requirements, also consider any team structures required. I would agree with btilly's recommendation that you start Monolithic and then identify later where Microservices might become beneficial, but be aware that scalability is not the only benefit.


答:
I find senior developers guilty of the same mistake; that's why I think this is a sign of being overwhelmed instead of "doesn't care."

My reaction is always the same: When I hear "doesn't work", I ask: "What error message do you get?" (and I try to be polite).

The answer will then tell me whether the person needs to vent some steam before they can start thinking again - if someone is in this state, no advice in the world will work since they simply can't listen; calm them down, first.

If they were just lazy, insist that they go back and read the error message. If you think they should know what it means/how to solve it, start asking questions: like "What do you think could cause this?", "What does foo mean here?", "What did you change right before the error happened?" Asking questions is a good way to kickstart someone else's brain since most people try to be helpful when asked. So this is received as positive support even though you don't actually "help" them.

If they simple don't understand what is going on, sit with them and explain to them how to fix the error. I tend to have them fix the error themselves for two reasons:

The brain remembers things better that you have done yourself (instead of watching someone else do it).

If they don't understand the explanation, that gives them a chance to ask.

If I'd fix the error myself, there is always the danger that they now have working code but don't know why.

PS: This goes to all the senior developers: Write better error messages. A good error message explains how to fix a problem; a bad one is a variant of "There were errors."

So instead of File not found, say File ...path... not found. Instead of Glabarfel couldn't be initialized, say Glabarfel wasn't initialited properly; missing Foo. See http://.../docs/setup/glabarfel/foo.html for details.


答:
Why, then, don't we write code exactly like that?

We do. Your Fibonacci example is a clear violation of the single responsibility principle. One method should be responsible for being a generator that provides the Fibonacci sequence. Other parts are then responsible for taking N values from it, or skipping N values, or getting input, etc.

I would imagine the user's operating system or desktop manager or whatever to take care of that - it could display a terminal, it could generate a GUI, it could tell the user do write the number into the air with his nose; either way it does not (should not) concern me, the programmer.

Sometimes it does not concern you the programmer. In those cases, you use some UI abstraction that does that glue to turn "get a number" and "print these numbers" into platform specific implementations. These already exist and are commonly used.

But you're missing the point.

The vast majority of a programmer's job isn't making these whole programs, but gluing disparate bits of existing code together. There is already code to make the Fibonacci sequence. There is already code to take the first N of a sequence. There's already code to print numbers on this platform.

The only reason you're there is because someone wants all of those bits of code together. Why wasn't it the first N primes instead? The specifics of how to get input and print output are just as vital requirements as what sequence to use.

Why not something like Process.from_name("Music player").play_random_song()

AppleScript already does stuff like this. WCF in many ways already abstracts away the mechanics of the communication from the semantics of the communication.

Why not download(url)

C# (and others) already have libraries to do this. Granted they already have well defined semantics, because configuration is vile. It's code without any of the framework/process to make code with quality. Worse yet, it removes any quality (and often, performance) from your real code.

Why is there no FilePath class that takes care of this?

C# (and others) already have libraries to do this.

Going a step further, why not apply the duck-typing concept to modules?

Some (more esoteric) languages do. Modules are treated as large objects, which can have their own interfaces, be instantiated, parameterized, etc.

The problem is that the vast majority of "how it works" is defined by the interface to the module. One implementation will have auto-closing file streams, and another will use Open and Close. These are strictly different interfaces.

Why is programming not like this?

There are a boatload of reasons.

Probably the most compelling is this sort of scenario. No matter that having your OS control how to input/output makes programmers make better code faster, some business person will want you to do something different to "differentiate".


问:
Should I use ASP .resx resources if the website is available in a single language?
Is it a best practice to always store strings in ASP .resx resources files, even when the application is not localized according to the user culture ? (Web pages will be displayed in french.)

Is there reasons for using resources other than provide pages in different languages easily ?

In favour of resources, something "smells wrong" or "seems ugly" about writing code that mix HTML, ASP/Razor and hard-coded strings :

```<code>@Html.LabelFor(Model.FirstName, "Votre prénom :");
...
<input type="submit" value="Modifier votre profil" />
...
<div class="error">Une erreur est survenue</div>
</code>```

Or worse, mixing .NET/C# code and hard-coded strings :

```<code>[Display(Name = "Le salaire actuel de l'employé")]
public int Salary { get; set; }
</code>```

In favour of hard-coded strings, using resources when they aren't needed is consequent extra-work for the developer and (seems to) violate YAGNI.

答:
The nice thing about YAGNI is that it can be quantified. There are three metrics too look at:

The time saved by applying YAGNI and not implementing something up-front.

The probability that the application will have to be rewritten

The time needed for rewriting the application a couple of years in the future.

When time saved > time needed for rewriting × probability of rewrite, then it is advantageous to not invest in a more flexible architecture right now. YAGNI can be understood as a heuristic that says “the probability of a rewrite is near zero, so it can usually be ignored”.

But here we have a case where the time saved is very small compared to the time needed for a rewrite of all your templates, and the probability of a rewrite is probably not nil – what are the odds that the website would want to offer navigation in English some time during the next five years? That sounds like a reasonable requirement for most sites.

So instead of having to rewrite the application later, you may want to do it right the first time.

Of course, using localization has advantages beyond supporting multiple languages, for example proper formatting of numbers and quotation marks. Also, not putting text into templates helps separating implementation from design from content. Ideally, a non-programmer would be able to change the text of a button, and would not have to search through a template file. Such considerations further skew the advantage towards using a proper design even when it feels like overkill.

I recently wrote a small website (using a different technology stack) and went through these considerations. In the end, I found that in my case the probability of having to support additional languages was negligible, so I didn't go for internationalization. However, I took on some technical debt through this decision because my template files are admittedly a bit of a mess. Using localization files would not have completely solved this, but would have helped keeping different concerns separate. I estimate that my decision to skimp on localization files was not worth it, because I'll have to rewrite the templates anyway.


答:
I worked at a place that had a fair amount of independent data sources. They did put them all into a single database, but into different schemas that were accessed by webservices. The idea was that each service could only access the minimum amount of data they required to perform their work.

It wasn't much overhead compared to a monolithic database, but I guess this was mostly due to the nature of the data that was already in isolated groups.

The webservices were called from the web server code that generated a page, so this is a lot like your microservices architecture, though possibly not as micro as the word suggests and not distributed, though they could have been (note that one WS did call out to obtain data from a 3rd party service, so there was 1 instance of a distributed data service there).  The company that did this was more interested in security than scale however, these services and the data services provided a more secure attack surface in that an exploitable flaw in one would not give full access to the entire system.

Roger Sessions in his excellent Objectwatch newsletters described something similar with his Software Fortresses concept (unfortunately the newsletters are no longer online, but you can buy his book).

Title: Decentralized Data Management - encapsulating databases into microservices

Body:
I've recently been taking a course on Software design and there was a recent discussion/recommendation about using a 'microservices' model where components of a service are separated into microservice sub-components that are as independent as possible.

One part that was mentioned was instead of following the very often seen model of having a single database that all the microservices talk to, you would have a separate database running for each of the microservices.

A better worded and more detailed explanation of this can be found here:
http://martinfowler.com/articles/microservices.html under the section
Decentralized Data Management

the most salient part saying this:

Microservices prefer letting each service manage its own database,
  either different instances of the same database technology, or
  entirely different database systems - an approach called Polyglot
  Persistence. You can use polyglot persistence in a monolith, but it
  appears more frequently with microservices.

Figure 4

I like this concept and, among many other things, see that as a strong improvement on maintenance and having projects with multiple people working on them. That said, I am by no means an experience software architect. Has anyone ever tried to implement it? What benefits and hurdles did you run into?


问:
Is there ever a reason to use an array when lists are available?
It seems like List<T> in C# can do everything an array can do and more, and seems also just as efficient in memory and performance as an array.

So why would I ever want to use an array?

I'm obviously not asking about cases where an API or other external constraint (i.e. the Main function) requires me to use an array... I'm only asking about creating new data structures in my own code.

答:
This actually goes for other languages which have lists as well (such as Java or Visual Basic). There are cases where you need to use an array because a method returns an array instead of a List. </p>

<p>In an actual program, I don't think an array will be used very often, but sometimes you know the data will be a fixed size and you like the small performance gain you get from using an array. Micro-optimisation would be a valid reason, just as a method returning a list, or the need for a multidimensional datastructure. </p>

Body:
This actually goes for other languages which have lists as well (such as Java or Visual Basic). There are cases where you need to use an array because a method returns an array instead of a List.

In an actual program, I don't think an array will be used very often, but sometimes you know the data will be a fixed size and you like the small performance gain you get from using an array. Micro-optimisation would be a valid reason, just as a method returning a list, or the need for a multidimensional datastructure.


答:
So why would I ever want to use an array?

Rarely, you will have a scenario where you know that you need a fixed number of elements. From a design perspective, this should be avoided. If you need 3 things, the nature of business means that you'll very often need 4 in the next release.

Still, when this rare scenario actually occurs, using an array to enforce that fixed size invariant is useful. It provides a signal to other programmers that it is a fixed size, and helps prevent misuse where someone adds or removes an element - breaking expectations elsewhere in code.

Title: Is there ever a reason to use an array when lists are available?

Body:
It seems like List<T> in C# can do everything an array can do and more, and seems also just as efficient in memory and performance as an array.

So why would I ever want to use an array?

I'm obviously not asking about cases where an API or other external constraint (i.e. the Main function) requires me to use an array... I'm only asking about creating new data structures in my own code.


问:
Why not use the word bug instead of exception?
If we refer to exceptions as bugs, why not just call it a bug in the first place instead of an exception?

If in the code it's called exception and as soon as it occurs it's called a bug. Then why not call it a bug in the first place?

Thank you for any answer or comment.

答:
Synopsis: Exceptions are evidence of bad outcomes, bugs are (some of the) causes of bad outcomes. The problem (to be solved) isn't the exception, the problem is what caused the exception.

Resoning:
A bug is a defect in the design or implementation of a product (not limited to software). For example, not using a properly rated relay (time/sensitivity/reliability/capacity) either due to incorrect specs or simple build error.
An exception is a real world / run time deviation from predicted (dare I say 'expected'?) behavior, e.g., the loss of control of a vehicle while driving.

Clearly, a bug can cause an exception as the example in 1) could lead to the example in 2). But not all exceptions would be caused by bugs, e.g., loss of control of a vehicle because the operator had a stroke.


答:
I tell them to check error messages when compilation fails.

I sit and check the error messages with them.

When they ask me for help, I ask if they have checked the error or not.

From what you're writing, it seems like your juniors either don't really understand your solutions and aren't able to apply them in other situations that are not 100% identical to the previous one, or theyve learned that you're the magical solution fairy and that bugging you is the quickest way to make their problems go away.

Luckily, most of the time, you can help them in the same way: lead them with analytical questions rather than with your knowledge.

"What seems to be the problem?"  Sometimes, just trying to explain the problem to you will make the answer dawn to them.  At the least, it allows you a look into their frame of reference and, not to be underestimated in importance, tells you what they perceive the problem to be.

"What does the documentation/Google/whatever say?"  Do assume that they at least tried to figure it out.  If they haven't, stay with them for a bit while they do look it up (don't jump ahead and give them the solution).  If the solution is there, give them a friendly goodbye, happy to help, and go back to work.  If not, or if it's not really applicable, move on to the next bit:

Walk them through finding the underlying issue.  Function already defined?  Ask them where else the function may be defined; point them to search functions if needed.  Undefined variable?  Ask them to verify where they defined it, and scrutinise the spelling.  Unexpected if?  Is this really the start of a new statement?  Did you end the preceding one?

(There's no need to be pedantic or go Aristotle's Teachings 660 on them, but you do need to guide them through the required steps of finding a solution, and you need to be open and patient.)

Once you have found the source of the problem, hopefully the solution is trivial; if it's not, then your junior developer hit an actual snag that's not obvious to the uninitiated.

But doesn't all this take longer than your previous approach?  Probably.  The principles of the approach are three-fold:

You teach people how to find a solution to their problems.  In particular, that analysing feedback from their actions (error messages) is crucial to finding a solution.  Not only will this improve their independence, but their analytical thinking as well, ultimately making them more at home in an automated environment or, at the very least, less likely to actively hinder others.

You don't assume that they're idiots or lazy; this will make them more likely to listen to you and follow your example.  Approach their issue as an actual, bona-fide problem that needs to be solved.  Who knows, maybe it is.

You help establish a cultural (team) standard that it's okay to ask for help in solving issues that you can't figure out, that you're willing to coach and help them find and learn a solution, but also that you're not the office's magical solution fairy, and that there has to be at least a token effort from their side.  Trying to figure out the information you have, such as an error message, is the most basic step.


答:
Legacy compatibility.

All form personal experience:

Legacy programmers - my colleague uses arrays everywhere, has done for 30+ years, good luck changing his mind with your new fangled ideas.

Legacy code - foo(array bar[]) sure you can use a list/vector/collection toarray function but if you not using any of there additional features its easier to use an array to begin with, often more readable without the type switching.

Legacy boss - my boss was a good programmer before she went into management many years ago and still thinks she's up to date, "were using arrays" can end a meeting, explaining what a collection is can cost everyone lunch.


答:
In addition to reasons listed in other answers, array literal takes fewer characters to declare:

```<code>var array = new [] { "A", "B", "C" };
var list = new List<string>() { "A", "B", "C" };
</code>```

Using array instead of List makes the code a bit shorter and just a bit more readable in cases when (1) you  need to pass any IEnumerable<T> literal, or (2) where other functionality of List doesn't matter and you need to use some list-like literal.

I've done this occasionally in unit tests.

Body:
In addition to reasons listed in other answers, array literal takes fewer characters to declare:

var array = new [] { "A", "B", "C" };
var list = new List<string>() { "A", "B", "C" };

Using array instead of List makes the code a bit shorter and just a bit more readable in cases when (1) you  need to pass any IEnumerable<T> literal, or (2) where other functionality of List doesn't matter and you need to use some list-like literal.

I've done this occasionally in unit tests.


问:
What is the preferred way to hold a file over multiple requests in MVC
I am building a wizard and the first step of this wizard is to let the user select a file. In the following steps I need this file to display some data from it and as a final step I have to import some content of the selected file.

How can i preserve this file along the steps?

I can save the file on the server in a temp dir (and make sure it is linked to the user's session, so that no other import session will intervene).
I can save the file in the session state (Viewbag maybe?)
What would you do?

Edit:

The size can vary from 100kb - 10mb

答:
The last MVC app I designed I had to hold onto a file through multiple pages before it was 'saved' (as at any point the user could cancel).  I stuck it in Session and all has worked well since.  That said, this feature doesn't get much use (10s of users at once) so I do not have data on how it scales.

While the web is stateless and MVC design lends itself to being as stateless as possible, the only way to make this bit stateless was to have the user send the file with every request that needs it, and that seems bad from a UX side (as well as having to handle scenarios like different files being passed).


答:
You need arrays to manage your collection of mutable structs, of course, and what would we do without those.

```<code>struct EvilMutableStruct { public double X; } // don't do this

EvilMutableStruct[] myArray = new EvilMutableStruct[1];
myArray[0] = new EvilMutableStruct()
myArray[0].X = 1; // works, this modifies the original struct

List<EvilMutableStruct> myList = new List<EvilMutableStruct>();
myList.Add(new EvilMutableStruct());
myList[0].X = 1; // does not work, the List will return a *copy* of the struct
</code>```

(note that there may be some cases where an array of mutable struct is desireable, but usually this differing behavior of mutable structs within arrays versus other collections is a source of errors that should be avoided)

More seriously, you need an array if you want to pass an element by reference. i.e.

```<code>Interlocked.Increment(ref myArray[i]);  // works
Interlocked.Increment(ref myList[i]);   // does not work, you can't pass a property by reference
</code>```

That can be useful for lock-free threadsafe code.

You need an array if you quickly and efficiently want to initialize your fixed-size collection with the default value.

```<code>double[] myArray = new double[1000]; // contains 1000 '0' values
                                     // without further initialisation

List<double> myList = new List<double>(1000) // internally contains 1000 '0' values,
                                             // since List uses an array as backing storage,
                                             // but you cannot access those
for (int i =0; i<1000; i++) myList.Add(0);   // slow and inelegant
</code>```

(note that it would be possible to implement a constructor for List that does the same, it's just that c# does not offer this feature)

you need an array if you want to efficiently copy parts of the collection

```<code>Array.Copy(array1, index1, array2, index2, length) // can't get any faster than this

double[,] array2d = new double[10,100];
double[] arraySerialized = new double[10*100];
Array.Copy(array2d, 0, arraySerialized, 0, arraySerialized.Length);
// even works for different dimensions
</code>```

(again, this is something that could be implemented for List as well, but this feature does not exist in c#)

Body:
You need arrays to manage your collection of mutable structs, of course, and what would we do without those.

struct EvilMutableStruct { public double X; } // don't do this

EvilMutableStruct[] myArray = new EvilMutableStruct[1];
myArray[0] = new EvilMutableStruct()
myArray[0].X = 1; // works, this modifies the original struct

List<EvilMutableStruct> myList = new List<EvilMutableStruct>();
myList.Add(new EvilMutableStruct());
myList[0].X = 1; // does not work, the List will return a *copy* of the struct

(note that there may be some cases where an array of mutable struct is desireable, but usually this differing behavior of mutable structs within arrays versus other collections is a source of errors that should be avoided)

More seriously, you need an array if you want to pass an element by reference. i.e.

Interlocked.Increment(ref myArray[i]);  // works
Interlocked.Increment(ref myList[i]);   // does not work, you can't pass a property by reference

That can be useful for lock-free threadsafe code.

You need an array if you quickly and efficiently want to initialize your fixed-size collection with the default value.

double[] myArray = new double[1000]; // contains 1000 '0' values
                                     // without further initialisation

List<double> myList = new List<double>(1000) // internally contains 1000 '0' values,
                                             // since List uses an array as backing storage,
                                             // but you cannot access those
for (int i =0; i<1000; i++) myList.Add(0);   // slow and inelegant

(note that it would be possible to implement a constructor for List that does the same, it's just that c# does not offer this feature)

you need an array if you want to efficiently copy parts of the collection

Array.Copy(array1, index1, array2, index2, length) // can't get any faster than this

double[,] array2d = new double[10,100];
double[] arraySerialized = new double[10*100];
Array.Copy(array2d, 0, arraySerialized, 0, arraySerialized.Length);
// even works for different dimensions

(again, this is something that could be implemented for List as well, but this feature does not exist in c#)


答:
The same reason I don't drive a truck when going to work. I don't use something that I won't use the features of.

First of all an array is a primitive construct so an array is faster and more efficient than a List<> for sure, so your argument is not true. Array is also available everywhere and known by developers using different languages and platforms.

The most important reason I use an array instead of a List<> is to imply that the data is fixed length. If I won't add or remove any items from that data collection, I want to make sure that the type reflects that.

Another thing is let's say you are implementing a new data structure and you've read some papers about it. Now while implementing specific algorithms, you can't always rely on someone else's implementation of a type that is general purpose. It changes from .NET to Mono and even between different versions of the framework.

And it is sometimes easier to port a piece of code that uses an array instead of a framework dependent type.


问:
Is it possible to have a keyed dictionary stored on disk?
for example) would it be possible to be able to use the key of an item to access the item stored in a file out on disk (without searching through the whole file)?

I'm looking fora general example of how to do this (assuming it's possible), as I don't actually need to do this, it was just a question from an old exam.

答:
Yes indeed. There's something called disk-based hash tables. You generate keys that correspond with a physical location in disk.

The accepted answer in this SO question tells you a possible implementation.

I would suggest though that you use a SQLite dabatase. Load the data into it and create an index.

When you use the indexed column for searches you don't search through the table. A fast hash-based or b-tree-based look up is done on the index ( which is sorted ). Then the index points to the row in the table directly. Probably SQLite uses a hash function for that also, like most RDBMS.

SQLite requires no database daemon running, just the SQLite binary or a library for your programming language of choice.


问:
Easy way to make old javascript files conform to new quoting standard?
We've just started putting linting in place at my workplace, and a lot of the devs didn't realize our standards called for double-quotes everywhere. About 50% of the codebase uses single-quotes, so it's no easier to change the rule than to make the older code conform. Is there a tool or utility we could use to automatically fix older files? It's fine if we have to verify the output after, it's a lot easier to find problems in a few edge cases than to open and adjust every single file in a large codebase.

Before:

```<code>var foo = 'bar'
var bat = 'baz: "stuff"'
</code>```

After:

```<code>var foo = "bar"
var bat = 'baz: "stuff"' //allowed
</code>```

I'm open to any method, including using an existing tool, using regex in some kind of perl or batch file, anything to avoid spending large amounts of human time fixing what is ultimately a minor problem writ large across multiple code bases. The sheer magnitude of the problem dissuades people from attempting to fix it, and I'd like a way to help with that. Please leave discussion about the wisdom of this option out of it, as this is just one of many options I'm looking into -- if there's a nice easy way to deal with it, then the team leads will want to know about it, and if there's not, that will factor into the discussion as well.

Also keep in mind that this is just the rule that's most obvious now that the linting standards are in effect. Anything that can fix other errors as well (double equals where triple was needed also comes to mind) would be useful as well.

答: I've done some similar things (migrating a VB3 app to VB4, for example) with some perl scripts. The scripts would take the original file and produce two new files: one the output file (with the corrections) and the other a list of the changes/substitutions performed, as well as messages indicating that something unusual was seen and wasn't changed. I found this easier to read than a diff (which you can easily generate if you prefer that).  The key seems to be to create a sample file with every permutation you can think of and run your script against that until you have it right. Then run it against your biggest/most-challenging file and hand-check the output to make sure everything looks right. If your code is under source control, then you can easily revert to the original version if things aren't working right, but for a well-defined problem a good script should get you 99% of the way there.</p>


答:
This is strictly from an OO perspective.

While I can't think of a reason to pass just an array around, I can certainly see situations where an array representation internal to the class is probably the best choice.

While there are other options that give similar characteristics, none seem as intuitive as an array for problems dealing with processing permutations, nested for loops, matrix representation, bitmaps and data interleaving algorithms.

There's a substantial number of scientific fields that rely on matrix math extensively. (e.g. image processing, data error correction, digital signal processing, a ream of applied mathematics problems). Most of the algorithms in those fields are written in terms of using multidimensional arrays/matrixes. So it would be more natural to implement the algorithms as they are defined rather than make them more "software" friendly at the expense of losing the direct tie-ins to the papers the algorithms are based upon.

Like I said, in these cases you can probably get away with using lists but that adds yet another layer of complexity on top of what are already complex algorithms.


答:
Well, I found a use for arrays in a game I have been writing. I used it for creating an inventory system with a fixed number of slots. This had several benefits:

I knew exactly how many open inventory slots the game object had by looking and seeing which slots were null.

I knew exactly what index each item was in.

It was still a "typed" array (Item[] Inventory), so I could add/remove the objects of type "Item".

I figured that if I ever needed to "increase" the size of the inventory, I could do so by transferring the old items into the new array, but since the inventory was fixed by screen space and I had no need to dynamically make it larger/smaller, it worked well for the purpose I was using it for.


答:
If you're traversing all elements of a list, then no, an array is not necessary, 'next' or arbitrary 'selection without replacement' will do fine.

But if your algorithm needs random access to the elements in the collection, then, yes, an array is necessary.

This is somewhat analogous to "is goto necessary?". In a reasonable modern language it is not needed at all. But if you peel away the abstractions, at some point, that's all that is actually available to you, that is, the only way to implement these abstractions is with the  'unnecessary' feature. (Of course, the analogy isn't perfect, I don't think anyone says that arrays are poor programming practice; they are easy to understand and think about).


问:
Does TCP guarantee packet transmission time?
This is a review question but I can't find anything in my book about it. What I did find online is contradictory and confusing.</p>

答: No, TCP will time out and request that a packet be re-sent, but there's no guaranteed transit time. TCP (typically) relies on IP, which can dynamically route packets, so there's no way to estimate how long it will/should take.</p>


问:
Company decides standard language for all development, or coder can pick their own standard...so that is the standard? What is the norm?
Our company is moving from IBM mainframe environment and coding, to an OO environment. Is it possible...or is it correct/plausable to NOT have any standard whatsoever with regard to the server side language of the OO environment we move to? Is it normal to say "Dave works in PHP" so all things he does will be in "PHP"...and we'll hire Liz who has Python..that will work too.  Dave works on a financial application in PHP, will Liz does time cards in Python.  OR would it be better to say.."Company ABC programming standard is Python..." Dave has to learn Python, and Liz is ready to rock and roll with the company. I'm just trying to know what an OO environment looks like with regard to standardized language or free do what  works best for the situation/coder environment. </p>

答: Typically, companies standardize on a single language for a variety of reasons (tool support, talent availability, interoperability, etc). I've worked for some companies that used multiple languages, but they were the exception. Having individuals pick their own technologies is usually a recipe for disaster. When the PHP guy leaves, if nobody else knows PHP then who takes over his code? And do you keep it in PHP or will you wind up rewriting it in the "new guy"'s language of choice?</p>


答:
You could use Sessions here but that has a few downsides. The oft-quoted one is the default configuration (in process) is fast but the session dies if the app pool gets restarted. Code-wise this means you typically need to check if your session has not died so you can handle it gracefully. This is fairly easy to do but it is some overhead.

The bigger downside there is the fact that the browser shares a session between all tabs so if someone does some normal modern browser stuff you can get massive confusion or at least UI weirdness. A good example of someone doing something like this would be united airlines -- you can only look at one of your flights at once due to session contention.

The approach I would take here is to have them upload the file, stash it in an appropriate place, generate an ID for it and then keep that in the wizard. When they complete it you can pick up the file at the end. If they start 2 at once it is easy to handle. Stay stateless.

Title: What is the preferred way to hold a file over multiple requests in MVC

Body:
I am building a wizard and the first step of this wizard is to let the user select a file. In the following steps I need this file to display some data from it and as a final step I have to import some content of the selected file.

How can i preserve this file along the steps?

I can save the file on the server in a temp dir (and make sure it is linked to the user's session, so that no other import session will intervene).
I can save the file in the session state (Viewbag maybe?)
What would you do?

Edit:

The size can vary from 100kb - 10mb


答:
1)  There is no multi-dimensional version of List.  If your data has more than one dimension it will be very inefficient to use lists.

2)  When you are dealing with a large number of small data types (say, a map where all you have is one byte for the terrain type) there can be considerable performance differences due to caching.  The array version loads several items per memory read, the list version loads only one.  Furthermore, the array version holds several times as many cells in the cache as the list version--if you're repeatedly processing the data this can make a big difference if the array version fits in cache but the list version does not.

For an extreme case, consider Minecraft.  (Yeah, it's not written in C#.  The same reason applies.)


问:
ADT design choices
How do you go about deciding which of the following two representations (in F# syntax) is the right choice in a particular situation?

```<code>type Choice = A of string | B of string
</code>```

Or:

```<code>type ChoiceKind = A | B
type Choice = { Kind: ChoiceKind; Value: string }
</code>```

I'm deliberately avoiding giving a more specific example, as either approach can "feel more natural" in a particular scenario; I'm interested in the general reasoning that goes into the design choice.

答:
In my opinion the former makes more sense if there's not much you can sensibly do without knowing whether you have an A or B. If you wanted to unconditionally get the string with the former declaration, you'd end up with redundant cases in the pattern match. Of course, you could easily write a function to do it.

I would imagine the latter is easier for other .NET languages to work with since they lack pattern matching, but you can fake it well enough in C# using named arguments and lambda expressions.

Disclaimer: I've never coded in F# but I'm familiar with Standard ML, which is related (through OCaml).

Title: ADT design choices


答:
It should be pretty obvious that if you have two or more persons working on the same program, they need to use the same language, or at least the same (small) set of languages. So when there is is only one team or department in the company who does software development, they will typically not make their lifes harder by unnecessarily chosing a new language for every new program they have to develop.

The real world situation looks often like this: in lots of companies of reasonable size, you will find different, independent teams or departments, which chose they toolset some time ago for a specific programming task. And if the teams are working independently, the chances are high they make different decisions about the programming language. The bigger the company, the more likely this will happen.

After a while, most companies tend to change their structure, for example one department will be closed or cut down to half of the people, or the programming tasks are "outsourced" to a different department, which can easily lead to a situation where another department has to take over some existing software packages for maintenance. Or two former independent departments have to work together on a common software project. This will quickly leave you in a situation where one team has to manage different programs in different languages. And that is IMHO the "norm" for lots of companies I have seen before - not because "it works best", but because "that's the way it works".

Title: Company decides standard language for all development, or coder can pick their own standard...so that is the standard? What is the norm?

Body: Our company is moving from IBM mainframe environment and coding, to an OO environment. Is it possible...or is it correct/plausable to NOT have any standard whatsoever with regard to the server side language of the OO environment we move to? Is it normal to say "Dave works in PHP" so all things he does will be in "PHP"...and we'll hire Liz who has Python..that will work too.  Dave works on a financial application in PHP, will Liz does time cards in Python.  OR would it be better to say.."Company ABC programming standard is Python..." Dave has to learn Python, and Liz is ready to rock and roll with the company. I'm just trying to know what an OO environment looks like with regard to standardized language or free do what  works best for the situation/coder environment. </p>


答:
A 100-element array of some type T encapsulates 100 independent variables of type T.  If T happens to be a value type which has a mutable public field of type Q and one of type R, then each element of the array will encapsulate independent variables of types Q and R.  The array as a whole will thus encapsulate 100 independent variables of type Q and 100 independent variables of type R; any of those variables may be accessed individually without affecting any other.  No collection type other than arrays can allow the fields of structures to be used as independent variables.

If T happened instead to be a class type with public mutable fields of type Q and R, each element of the array holds the only reference, anywhere in the universe, to an instance of T, and if none of the elements of the array will ever be modified to identify an object to which any outside reference exists, then the array will effectively encapsulate 100 independent variables of type Q and 100 independent variables of type R.  Other collection types can mimic the behavior of such an array, but if the only purpose of the array is to encapsulate 100 variables of type Q and 100 of type R, encapsulating each pair of variables in its own class object is an expensive way of doing that. Further, using an array or collection of mutable class type creates the possibility that the variables identified by array elements may not be independent.

If a type is supposed to behave like some kind of object, then it should either be a class type or a private-field structure which provides no means of mutation other than replacement.  If, however, a type is supposed to behave like a bunch of related-but-independent variables stuck together with duct tape, then one should use a type which is a bunch of variables stuck together with duct tape--an exposed-field struct.  Arrays of such types are very efficient to work with, and have very clean semantics.  Use of any other type will lead to muddled semantics, inferior performance, or both.


答:
TCP cannot promise delivery, but it can guarantee that either the packet will be delivered and acknowledged within a timeout (4 minutes IIRC), or you will get an error response. (Which, come to think of it, is what the word "guarantee" usually means: if the promised action does not occur, you will have some remedy available. A guarantee on a hard drive doesn't mean it won't fail; it means that if it fails you can get a replacement or your money back.)

In the sense of "guarantee means unbreakable promise", nothing is ever guaranteed. In the sense of "guarantee = warranty", then yes, TCP guarantees delivery.

Title: Does TCP guarantee packet transmission time?

Body: This is a review question but I can't find anything in my book about it. What I did find online is contradictory and confusing.</p>


答:
The biggest thing you're missing is that abstraction has costs as well as benefits.

"All problems in computer science can be solved by another level of indirection, except of course for the problem of too many indirections." -David Wheeler

Sometimes the cost is really small, like in your fibonacci example, so even if it doesn't gain us anything, it doesn't much matter, because it didn't cost us much either.  Wrapping a few lines of code in a function isn't something that takes a lot of time or effort to do.  Sometimes the cost is large, and then we need to be sure we're getting something significant out of it.

If we were to decide to make an abstract HTML parsing interface, spend time designing it, and then implementing an instance of that interface that used BeautifulSoup, have we wasted our time?  Probably, if we only ever use our fancy interface to call BeautifulSoup.  (Note that the proposed replacement for BeautifulSoup in your question essentially did nothing for you except change the name from BeautifulSoup to HTMLParser.)

Wrapping something that doesn't need to be wrapped in the first place is a waste of time.

On the other hand, if we're going to write a program that uses BeautifulSoup for most parsing, but sometimes really needs the parsing capabilities of UglyOatmeal or SloppySandwich, an interface that wraps them might save us a lot of time and effort.

You seem to think that details should not concern you as a programmer.  This is only sometimes true; some details are already handled by the hardware, OS, programming language, and libraries.  Other details matter fundamentally in ways that make them impossible to handle automatically -- in your fibonacci example, it matters to the behavior of the program whether the number type used is an int or a type that can handle larger numbers.  Sometimes the details of the representation of something make a big difference to performance.

It's nice when things get handled automagically for us, but there is usually a cost of some kind or another.  Often the cost is performance, and often it's lack of control over something.

Even with beautiful languages and awesome libraries, not every detail can be handled automatically, and software fundamentally is about handling enormous numbers of details, so we shouldn't be too surprised or annoyed to find out that some of them couldn't be handled for us.

It isn't that we need more abstraction, we need the right abstractions in the right places.  Abstraction is one of our most powerful tools in programming, but there are ways of misusing it or unrealistically expecting it to do magic.


答:
One important different is memory allocation. For example, traversing a linked list could result in a lot of cache misses and slower performance, whereas an array represents a contiguous chunk of memory holding multiple instances of some particular data type, and do traversing it in order is more likely to hit the CPU cache.

Of course, an array of object references may not benefit as much from cache hits, since dereferencing could still take you anywhere in memory.

Then there are list implementations such as ArrayList, which implement a list using an array. They're useful primitives to have.


问:
How to protect an AES encryption key in shrinkwrapped software
If I want to do file encryption in a desktop piece of software I'm assuming I'll have to hardcode an encryption key in my compiled code. Is that assumption correct and if so what precautions can I take to protect the key? </p>

答:
There's nothing you can do to "protect" the encryption key so long as the key exists somewhere in a user's environment.

Here's some possible attack vectors:

I could scan the memory of the computer and extract the key once it was loaded into RAM.

I could look through your program's resources and find anything (such as a string) that resembles your key.

I could reverse-engineer your program to find out how the key is loaded, then reproduce the same steps to load the key myself.

As long as the encryption key exists in an environment that a potential hacker has control over, said hacker can modify the environment in any way necessary to find your key. The only possible way of preventing said hacker from getting the key would be to isolate the encryption in an environment that the hacker couldn't control. A couple possible solutions:

A hardware-based device with the key built-in that does the encryption for you. Measures would have to be taken to protect the physical device.

A server-based solution where the data is uploaded, encrypted, then downloaded.

An asymmetric encryption scheme, where a "public" key is used to encrypt, and a "private" key is used to decrypt (or the other way around), though this depends on the purpose of "hiding" the keys.


问:
Python Open Source Development
I am looking to contribute to some Python projects on Github, and I am looking for a bit of clarification on the mechanics of doing this effectively.  As I understand it, the typical workflow is as follows:

Fork the repository you would like to contribute to.

Clone the your forked repository.

Create a Python virtual environment and install / locally import your repo. My understanding is that this portion is needed to ensure the module you are looking to contribute to is the one from Github, and not the one already installed on your machine.

Develop, test, etc. your intended changes.

Commit back to Github.

Submit pull requests to have your changes incorporated into the parent project.

While I'm looking for confirmation overall, I'm looking for confirmation regarding Step 3 primarily as my understanding at this point remains a bit grey.

答:
The first thing you want to do is check how projects accept submissions and in what format (e.g. where to branch from, do you need to rebase, style guide etc.). Make that step 0.

For step 3, it depends on your workflow. Mine is to clone the repo to a folder I have specially for such projects, create a virtualenv (usually using virtualenvwrapper, as it makes creating new virtualenvs easy, especially useful for testing that installing still works), install any build/dev requirements not listed in the setup.py (the readme/documentation should say what these are), then install the project in editable mode (running pip install -e . ). See https://virtualenv.pypa.io/en/latest/virtualenv.html#usage for how to get started using virtualenv.

Note that this may not work for every package (typically if it cannot be installed using pip, then this will not work), in this case you could use user site-packages (i.e. pip install --user instead of pip install).

In the case of sklearn, you need to install numpy and scipy into the virtualenv before installing sklearn. Make sure to do the numpy install separately to scipy, pip install numpy scipy won't work.

Finally, step 3 will vary for every developer, it's best to develop your own workflow. The main thing is to make sure that any changes are acceptable to the project.

Title: Python Open Source Development


问:
Is it possible to use functional paradigm in imperative languages?
If I understand the concept correctly the goal, which functional languages are trying to achieve is to eliminate any side effects from functions and to eliminate a state. The rationale behind this is to obtain referential transparency, which leads to more predictable execution.

However, nothing prevents me from writing the code with above in mind in imperative language. I'm thinking only about classic constructs and not functional mixins.

Let's say I have following code in C.

```<code>int add(int x, int y) {
    return x + y;
}

int sqr(int x)
{
    return x*x;
}

int main()
{
    return sqr(add(3,5));
}
</code>```

So, I have two functions, which do not posses any side effects. Neither program has any state. Is this code missing something exceptionally functional?

Currently, I perceive functional languages like if they had built impressive decoration made of syntactic sugar over the core concept of functional programming. Their syntax discourages slicing the code into statements, however I don't see any substantial difference that prevents me to take functional approach (and yield its fruits) in imperative language. Am I wrong? Hence my question.

答: I'm not an absolute expert on functional languages and paradigms; however, I do know that compilers have the job of translating their native language (C, Ada, Prolog, Java…) to a machine language (x86, JVM, sparc, amd64…). Since both functional and imperative languages can be translated to machine code, given that they are both Turing-complete and not domain specific; it follows that they can be translated to each other. So, I would think yes.</p>


答:
Your question has actually already been answered before.

and seems also just as efficient in memory and performance as an array.

It isn't. From the question I linked:

```<code>List/foreach:  3054ms (589725196)
Array/foreach: 1860ms (589725196)
</code>```

Arrays are twice as fast in certain important cases. I am certain the memory usage also differs non-trivially.

Since the main premise of your question is thus defeated, I'm assuming this answers your question. In addition to this, sometimes arrays are forced on you by Win32 API, or your GPU's shader, or some other non-DotNet library.

Even within DotNet, some methods consume and/or return arrays (such as String.Split). Which means either you must now eat the cost of calling ToList and ToArray all the time, or you must conform and use array, possibly continuing the cycle by propagating this to poor downstream users of your code.

More questions and answers on Stack Overflow on this topic:

Array versus List<T>: When to use which?

Why do we use arrays instead of other data structures?

Which is better to use array or List<>?

Body:
Your question has actually already been answered before.

and seems also just as efficient in memory and performance as an array.

It isn't. From the question I linked:

List/foreach:  3054ms (589725196)
Array/foreach: 1860ms (589725196)

Arrays are twice as fast in certain important cases. I am certain the memory usage also differs non-trivially.

Since the main premise of your question is thus defeated, I'm assuming this answers your question. In addition to this, sometimes arrays are forced on you by Win32 API, or your GPU's shader, or some other non-DotNet library.

Even within DotNet, some methods consume and/or return arrays (such as String.Split). Which means either you must now eat the cost of calling ToList and ToArray all the time, or you must conform and use array, possibly continuing the cycle by propagating this to poor downstream users of your code.

More questions and answers on Stack Overflow on this topic:

Array versus List<T>: When to use which?

Why do we use arrays instead of other data structures?

Which is better to use array or List<>?


答:
I'm learning Scala right now, and it allows for both. You can either write imperatively using standard curly braces like C, or you can omit the braces and write functionally. Obviously the functions you use decide whether or not you'll be able to write it purely functionally, but it is possible.

If I think of a good comparative example, I'll edit it in when I get on my laptop.

Title: Is it possible to use functional paradigm in imperative languages?

Body:
If I understand the concept correctly the goal, which functional languages are trying to achieve is to eliminate any side effects from functions and to eliminate a state. The rationale behind this is to obtain referential transparency, which leads to more predictable execution.

However, nothing prevents me from writing the code with above in mind in imperative language. I'm thinking only about classic constructs and not functional mixins.

Let's say I have following code in C.

```<code>int add(int x, int y) {
    return x + y;
}

int sqr(int x)
{
    return x*x;
}

int main()
{
    return sqr(add(3,5));
}
</code>```

So, I have two functions, which do not posses any side effects. Neither program has any state. Is this code missing something exceptionally functional?

Currently, I perceive functional languages like if they had built impressive decoration made of syntactic sugar over the core concept of functional programming. Their syntax discourages slicing the code into statements, however I don't see any substantial difference that prevents me to take functional approach (and yield its fruits) in imperative language. Am I wrong? Hence my question.


答:
If by functional programming you mean programming only with immutable values, sure, you can do that. But it's going to be painful. In a lot of cases you don't get to take advantage of:

First-class functions with lexical scoping (a.k.a. closures)

Functions with identifiers that are mostly special characters

Infix functions

Type inference

Tail call optimizations (so no recursion as a form of looping unless you're fine with stack overflows, which means you have to use looping statements, which means you need to mutate something to get results out of a loop)

Automatic currying

if/else and try expressions instead of statements.

Algebraic data types

Pattern matching

Not having to deal with null

Persistent data structures (usually need to pull in external libraries for these if they're available at all)

Advanced module systems

Lazy evaluation (though this can be simulated using lambda expressions)

And of course a compiler for a functional language will have different optimizations than a compiler for an imperative language. A language where functions aren't a primitive type is unlikely to optimize function composition or currying as well as a language where functions are primitives and it's expected that they'll be composed and curried often.


问:
Best approach for storing huge data
I'll be handling 300,000+ users. Each user (after logging in) will be able to create lets say "folders", in each folder, users will create "name=value,name2=value2,name3=value3" entry pairs. Each name won't be more than 260 chars and each value won't be more than 1024 bytes. All readable characters.

My ideas for possible approaches:

Create tables called userentries_[first letter of username] so there will be 26 tables, each table will have entries and user ID. So when I want to retrieve user data, I'll do

```<code>select * from userentries_[firstletter] where userid= $UID"
</code>```

Create a single table to hold all information.

Create a table called userdata, here I'll have UID and FileName. So when user wants to retrieve data, I'll read database to find the name of file, then open FileName in PHP, create an XML/JSON response and client (which will be android/ios/desktop app) process it.

Which one is the best and most optimized (speed/performance vise) ?

P.S. name=value pairs etc. won't be searchable, even if user supposed to search through them, it will be in client-side, definitely not on DB

答:
You might use three total tables (adjust table/column names and SQL dialect to taste).

The first is the user table, which contains the master list of user_id's.

The second is the folder table, that will contain a list of folders for users.

```<code>|  folders         |
|------------------|
| id (int)         |
| user_id (int)    |
| name (varchar)   |
</code>```

And a third for the name/value pairs

```<code>|  user_data       |
|------------------|
| id (int)         |
| folder_id (int)  |
| name (varchar)   |
| value (varchar)  |
</code>```

To query for the name/values in a specific folder then, you'd do something like:

```<code>select name, value from user_data where folder_id = ?
</code>```

To query all data for a user it can be something like:

```<code>select user_data.name, user_data.value
  from folders
  join user_data on (user_data.folder_id = folders.id)
  where folders.user_id = ?
</code>```

Alternatively, denormalize the user_data table slightly and add the user_id in there as well.  That will simplify queries for all of the user's data, but you'll have to manually keep the keys in sync.

Properly indexed, this will work fine for large data sets.

Title: Best approach for storing huge data

Body:
You might use three total tables (adjust table/column names and SQL dialect to taste).

The first is the user table, which contains the master list of user_id's.

The second is the folder table, that will contain a list of folders for users.

|  folders         |
|------------------|
| id (int)         |
| user_id (int)    |
| name (varchar)   |

And a third for the name/value pairs

|  user_data       |
|------------------|
| id (int)         |
| folder_id (int)  |
| name (varchar)   |
| value (varchar)  |

To query for the name/values in a specific folder then, you'd do something like:

select name, value from user_data where folder_id = ?

To query all data for a user it can be something like:

select user_data.name, user_data.value
  from folders
  join user_data on (user_data.folder_id = folders.id)
  where folders.user_id = ?

Alternatively, denormalize the user_data table slightly and add the user_id in there as well.  That will simplify queries for all of the user's data, but you'll have to manually keep the keys in sync.

Properly indexed, this will work fine for large data sets.


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答:
I mentally translate "Everything is fine.  We have nothing to worry about." to "We're all screwed" every time I hear it management say it.  You usually hear managers throw it in incidentally in unrelated meetings ("Oh and by the way, everything is going fine.  There's no reason to worry!"), but it's an even bigger red flag to have a meeting specifically called to say that.

I have yet to hear a manager say something along these lines and have it not turn out to be a lie.

ContentLicense: CC BY-SA 2.5


问:
Separate servers vs local machine for builds, issue tracking etc on solo project
For solo projects, do you keep your build / management tools on your local machine, or on a separate server? If the server is not guaranteed to be safer or more reliable than my own machine I struggle to see the point, but maybe I'm missing some things.

Note that I'm not debating the value of continuous integration or having a staging environment etc.. just the question of whether it exists on separate hardware.

答:
My day job is as a solo C# developer working on a single in-house system for a small company. The system uses Mercurial for version control, with a central repository on the company file server. I have use a build server which is actually a Windows XP VM running on a Hyper-V server. I find that with this setup:

The build environment is separate from the development environment, so I can manage dependencies easier

Most of the client PCs are Win XP, so I can develop on any OS (usually Win 7) but I can run all my automated and manual tests on XP, with a similar configuration to the users

I develop on a 64 bit OS, but build for 32bit, and some unit tests for complicated calculations like Internal Rate of Return can fail due to architecture differences. Not necessarily an issue but it could have been.

I used to have a VM running on the development machine, but that meant I couldn't run builds when working from home - now I can just RDP into the build machine

Having a clean repository makes it easier to find issues like forgetting to add files to VCS. Of course just having a seperate build chain on your dev machine could achieve that as well, but it is nice to have it all in a physically seperate environment.

A full build with all the tests takes about 4 minutes, and then manual tests can take some time as well. With a seperate build server I can keep working while the build looks after itself.


问:
Is a developer-driven product a good thing?
I work in a company where the CEO manages the product team, who mockup features and drop in the lap of developers to then implement said features. There is some iteration of course, developer's opinions are respected. But I wonder how effective this process is.

Jason Calacanis just wrote :

The Zuckerberg Doctrine: Developers
  design products with significantly
  improved speed and functionality
  compared to product managers and
  designers, outweighing potential
  mistakes and drawbacks.

...

Then it really hit me:
  Developer-driven startups always
  produce product faster.

This stands to reason: our
  nontechnical people are having
  discussions and debates while
  Zuckerberg is coding his next feature.
  This is why no one has been able to
  keep up with Facebook!

While MySpacers debated how to iterate
  on their product, Facebook simply
  tried stuff.

Does this actually work better in practice ?

答:
(Oh gosh ... where did I just read something like "I've got a great idea!  All I need is a developer."  It was within a week I think.  Anyway ... )

Great ideas are a dime a dozen.  Implementing the thing is what matters.  If the developer is the one with the great idea, he can just implement it.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
I was once asked to make a field in a database "semi-compulsory" by a manager.

Just recently I was asked to develop a web application I had no prior knowledge of based on some JPEG mocks of what the website should look like that had been created by a design agency in another country who normally do print designs and have no idea about the web.


答:
As a developer, I'd like to think that we do a better job than managers and designers.  But I don't think you can generalize.

One of the problems with developers doing the design is that they may not be in touch with the needs of the end users, and may not be good at asking the right people the right questions.  A manager, and particularly a good designer may be better at figuring this out.

However, I think the more cogent thing is not the people but how they approach they approach the problem.  The approach that works is to get down and implement stuff, rather than spending endless meetings and cutting down trees to come up with the "ideal" design.  It is really the Agile versus Waterfall revisited.

(It should be clear that Facebook is an example of how NOT to do things too.  For instance, their cavalier approach to privacy issues is starting to get them into legal trouble ...)

Title: Is a developer-driven product a good thing?

Body:
I work in a company where the CEO manages the product team, who mockup features and drop in the lap of developers to then implement said features. There is some iteration of course, developer's opinions are respected. But I wonder how effective this process is.

Jason Calacanis just wrote :

The Zuckerberg Doctrine: Developers
  design products with significantly
  improved speed and functionality
  compared to product managers and
  designers, outweighing potential
  mistakes and drawbacks.

...

Then it really hit me:
  Developer-driven startups always
  produce product faster.

This stands to reason: our
  nontechnical people are having
  discussions and debates while
  Zuckerberg is coding his next feature.
  This is why no one has been able to
  keep up with Facebook!

While MySpacers debated how to iterate
  on their product, Facebook simply
  tried stuff.

Does this actually work better in practice ?


答: IMHO, I would say you are partially right. It sounds reasonable. But, this may not apply to all the products/software. So, I would put it this way. A designer should be a person with ample amount of development experience under his belt AND not just that - the person should still be coding and not not just designing.</p>


答: That depends, all my computers are set up with different tools for different languages, projects, etc.  For example, on one computer I have Django and Apache, on another I have Python, Pygame, and Tkinter, on another I have Eclipse and PHP, on yet another I have a different version of Eclipse along with the Android SDK and a few emulators.  I'm considering setting one up for RoR.  I use whichever I'm near, or sometimes I will remote-desktop into whatever computer has what I need.</p>

Title: Separate servers vs local machine for builds, issue tracking etc on solo project

Body:
For solo projects, do you keep your build / management tools on your local machine, or on a separate server? If the server is not guaranteed to be safer or more reliable than my own machine I struggle to see the point, but maybe I'm missing some things.

Note that I'm not debating the value of continuous integration or having a staging environment etc.. just the question of whether it exists on separate hardware.


答: I think this is clearly the best approach to a developer-oriented product (like AWS or Visual Studio), but I'm not sure that it's clearly the better approach in general.  I mean, I usually see things happening the other way around:  developers stand around arguing the best approach while the non-technical people quickly make decisions.  Personally, I'm inclined to say the correct answer is somewhere in the middle.  There should be a product manager with the ability to set broad direction that the developers then implement.</p>


问:
Why do some projects not use generics
I've been looking at a number of OSS java projects and a number of them still have not adopted generics.  They're using raw types (e.g. List foo) instead of generic types (e.g. List<string> foo).  Other projects have only begun using generics in the last few years even thought they've been around for a long time.

I'm interested to know why people and projects eschew the use of generics when there appears (to me) to be now downside in using them instead of rawtypes.  For those of you who use java, but not generics, what (if anything) would make you switch?

答:
It's helpful, when trying to understand stuff like this, to think of each new release of a language as a different language. Different features, different idioms, different users...

Sure, the new version is a fairly easy language for users of the previous version to pick up... But some programmers - actually quite a few programmers - learn one language and then stop. Whether that's K&R C, late-80s C++, VB5, Java 1.4, or C# 1.1... You'll find programmers, even entire shops, who learned that one version of that one language, bought a reference book, put it on the shelf, and then set about using it. Suggesting that they spend extra time tracking and integrating each new standard into their work is only slightly less ridiculous than suggesting that they type one-handed while juggling oranges with the other, or start using Scala - it just doesn't seem necessary.

With that in mind, read: How can I introduce new technology to my team?

Title: Why do some projects not use generics


答:
Some projects have to run on older JVMs. For example, some projects might not even be able to use assert yet (introduced in Java 1.4), because they still need to work on Java 1.3 JVMs.

Another factor is simply inertia: If code was already written, and performs fine without adding the use of generics, there's little reason to take the risk in changing the code. But today, there are several automatic tools to help you migrate your Java code to use generics.

Title: Why do some projects not use generics

Body:
I've been looking at a number of OSS java projects and a number of them still have not adopted generics.  They're using raw types (e.g. List foo) instead of generic types (e.g. List<string> foo).  Other projects have only begun using generics in the last few years even thought they've been around for a long time.

I'm interested to know why people and projects eschew the use of generics when there appears (to me) to be now downside in using them instead of rawtypes.  For those of you who use java, but not generics, what (if anything) would make you switch?


答:
Products should be customer-driven.

If your customers are software developers, and you use your own product (which you should, in any case), then I suppose you can be your own best customer.

But as a developer, your perspective is already compromised by what happens under the hood.  You need the customer to tell you that what you are doing with the user interface or the application workflow is goofy and doesn't make any sense.

As a developer, you need to know the right questions to ask of the stakeholders so that you can combine your experience with their wants to produce the best possible product.


答:
This may be bad form, but I'm posting an answer as a response to Macneil's answer; I'm not able to comment everywhere yet.

I don't think that running on older JVMs would be the issue; my understanding is that generics were added to the language the way they were (with type erase) so that new code using generics could run on old JVMs.  That isn't to say that the same is true of asserts, though, but that isn't what the question is about anyway.

Title: Why do some projects not use generics


答: Another answer is that some programmers don't really understand what they're doing.  Java is a very accessible language which inevitably leads to people learning it to a "usable" degree quickly and never progressing further.  I know as a 16-year-old I knew enough about Java too make good everyday apps, but if I hadn't kept learning I still wouldn't know what a generic was.</p>

Title: Why do some projects not use generics