问:
Connect different programming paradigms in a real app written in JavaScript
I am learning functional programming, working generally with JavaScript. Many things look promising, like immutable data and stateless flow.

Now, I want to build quite a basic CRUD app as a pet project to practice functional techniques. I am going to use Node for server-side part of the app and vanilla JavaScript for client side.

Being practical and having no will to pass a functional elephant through a needle's eye of web app requirements and realities, I suppose, I don't want to build everything in the app with the functional approach just for the sake of purity and academical perfection.

Should I rather connect functional with imperative, and OOP? If so, are there clear hints for where I should use functional, and where I'd better run OOP? Should I tend to keep domination of one paradigm over others, making one of them a basement of the app, then introducing others on top of it?

Does a CRUD app better fall into 80% of functional and 20% of helper OOP or vice versa? Is it worth and makes sense to wade through the jungle and apply techniques where not applicable, just to say "It's 100% functional app, look at it!"?

What are the signs of preferring one paradigm over another in a context of web?

答:
Programming paradigms have several goals. Some goals are shared, some not. But mainly it comes down to two absctract ideas:

being readable

taming complexity

And if you want to, you could summarize the peculiarties of the paradigms into these two categories.

I put the categories on purpose in this order. The primary goal of writing code should be readability, since code is more often read and reread than written. The smartest algorithm is worthless, if you have to find a bug and need hours to think about how it worked.

That said, the answer to your question, whether to choose one paradigm and strictly adhere to it or to mix paradigms, could be answered in that way:

As long as it doesn't impair readability, you are free to mix paradigms

Especially in Javascript, where there is no paradim (like in Java) forced, you are mainly free to mix functional and imperative style and spice your code with some OOP, when it comes in handy.

Does a CRUD app better fall into 80% of functional and 20% of helper OOP or vice versa?

That is just a matter of the implementation, not the app itself.


问:
How to manage tailored/branded web tools?
We produce a number of analysis tools which we re-brand and customise for other businesses to include in their websites.

The tools are typically product comparison, data/trend analysis and report production (in a very particular sector). At present these tools run as a single instance in house, our clients redirect there traffic to us with a URL param specifying the client for branding and customisation.

Up until now we've been using an MVC approach with XSLT views. If a customer wants customisation we add switches in the MVC and/or imports&override in the XSLT. This was manageable for a while but now we have so many versions and customisations for sooo many clients, getting stable builds out the door is becoming a nightmare

We are looking to move to MS asp.mvc3 with using Razor for our views but before this I am wondering are there any standard practices or patterns for developing and managing the kind of mess we are sliding towards?

Cheers,
T

答:
If switching views causes application stability issue, you've coupled the view to the business logic too tightly. This also creates testing issues because of the view permutations.

This leads me to think that the Model-View-Presenter (MVP) pattern would suit your development needs better. You can read up on 2 derivations of them on Martin Fowler's site:

Supervising Presenter

Passive View

You won't be able to achieve what you want overnight, but hopefully with some planning and foresight you'll get most of the way there in a couple release cycles.

Also look into good continuous integration practices/tools.

ContentLicense: CC BY-SA 2.5


问:
Process of handing over source code to a customer
Should I just copy the project files to him? Should I sit and explain the code to him ? If so, up to which level of details? Or do I just tell him where everything is within the solution and not how the code works?

I would appreciate your input

答:
You make a copy of the code.

You take that copy of the code to a different computer and verify that you can build the application on that computer from the code.

If that doesn't work, then you fix all the problems in the code until it works to build the application on your computer, and on the second computer.

You document all the steps that are needed to build the application, so that another person can build the application using those instructions only. When you document the steps, you assume that the reader can read the instructions, but not your mind.

You give the code and the instructions to a secretary at your company, or to your mother, and make sure that they can build the application following the instructions without asking you any questions.

Until that works, you improve the instructions.

At that point, you hand over the code and the instructions to the customer.

ContentLicense: CC BY-SA 3.0


答:
I would approach this the same as when handing over to any other maintainer:

Include the source control files so that they have the entire history of the project.

Make sure that the code builds from source with just one command. Nothing is more depressing then having to spend several hours/days before getting it to compile.

If external resources are required (say a database) the code for setting them up should be part of the source control. (Think: Migrations and/or for example a Vagrant file for local testing.)

Documentation:

A High Level overview of the project (the different layers, their intent and their dependencies)

Deployment configuration: How to deploy (again, ideally with one command), where to find the log files, which firewalls, reverse proxies, ... are passed, credentials for databases etc.

Anything that you think your client could benefit from...  (ex: ubiquitous language, design/architectural decisions etc)

Most importantly, keep documentation as short as possible. If you hand over 50+ pages of documentation, chances are it will never be read. (it all depends on the size of the project of course but less is almost always better)

Going through the code with the client: I guess this is up to him. If the client will continue work on it right away, going through the code together is a very good idea. He will not remember everything you say and show but will have some general idea of your project layout.

Title: Process of handing over source code to a customer

Body:
Should I just copy the project files to him? Should I sit and explain the code to him ? If so, up to which level of details? Or do I just tell him where everything is within the solution and not how the code works?

I would appreciate your input


问:
Explaining floating point precision to customers
What is the best way to explain floating point rounding issue to customers?

I know

http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html

as well as the entries in the C++ FAQ and various other pages aimed at developers and scientists, but is there a web page, article or explanation, aimed at "regular" customers with limited mathematical or scientific background? (for which the above references fall flat).

If it were maintained or coming from a well-known and well-recognized institution or corporation, all the better, given that, as some of you might have experienced, it can be a little complicated to explain that yourself.

答:
Some calculations are done according to some legal rule. For example, if you want to calculate how much income tax has to be paid on a taxable annual income of €79.245,18 in Germany, there is only one correct answer. You get it right or you get it wrong. If you get it right, you don't need to explain how floating point arithmetic works. If you get it wrong, you don't need to explain how floating point arithmetic works, you have to fix your broken code.

Sometimes you display results that don't look right. For example, if you convert US$ 13,297.46 into UK£ with two decimal digits, and then convert that amount of UK£ back to US$, you might not get US$ 13,297.46 but US$ 13,297.45 or US$ 13,297.47. That has nothing to do with floating-point arithmetic. It's an unavoidable problem and you better be able to explain why it is unavoidable. (You should also know why the problem doesn't happen when you convert from UK£ to US$ and back).

There are other possible results that don't look right. If you convert numbers to percentages the percentages should add up to 100%, but they might not. If you display four percentages with two decimals, the four displayed percentages might add up to 99.99% or 100.01%. Nothing to do with floating-point arithmetic. Still you should be able to explain why.

Next, there are situations where careless use of floating-point arithmetic leads to inappropriate results. For example, a + b + c is usually not the same as b + c + a. If that causes a problem, there is nothing to explain, it's something that you fix.


问:
How to reduce redundancy in a service implemented using multilayer architecture while maintaining consistency across the system?
Currently our service is implemented using a multilayer architecture dividing the whole service into three:

API

Business

Persistence

However this introduces a lot of redundancy within our system. A common adage in the industry is "DRY" (Don't Repeat Yourself). The redundancy has increased the development time, and made the system more fragile and cluttered our code with "copy" methods.

To give a better idea, say we have a Person service. This would require the following:

Person entity - JPA annotated class for ORM

Repository service request - contains field values to be persisted of the Person domain object with additional persistence options

Repository service response - contains field values of the Person entity

Person - class with business logic, domain fields and computed fields

Domain service request - contains field values of Person resource and additional business options

Domain service response - contains field values of Person business object excluding those that shouldn't be visible to API users

Person resource - class representing what should be viewable to the API users

And things get worse when taking nested objects into consideration.

The current design facilitates difference between concerns (business, API, persistence), however:

Currently, the differences are very small. This is causing us to have
very similar classes with only minor differences

Services returning
service response objects with fields instead of just the objects
itself hampers other services from depending on other services

Questions:

Is it worth it to go through with this design?

What are our alternatives?

What could we change to improve our situation?

答:
On first sight, I find your architecture overly complex.

What is the purpose of having a Person(@Entity), a ServiceRequest, ServiceResponse, DomainServiceRequest, DomainServiceResponse besides sleeping good at night with abstractions for the abstractions sake?

You are drowning little puppies here

Within the Backend of your application, using only the Person POJO (=Entity) would be sufficient.

In a typical MVC-style (web-)application you have a Rest-Controller where all requests from the "outside" land. Depending on what action is required, you could make a request to the repository for querying data ( e.g. GET /api/users/1 you call personRepository.findOne(1) and return the result ) or you ask a service to manipulate data or do something more complex than just retrieving data.

Then you have a servicelayer, where your business logic sits and your POJOS are manipulated. The changes are then persisted in the Repository-Layer (eg. personRepository.save(person)).

This is a rather pragmatic than orthodox architecture: querying data in the Controller is not 100% separation of concerns - on the other hand, what would be won, when the query is encapsulated in the service-layer?

You could even go further and organizing your code in such a way, that you have a Package Person which contains the Controller, the Service and the Repository, which makes it easy later on cutting your app up into separate services (if needed).

Besides the internal use of the POJO/Model, perhaps it makes sense to use another modelling object to transfer over the wire. It's dependend on the use case.

The redundancy has increased the development time, and made the system more fragile and cluttered our code with "copy" methods.

That is a clear sign, that your architecture needs some revision.

Your design is a typical onion-design: it has many layers and makes you cry.


答:
If your personal opinion is already that it is too much work, then yes, look at ways to simplify the design by merging or omitting certain classes.

Some things to consider:

Merge the entity and the business classes. If it can be done in a 'clean' way with your ORM framework.

Be adaptable. For some crazy classes you may benefit from all this infrastructure but keep simple cases simple. If a Person has an Ethnic property that has admin screens which are pretty much taking the UI fields and updating them in the database, do not bother with all the overhead. A DTO, an Entity and a generic Repository may do the trick.

Request/Response/resource classes: You have different options here

Allow the Repository service and Domain service to be more intimate: use the same Request/Response classes for this boundary.

Repository service request: If you extract all the options to its own class, you might no longer need these. (Especially useful if you would only end up with one/a few identical options classes) - similar option classes could be used instead of special domain service request objects.

Domain service response: These could already be returned directly from the Repository or the Domain layer in those cases that the layers below don't actually do anything with the fields that are stripped off.

Keep the repositories down by using aggregated roots for nested objects. ex: The Person repository automatically updates/inserts/deletes all Hobbys instead of having its own Hobby Repository.

Keep in mind that if you have large compositions of objects all this serializing/deserializing between layers might start taking noticeable time.

Title: How to reduce redundancy in a service implemented using multilayer architecture while maintaining consistency across the system?

Body:
Currently our service is implemented using a multilayer architecture dividing the whole service into three:

API

Business

Persistence

However this introduces a lot of redundancy within our system. A common adage in the industry is "DRY" (Don't Repeat Yourself). The redundancy has increased the development time, and made the system more fragile and cluttered our code with "copy" methods.

To give a better idea, say we have a Person service. This would require the following:

Person entity - JPA annotated class for ORM

Repository service request - contains field values to be persisted of the Person domain object with additional persistence options

Repository service response - contains field values of the Person entity

Person - class with business logic, domain fields and computed fields

Domain service request - contains field values of Person resource and additional business options

Domain service response - contains field values of Person business object excluding those that shouldn't be visible to API users

Person resource - class representing what should be viewable to the API users

And things get worse when taking nested objects into consideration.

The current design facilitates difference between concerns (business, API, persistence), however:

Currently, the differences are very small. This is causing us to have
very similar classes with only minor differences

Services returning
service response objects with fields instead of just the objects
itself hampers other services from depending on other services

Questions:

Is it worth it to go through with this design?

What are our alternatives?

What could we change to improve our situation?


问:
Design decisions while porting a non object-oriented C program to Java
Background:
My boss made a comment on porting a C program that acts as some a simulator that communicates with a remote process through sockets to Java. He didn't assign it to me, or to anyone for that matter, it was just a project he had in mind. He showed and gave me access to the C source code file for said program so I could take a look.

Now I'm an intern in this company and haven't really been assigned something in particular so I wanted to start this project on my own and then show it to my boss.

Problem:
The C program is ~4k lines long. It consists on many global variables and functions that use those variables; I guess this is mainly to avoid passing many parameters. There are even some goto statements (yeah, also most of the codebase is from 1980). So basically my question is: should I aim to replicate the structure of the C program in a single Java class so there is a visible mapping of behavior between both? Or should I come up with
a better object oriented design that may imply the creation of many components? What would be your approach to solving this problem?

Thanks.

答:
It seems you want to achieve two things: Create a Java program instead of a C program, and have an improved structure. Both represent work. However, it is less work to convert a C program with a good structure to Java than a badly structured C program. And improving the structure is easier with a known working application, so you can make one improvement, test that it works, undo the work if you introduced a bug, take the improvement if it worked, and so on. </p>

<p>So if you do this, improve the structure of the C program first, and then convert to Java when the C code is in a good state. The problem with this conversion is that for a long time you won't have something that works, which is why you want to put the C code into a state where you know exactly how to convert each part to Java. </p>

Body:
It seems you want to achieve two things: Create a Java program instead of a C program, and have an improved structure. Both represent work. However, it is less work to convert a C program with a good structure to Java than a badly structured C program. And improving the structure is easier with a known working application, so you can make one improvement, test that it works, undo the work if you introduced a bug, take the improvement if it worked, and so on.

So if you do this, improve the structure of the C program first, and then convert to Java when the C code is in a good state. The problem with this conversion is that for a long time you won't have something that works, which is why you want to put the C code into a state where you know exactly how to convert each part to Java.


答:
2/3

Ask them to write down the exact answer to two divided by 3.

Since the answer 'goes on for forever' you can point that out.

Using 1/3 would also work but 2/3 is perhaps a slightly better example as rounding gives you (e.g.) .6666667 whereas .3333333 looks like it can just be truncated.

Title: Explaining floating point precision to customers

Body:
What is the best way to explain floating point rounding issue to customers?

I know

http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html

as well as the entries in the C++ FAQ and various other pages aimed at developers and scientists, but is there a web page, article or explanation, aimed at "regular" customers with limited mathematical or scientific background? (for which the above references fall flat).

If it were maintained or coming from a well-known and well-recognized institution or corporation, all the better, given that, as some of you might have experienced, it can be a little complicated to explain that yourself.


问:
Snippets (based on MIT licence) from snippets services
I have question about MIT licence code sources

Can I publish code snippets [MIT licence] from site like bootsnipp to my blog?

Do I have to include source link to site where I have found that snippet (it has been published there first and its MIT)? or not?

答:
The MIT license states:

Permission is hereby granted ... to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software ... subject to
  the following conditions:

The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

There's only one condition you are subject to: include the copyright notice. Therefore, the answers to your questions are:

1) Yes, you can copy and publish them as long as you include the copyright notice.

2) No, you are not required to link to where you found it. But it's still a good idea to cite your sources even if the license doesn't require you to do so.


问:
How to prevent accidental deployment of branch under a legacy deployment process?
We have a feature branch right now in development that must not be deployed to production. At the moment there is nothing that would prevent such a mistake from happening.

Deployment happens manually at the moment (SVN export + FTP to production). Migration to a better model is planned but not available in the short term.

Now when you work on a branch locally, then export and upload the files it is really easy to accidentally deploy the wrong branch.

What are some easy and light-weight ways to prevent accidental deployments? We also would be happy with preventing accidental code execution. Downtime is much more acceptable than execution of the feature branches code. So it would be OK for the app to refuse to work in production. This would be noticed right away.

答:
Deployment happens manually at the moment (SVN export + FTP to production).
  Migration to a better model is planned but not available in the short term.

I do not know what "better model" you have in mind, but you seem to think of something which is so complicated that you cannot implement it by yourself in one or two hours. Why don't you just put the SVN export + FTP steps you currently do manually into a simple shell script? SVN and FTP are available as command line tools for every OS I know. You just have to care for these two things:

make sure the deploy script exports only from the trunk, but not from the feature branch.

make sure noone in your team tries to deploy manually, only by that script.

This does not only solve your current problem, it also makes the deployment more smooth and less error prone when you have no feature branch.


答:
I see no reason to port the code from a procedural language to an object oriented language without making the code object oriented. Do you just wish to be able to write procedural code in an object oriented language?

Object oriented code is a step forward. Procedural code in an object oriented language is for the least not forward if not exclusively backwards. With the exercise that you saying that you are going to do, at the most you are going to learn How to change a code with GOTOs to a code without them.

IMHO, try to understand the purpose of that procedural code and then design it in terms of Classes. Make use of the four principles of Object Oriented Design - Abstraction, Polymorphism, Inheritance and Encapsulation. Learn about and bring into your practice the SOLID principles. Learn also how to test your code.

Designing an object oriented system is far more fundamental than coding.

Title: Design decisions while porting a non object-oriented C program to Java

Body:
Background:
My boss made a comment on porting a C program that acts as some a simulator that communicates with a remote process through sockets to Java. He didn't assign it to me, or to anyone for that matter, it was just a project he had in mind. He showed and gave me access to the C source code file for said program so I could take a look.

Now I'm an intern in this company and haven't really been assigned something in particular so I wanted to start this project on my own and then show it to my boss.

Problem:
The C program is ~4k lines long. It consists on many global variables and functions that use those variables; I guess this is mainly to avoid passing many parameters. There are even some goto statements (yeah, also most of the codebase is from 1980). So basically my question is: should I aim to replicate the structure of the C program in a single Java class so there is a visible mapping of behavior between both? Or should I come up with
a better object oriented design that may imply the creation of many components? What would be your approach to solving this problem?

Thanks.


问:
What is the problem will happen if I create auto generate ID without using mysql auto increase of mysql table by my self?
I would like to ask you a question about MySQL AUTO_INCREMENT.

I already created my own function to generate AUTO_INCREMENT when the user inserts any data input a table in MySQL. This function works very well but I am concerned about the problem which I may face in the future because it is really new to me.

This table is used to store navigation menus and it will store only 400 of rows. Is it possible or not?

答:
Whenever a database has multiple concurrent writers, there are potential race conditions. In particular, if each writer tries to add a new row, they may all choose the same primary key if they're just doing max(...)+1, and then all but one of the inserts will fail.

When a database has an "auto increment" feature, they're not saving you the trouble of writing max(...)+1, they're saving you the trouble of doing so in a perfectly thread-safe way, which may be impossible for you to do yourself if some of the database writers are written in other languages and owned by different developers.

If you only ever have one writer at a time, then this may not cause any problems. But you shouldn't commit to the assumption that you'll never want multiple writers, so let the database do this for you.


问:
Does music increase your productivity?
I wanted to know whether you think and audio background is just a distraction or could be of some help while programming.

For me, it works like this:

when I'm writing pseudocode, or implementing procedures that are very clear in my mind in a language I can write without looking up docs, having music playing in the background (very straightforward electronics, mostly) helps me a lot: it kind of gives some rhythm to my coding and, if the procedures are trivial, avoids the distractions that boredom can cause.

When I incur in a problem, or I have to try to fix a bug, instead, it just distracts me.

Also, if the song is really regular and I know it well enough not to cause me to focus on it, it eliminates unexpected environmental noise that sometimes make me waste precious seconds before I can concentrate on the code again.

Guidelines checklist: 1 ok, 2 I hope; 3 I suppose; 4 Definitely; 5 I would like that to happen; 6 Doch (English should implement a way to disambiguate double negatives in answers)

答:
It depends.

If you ask me, listening to Pandit Ravishankar on my noise cancelling headphones definitely cuts me off from whats happening in the outside world. Concentration booster, big time.

Title: Does music increase your productivity?


答:
Naturally, the correct procedure would be to do it the right way, Java is an OO language after all, but whether you should mimic the current coding style or do it the right way an OO programmer would is not up to you, but up to your lead.

Therefore discuss with your manager first, if they want to keep the structure as is, or make the code more agile friendly, introducing design patterns, the SOLID principles,...


问:
Squashing commits from multiple developers into a single commit
I work in a large software development group and we've recently made the switch from Clearcase to Git.  Some predictions have been made with regard to the quality of the mainline in that it would become too noisy and unmanageable with commits from hundreds of developers and that the repo would get too large too quickly.

The current proposal to address this is that when feature teams bring in changes to the mainline (this can happen every week or so, and there are multiple feature teams working in parallel on the product) a single developer would be responsible for squashing multiple commits from multiple developers into a single commit.

The above approach worries me mainly because 'git bisect' and 'git blame' functionality would be compromised (a single developer would now represent the work of multiple developers).  I've countered with the following proposals:

To address the noise in mainline, each developer should squash into a single commit before creating a pull request.  This appears to be standard practice.

To address the size of the repo, devs could do shallow cloning and grafting (both approaches detailed here: http://blogs.atlassian.com/2014/05/handle-big-repositories-git/)

So far I haven't been able to convince anyone that these would be good approaches.  FWIW I also proposed using Gitflow as the main development workflow to separate out development and release branches but that also didn't gain any traction.  Personally I think so long as developers squash into a single commit before generating a pull request then that's fine... having commits from many different developers in the mainline is pretty much a non-issue after that point, it just shows that a lot of work is being done.

So my question to those of you who work on large projects in Git: is having many commits coming into your mainline actually an issue, thus forcing you to resort to solutions like squashing commits from multiple developers into single commits?

答:
At my company, we have never really had problems with too many commits. The key to organizing is to create well named branches and do your work in them. That helps to organize not only commits, but the developing group as a whole.

Yes, without branching, it could become a huge mess, but with them, your management can just browse the commits using them without needing to squash commits together.

Squashing multiple commits into single does not really make sense, as using that way it is more difficult to retrieve single edits.


问:
Why is there no 'finally' construct in C++?
Exception handling in C++ is limited to try/throw/catch. Unlike Object Pascal, Java, C# and Python, even in C++ 11, the finally construct has not been implemented.

I have seen an awful lot of C++ literature discussing "exception safe code". Lippman writes that exception safe code is an important but advanced, difficult topic, beyond the scope of his Primer - which seems to imply that safe code is not fundamental to C++. Herb Sutter devotes 10 chapters to the topic in his Exceptional C++ !

Yet it seems to me that many of the problems encountered when attempting to write "exception safe code" could be quite well solved if the finally construct was implemented, allowing the programmer to ensure that even in the event of an exception, the program can be restored to a safe, stable, leak-free state, close to the point of allocation of resources and potentially problematic code. As a very experienced Delphi and C# programmer I use try.. finally blocks quite extensively in my code, as do most programmers in these languages.

Considering all the 'bells and whistles' implemented in C++ 11, I was astonished to find that 'finally' was still not there.

So, why has the finally construct never been implemented in C++? It's really not a very difficult or advanced concept to grasp and goes a long ways towards helping the programmer to write 'exception safe code'.

答:
I'm not sure I agree with assertions here that RAII is a superset of finally.  The achilles heel of RAII is simple: exceptions.  RAII is implemented with destructors, and it's always wrong in C++ to throw out of a destructor.  That means that you cannot use RAII when you need your cleanup code to throw.  If finally were implemented, on the other hand, there's no reason to believe that it would not be legal to throw from a finally block.

Consider a code path like this:

```<code>void foo() {
    try {
        ... stuff ...
        complex_cleanup();
    } catch (A& a) {
        handle_a(a);
        complex_cleanup();
        throw;
    } catch (B& b) {
        handle_b(b);
        complex_cleanup();
        throw;
    } catch (...) {
        handle_generic();
        complex_cleanup();
        throw;
    }
}
</code>```

If we had finally we could write:

```<code>void foo() {
    try {
        ... stuff ...
    } catch (A& a) {
        handle_a(a);
        throw;
    } catch (B& b) {
        handle_b(b);
        throw;
    } catch (...) {
        handle_generic();
        throw;
    } finally {
        complex_cleanup();
    }
}
</code>```

But there is no way, that I can find, to get the equivalent behavior using RAII.

If someone knows how to do this in C++, I'm very interested in the answer.  I'd even be happy with something that relied on, for example, enforcing that all exceptions inherited from a single class with some special capabilities or something.

Body:
I'm not sure I agree with assertions here that RAII is a superset of finally.  The achilles heel of RAII is simple: exceptions.  RAII is implemented with destructors, and it's always wrong in C++ to throw out of a destructor.  That means that you cannot use RAII when you need your cleanup code to throw.  If finally were implemented, on the other hand, there's no reason to believe that it would not be legal to throw from a finally block.

Consider a code path like this:

void foo() {
    try {
        ... stuff ...
        complex_cleanup();
    } catch (A& a) {
        handle_a(a);
        complex_cleanup();
        throw;
    } catch (B& b) {
        handle_b(b);
        complex_cleanup();
        throw;
    } catch (...) {
        handle_generic();
        complex_cleanup();
        throw;
    }
}

If we had finally we could write:

void foo() {
    try {
        ... stuff ...
    } catch (A& a) {
        handle_a(a);
        throw;
    } catch (B& b) {
        handle_b(b);
        throw;
    } catch (...) {
        handle_generic();
        throw;
    } finally {
        complex_cleanup();
    }
}

But there is no way, that I can find, to get the equivalent behavior using RAII.

If someone knows how to do this in C++, I'm very interested in the answer.  I'd even be happy with something that relied on, for example, enforcing that all exceptions inherited from a single class with some special capabilities or something.


问:
Open Source PHP Encoder
Are there some recomendations on Open Source or Free PHP Encoder systems?
Is something available?

答: Don't fool yourself. You don't need an encoder. If you still feel like it, there is a Raiz Labs PHP Obfuscator. Any many others, just use Google.</p>

Title: Open Source PHP Encoder


问:
Why do Haskell and Scheme use singly-linked lists?
A doubly linked list has minimal overhead (just another pointer per cell), and allows you to append to both ends and go back and forth and generally have a lot of fun.</p>

答:
Because they work well with immutability. Suppose you have two immutable lists, [1, 2, 3] and [10, 2, 3]. Represented as singly linked lists where each item in the list is a node containing the item and a pointer to the rest of the list, they'd look like this:

```<code>node -> node -> node -> empty
 1       2       3

node -> node -> node -> empty
 10       2       3
</code>```

See how the [2, 3] portions are identical? With mutable data structures, they're two different lists because code writing new data to one of them needs to not affect code using the other one. With immutable data however, we know that the contents of the lists will never change and code can't write new data. So we can re-use the tails and have the two lists share part of their structure:

```<code>node -> node -> node -> empty
 1      ^ 2       3
        |
node ---+
 10
</code>```

Since code using the two lists will never mutate them, we never have to worry about changes to one list affecting the other. This also means that when adding an item to the front of the list, you don't have to copy and make a whole new list.

However, if you try and represent [1, 2, 3] and [10, 2, 3] as doubly linked lists:

```<code>node <-> node <-> node <-> empty
 1       2       3

node <-> node <-> node <-> empty
 10       2       3
</code>```

Now the tails aren't identical anymore. The first [2, 3] has a pointer to 1 at the head, but the second has a pointer to 10. Additionally, if you want to add a new item to the head of the list you have to mutate the previous head of the list to make it point to the new head.

The multiple heads problem could potentially be fixed by having each node store a list of known heads and having the creation of new lists modify that, but then you have to work in maintaining that list to garbage collection cycles when versions of the list with different heads have different lifetimes due to being used in different pieces of code. It adds complexity and overhead, and most of the time it's not worth it.

Body:
Because they work well with immutability. Suppose you have two immutable lists, [1, 2, 3] and [10, 2, 3]. Represented as singly linked lists where each item in the list is a node containing the item and a pointer to the rest of the list, they'd look like this:

node -> node -> node -> empty
 1       2       3

node -> node -> node -> empty
 10       2       3

See how the [2, 3] portions are identical? With mutable data structures, they're two different lists because code writing new data to one of them needs to not affect code using the other one. With immutable data however, we know that the contents of the lists will never change and code can't write new data. So we can re-use the tails and have the two lists share part of their structure:

node -> node -> node -> empty
 1      ^ 2       3
        |
node ---+
 10

Since code using the two lists will never mutate them, we never have to worry about changes to one list affecting the other. This also means that when adding an item to the front of the list, you don't have to copy and make a whole new list.

However, if you try and represent [1, 2, 3] and [10, 2, 3] as doubly linked lists:

node <-> node <-> node <-> empty
 1       2       3

node <-> node <-> node <-> empty
 10       2       3

Now the tails aren't identical anymore. The first [2, 3] has a pointer to 1 at the head, but the second has a pointer to 10. Additionally, if you want to add a new item to the head of the list you have to mutate the previous head of the list to make it point to the new head.

The multiple heads problem could potentially be fixed by having each node store a list of known heads and having the creation of new lists modify that, but then you have to work in maintaining that list to garbage collection cycles when versions of the list with different heads have different lifetimes due to being used in different pieces of code. It adds complexity and overhead, and most of the time it's not worth it.


问:
Why do we need an instance of the Scanner Class to get an Input on Java?
Java is object oriented, but, why do we need to create an object from the Scanner Class to get input? Couldn't next() methods, for example, just be Static?

C looks to me pretty simpler as you just use scanf(), gets() or fgets().
I'm sure there's a reason for Java developers for creating the Scanner class, but how is it better than just having a normal function to do the work?

I've found this link that may seem asking the same question, but answers are just about

"you need to create an object because is not static"...

My guess is: since Java is Object Oriented, they decided to put all input methods in a class. They didn't do static methods so you can have all kind of different sources (keyboard Input, file Input...) in different objects ?

I would appreciate if someone can edit the question to make it sound more clear!

答:
The answer is "because a scanner has state."

Looking at the code for java.util.Scanner, you will see a number of private fields such as a buffer and its associated information, a Matcher, a Pattern, an input source, information about if the source is closed or not, the type of the last thing matched, information about if the last thing was a valid match or not, the radix used for numbers, the locale (information about if you are using . or , as a thousands separator), and its own LRU cache for recently used patterns, the information about the last exception that was encountered, some information about parsing numbers, some information about parsing booleans, quite a bit more information about parsing integers... and I think thats about it.

As you can see, thats a fairly large block of text there. That is the state of the Scanner.  In order to make the Scanner into a static class, that state would need to be stored somewhere else.  The C way of doing it really doesn't have that much state with it.  You've got a fscanf.  The FILE maintains some state about the position it is at (but that needs to be passed in for each invocation of fscanf).  If there was an error, you have to process it (and then you start writing code that looks like this) - and that doesn't tell you information like "I was expecting an Integer, but found a String."

When one looks at the theoretically static Scanner - all of the state is maintained outside of the class, it isn't encapsulated within the class.  Other bits of code could tinker with those variables.  When other code can tinker with the state of the class, it becomes very difficult to reason about what the class will do in any given situation.

You could, maybe, write something like ScannerState { Locale loc; ... } and have code that results in:

```<code>ScannerState state = new ScannerState(a whole lot of arguments);
int foo = Scanner.nextInt(state);
</code>```

But then, this is much more cumbersome than having the state encapsulated within a Scanner object in the first place (and not needing to pass in the state).

Lastly, the Scanner implements the interface of Iterator<String> which means that one can use it in code such as:

```<code>Scanner in = new Scanner(someFile);
whie(in.hasNext()) { ... }
</code>```

Without being able to get an instance of the Scanner class, this type of structure becomes more cumbersome within an object oriented language.

Body:
The answer is "because a scanner has state."

Looking at the code for java.util.Scanner, you will see a number of private fields such as a buffer and its associated information, a Matcher, a Pattern, an input source, information about if the source is closed or not, the type of the last thing matched, information about if the last thing was a valid match or not, the radix used for numbers, the locale (information about if you are using . or , as a thousands separator), and its own LRU cache for recently used patterns, the information about the last exception that was encountered, some information about parsing numbers, some information about parsing booleans, quite a bit more information about parsing integers... and I think thats about it.

As you can see, thats a fairly large block of text there. That is the state of the Scanner.  In order to make the Scanner into a static class, that state would need to be stored somewhere else.  The C way of doing it really doesn't have that much state with it.  You've got a fscanf.  The FILE maintains some state about the position it is at (but that needs to be passed in for each invocation of fscanf).  If there was an error, you have to process it (and then you start writing code that looks like this) - and that doesn't tell you information like "I was expecting an Integer, but found a String."

When one looks at the theoretically static Scanner - all of the state is maintained outside of the class, it isn't encapsulated within the class.  Other bits of code could tinker with those variables.  When other code can tinker with the state of the class, it becomes very difficult to reason about what the class will do in any given situation.

You could, maybe, write something like ScannerState { Locale loc; ... } and have code that results in:

ScannerState state = new ScannerState(a whole lot of arguments);
int foo = Scanner.nextInt(state);

But then, this is much more cumbersome than having the state encapsulated within a Scanner object in the first place (and not needing to pass in the state).

Lastly, the Scanner implements the interface of Iterator<String> which means that one can use it in code such as:

Scanner in = new Scanner(someFile);
whie(in.hasNext()) { ... }

Without being able to get an instance of the Scanner class, this type of structure becomes more cumbersome within an object oriented language.


问:
What's the Content-Security-Policy-friendly way to hand data from the server to the browser on page load?
When developing for the web, I often find myself wanting to pass a few variables from the server scripts to my javascript - data pulled from a database, and set differently on different pages running basically the same code. (Typically, this is something along the lines of example.com/slideshows/1 needing to know that that slideshow 1 has 8 images, and what their urls are, but that's just a random example; I'm looking for a general answer.)

My normal approach is to include a short block of inline javascript that sets a few global variables or calls some initializer functions, which is straightforward and effective. It is not, however, Content Security Policy-friendly, since inline javascript is blocked by default, and not without reason. (I know the policy can be set to allow inline javascript if you have access to it, but even if you do that opens potential security issues.) I need a strategy that plays nicely with proper CSPs.

I know that it could be done with an ajax call, but that's overkill for something that only needs to be set once, and adds an extra call that slows down the page load. In some cases, like the slideshow I mentioned, this could be handled by having the javascript examine other dynamically-constructed page elements to reconstruct the desired data, which is fine, but not a very general solution. What's the best way to handle this?

(I almost posted this question on SO, but it seems kind of subjective; I can think of ways to do this, I just don't like any of them.)

答:
You could use a hash. If you had an inline script like this:

```<code><script>alert('Hello, world.');</script>
</code>```

You can hash it and specifiy it in your Content-Security-Policy header.

```<code>Content-Security-Policy: script-src 'sha256-qznLcsROx4GACP2dm0UCKCzCG-HiZ1guq6ZZDob_Tng='
</code>```

There's also a mechanism for using a nonce:

```<code><script nonce=EDNnf03nceIOfn39fn3e9h3sdfa>
Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'
</code>```

Examples taken from: http://www.html5rocks.com/en/tutorials/security/content-security-policy/

If you really don't even want that, you don't have many options, but you could:

If you can use HTTP 2.0 (SPDY) you can take advantage of server-side push. (https://www.igvita.com/2013/06/12/innovating-with-http-2.0-server-push/)

Put the data in hidden HTML tag or data attribute (gross, I know, but we're exploring the options here)

Stuff it in a custom header.

Body:
You could use a hash. If you had an inline script like this:

<script>alert('Hello, world.');</script>

You can hash it and specifiy it in your Content-Security-Policy header.

Content-Security-Policy: script-src 'sha256-qznLcsROx4GACP2dm0UCKCzCG-HiZ1guq6ZZDob_Tng='

There's also a mechanism for using a nonce:

<script nonce=EDNnf03nceIOfn39fn3e9h3sdfa>
Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'

Examples taken from: http://www.html5rocks.com/en/tutorials/security/content-security-policy/

If you really don't even want that, you don't have many options, but you could:

If you can use HTTP 2.0 (SPDY) you can take advantage of server-side push. (https://www.igvita.com/2013/06/12/innovating-with-http-2.0-server-push/)

Put the data in hidden HTML tag or data attribute (gross, I know, but we're exploring the options here)

Stuff it in a custom header.


答:
short answer: you don't. You can get user input without using a Scanner instance.

For example: https://docs.oracle.com/javase/tutorial/essential/io/cl.html or

http://alvinalexander.com/blog/post/java/java-source-code-read-command-line-input

Title: Why do we need an instance of the Scanner Class to get an Input on Java?

Body:
Java is object oriented, but, why do we need to create an object from the Scanner Class to get input? Couldn't next() methods, for example, just be Static?

C looks to me pretty simpler as you just use scanf(), gets() or fgets().
I'm sure there's a reason for Java developers for creating the Scanner class, but how is it better than just having a normal function to do the work?

I've found this link that may seem asking the same question, but answers are just about

"you need to create an object because is not static"...

My guess is: since Java is Object Oriented, they decided to put all input methods in a class. They didn't do static methods so you can have all kind of different sources (keyboard Input, file Input...) in different objects ?

I would appreciate if someone can edit the question to make it sound more clear!


问:
How can I keep data integrity across multiple services in a transaction-like fashion with PHP?
I find the concept of transactions really useful when working with databases because obviously it allows you to rollback changes if one step of a modification goes awry.

Is there some way I can extend the same principle across multiple services? Say I have the following example of someone uploading something to a website (not contrived by the way, I'm dealing with something similar now):

```<code>// Store data in an object store
$object->putToS3();

// Add to ElasticSearch node
Search::indexObject($object);

// Remove local files
$object->deleteLocalFiles();

// Increment some Redis counter
Redis::hmset(...);

// Add to database
$object->save();
</code>```

Is there some standardized solution on how I can undo all of these actions if any one fails, to keep my data in the correct state? I don't have much knowledge about this.

What I do know however is that it would suck to have something added to your database that doesn't exist in your storage solution or in your Redis store.

Has anyone dealt with anything similar?

答:
I think there is no such thing you are asking for.

I would use a simple try-catch block during the store process, and throw any exception if something goes wrong. You need to manually track the results of each suboperation, and roll-back any changes happened.

OwnerDisplayName: EchoLogic

OwnerDisplayName: SalDev


答: The technique you're looking for is called two phase commit. Essentially, the idea is that you ask each of your services to determine whether the transaction will succeed or not, then you separately tell each of them whether or not to actually proceed with the transaction. They may have to lock resources during the preparation phase in order to ensure the transaction is still able to complete when it is committed.

Title: How can I keep data integrity across multiple services in a transaction-like fashion with PHP?

Body:
I find the concept of transactions really useful when working with databases because obviously it allows you to rollback changes if one step of a modification goes awry.

Is there some way I can extend the same principle across multiple services? Say I have the following example of someone uploading something to a website (not contrived by the way, I'm dealing with something similar now):

```<code>// Store data in an object store
$object->putToS3();

// Add to ElasticSearch node
Search::indexObject($object);

// Remove local files
$object->deleteLocalFiles();

// Increment some Redis counter
Redis::hmset(...);

// Add to database
$object->save();
</code>```

Is there some standardized solution on how I can undo all of these actions if any one fails, to keep my data in the correct state? I don't have much knowledge about this.

What I do know however is that it would suck to have something added to your database that doesn't exist in your storage solution or in your Redis store.

Has anyone dealt with anything similar?


问:
Killer semi-unique programming language features
When learning a new programming language you sometimes come across a language feature which
makes you wish you had it in your other programming languages that you know.

What are some language feature which were at the time of learning very new to you and that you wish your other programming languages had.

An example of this is generators in Python or C#.
Other examples may include list comprehensions in Python, template in C++ or LINQ in .NET or lazy evaluation in Haskell.

What other semi-unique language features have you come across which were completely new and enlightening to you?  Are there other features of older programming languages which were unique and have fallen out of fashion?

答:
Unions in C

I can't honestly say that I haven't written enough C to make any of these myself but I have worked with other's code that does.

When it comes down to packaging mixtures of different data in applications that manipulate raw bits/bytes such as networking or binary data storage. In strongly typed languages theres just no easy way to do the equivalent.

Disclaimer:

Although Unions are extremely useful in some cases, they aren't found in most higher level languages because they aren't type safe. IE, you can make data bleed across boundaries of variables using unions (a big no no in the type safe world). With great power comes great responsibility.


答:
Personally, without music I find it very hard to get "in the zone."

...which has been a problem lately.  Internet Radio sites are blocked, we're allowed to listen to headphones but my phone/mp3 player bricked about a week ago and has yet to be replaced. :(.  Generic office background noise does not conduce good work.

Title: Does music increase your productivity?

Body:
I wanted to know whether you think and audio background is just a distraction or could be of some help while programming.

For me, it works like this:

when I'm writing pseudocode, or implementing procedures that are very clear in my mind in a language I can write without looking up docs, having music playing in the background (very straightforward electronics, mostly) helps me a lot: it kind of gives some rhythm to my coding and, if the procedures are trivial, avoids the distractions that boredom can cause.

When I incur in a problem, or I have to try to fix a bug, instead, it just distracts me.

Also, if the song is really regular and I know it well enough not to cause me to focus on it, it eliminates unexpected environmental noise that sometimes make me waste precious seconds before I can concentrate on the code again.

Guidelines checklist: 1 ok, 2 I hope; 3 I suppose; 4 Definitely; 5 I would like that to happen; 6 Doch (English should implement a way to disambiguate double negatives in answers)


问:
What to do with my unit tests when refactoring code to a new class
I hope I can make a clear question...
I've simplified my code example for this question, I hope it still makes sense.

public class PersonComponent
{
    public bool IsQualified(Person person)
    {
        if (person.PropertyA){ return true; }
        if (person.PropertyB && !person.PropertyC) { return true; }
        if (VeryDifficultFunction(person.Certificates))
        {
            return true;
        }
        return false;
    }

    private bool VeryDifficultFunction(List<Certificate> certificates)
    {}
}

public class Person
{
    public bool PropertyA { get; set; }
    public bool PropertyB { get; set; }
    public bool PropertyC { get; set; }
    public List<Certificate> Certificates { get; set; }
}

public class Certificate
{ }
```

<p>I have a <code>personcomponent</code> which determines if a given <code>person</code> is qualified or not.</p>

<p>Besides a few simple validations on properties <code>A</code>, <code>B</code> and <code>C</code> there is a complicated decision tree on the list of <code>Certificates</code> of the Person.</p>

<p>Now when I implement this complicated decision in the <code>PersonComponent</code> I would create all unit tests on the PersonComponent (lets say the number of tests is 12).
Then, I decide that this knowledge (the complicated decision tree) is too much knowledge for the <code>personcomponent</code> so I refactor it to a new class, the <code>personCertificatescomponent</code>.</p>

<p>Let's say this class now looks like this:</p>

<pre class="lang-cs prettyprint-override"><code>public class PersonCertificatesComponent
{
    public bool GetVeryDifficultFunctionResult(List<Certificate> certificates)
    {}
}
</code>```

Now, what do I do with my (12) unit tests for this specific code?

Do I MOVE them to operate on the personCertificatescomponent?

PROS:

That seems like a good idea because the personCertificatescomponent is then separately unit tested (which I think is nice if someone wants to reuse this component), AND (whic is a big plus imo) I don't have to setup the unit tests for the personcomponent every time with the right values for PropertyA/B/C so it reaches the VeryDifficultFunction part.

I separated the unit tests for the 2 classes so it makes my code more 'clear' (Somehow I like 2 classes with 8 unit tests better than 1 class with 16 unit tests, but maybe that is something I should unlearn)

CONS:

But now I don't have the tests on the personcomponent anymore. An idea what came up was to unit test if the personCertificatescomponent was used (Mock test) but then I'm tied with my unit test to the implementation of the personcomponent

Or do I COPY them, so the personCertificatescomponent AND the personcomponent are both unit tested? (that seems nice, but copying the tests seems not DRY)

Or do I leave the tests where they are? (pro's and cons inverse of moving the unit tests).

I can't stand it that I can't get a good answer for myself.....

答:
When you refactor a class without changing it's API, you want your unit tests to make sure you do not break anything during the refactoring. So you obviously don't want to change your existing unit tests on PersonComponent before the refactoring is complete.

The interesting question is: is it a good idea to change the tests afterwards, to make it possible to test PersonCertificatesComponent in isolation? IMHO this depends on the following questions:

how good is your code & branch coverage for PersonCertificatesComponent with the existing tests through PersonComponent? If it is fine, do nothing. If not, consider to add additional tests afterwards for this class, but do not remove the existing tests.

are the existing unit tests not running fast enough, or are they overly complicated, and could this be improved by refactoring to simpler, faster tests for PersonCertificatesComponent? If the answer is yes, consider refactoring of the tests, otherwise do nothing.

When you decide to refactor some of your tests because of the second criterion, you should indeed avoid to repeat yourself and do not create code with essentially the same logic twice - this would lead straightforward to maintenance problems. So either verify the code & branch coverage of PersonComponent will not decrease when moving tests from there to PersonCertificatesComponent, or, if you are going to use an existing test as a "template" for a new one, make sure you reuse the same code in a "duplicated" test.


答: In TDD fashion, you refactor your tests along with your code. First you are supposed to change your test, then your code. But try to ensure you have only 1 or few tests failing at a time. To accomplish, you might end up in an intermediate state, that won't exit in final code.</p>

Title: What to do with my unit tests when refactoring code to a new class

Body:
I hope I can make a clear question...
I've simplified my code example for this question, I hope it still makes sense.

public class PersonComponent
{
    public bool IsQualified(Person person)
    {
        if (person.PropertyA){ return true; }
        if (person.PropertyB && !person.PropertyC) { return true; }
        if (VeryDifficultFunction(person.Certificates))
        {
            return true;
        }
        return false;
    }

    private bool VeryDifficultFunction(List<Certificate> certificates)
    {}
}

public class Person
{
    public bool PropertyA { get; set; }
    public bool PropertyB { get; set; }
    public bool PropertyC { get; set; }
    public List<Certificate> Certificates { get; set; }
}

public class Certificate
{ }
```

<p>I have a <code>personcomponent</code> which determines if a given <code>person</code> is qualified or not.</p>

<p>Besides a few simple validations on properties <code>A</code>, <code>B</code> and <code>C</code> there is a complicated decision tree on the list of <code>Certificates</code> of the Person.</p>

<p>Now when I implement this complicated decision in the <code>PersonComponent</code> I would create all unit tests on the PersonComponent (lets say the number of tests is 12).
Then, I decide that this knowledge (the complicated decision tree) is too much knowledge for the <code>personcomponent</code> so I refactor it to a new class, the <code>personCertificatescomponent</code>.</p>

<p>Let's say this class now looks like this:</p>

<pre class="lang-cs prettyprint-override"><code>public class PersonCertificatesComponent
{
    public bool GetVeryDifficultFunctionResult(List<Certificate> certificates)
    {}
}
</code>```

Now, what do I do with my (12) unit tests for this specific code?

Do I MOVE them to operate on the personCertificatescomponent?

PROS:

That seems like a good idea because the personCertificatescomponent is then separately unit tested (which I think is nice if someone wants to reuse this component), AND (whic is a big plus imo) I don't have to setup the unit tests for the personcomponent every time with the right values for PropertyA/B/C so it reaches the VeryDifficultFunction part.

I separated the unit tests for the 2 classes so it makes my code more 'clear' (Somehow I like 2 classes with 8 unit tests better than 1 class with 16 unit tests, but maybe that is something I should unlearn)

CONS:

But now I don't have the tests on the personcomponent anymore. An idea what came up was to unit test if the personCertificatescomponent was used (Mock test) but then I'm tied with my unit test to the implementation of the personcomponent

Or do I COPY them, so the personCertificatescomponent AND the personcomponent are both unit tested? (that seems nice, but copying the tests seems not DRY)

Or do I leave the tests where they are? (pro's and cons inverse of moving the unit tests).

I can't stand it that I can't get a good answer for myself.....


问:
Is it a good idea to modify the array keys in foreach
Some times I need to modify an array key for example something like:

$temp = array();
foreach($arrayIWantToModify as $key => $value) {
    if($value % 2) == 0) {
        $temp['odd_' . $key] = $value;
    } else {
        $temp[$key] = $value;
    }
}
```

<p>I always use a temp array to achieve that, but I had a memory problem when working on a project that had some big arrays. Of course the best solution is to increase the memory but, but i was just wondering is it so bad to just do it like:</p>

<pre class="lang-php prettyprint-override"><code>foreach($arrayIWantToModify as $key => $value) {
    if(($value % 2) == 0) {
        $arrayIWantToModify['odd_' . $key] = $value;
        unset($arrayIWantToModify[$key]);
    }
}
</code>```

It seems to work but I always saw it as a bad practice because you are changing an array you are iterating.

答:
In PHP the foreach loop creates a temporary variable storing the initial array passed. you can pass $value by reference using &$value. In the two examples below the loops remove the next element in the array.

Since it is a temporary variable changes to the original have no effect on the foreach loop.

```<code><?php
$arr = array(1,2,3,4,5,6,7,8,9);

foreach($arr as $key=>$value)
{
    unset($arr[$key + 1]);
    echo $value . PHP_EOL;
}
?>
</code>```

Output:     1 2 3 4 5 6 7 8 9

```<code><?php
$arr = array(1,2,3,4,5,6,7,8,9);

while (list($key, $value) = each($arr))
{
    unset($arr[$key + 1]);
    echo $value . PHP_EOL;
}
?>
</code>```

Output:     1 3 5 7 9

Body:
In PHP the foreach loop creates a temporary variable storing the initial array passed. you can pass $value by reference using &$value. In the two examples below the loops remove the next element in the array.

Since it is a temporary variable changes to the original have no effect on the foreach loop.

<?php
$arr = array(1,2,3,4,5,6,7,8,9);

foreach($arr as $key=>$value)
{
    unset($arr[$key + 1]);
    echo $value . PHP_EOL;
}
?>

Output:     1 2 3 4 5 6 7 8 9

<?php
$arr = array(1,2,3,4,5,6,7,8,9);

while (list($key, $value) = each($arr))
{
    unset($arr[$key + 1]);
    echo $value . PHP_EOL;
}
?>

Output:     1 3 5 7 9


答:
Definitely. I listen to a lot of music, it's my main passion outside of computer-related stuff. I find non-vocal music to be the least distracting.

I don't use sound cancelling headphones- my music is just loud enough for me to ignore the managerial murmurings from the other room, and people having impromptu meetings at a desk next to me, but it's quiet enough for me to be able to hear people when they want to get my attention.

The only time I find it distracting is when I'm fixing something super-critical. The rest of the time it helps me get into, and stay in the zone.

edit: I tend to listen to late night shows on the bbc iplayer, or stuff from various music hosting sites like soundcloud.

Title: Does music increase your productivity?


问:
Why does databases use text?
This might be a little dumb question but why do we save text in the db instead of something smaller?

Couldn't there be some other way to store data in the db like in a compressed form, and then have "our computer", which wants the data, uncompress the data from the db? What I mean is to put the load on the computers and not on the db and bandwidth.

Like let's say we store compressed form in the db, and have all the computing done by the user's computer. So if we would do a select statement it would compresse it into something only the db understands, and get back the compressed data which our computer would uncompress and show in the same way we get it now? or is text better?

Wouldn't that be better considering there's usually a lot of load on the db and that it usually can become quite large? but if the data would be compressed already it would take up less space at least

答:
Well for one it would make querying the db outside of your program quite a hassle. I don't think the slight gain is worth the time effort, and this includes support on the db later on.

If your goal is quick look ups you are also adding overhead to searching.

Sure if you have large blocks of text it might be more worth it but a better approach might be to then separate your databases or archive more regularly.

Title: Why does databases use text?


答:
You are mixing serialize with compress. Can use XML serialzation to store a form or class.

You can compress text and store it in a binary.  You might get all of 7:1 compression.  For that compression you lose the ability to search the text which is the primary purpose of a database.

Title: Why does databases use text?

Body:
This might be a little dumb question but why do we save text in the db instead of something smaller?

Couldn't there be some other way to store data in the db like in a compressed form, and then have "our computer", which wants the data, uncompress the data from the db? What I mean is to put the load on the computers and not on the db and bandwidth.

Like let's say we store compressed form in the db, and have all the computing done by the user's computer. So if we would do a select statement it would compresse it into something only the db understands, and get back the compressed data which our computer would uncompress and show in the same way we get it now? or is text better?

Wouldn't that be better considering there's usually a lot of load on the db and that it usually can become quite large? but if the data would be compressed already it would take up less space at least


答:
You are suffering from a common problem among engineers: that of over-optimization in one frame. The two classical constraints of computation are time & space. They are generally opposed; you cannot conserve one without "spending" another. The Y2K bug was in fact an example of this. Space constraints made programmers "save" two digits in the year, appending "19" in front of the date year is a computation (aka time). Likewise, you  are suggesting we save space by compressing the file, consuming computation time to save space on disk.

Sometimes this is valid. In fact, a significant quantity of TCP/IP is already transparently gzip-compressed in transit. The time spent compressing & decompressing it is negligible compared to the network resources required to transfer an uncompressed HTML document.

In your case, it isn't, for the following reasons:
Data storage is cheap compared to Computation;
Think of your computer today vs. your first computer. My first computer (that I bought for myself) was a 120Mhz processor, with 16MB of RAM and a 1.2 Gb drive. My current computer (somewhat aged) has a 3.6Ghz CPU, 32GB of RAM and about 16TB of storage. The CPU is 30x faster, but the RAM is 2000x greater (not to mention waaaay faster) and the storage is 12500x greater. Rainbow "decryption" attacks are an example of leveraging space to compensate for our computational defects. We've gotten much more room than we have time.

Second, and more practical:
If you compress the text in situ, you lose the ability to search it. Depending on the compression algorithm and surrounding data, the string "WKRP in Cincinnati" might be compressed to a different set of characters, and the similar string "WKRP/Cincinnati" would almost certainly be different in any cypher. In order to search your compressed database, the user would need to decompress (or god forbid, download) the entire thing.

Title: Why does databases use text?


问:
How to simplify structure of a monitoring software that uses the Observer pattern?
I am working on a project where I have to monitor the status of an elevator. So far, my design looks like this:

We are using a third party library to read and monitor real-time values from the elevator's logic controller. A tag is an integer value in a memory register of the logic controller. For example, DM140 contains the elevator direction.

I use an adapters layer in order to keep my application domain isolated from the third party library.

In the domain, the ElevatorDirectionMonitor takes the ElevatorTag integer value, extrapolates the elevator's current direction, and then notifies its clients that the elevator's direction has changed. So far, so good.

Here's my problem: There will be a lot (a hundred or more) of types of information to monitor from the elevator, such as the current floor, whether the  doors are opened/closed, etc. If I continue this way, I will have to create one monitor class for each type of information I want to monitor (e.g. an ElevatorFrontDoorStatusMonitor, ElevatorRearDoorStatusMonitor) and each monitor associated with its own Observer interface. This means a lot of work. I've been trying to find another way to structure my application, but haven't found anything more "elegant".

The basic logic in each monitor class would be pretty much the same across the board: listen for value change on an ElevatorTag instance, extrapolate the information from the new tag value, and then notify the observers. The problem seems to come from the fact that each observer class must have a different interface signature (e.g. ElevatorDirectionObserver's has NotifyDirectionChanged(ElevatorDirection newDirection) when a DoorStatusMonitor would rather have something like NotifyDoorStatusChanged(DoorPosition frontOrRear, DoorStatus openOrClosed)).

Do you think that the solution I am working on is acceptable. If not,could someone suggest which patterns I should use or investigate, or anything that could help me to simplify my design?

答:
I would try to find a middle-ground. If there are, as you wrote, a hundred or more of types of information, the chance is high there will be a lot of similar types, with similar interface signatures. For example, instead of having an ElevatorFrontDoorStatusMonitor and an ElevatorRearDoorStatusMonitor, create ElevatorDoorStatusMonitor, where "Front" or "Rear" is just a parameter. If there are sensors for each floor, make the floor number a parameter.

You might end up with a dozen different types of observers, maybe more, maybe less, each one supporting a different list of "pic tags". Which of the pic tags  you can group together depends, of course, how much the operations in your program differ for the different types.


答:
It's a pretty good instinct to balk at creating one hundred very similar classes.  That's generally a sign those should be instances instead.  You might try something like:

```<code>monitors.createIntMonitor("Floor", "DM141")
monitors.createBoolMonitor("Front door open", "DM142")
monitors.createEnumMonitor("Direction", "DM140", ["Up", "Down", "None"])
// or alternately
monitors.createEnumMonitor<ElevatorDirection>("Direction", "DM140")

monitors.getMonitor("Front door open").addObserver(observer)
</code>```

This design can easily be initialized dynamically, such as from a configuration file or database, including adding new fields, without requiring your app to be recompiled.  These kinds of changes often end up being the biggest maintenance cost if you do it statically.  It also requires a lot less copy/paste/minor changes, which is a big source of errors.

The disadvantage is you no longer get compile errors when you put a RearDoorMonitor into a variable expecting a FrontDoorMonitor.  It's also somewhat more problematic to cram multiple observers into one class, but that usually isn't the best idea anyway.

Your subscribers for a templatized enum monitor could look like this:

```<code>// Common interface
template <typename T>
class Subscriber
{
    public:
      virtual void receiveEvent(T t) = 0;
};

// Individual subscriber instance
class ElevatorSubscriber : public Subscriber<ElevatorDirection>
{
    public:
        void receiveEvent (ElevatorDirection direction);
};
</code>```

Title: How to simplify structure of a monitoring software that uses the Observer pattern?

Body:
I am working on a project where I have to monitor the status of an elevator. So far, my design looks like this:

We are using a third party library to read and monitor real-time values from the elevator's logic controller. A tag is an integer value in a memory register of the logic controller. For example, DM140 contains the elevator direction.

I use an adapters layer in order to keep my application domain isolated from the third party library.

In the domain, the ElevatorDirectionMonitor takes the ElevatorTag integer value, extrapolates the elevator's current direction, and then notifies its clients that the elevator's direction has changed. So far, so good.

Here's my problem: There will be a lot (a hundred or more) of types of information to monitor from the elevator, such as the current floor, whether the  doors are opened/closed, etc. If I continue this way, I will have to create one monitor class for each type of information I want to monitor (e.g. an ElevatorFrontDoorStatusMonitor, ElevatorRearDoorStatusMonitor) and each monitor associated with its own Observer interface. This means a lot of work. I've been trying to find another way to structure my application, but haven't found anything more "elegant".

The basic logic in each monitor class would be pretty much the same across the board: listen for value change on an ElevatorTag instance, extrapolate the information from the new tag value, and then notify the observers. The problem seems to come from the fact that each observer class must have a different interface signature (e.g. ElevatorDirectionObserver's has NotifyDirectionChanged(ElevatorDirection newDirection) when a DoorStatusMonitor would rather have something like NotifyDoorStatusChanged(DoorPosition frontOrRear, DoorStatus openOrClosed)).

Do you think that the solution I am working on is acceptable. If not,could someone suggest which patterns I should use or investigate, or anything that could help me to simplify my design?

Body:
It's a pretty good instinct to balk at creating one hundred very similar classes.  That's generally a sign those should be instances instead.  You might try something like:

monitors.createIntMonitor("Floor", "DM141")
monitors.createBoolMonitor("Front door open", "DM142")
monitors.createEnumMonitor("Direction", "DM140", ["Up", "Down", "None"])
// or alternately
monitors.createEnumMonitor<ElevatorDirection>("Direction", "DM140")

monitors.getMonitor("Front door open").addObserver(observer)

This design can easily be initialized dynamically, such as from a configuration file or database, including adding new fields, without requiring your app to be recompiled.  These kinds of changes often end up being the biggest maintenance cost if you do it statically.  It also requires a lot less copy/paste/minor changes, which is a big source of errors.

The disadvantage is you no longer get compile errors when you put a RearDoorMonitor into a variable expecting a FrontDoorMonitor.  It's also somewhat more problematic to cram multiple observers into one class, but that usually isn't the best idea anyway.

Your subscribers for a templatized enum monitor could look like this:

// Common interface
template <typename T>
class Subscriber
{
    public:
      virtual void receiveEvent(T t) = 0;
};

// Individual subscriber instance
class ElevatorSubscriber : public Subscriber<ElevatorDirection>
{
    public:
        void receiveEvent (ElevatorDirection direction);
};


问:
How does Java's Scanner (System.in) input's buffering actually work?
Over the last days, I've being reading questions as the one that follows: "Why is my input code not working?" I myself had a couple times problems getting the input working right...

as far as good, i found a couple solutions to avoid the problem like typing nextLine() to flush the buffer. But I'm still not sure what am I doing.

I think that Scanner(somefile) looks simpler to understand to me, since every character (including space or enter) are written on the file. But does it work the same way when we get the input from the keyboard? When I ask for an Integer for example (using nextInt() ), and then I give the number in the command-line and press 'intro', why is that \n staying on the buffer?

Could anyone help us understand it by giving a step-by-step answer?

答:
According to Java Docs: About nextInt()

Scans the next token of the input as an int. If the translation is successful, the scanner advances past the input that matched.

This method consumes the integer, but not the new-line character or other character after that integer.
So after consumption of integer by nextInt(), there only remain newline character (In this case) as entered by keyboard or file. It cannot discarded by nextInt(). Thus \n staying on the buffer.

And description of nextLine() says

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

As we expected by nextLine(), it consumes the new-line character that was not consumed by nextInt(). But when it return it exclude newline so returned string by nextLine() becomes empty.


问:
Haskell: Is it possible to convert a Num to a Float?
I need to be able to convert generic numbers (instances of Num) to a Float. I searched Hoogle for a function with the signature Num n => n -> Float, but I couldn't find any such functions (although it may be possible to compose it). I also looked over the Num typeclass, and it doesn't seem to require instances of it to supply any conversion functions that may help me.

Why do I need to do this? I created a typeclass Moveable that defines operations to move a coordinate, and allowed it to work with any instance of Num, since the only thing required to move a coordinate is +, which is defined by Num. My end goal was to use this with Gloss (a graphics library), but unfortunately, Gloss only uses Floats. That means that if I'm storing the coordinate as a Num, I'll eventually need to convert it when I try to display an object.

I'd rather not make the number type more specific to so it'll work with Gloss. Does anyone have any ideas that could help?

答:
Why are you "storing" your values as Num instead of Float? (How are you storing them? Num isn't even a type so you can't be storing them as that...)

```<code>Prelude> let y = 3.0::Float
Prelude> :t y
y :: Float
Prelude> let plus a b = a+b
Prelude> :t plus
plus :: Num a => a -> a -> a
Prelude> :t (plus y)
(plus y) :: Float -> Float
Prelude> plus y y
6.0
Prelude>
</code>```

In conclusion:
Just use Float. Unless you have some reason not to?

As a rule, just remember that Haskell has very little in the way of conversions made available even though you can force them in a variety of ways if it's really necessary. The idiomatic approach to these things is always:

Figure out how to make the type information available to the compiler so your types are gauranteed and you won't need to do conversions

Body:
Why are you "storing" your values as Num instead of Float? (How are you storing them? Num isn't even a type so you can't be storing them as that...)

Prelude> let y = 3.0::Float
Prelude> :t y
y :: Float
Prelude> let plus a b = a+b
Prelude> :t plus
plus :: Num a => a -> a -> a
Prelude> :t (plus y)
(plus y) :: Float -> Float
Prelude> plus y y
6.0
Prelude>

In conclusion:
Just use Float. Unless you have some reason not to?

As a rule, just remember that Haskell has very little in the way of conversions made available even though you can force them in a variety of ways if it's really necessary. The idiomatic approach to these things is always:

Figure out how to make the type information available to the compiler so your types are gauranteed and you won't need to do conversions


问:
How to authenticate against an API?
In a enterprise distributed system, a user of a web portal can sign into one site, be redirected to a federation provider. Once they log in with, for example, a facebook account, that user is federated (single-sign-on) with each service that exists in the enterprise that trusts the same federation provider for authentication.

My question is this; How can API users of the same system benefit from the same luxury (single sign on) ? As far as I understand it, API calls should be stateless, thus each request should require separate authentication.

If each of the distributed API's, when called by a client, need to make a call to the federation provider, get authenticated, pass claims back to the API, then process the clients request, it seems a little network chatty to me.

To clarify, an example scenario for an API client might be :

Create a customer (customer API)

Create a user for that customer (user API)

Place an order (order API)

View billing statement (billing API)

View customer report (report API)

Like I say, it seems a little chatty for each API to talk to the federation provider on each request.

答:
In general:

User logs into some authentication system.

Authentication system provides a token that effectively says "Authentication System X asserts that you are Bob, until 3:00 PM 8/31/2015 UTC".

User then passes that token as metadata (header, some data envelope) to the various APIs.

The various APIs look at it and decide if they trust Authentication System X. If they do, they let Bob in, since only Bob could've had the authorization credentials (password, fingerprint, retina, etc) to get this token.

The nitty gritty details of setting all that up will vary depending on what Authentication System, what sort of Token, and what API libraries you're using. Though if you're doing something beyond basic google/facebook integration, it's likely to be agonizing.

Title: How to authenticate against an API?


问:
Design decisions while porting a non object-oriented C program to Java
Background:
My boss made a comment on porting a C program that acts as some a simulator that communicates with a remote process through sockets to Java. He didn't assign it to me, or to anyone for that matter, it was just a project he had in mind. He showed and gave me access to the C source code file for said program so I could take a look.

Now I'm an intern in this company and haven't really been assigned something in particular so I wanted to start this project on my own and then show it to my boss.

Problem:
The C program is ~4k lines long. It consists on many global variables and functions that use those variables; I guess this is mainly to avoid passing many parameters. There are even some goto statements (yeah, also most of the codebase is from 1980). So basically my question is: should I aim to replicate the structure of the C program in a single Java class so there is a visible mapping of behavior between both? Or should I come up with
a better object oriented design that may imply the creation of many components? What would be your approach to solving this problem?

Thanks.

答:
Like Basile said, 4K lines is a small program.  It should be relatively straightforward for you to puzzle out what it does and how it does it.1

You said this was a simulator of some sort; I'm guessing it acts as a server or client to some other process for testing purposes.  We have similar tools for testing our software - the simulator stands in for a remote customer and sends us canned data so we can verify our processing.

Do not try to replicate the C code's structure in Java.  Rather, identify what the C program does, write up a list of functional requirements to achieve the same result, and write the Java code from scratch. If this is typical '80s-vintage C, you probably won't be able to replicate it in Java anyway.

1.  Emphasis on should.  Back in the early '90s we got handed a pile of C code and were asked if we could make it run faster.  It was a mess - 5K lines (all in main), literally hundreds of separate variables, some declared at file scope, some local to main, gotos out the wazoo branching in every concievable direction.  It took my coworker two weeks of dedicated effort to puzzle out the flow of control.  We found out that we literally could not change any of the code without breaking something.  As a first step to speeding it up, we tried compiling with optimizations turned on.  The compiler used up all available RAM, then it used up all available swap, and eventually panicked the system.

We told the customer that we would either need to rewrite the whole thing from scratch, or they would need to buy faster hardware.

They wound up buying faster hardware.


问:
How do I prevent people from abusing my endpoint that accepts files?
So I have a Django app hosted on Heroku that has an endpoint which accepts image uploads. The images are saved to my AWS bucket, which is charged to me. Right now, I am able to upload images by making a multipart request with the Postman app.

My goal is to allow my android app to accept image uploads from the user. However, my understanding of web applications is very limited, and I don't understand how to prevent people from just uploading arbitrarily large files to my endpoint and racking up a big charge to my AWS/Heroku accounts. After all, it's just a URL I send POST requests to. So,

What is a good way of preventing people from uploading indiscriminately to my server so I dont wake up with a $10k bill from Amazon?

My blind guess is that there is some practice of sending authentication from the client - Is there a good way of doing this without making users go through a log in service?

If I mess up, will hosting services, (like Heroku or Amazon) provide some safety net to prevent racking up massive charges?

What do big services like imgur do to prevent people from uploading huge amounts of data?

答:
If your data is only meant to be persisted in Amazon S3 it's not performant to proxy it through your web server and should be avoided if possible.

What you can do is create a POST policy that contains constraints on what the uploader (your Android app can do).

You might create the following policy:

Can only upload to specific bucket

Specify min/max size of file

etc

The beauty of this is that your web server can dynamically generate these policies on the fly and send them to the client (Android app). Perhaps your user pays for a specific amount of storage space, that would be possible to control using this method.

You can read about Post policy here: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html

Your workflow might go something like this:

User navigates to upload view in your app

App makes request to your rest service to retrieve policy

Rest service constructs policy JSON, base64 encodes it and sends it back

App sends data to Amazon S3 directly passing along the policy

Amazon will read the policy, make sure it hasn't been tampered with and accepts or rejects the file based on the constraints of the policy.

There's also this library for Android https://mobile.awsblog.com/post/Tx1V588RKX5XPQB/TransferManager-for-Android but you have to provide your Amazon S3 credentials which I don't think is very secure.


答: You can try to limit size and number of files the user can send to your API and use an strategy to identify the application (or device) when you receiving the request something like a key in the request header (for example 'Authentication: key '). This way you difficult people to use a REST client to post many files.</p>

Title: How do I prevent people from abusing my endpoint that accepts files?

Body:
So I have a Django app hosted on Heroku that has an endpoint which accepts image uploads. The images are saved to my AWS bucket, which is charged to me. Right now, I am able to upload images by making a multipart request with the Postman app.

My goal is to allow my android app to accept image uploads from the user. However, my understanding of web applications is very limited, and I don't understand how to prevent people from just uploading arbitrarily large files to my endpoint and racking up a big charge to my AWS/Heroku accounts. After all, it's just a URL I send POST requests to. So,

What is a good way of preventing people from uploading indiscriminately to my server so I dont wake up with a $10k bill from Amazon?

My blind guess is that there is some practice of sending authentication from the client - Is there a good way of doing this without making users go through a log in service?

If I mess up, will hosting services, (like Heroku or Amazon) provide some safety net to prevent racking up massive charges?

What do big services like imgur do to prevent people from uploading huge amounts of data?


答: Depending on how you will implement your application you can create a resource/API to generate a token as @Telastyn said (or you can use an authorization server - a different application to generate and validate these tokens) and pass it as a header field (usually people use the Authorization header) and your API check it's validity (in the same application or in the authorization application).</p>

Title: How to authenticate against an API?

Body:
In a enterprise distributed system, a user of a web portal can sign into one site, be redirected to a federation provider. Once they log in with, for example, a facebook account, that user is federated (single-sign-on) with each service that exists in the enterprise that trusts the same federation provider for authentication.

My question is this; How can API users of the same system benefit from the same luxury (single sign on) ? As far as I understand it, API calls should be stateless, thus each request should require separate authentication.

If each of the distributed API's, when called by a client, need to make a call to the federation provider, get authenticated, pass claims back to the API, then process the clients request, it seems a little network chatty to me.

To clarify, an example scenario for an API client might be :

Create a customer (customer API)

Create a user for that customer (user API)

Place an order (order API)

View billing statement (billing API)

View customer report (report API)

Like I say, it seems a little chatty for each API to talk to the federation provider on each request.


问:
Squashing commits from multiple developers into a single commit
I work in a large software development group and we've recently made the switch from Clearcase to Git.  Some predictions have been made with regard to the quality of the mainline in that it would become too noisy and unmanageable with commits from hundreds of developers and that the repo would get too large too quickly.

The current proposal to address this is that when feature teams bring in changes to the mainline (this can happen every week or so, and there are multiple feature teams working in parallel on the product) a single developer would be responsible for squashing multiple commits from multiple developers into a single commit.

The above approach worries me mainly because 'git bisect' and 'git blame' functionality would be compromised (a single developer would now represent the work of multiple developers).  I've countered with the following proposals:

To address the noise in mainline, each developer should squash into a single commit before creating a pull request.  This appears to be standard practice.

To address the size of the repo, devs could do shallow cloning and grafting (both approaches detailed here: http://blogs.atlassian.com/2014/05/handle-big-repositories-git/)

So far I haven't been able to convince anyone that these would be good approaches.  FWIW I also proposed using Gitflow as the main development workflow to separate out development and release branches but that also didn't gain any traction.  Personally I think so long as developers squash into a single commit before generating a pull request then that's fine... having commits from many different developers in the mainline is pretty much a non-issue after that point, it just shows that a lot of work is being done.

So my question to those of you who work on large projects in Git: is having many commits coming into your mainline actually an issue, thus forcing you to resort to solutions like squashing commits from multiple developers into single commits?

答: Instead of a single repository with a ton of branches and all code funneling into one place, consider many distinct repositories. And, use a CI build server to build from the repos. Last, output the build artifacts like WARs or MSIs or whatever to a company wide Nexus or Nuget server. This way, you can manage the life cycles of each little module separately. Any interdependencies between modules can be loaded from your Nexus/Nuget server during your build using dependency management build-software like Maven or MSBuild.</p>


问:
What does your Technical Documentation look like?
I'm working on a large project and I would like to put together some technical documentation for other members of the team and for new programmers joining the project.

What sort of documentation should I have? Just /// code comments or some other file(s) explaining the architecture and class design?

I've never really done documentation except the occasional word doc to go with smaller apps, and I think this project is too large to doc in a single word file.

答:
Following are the documents I will recommend. Even if you put the comments in the code, I feel that you should know something about what the code is doing before going to code.
1) Use case documents/Detailed Requirements

2) Design Document

3) Unit test case documents

4) Integration test documents