答:
Another commentor, Inaimathi, recommended this book a few days ago: The Little Schemer

Received it today and I can say as someone who has a very hefty library of programming books acquired over many years, that I may have only read one chapter, but I will definitely need a hardback version of this.  It reads like the Tao Te Ching, lots of little snippets of divine wisdom regarding the language.  It may say Scheme, but it was originally called "The Little LISPer", the languages at the level it discusses are sufficiently similar to be taught as one.

It is not an advanced text, but has a mission to instil the principles of the language and what it is really for, how to think like it.  I believe it would be an excellent starter to LISP.

NB. The Programmer Competency Matrix actually mentions this book in the top level of competency of things to look for. (see Books section)

Title: How should I start with Lisp?

Body:
I've been programming for years now, working my way through various iterations of Blub (BASIC, Assembler, C, C++, Visual Basic, Java, Ruby in no particular order of "Blub-ness") and I'd like to learn Lisp. However, I have a lot of intertia what with limited time (family, full time job etc) and a comfortable happiness with my current Blub (Java).

So my question is this, given that I'm someone who would really like to learn Lisp, what would be the initial steps to get a good result that demonstrates the superiority of Lisp in web development? Maybe I'm missing the point, but that's how I would initially see the application of my Lisp knowledge.

I'm thinking "use dialect A, use IDE B, follow instructions on page C, question your sanity after monads using counsellor D". I'd just like to know what people here consider to be an optimal set of values for A, B, C and perhaps D. Also some discussion on the relative merit of learning such a powerful language as opposed to, say, becoming a Rails expert.

Just to add some more detail, I'll be developing on MacOS (or a Linux VM) - no Windows based approaches will be necessary, thanks.

Notes for those just browsing by

I'm going to keep this question open for a while so that I can offer feedback on the suggestions after I've been able to explore them. If you happen to be browsing by and feel you have something to add, please do. I would really welcome your feedback.

Interesting links

Assuming you're coming at Lisp from a Java background, this set of links will get you started quickly.

Using Intellij's La Clojure plugin to integrate Lisp (videocast)

Lisp for the Web

Online version of Practical Common Lisp (c/o Frank Shearar)

Land of Lisp a (+ (+ very quirky) game based) way in but makes it all so straightforward

Install Clojure and Sublime 2 on MacOS an excellent getting started guide

Look at the Clojure in Action book. Worked for me.


问:
How to conciliate OOAD and Database Design?
Recently I've studied object oriented analysis and design and I liked a lot about it. In every place I've read people say that the idea is to start with the minimum set of requirements and go improving along the way, revisiting this each iteration and making it better as we continuously develop and contact the customer interested in the software. In particular, one course from Lynda.com said a lot of that: we don't want to spend a lot of time planning everything upfront, we just want to have the minimum to get started and then improve this each iteration.

Now, I've also seen a course from the same guy about database design, and there he says differently. He says that although when working with object orientation he likes the agile iterative approach, for database design we should really spend a lot of time planning things upfront instead of just going along the way with the minimum.

But this confuses me a little. Indeed, the database will persist important data from our domain model and perhaps configurations of the software and so on. Now, if I'm going to continuously revisit the analysis and design of the model, it seems the database design should change also. In the same way, if we plan all the database upfront it seems we are also planning all the model upfront, so the two ideas seems to be incompatible.

I really like agile iterative approach, but I'm also looking at getting better design for the database also, so when working with agile iterative approach, how should we deal with the database design?

答:
The trick is in the way you approach the data persistance end of your code. I like keeping it iterate on all fronts.

If you maintain a good model of the database (I like to do that with MySQL Workbench) and have a sensible solution for persistence (I like to use JPA), then you can change and redeploy database and all related code with relative ease.

Sadly, the traditional approach is partial to getting all of the information so as to get the full data model ready, thus spending a long time before the working prototypes can be written.

A middle ground is the following: have as many forms used in the process being automatized as possible have its persistence defined, and iterate with the rest of the data base structure (views, stored procedures and auxiliary tables).

ContentLicense: CC BY-SA 3.0


问:
Should mock objects for tests be created at a high or low level
When creating unit tests for those other objects, what is the best way to create mock objects that provide data to other objects. Should they be created at a 'high level' and intercept the calls as soon as possible, or should they be done at a 'low level' and so make as much as the real code still be called?

e.g. I'm writing a test for some code that requires a NoteMapper object that allows Notes to be loaded from the DB.

```<code>class NoteMapper {

    function getNote($sqlQueryFactory, $noteID) {
        // Create an SQL query from $sqlQueryFactory
        // Run that SQL
        // if null
        //     return null
        // else
        //    return new Note($dataFromSQLQuery)
    }
}
</code>```

I could either mock this object at a high level by creating a mock NoteMapper object, so that there are no calls to the SQL at all e.g.

```<code>class MockNoteMapper {

    function getNote($sqlQueryFactory, $noteID) {
        //$mockData = {'Test Note title', "Test note text" }
        // return new Note($mockData);
    }
}
</code>```

Or I could do it at a very low level, by creating a MockSQLQueryFactory that instead of actually querying the database just provides mock data back, and passing that to the current NoteMapper object.

It seems that creating mocks at a high level would be easier in the short term, but that in the long term doing it at a low level would be more powerful and possibly allow more automation of tests e.g. by recording data in an out of a DB and then replaying that data for tests.

Is there a recommended way of creating mocks? Are there any hard and fast rules about which are better, or should they both be used where appropriate?

答:
I would suggest the high-level approach. Mock as soon as possible.

This way you are sure what your method will receive and thus will be faster to trace the error. Remember: you want to isolate your unit test from everything else. If you would mock on the low level as you described you would test not only your method you want to test, but also getNote. This would resemble more an integration or acceptance test.


答:
Higher level approaches are more appropriate for unit testing.  Lower-level approaches are more appropriate for integration testing.

The whole point of a unit test is to make sure that single unit works, so you want to remove the possibility of a test failing due to another component's bug.  The notion that lower-level testing is more "automatic" is false.  Unit tests could still draw upon an external data source for fixtures.  The level of mocking and testing is what makes a unit test, not the data source.

Imagine for a minute that you're creating a component to transform a piece of text that comes from a database.  Something like public String removeSpaces(Database db).  You could store some test text in file A and the expected outcome in file B.  Your test case would then have to mock db return the contents of A.  Once you've called the method you're testing, you can compare the returned value to the contents of B.  Your data is external and editable without recompiling.  You could even be cool and use a file naming convention so that the reading of A and B is simpler.

The lower-level testing is nice for integration testing.  They are powerful, but they also serve a different purpose.  I'll leave that topic alone since the question is primarily about unit testing.

Title: Should mock objects for tests be created at a high or low level

Body:
When creating unit tests for those other objects, what is the best way to create mock objects that provide data to other objects. Should they be created at a 'high level' and intercept the calls as soon as possible, or should they be done at a 'low level' and so make as much as the real code still be called?

e.g. I'm writing a test for some code that requires a NoteMapper object that allows Notes to be loaded from the DB.

```<code>class NoteMapper {

    function getNote($sqlQueryFactory, $noteID) {
        // Create an SQL query from $sqlQueryFactory
        // Run that SQL
        // if null
        //     return null
        // else
        //    return new Note($dataFromSQLQuery)
    }
}
</code>```

I could either mock this object at a high level by creating a mock NoteMapper object, so that there are no calls to the SQL at all e.g.

```<code>class MockNoteMapper {

    function getNote($sqlQueryFactory, $noteID) {
        //$mockData = {'Test Note title', "Test note text" }
        // return new Note($mockData);
    }
}
</code>```

Or I could do it at a very low level, by creating a MockSQLQueryFactory that instead of actually querying the database just provides mock data back, and passing that to the current NoteMapper object.

It seems that creating mocks at a high level would be easier in the short term, but that in the long term doing it at a low level would be more powerful and possibly allow more automation of tests e.g. by recording data in an out of a DB and then replaying that data for tests.

Is there a recommended way of creating mocks? Are there any hard and fast rules about which are better, or should they both be used where appropriate?


问:
Layering Design Pattern in Java clean code style
As a Java developer, I am developing trying to use the clean code rules. But in my team we are facing a concrete problem:

We have a business layer offering a service called "createObject", this service makes a lot of operation which can result to problem. E.g: parentObjectDontExist, objectAlreadyExist, dontHaveAuthorizationToCreate, operationFailed...

and we want the UI using this service to display different information messages depending which error occurred.

In old java dev, we should have create all signed exception type and throw it in createObject.

As Clean code says, it is forbidden to use Exception for business logic AND signed exceptions are evil...
Why not...But i don't know how to solved this problem and i don't want to use return code.

How do you do?
Thanks for youre experience return.

答:
The answer is to use Callbacks

Create an interface that defines outputs of the system and instead of throwing an exception, call the right method from this interface. You may see it as "convert" one of your signed exception to a method in that interface.

This is also true for non-error "return" values. As you already know, you want to avoid exceptions and return values, in most* of your code. What you really want to do, is to have a callbacks, or multiple types of callbacks to use in order to pass the information to the proper handler.

That gives you the opportunity to create the proper handler that will implement your "error" interface and deal with the specifics of it.

(Same thing for "non-errors" paths!)

This will shape your code in a way that everything will be small, defined and extendable.(Read Single Responsibility Principle and Open Close principle from the SOLID principles, clean code, uncle Bob Martin.) By using the interfaces, you also comply to the L and D of the SOLID principles.. Better than that, if you have created the interfaces in a way that each one of them represents the method of one "domain", one "client", than, you also comply to I.

reminder:

```<code>S. Single Responsibility Principle
O. Open/Closed Principle
L. Liskov Substitution Principle
I. Interface Segregation Principle.
D. Dependency Inversion Principle.
</code>```

sometimes, it may happen to return a value and use an exception. The trick is to  catch the "known" exception and use the callback methods of your output interface.

Body:
The answer is to use Callbacks

Create an interface that defines outputs of the system and instead of throwing an exception, call the right method from this interface. You may see it as "convert" one of your signed exception to a method in that interface.

This is also true for non-error "return" values. As you already know, you want to avoid exceptions and return values, in most* of your code. What you really want to do, is to have a callbacks, or multiple types of callbacks to use in order to pass the information to the proper handler.

That gives you the opportunity to create the proper handler that will implement your "error" interface and deal with the specifics of it.

(Same thing for "non-errors" paths!)

This will shape your code in a way that everything will be small, defined and extendable.(Read Single Responsibility Principle and Open Close principle from the SOLID principles, clean code, uncle Bob Martin.) By using the interfaces, you also comply to the L and D of the SOLID principles.. Better than that, if you have created the interfaces in a way that each one of them represents the method of one "domain", one "client", than, you also comply to I.

reminder:

S. Single Responsibility Principle
O. Open/Closed Principle
L. Liskov Substitution Principle
I. Interface Segregation Principle.
D. Dependency Inversion Principle.

sometimes, it may happen to return a value and use an exception. The trick is to  catch the "known" exception and use the callback methods of your output interface.


问:
Initiating processing in a RESTful manner
Let's say you have a resource that you can do normal PUT/POST/GET operations on.  It represents a BLOB of data and the methods retrieve representations of the data, be they metadata about the BLOB or the BLOB itself.

The resource is something that can be processed by the server on request.  In this instance a file that can be parsed multiple times.

How do I initiate that processing?  It's a bit RPC like.  Is there best practice around this?

I've read this: RESTFul: state changing actions but it doesn't really answer the question.

(First time on programmers. This is the right place for this sort of question, right?)

答:
The processor for this resource could be its own resource.  Consider for a minute that the name of the BLOB resources is /data/.  By making the processor its own resource, you allow yourself to make different processors.  This also prevents you from having to modify the data resource to facilitate processing.  It could work like this:

POST

A post might take the id of the data that you're trying to process.  This would return some sort of id that represents the process or job.

GET

Given an Id, this would get the result of the processing.  If it's not done, you could return an empty response or a 204 NO CONTENT.

HEAD

Given an Id, this could return just the status without returning the result of the processing.  The "job metadata," if you will.  If you really wanted to, you could return the parameters, such as the data Id that is being processed, the start date, etc.

DELETE

Given an Id, this would cancel the request.

PUT

I'm not sure that PUT is applicable here.


答:
Both.

When testing objects that use NoteMapper, you can use its mock to avoid calls to SQL, and tell it to do whatever you want with complete freedom in order to test how the SUT responds to it.

Additionally, when testing NoteMapper dependencies, if you'd define expectations on the inner SQL object NoteMapper uses, you're coupling to its implementation tightly, and also creating a lot of boilerplate in each test about things it really shouldn't care about.

When testing NoteMapper itself, you might want to mock out the SQL so that you're testing only the logic and not the actual SQL implementation.

However, I believe that NoteMapper would turn out to not do much besides SQL queries, and so its test should actually be an integration test, testing the integration between its implementation and the particular SQL DB's implementation.


答: Unit tests are exactly that, to test a small unit of code. Based on your description of the problem, it sounds like a high-level mocked up data test and a low-level test will test different units of functionality, so, for complete coverage of your code, it would be wise to test both scenarios.</p>


问:
Solution with multiple projects and (GitHub) single issue tracker and repository
I have a Visual Studio solution with multiple projects:

Acme.Core

Acme.Core.Tests

Acme.UI.MvcSite1

Acme.UI.MvcSite2

Acme.UI.WinformsApp1

Acme.UI.WinformsApp2

...

The entire solution is checked-in in a single GitHub (private) repo. Acme.Core contains our business logic and all UI projects are deployables. UI projects have different requirements and features, but some of them are implemented in more than one project.

All issues are opened in a single issue tracker and classified using labels ([MvcSite1], [WinformsApp1], etc) but I'm thinking it's starting to get messy.

Is it ok to use a single repository and issue tracker to track multiple projects in one solution?

答:
Re-using the issue tracker should be fine, as long as you're tagging the issues properly so that it's easy to differentiate between projects.

Re-using the same repository is more convoluted. The advantage to this approach is removing potentially extravagant merges. On the other hand, it may become more difficult to deploy to test environments unless you can push branches out. Maybe the worst case I can think of in that scenario is if you introduce a major bug in one project, and while resolving it, require a rollback that wipes out changes made in other projects. I would think your best bet is to compartmentalize your code as best as you can and use separate repositories.


答:
The problem with databases is that they contain data.  This means that if you want to change the structure of a database, you need to cope with all the data therein, making sure to maintain its integrity from the orignal schema to the revised schema.

That's not always easy.  It introduces risks.  Data migration between schema changes can be difficult to test. Basically, databases can be developed iteratively, but doing so tends to be a pain in the butt.

Code, on the other hand is much easier to change.  So long as you have tests in place, it's reasonably straightforward to determine that refactored code still does the same thing as the original.  Thus refactoring and iterative development works well on program code.

There's no definitive answer to reconciling these items.  I'd say the advice you've been given is good--try to minimize the number of times you restructure your database.  This doesn't mean you can never change your DB, just don't do it all the time.  Try to predict the changes you'll need over several iterations and update the schema once for every 3 or 10 coding iterations.  Think of database schema changes as part of your major version releases while code changes can be dot releases.

Title: How to conciliate OOAD and Database Design?

Body:
Recently I've studied object oriented analysis and design and I liked a lot about it. In every place I've read people say that the idea is to start with the minimum set of requirements and go improving along the way, revisiting this each iteration and making it better as we continuously develop and contact the customer interested in the software. In particular, one course from Lynda.com said a lot of that: we don't want to spend a lot of time planning everything upfront, we just want to have the minimum to get started and then improve this each iteration.

Now, I've also seen a course from the same guy about database design, and there he says differently. He says that although when working with object orientation he likes the agile iterative approach, for database design we should really spend a lot of time planning things upfront instead of just going along the way with the minimum.

But this confuses me a little. Indeed, the database will persist important data from our domain model and perhaps configurations of the software and so on. Now, if I'm going to continuously revisit the analysis and design of the model, it seems the database design should change also. In the same way, if we plan all the database upfront it seems we are also planning all the model upfront, so the two ideas seems to be incompatible.

I really like agile iterative approach, but I'm also looking at getting better design for the database also, so when working with agile iterative approach, how should we deal with the database design?


答:
Git doesn't scale. Git is fast, and awesome in handle huge repositories, but it doesn't scale very well. Therefor most projects using git has one repo for each project (not like svn where you can have one repo for the whole company and then have one path for each project).

The one project-one repo is quite fundamental in git's design and hence github is also built with the one project - one repo in mind.

It's of course fine to have multiple projects in one repo, until you hit the ceiling. If you think your bugtracker is too confusing and you rather treated the projects separately, then you've hit the ceiling and you really should divide your repo to one repo for each project.

You should probably look closer into git submodules (the pro-git book has a chapter about them) then you want to read up on git filter-branch on how to divide your current repo.

If I understand your enviroment correctly you would benefit from the power of submodules, that will make you able to do complicated configurations.

Title: Solution with multiple projects and (GitHub) single issue tracker and repository

Body:
I have a Visual Studio solution with multiple projects:

Acme.Core

Acme.Core.Tests

Acme.UI.MvcSite1

Acme.UI.MvcSite2

Acme.UI.WinformsApp1

Acme.UI.WinformsApp2

...

The entire solution is checked-in in a single GitHub (private) repo. Acme.Core contains our business logic and all UI projects are deployables. UI projects have different requirements and features, but some of them are implemented in more than one project.

All issues are opened in a single issue tracker and classified using labels ([MvcSite1], [WinformsApp1], etc) but I'm thinking it's starting to get messy.

Is it ok to use a single repository and issue tracker to track multiple projects in one solution?


问:
what is the meaning of following definition?
I am new to javascript and start learning from w3schools website. I'm not able to understand what the following line means. Can anyone please explain this with example?

You can only use document.write in the HTML output. If you use it
  after the document has loaded (e.g. in a function), the whole document
  will be overwritten.

答:
There are two moments where JavaScript may be executed:

When the browser is parsing HTML. Example:

```<code>...
<div>
    alert('Hello World!');
</div>
</code>```

When the page is already parsed and shown. Example:

```<code>...
<a href="onlick:alert('Hello World!');">Click me please</a>
</code>```

document.write() has a different behavior for those two cases. In the first one, it will simply insert content within the HTML. In the second case, it will override the whole page.

Example:

```<code>...
<div>
    <script type="text/javascript">
    document.write('Hello World!');
    </script>
</div>
</code>```

produces:

```<code>...
<div>
    Hello World!
</div>
</code>```

while:

```<code>...
<div>
    <a href="onlick:document.write('Hello World!');">Click me please</a>
</div>
</code>```

Produces:

```<code>Hello World!
</code>```

Also note that:

The statement you quoted is incorrect, as it is often the case with w3schools (if you want high quality documentation, use for example a similar explanation on Mozilla Developer Network. The incorrectness is that the quote talks about functions, which has nothing to do with the actual subject. The example from MDN shows very well why the quote is wrong.

document.write() is, among other features such as alert(), not very useful and very rarely used in real websites. If you want to change the content of a part of a page, you'll rather use innerHTML property.

you shouldn't use w3schools, as stated in the comment above.

Body:
There are two moments where JavaScript may be executed:

When the browser is parsing HTML. Example:

...
<div>
    alert('Hello World!');
</div>

When the page is already parsed and shown. Example:

...
<a href="onlick:alert('Hello World!');">Click me please</a>

document.write() has a different behavior for those two cases. In the first one, it will simply insert content within the HTML. In the second case, it will override the whole page.

Example:

...
<div>
    <script type="text/javascript">
    document.write('Hello World!');
    </script>
</div>

produces:

...
<div>
    Hello World!
</div>

while:

...
<div>
    <a href="onlick:document.write('Hello World!');">Click me please</a>
</div>

Produces:

Hello World!

Also note that:

The statement you quoted is incorrect, as it is often the case with w3schools (if you want high quality documentation, use for example a similar explanation on Mozilla Developer Network. The incorrectness is that the quote talks about functions, which has nothing to do with the actual subject. The example from MDN shows very well why the quote is wrong.

document.write() is, among other features such as alert(), not very useful and very rarely used in real websites. If you want to change the content of a part of a page, you'll rather use innerHTML property.

you shouldn't use w3schools, as stated in the comment above.


问:
Inserting HTML code with jquery
One of our web applications is a page that takes in a serial number and various information is returned and displayed to the user. The serial is passed via AJAX, and based on the response, one of the following can happen -

An error message is shown

A new form replaces the previous form

Now, the way I am handling this is to use jQuery to destroy (using $.remove()) the table that displayed the initial serial form, then I'm appending another html table that contains another form. Right now I am including that additional form as part of the html source, and just setting it to display:none, then using jQuery to show it when appropriate. However, I don't like this approach because if someone views source on the page, they can see that table html code that is not being displayed.

My next thought would be to use AJAX to read in another HTML file, and append it that way. However, I am trying to keep down the number of files this project uses, and since most pages in our project will use AJAX, I could see a case where there are multiple files containing HTML snippets - and that feels sloppy to me.

What is the best way to handle a case where multiple html elements are being shown and removed with jQuery?

答:
Yes this is right way , you can user to avoid IE problem

```<code>echo '<p>this is your html</p>'
</code>```

Js code

```<code>$.ajax({
url: "ajax.php",
type: "post",
data: values,
success: function(data){
    $("#myDiv").html($.trim(data));
}})
</code>```

Title: Inserting HTML code with jquery

Body:
Yes this is right way , you can user to avoid IE problem

echo '<p>this is your html</p>'

Js code

$.ajax({
url: "ajax.php",
type: "post",
data: values,
success: function(data){
    $("#myDiv").html($.trim(data));
}})


问:
Are there any benefits to removing unused script files in a web site/project?
VS Web sites/projects come loaded with several .js files, most of which I don't use (e.g., I use a CDN for newer versions of jQuery and jQuery-UI). I know it's safe to remove these unneeded .js files from my projects, but is there any benefit from doing so? Are they deployed to the web server if left alone?</p>

答:
yes, it's take time to load and cause to reduce the performance , other way to reduce it you can compile multiple js files in to one.please refer
https://developers.google.com/speed/articles/compressing-javascript
http://closure-compiler.appspot.com/home</p>


答:
I understand it got you confused. You can not build a complete datamodel when you will only start of by building a minimal set of features in your solution.

A good approach is to apply good design to the initial datastructure. If your design was good, all later additions will not require a redesign of your initial structure (there are some exceptions!). Make sure to read about DB Normalisation

What you will notice in an iterative software development process is that the datastructure will grow with the amount of requirements you have build in your software. In later phases of a software development process, the amount of requested changes lessens, so changes to the datasource are less likely aswell.

When a big change is imminent, there is some magic you can do to diminish the redesign needed. For instance, you can leave an existing datamodel untouched, and build some custom mapping in a abstract layer of your solution. Most of todays ORM's are very suitable for this.


问:
Is it possible to rewrite every line of an open source project in a slightly different way, and use it in a closed source project?
There is some code which is GPL or LGPL that I am considering using for an iPhone project.

If I took that code (JavaScript) and rewrote it in a different language for use on the iPhone would that be a legal issue?

In theory the process that has happened is that I have gone through each line of the project, learnt what it is doing, and then reimplemented the ideas in a new language.

To me it seems this is like learning how to implement something, but then reimplementing it separately from the original licence. Therefore you have only copied the algorithm, which arguably you could have learnt from somewhere else other than the original project.

Does the licence cover the specific implementation or the algorithm as well?

EDIT------

Really glad to see this topic create a good conversation. To give a bit more backing to the project, the code involved does some kind of audio analysis. I believe it is non-trivial to learn or implement, although I was prepared to embark on this task (I'm at the level where I can implement an FFT algorithm, and this was going to go beyond that.) It is a fairly low LOC script, so I didn't think it would be too hard to do a straight port.

I really like the idea of rereleasing my port as well as using it in the application. I don't see any problem with that, and it would be a great way to give something back to the community.

I was going to add a line about not wanting to discuss the moral issues, but I'm quite glad I didn't as it seems to have fired the debate a bit.

I still feel a bit odd about using open source code to learn from. Does this mean that anything one learns from an open source project is not allowed to be used in a closed source project? And how long after or different does an implementation have to be to not be considered violation of the licence? Murky!

EDIT 2 --------

Follow up question

答:
If you re-write each line individually you may or may not be "copying" the lines.

But you are copying verbatim the ordering, overall structuring and inclusion of the lines. In other words, the sort of stuff that makes the work a "whole".

You're copying the part that says "this line should go here, this line should go there". This is a large portion of the overall algorithm.

Additionally, when a project is started, nobody knows what to include, what things are to be considered more or less important, how to structure and compose the algorithms. This information needs to be produced and designed at some point. But you wouldn't need to, because you'd be "copying" it.

As an example:

If I have a set {a, b, c, d, e, f}.

I can create an ordered list of them, [f, e, c, b, d, a]. You must say that I have added some information to the list, known as ordering, that wasn't present in the unordered set. Depending on the size of the list, this information might be very specific and hard to come up with.

OwnerDisplayName: optician


问:
How many developers on the same virtualized Windows Microsoft machine?
How many c# developers on the same virtualized  Microsoft Windows edition is it sensible to have?

If everyone uses their own documents and settings folder, should I expect it should be fine?

Only Windows Server allows concurrent users if this option is enabled; How many concurrent users do you get out of the box?

答:
One.  For several reasons:

Windows has lots of aspects that don't mesh well with multi-user use, especially concurrent use.  Multiple user profiles and remote access are really only part of the answer, and a fair amount of the answer hasn't been done yet.

For C#, you'll be using Visual Studio, which is a heavyweight application.  Our experience is that even with only one user, a virtualized VS machine is noticeably slower than the user wants it to be.

Depending on the application(s) you're developing, you may have problems isolating the users work from each other.  For example, if you're building web services or a website, you'll need to keep user A from accidentally executing against user B's services.

As Phoshi implies in his comment, to serve multiple users well, you're probably going to spend at least as much on high-end hardware as you would going the non-shared route.


问:
How to support a product built with agile development?
Two of the functions our company provides our customers are:

Our Development team of ~10 employees creates software products for businesses in a particular industry. The software is used on hundreds of our customers' computers. Although the product is, for most customers, off-the-shell, larger customers drive its development, so it's somewhere between shrinkwrap software and custom software.

Our Support team of ~25 employees provides technical support for both our own software and a few other software products for which we are the vendor.

Our Development team recently switched to Scrum for their development methodology, and while I support this change, I worry that our Support team is going to have more trouble in the future.  With a quicker release cycle, our customers will have features and products in production which Support isn't even aware of until the customer calls. We've never been particularly good at getting documentation and information from Development to Support, but I fear Scrum will just exacerbate the problem.

What are good references on how companies reconcile Development's desire to release frequently with Support's desire to have full documentation and support information before customers see the product?  How should a company structure their release and change management when using agile methods?

EDIT: What I'm interested are specifics on how companies structure themselves to deal with these issues. Does the scrum team push releases to customers? Does the software have to go through a release/change management team who will not deploy until Support has been given documentation and brought up to speed?  How do you get releases to customers quickly yet still keep everyone informed of changes and new features?

答: Your support guys need to be involved in the iteration and release planning stage so that they know what's going into a release as early as possible. So while the developers are building the software the support guys can be preparing for it. One good thing about Scrum is that once an iteration starts you can be sure of what will come out at the other end.</p>

ContentLicense: CC BY-SA 2.5


问:
What is the advantage of a programmers VM apart from portability
I can understand the benefits of Java running on a JVM.  Portability.  Nice simple reason.  But I have always been puzzled as to why Microsoft brought out their own version of a JVM - .NET.  C# is supposed to be a fine language (haven't used myself) but could Microsoft have launched product to use native.  ie to generate an exe?

My colleague is learning F#.  The reason it has to be a language which runs on .NET is because the Microsoft Lync API which will be used is only available on .NET.  ie there is no C API for Lync.

A cynical view may be that the reason is vendor lockin.  F# will only run on a Microsoft platform (or C# for that matter) and so program is locked in.  But maybe I am missing some other benefit of a VM platform?

答:
One of the most important aspects of the .NET virtual machine is the reason why it is called the Common Language Runtime.

All .NET programming languages compile to the same bytecode format which is executed in the same VM. This allows programs where different parts are written in different programming languages to interoperate seamlessly.

Virtual machines also have performance advantages, because they allow just-in-time compilation and just-in-time optimization. A common offline compiler can only optimize for a specific CPU architecture. When an application is distributed and the user doesn't have exactly the same system the application was optimized for, they will experience slightly worse performance than possible. But a JIT compiler can check the architecture when the program is executed and make full use of the features available. Also, a common offline optimizer can only make educated guesses which parts of a program are executed most often and thus have to be preferred during optimization. But a JIT optimizer can monitor the program while it is running, check which branches are used most often, and optimize the program on-the-fly while it is running.

But the Java VM can do all of that too. Why isn't Microsoft targeting the JVM then? It's for business reasons. Microsoft is known for wanting as much control as possible over the whole stack an application runs on. Having Sun (now Oracle) control a major part of the software development ecosystem was considered a problem for them. Especially when it allows software to run on non-Microsoft operating systems! So they developed their .NET framework as a direct competition to Java to attack Sun's (now Oracle's) market share.


问:
More elegant way to avoid hard coding the format of a a CSV file?
I know this is trivial issue, but I just feel this can be more elegant.

So I need to write/read data files for my program, lets say they are CSV for now.  I can implement the format as I see fit, but I may have need to change that format later.  The simply thing to do is something like

```<code>out.write(For.getValue()+","+bar.getMinValue()+","+fi.toString());
</code>```

This is easy to write, but obviously is guilty of hard coding and the general 'magic number' issue.  The format is hard-coded, requires parsing of the code to figure out the file format, and changing the format requires changing multiple methods.

I could instead have my constants specifying the location that I want each variable to be saved in the CSV file to remove some of the 'magic numbers'; then save/load into the an array at the location specified by the constants:

```<code>int FOO_LOCATION=0;
int BAR_MIN_VAL_LOCATION=1;
int FI_LOCATION=2
int NUM_ARGUMENTS=3;

String[] outputArguments=new String[NUM_ARGUMENTS];
outputArguments[FOO_LOCATION] = foo.getValue();
outputArgumetns[BAR_MIN_VAL_LOCATION] = bar.getMinValue();
outptArguments[FI_LOCATOIN==fi.toString();

writeAsCSV(outputArguments);
</code>```

But this is...extremely verbose and still a bit ugly.  It makes it easy to see the format of existing CSV and to swap the location of variables within the file easily.  However, if I decide to add an extra value to the csv I need to not only add a new constant, but also modify the read and write methods to add the logic that actually saves/reads the argument from the array; I still have to hunt down every method using these variables and change them by hand!

If I use Java enums I can clean this up slightly, but the real issue is still present.  Short of some sort of functional programming (and java's inner classes are too ugly to be considered functional) I still have no obvious way of clearly expressing what variable is associated with each constant short of writing (and maintaining) it in the read/write methods.  For instance I still need to write somewhere that the FOO_LOCATION specifies the location of foo.getValue().

It seems as if there should be a prettier, easier to maintain, manner for approaching this?

Incidentally, I'm working in java at the moment, however, I am interested conceptually about the design approach regardless of language.  Some library in java that does all the work for me is definitely welcome (though it may prove more hassle to get permission to add it to the codebase then to just write something by hand quickly), but what I'm really asking is more about how to write elegant code if you had to do this by hand.

答:
Label your fields in the first row

When it comes to writing out data, the cardinal sin is to assume that you and only you will ever want to read it in.  Such an assumption leads to omitting the second most important part of your file, the identification of your data.

You can switch from CSV to self-describing formats such as XML or JSON, or you can simply implement the proper convention of including a label for each field in the first row.  With this convention, it becomes easy for your input engine to map incoming data to whatever internal structure is appropriate, and your output engine is freed from having to especially care about it column order.

The particulars of how you decide which fields to include will vary by language, but that's programming.


问:
Reverse subarray of an array with O(1)
I have an idea how to implement sub array reverse with O(1), not including precalculation such as reading the input. I will have many reverse operations, and I can't use the trivial solution of O(N).

Edit: To be more clear I want to build data structure behind the array with access layer that knows about reversing requests and inverts the indexing logic as necessary when someone wants to iterate over the array.

Edit 2: The data structure will only be used for iterations

I been reading this and this and even this questions but they aren't helping.

There are 3 cases that need to be taking care of:

Regular reverse operation

Reverse that including reversed area

Intersection between reverse and part of other reversed area in the array

Here is my implementation for the first two parts, I will need your help with the last one.

This is the rule class:

```<code>class Rule {
    public int startingIndex;
    public int weight;
}
</code>```

It is used in my basic data structure City:

```<code>public class City {
    Rule rule;
    private static AtomicInteger _counter = new AtomicInteger(-1);
    public final int id = _counter.incrementAndGet();

    @Override
    public String toString() {
        return "" + id;
    }
}
</code>```

This is the main class:

```<code>public class CitiesList implements Iterable<City>, Iterator<City> {

    private int position;
    private int direction = 1;
    private ArrayList<City> cities;
    private ArrayDeque<City> citiesQeque = new ArrayDeque<>();
    private LinkedList<Rule> rulesQeque = new LinkedList<>();

    public void init(ArrayList<City> cities) {
        this.cities = cities;
    }

    public void swap(int index1, int index2){
        Rule rule = new Rule();
        rule.weight = Math.abs(index2 - index1);
        cities.get(index1).rule = rule;
        cities.get(index2 + 1).rule = rule;
    }

    @Override
    public void remove() {
        throw new IllegalStateException("Not implemented");
    }

    @Override
    public City next() {
        City city = cities.get(position);
        if (citiesQeque.peek() == city){
            citiesQeque.pop();
            changeDirection();
            position += (city.rule.weight + 1) * direction;
            city = cities.get(position);
        }
        if(city.rule != null){
            if(city.rule != rulesQeque.peekLast()){
                rulesQeque.add(city.rule);
                position += city.rule.weight * direction;
                changeDirection();
                citiesQeque.push(city);
            }
            else{
                rulesQeque.removeLast();
                position += direction;
            }
        }
        else{
            position += direction;
        }
        return city;
    }

    private void changeDirection() {
        direction *= -1;
    }

    @Override
    public boolean hasNext() {
        return position < cities.size();
    }

    @Override
    public Iterator<City> iterator() {
        position = 0;
        return this;
    }

}
</code>```

And here is a sample program:

```<code>public static void main(String[] args) {
        ArrayList<City> list = new ArrayList<>();
        for(int i = 0 ; i < 20; i++){
            list.add(new City());
        }
        CitiesList citiesList = new CitiesList();
        citiesList.init(list);

        for (City city : citiesList) {
            System.out.print(city + " ");
        }
        System.out.println("\n******************");
        citiesList.swap(4, 8);

        for (City city : citiesList) {
            System.out.print(city + " ");
        }
        System.out.println("\n******************");
        citiesList.swap(2, 15);

        for (City city : citiesList) {
            System.out.print(city + " ");
        }
    }
</code>```

How do I handle reverse intersections?

答:
There is no point in seeking an efficient mechanism to actually reverse things in an array over and over. You can never get below linear complexity doing that, because you must touch (almost) all items in the subrange.

What you can do is encapsulate your data structure behind an access layer that knows about reversing requests and inverts the indexing logic as necessary when someone wants to iterate over the array. That can get you near-normal performance even for partially reversed arrays, as long as the number of reversing requests is small, i.e. the additional look-up logic is not more expensive than the memory accesses that it saves you. How soon this point is reached depends very much on circumstances such as the actual size of your arrays, likely access patterns, etc.

Title: Reverse subarray of an array with O(1)


答:
Code implementing unit tests is code that you need to develop, extend, fix and maintain and you are willing to do this correctly and to avoid useless work. If you plan a large unit test suite then its design deserves the same care and thoughts than the application itself: finding the right organisation is just as hard.

Besides this general statement, here are several aspects you may want to consider.  I assume you are writing a unit test for a class Consumer that uses the NoteMapper (this is the low-mocking case) or MockNoteMapper (this is the high-mocking case).

In the low-mocking case you are actually testing Consumer and NoteMapper so you probably want to add a separate test NoteMapper separately so that your test is an evidence that Consumer implements the correct behaviour.

In the low-mocking case the NoteMapper may contains hidden invariants that are not enforced by your design but by the implementation. In the high-mocking case you gain confidence that your implementation of Consumer is correct to the point where it does not use hidden invariants of NoteMapper.

Unit tests based on mocking objects are implemented similarly to regression tests, where the mocking object is used to inject values demonstrating some historical bug in the program.


答:
You could use a xor linked list variant (using indexes into an array for the pointer).

Then reversing is easy:

```<code>reverse(int city1prev, int city1index, int city2prev, int city2index)
{

    int city1next = array[city1index].ptr^city1prev;
    int city2next = array[city2index].ptr^city2prev;

    city1.ptr = city2next^city1next;
    city2.ptr = city2prev^city1prev;

    array[city1prev].ptr^= city1index^city2index;
    array[city2next].ptr^= city1index^city2index;

}
</code>```

The downside is (as with all linked list implementations) that indexing into it is O(n).

This will reverse the sub array due to how the xor link works: city2 will be where city1 used to be and city2prev will be after it and so on. So the new sequence becomes: city1prev, city2, city2prev,..., city1next, city1, city2next.

Key point is that there is no difference between traversing a xor linked list forward or backward (you keep a index to the current and the previous items and you get the next by doing array[current].ptr^previous).

Title: Reverse subarray of an array with O(1)

Body:
I have an idea how to implement sub array reverse with O(1), not including precalculation such as reading the input. I will have many reverse operations, and I can't use the trivial solution of O(N).

Edit: To be more clear I want to build data structure behind the array with access layer that knows about reversing requests and inverts the indexing logic as necessary when someone wants to iterate over the array.

Edit 2: The data structure will only be used for iterations

I been reading this and this and even this questions but they aren't helping.

There are 3 cases that need to be taking care of:

Regular reverse operation

Reverse that including reversed area

Intersection between reverse and part of other reversed area in the array

Here is my implementation for the first two parts, I will need your help with the last one.

This is the rule class:

```<code>class Rule {
    public int startingIndex;
    public int weight;
}
</code>```

It is used in my basic data structure City:

```<code>public class City {
    Rule rule;
    private static AtomicInteger _counter = new AtomicInteger(-1);
    public final int id = _counter.incrementAndGet();

    @Override
    public String toString() {
        return "" + id;
    }
}
</code>```

This is the main class:

```<code>public class CitiesList implements Iterable<City>, Iterator<City> {

    private int position;
    private int direction = 1;
    private ArrayList<City> cities;
    private ArrayDeque<City> citiesQeque = new ArrayDeque<>();
    private LinkedList<Rule> rulesQeque = new LinkedList<>();

    public void init(ArrayList<City> cities) {
        this.cities = cities;
    }

    public void swap(int index1, int index2){
        Rule rule = new Rule();
        rule.weight = Math.abs(index2 - index1);
        cities.get(index1).rule = rule;
        cities.get(index2 + 1).rule = rule;
    }

    @Override
    public void remove() {
        throw new IllegalStateException("Not implemented");
    }

    @Override
    public City next() {
        City city = cities.get(position);
        if (citiesQeque.peek() == city){
            citiesQeque.pop();
            changeDirection();
            position += (city.rule.weight + 1) * direction;
            city = cities.get(position);
        }
        if(city.rule != null){
            if(city.rule != rulesQeque.peekLast()){
                rulesQeque.add(city.rule);
                position += city.rule.weight * direction;
                changeDirection();
                citiesQeque.push(city);
            }
            else{
                rulesQeque.removeLast();
                position += direction;
            }
        }
        else{
            position += direction;
        }
        return city;
    }

    private void changeDirection() {
        direction *= -1;
    }

    @Override
    public boolean hasNext() {
        return position < cities.size();
    }

    @Override
    public Iterator<City> iterator() {
        position = 0;
        return this;
    }

}
</code>```

And here is a sample program:

```<code>public static void main(String[] args) {
        ArrayList<City> list = new ArrayList<>();
        for(int i = 0 ; i < 20; i++){
            list.add(new City());
        }
        CitiesList citiesList = new CitiesList();
        citiesList.init(list);

        for (City city : citiesList) {
            System.out.print(city + " ");
        }
        System.out.println("\n******************");
        citiesList.swap(4, 8);

        for (City city : citiesList) {
            System.out.print(city + " ");
        }
        System.out.println("\n******************");
        citiesList.swap(2, 15);

        for (City city : citiesList) {
            System.out.print(city + " ");
        }
    }
</code>```

How do I handle reverse intersections?

Body:
You could use a xor linked list variant (using indexes into an array for the pointer).

Then reversing is easy:

reverse(int city1prev, int city1index, int city2prev, int city2index)
{

    int city1next = array[city1index].ptr^city1prev;
    int city2next = array[city2index].ptr^city2prev;

    city1.ptr = city2next^city1next;
    city2.ptr = city2prev^city1prev;

    array[city1prev].ptr^= city1index^city2index;
    array[city2next].ptr^= city1index^city2index;

}

The downside is (as with all linked list implementations) that indexing into it is O(n).

This will reverse the sub array due to how the xor link works: city2 will be where city1 used to be and city2prev will be after it and so on. So the new sequence becomes: city1prev, city2, city2prev,..., city1next, city1, city2next.

Key point is that there is no difference between traversing a xor linked list forward or backward (you keep a index to the current and the previous items and you get the next by doing array[current].ptr^previous).


问:
"Whole-team" C++ features?
In C++, features like exceptions impact your whole program: you can either disable them in your whole program, or you need to deal with them throughout your code. As a famous article on C++ Report puts it:

Counter-intuitively, the hard part of coding exceptions is not the explicit throws and catches. The really hard part of using exceptions is to write all the intervening code in such a way that an arbitrary exception can propagate from its throw site to its handler, arriving safely and without damaging other parts of the program along the way.

Since even new throws exceptions, every function needs to provide basic exception safety — unless it only calls functions which guarantee throwing no exception — unless you disable exceptions altogether in your whole project.

Hence, exceptions are a "whole-program" or "whole-team" feature, since they must be understood by everybody in a team using them. But not all C++ features are like that, as far as I know.

A possible example is that if I don't get templates but I do not use them, I will still be able to write correct C++ — or will I not?. I can even call sort on an array of integers and enjoy its amazing speed advantage wrt. C's qsort (because no function pointer is called), without risking bugs — or not? It seems templates are not "whole-team".

Are there other C++ features which impact code not directly using them, and are hence "whole-team"? I am especially interested in features not present in C.

Update: I'm especially looking for features where there's no language-enforced sign you need to be aware of them. The first answer I got mentioned const-correctness, which is also whole-team, hence everybody needs to learn about it; however, AFAICS it will impact you only if you call a function which is marked const, and the compiler will prevent you from calling it on non-const objects, so you get something to google for. With exceptions, you don't even get that; moreover, they're always used as soon as you use new, hence exceptions are more "insidious". Since I can't phrase this as objectively, though, I will appreciate any whole-team feature.

Update 2: instead of C++ feature I should have written something like "C++-specific feature", to exclude things like multithreading which apply to a large amount of mainstream programming languages.

Appendix: Why this question is objective (if you wonder)

C++ is a complex language, so many projects or coding guides try to select "simple" C++ features, and many people try to include or exclude some ones according to mostly subjective criteria. Questions about that get rightfully closed regularly here on SO.

Above, instead, I defined (as precisely as possible) what a "whole-team" language feature is, provide an example (exceptions), together with extensive supporting evidence in the literature about C++, and ask for whole-team features in C++ beyond exceptions.

Whether you should use "whole-team" features, or whether that's a relevant concept, might be subjective — but that only means the importance of this question is subjective, like always.

答:
The only one besides const correctness (seen above) that comes to mind is stream(ing) state. If you write C++ code where you use objects and subobjects and object hierarchies chances are, you'll eventually want to send or receive data to/from the operator of the program. You can write simple streaming operations that will compile and will be semantically correct...

```<code>std::ostream& operator<< (std::ostream&, MyClass const&) {...}
std::istream& operator>> (std::istream&, MyClass&) {...}
</code>```

...But once you do, you'll never have any guarantee that what you are trying to write (or most importantly, read) follows the same format as what the client is sending you. There's too many weirdnness cases going on with streams, even worse if you have to pass streams or stream flags as arguments down your function call chain… which is what streaming of classes is usually implemented as. So streaming can be defined as "insidious" as you used the term above, or perhaps even as "viral" (though not anywhere to the same degree as const-correctness).

Have a member deep down your class hierarchy that is a string? Surprise, the client better sends a single word, or else. Have some numbers you want to serialize? You better check, save and restore the stream flags at every function call depth, because you never know who's the idiot who just set his stream to octal output before calling your function. Or worse - who just called something like setfill and setw and thus broke the input/output formatting of your first -and only your first- integral members because those states don't propagate. Oh and let's not ask about streams and internationalization.

There's no warning in the language whatsoever that you are streaming the right way, or the wrong way, or even streaming at all. Asked client code for a stream to pass to write data backup to? You don't really have a way to know that the stream points to /dev/null. (On the other hand, you can claim incredible backup speeds and compression rates that way!)

OwnerDisplayName: Blaisorblade

Title: "Whole-team" C++ features?

Body:
The only one besides const correctness (seen above) that comes to mind is stream(ing) state. If you write C++ code where you use objects and subobjects and object hierarchies chances are, you'll eventually want to send or receive data to/from the operator of the program. You can write simple streaming operations that will compile and will be semantically correct...

std::ostream& operator<< (std::ostream&, MyClass const&) {...}
std::istream& operator>> (std::istream&, MyClass&) {...}

...But once you do, you'll never have any guarantee that what you are trying to write (or most importantly, read) follows the same format as what the client is sending you. There's too many weirdnness cases going on with streams, even worse if you have to pass streams or stream flags as arguments down your function call chain… which is what streaming of classes is usually implemented as. So streaming can be defined as "insidious" as you used the term above, or perhaps even as "viral" (though not anywhere to the same degree as const-correctness).

Have a member deep down your class hierarchy that is a string? Surprise, the client better sends a single word, or else. Have some numbers you want to serialize? You better check, save and restore the stream flags at every function call depth, because you never know who's the idiot who just set his stream to octal output before calling your function. Or worse - who just called something like setfill and setw and thus broke the input/output formatting of your first -and only your first- integral members because those states don't propagate. Oh and let's not ask about streams and internationalization.

There's no warning in the language whatsoever that you are streaming the right way, or the wrong way, or even streaming at all. Asked client code for a stream to pass to write data backup to? You don't really have a way to know that the stream points to /dev/null. (On the other hand, you can claim incredible backup speeds and compression rates that way!)


答:
I think what you are looking for is an undirected graph. If you use an adjacency list representation to store the route, then if you swap two links in the route (because they were crossing), you need to update the adjacency list for the four nodes that you are affecting.

This is a constant time operation - no matter how big your route, no matter how many links in between nodes, you only have to change the four nodes you're affecting.

In addition, it may be possible to represent the links as a system of linear equations. If there are any solutions to the system of equations, there are links crossing over. Don't quote me on this - you'll have to ask better mathematicians than myself how you'd go about doing this. That way you won't need O(n^2) to check for crossings.

Another way is to have two arrays that store respectively the latitude and the longitude of your nodes. You take the subset A of nodes that is within the latitude +/- the length L of the link you are currently checking. You do the same with the longitude and form set B. The set C that is the intersection of A and B is the set of nodes that are close enough to bother checking.

LatArray = Sorted array of node latitudes

LongArray = Sorted array of node longitudes

L = length of the current link you are checking

A = The set of nodes from LatArray that are in latitude +/- L of the first node of the link you are checking

B = The set of nodes from LongArray that are in longitude +/- L of the first node of the link you are checking

C = intersection of sets A and B

D = Same as C, but for the second node of the link you are checking

What the above does is give you a fast way to determine which other nodes should be checked because they are in the range of the current link. The search function for LatArray and LongArray can be binary.

The above becomes useful when you are dealing with millions of nodes.

However, be warned that the algorithm that you link to here is not sufficient to ensure good routes. Just because an optimal route has no intersections, does not mean that if a route has no intersections it is optimal.

Something like the Clarke-Wright algorithm is probably closer to what you're looking for. There's an explanation and a textbook with more background here:

http://web.mit.edu/urban_or_book/www/book/chapter6/6.4.12.html

Title: Reverse subarray of an array with O(1)


答:
Regardless of language, if you don't want to hard code the values, then one will need some sort of meta data that describes how the data will be mapped, formatted, and output.

In this example, it could be called a mapper or formatter.

Map/format files (XML, JSON, or simliar) would describe how the data would be formatted and written.  Your application would read in the map/format file and use it to create the output.

Then your application could format the CSV anyway you see fit, without a programming change.  One could also extend this to flat or fixed formats and XML as well.  Then your code is generic as it uses the mapping meta data to create the CSV file.

For the CSV case, at a high level one would need to describe:

Name and Order of fields

Delimiter (Sometimes comma is not used)

Whether or not to include a header

Whether or not to include quotes around the data

Just as a side note, there is a time difference to develop the two applications.  Hardcoded field values are much faster to develop, although as you have pointed out less elegant.  But if you need to get something done quickly, the aproach is OK.

Developing something more generic would take more time up front, but if your producing a lot of CSV formatted files of different format, in the long run one would get ROI on it.

With this approach, one can also write some sort of nice "GUI" for business analysts to use to create the map files so developers will be less involved in the overall process.

Title: More elegant way to avoid hard coding the format of a a CSV file?

Body:
I know this is trivial issue, but I just feel this can be more elegant.

So I need to write/read data files for my program, lets say they are CSV for now.  I can implement the format as I see fit, but I may have need to change that format later.  The simply thing to do is something like

```<code>out.write(For.getValue()+","+bar.getMinValue()+","+fi.toString());
</code>```

This is easy to write, but obviously is guilty of hard coding and the general 'magic number' issue.  The format is hard-coded, requires parsing of the code to figure out the file format, and changing the format requires changing multiple methods.

I could instead have my constants specifying the location that I want each variable to be saved in the CSV file to remove some of the 'magic numbers'; then save/load into the an array at the location specified by the constants:

```<code>int FOO_LOCATION=0;
int BAR_MIN_VAL_LOCATION=1;
int FI_LOCATION=2
int NUM_ARGUMENTS=3;

String[] outputArguments=new String[NUM_ARGUMENTS];
outputArguments[FOO_LOCATION] = foo.getValue();
outputArgumetns[BAR_MIN_VAL_LOCATION] = bar.getMinValue();
outptArguments[FI_LOCATOIN==fi.toString();

writeAsCSV(outputArguments);
</code>```

But this is...extremely verbose and still a bit ugly.  It makes it easy to see the format of existing CSV and to swap the location of variables within the file easily.  However, if I decide to add an extra value to the csv I need to not only add a new constant, but also modify the read and write methods to add the logic that actually saves/reads the argument from the array; I still have to hunt down every method using these variables and change them by hand!

If I use Java enums I can clean this up slightly, but the real issue is still present.  Short of some sort of functional programming (and java's inner classes are too ugly to be considered functional) I still have no obvious way of clearly expressing what variable is associated with each constant short of writing (and maintaining) it in the read/write methods.  For instance I still need to write somewhere that the FOO_LOCATION specifies the location of foo.getValue().

It seems as if there should be a prettier, easier to maintain, manner for approaching this?

Incidentally, I'm working in java at the moment, however, I am interested conceptually about the design approach regardless of language.  Some library in java that does all the work for me is definitely welcome (though it may prove more hassle to get permission to add it to the codebase then to just write something by hand quickly), but what I'm really asking is more about how to write elegant code if you had to do this by hand.


问:
Has anyone used "Design Pattern Framework (TM)"?
Has anyone purchased Design Pattern FrameworkTM?

Are these samples worth investment? Are they practical? What are the pro and cons of the guidelines? Anyone used this in the real-world development?

答:
I used the .NET Framework many years ago and found it to be useful as examples of patterns. But I learn well dinking with code. Others learn better from books and the C# Design Patterns is a good choice for learning the patterns in .NET. Others learn via videos and Pluralsight a course on patterns.

As for the generation, that is the Pro .NET Design Patterns Framework, which contains a generator called Spark. I have not tried it, so I cannot vouch whether it is worth it or not.


答:
Use metadata.

I generally associate a CSV file with a separate resource file containing format version and listing the fields. In this way one can develop the quality at the same spot: checking the number of fields, field types and all, in one generic piece of code.

And it is a tiny bit more declarative as an enum.

In fact, on that level one is not interested in specific business processing of data, giving special meanings to fields. So why creating specific coding fluff. As soon as the data arrives on the business side in DTOs or so, the enum (for instance) has its final use, and is further dead: you have built two layers, where only one would be needed to be maintained.


问:
Editing files without race conditions?
I have a CSV file that needs to be edited by multiple processes at the same time. My question is, how can I do this without introducing race conditions?

It's easy to write to the end of the file without race conditions by open(2)ing it in "a" (O_APPEND) mode and simply write to it. Things get more difficult when removing lines from the file.

The easiest solution is to read the file into memory, make changes to it, and overwrite it back to the file. If another process writes to it after it is in memory, however, that new data will be lost upon overwriting. To further complicate matters, my platform does not support POSIX record locks, checking for file existence is a race condition waiting to happen, rename(2) replaces the destination file if it exists instead of failing, and editing files in-place leaves empty bytes in it unless the remaining bytes are shifted towards the beginning of the file.

My idea for removing a line is this (in pseudocode):

```<code>    filename = "/home/user/somefile";
    file = open(filename, "r");
    tmp = open(filename+".tmp", "ax") || die("could not create tmp file"); //"a" is O_APPEND, "x" is O_EXCL|O_CREAT
    while(write(tmp, read(file)); //copy the $file to $file+".new"
    close(file);
//edit tmp file
    unlink(filename) || die("could not unlink file");
    file = open(filename, "wx") || die("another process must have written to the file after we copied it."); //"w" is overwrite, "x" is force file creation
    while(write(file, read(tmp))); //copy ".tmp" back to the original file
    unlink(filename+".tmp") || die("could not unlink tmp file");
</code>```

Or would I be better off with a simple lock file?
Appender process:

```<code>lock = open(filename+".lock", "wx") || die("could not lock file");
file = open(filename, "a");
write(file, "stuff");
close(file);
close(lock);
unlink(filename+".lock");
</code>```

Editor process:

```<code>lock = open(filename+".lock", "wx") || die("could not lock file");
file = open(filename, "rw");
while(contents += read(file));
//edit "contents"
write(file, contents);
close(file);
close(lock);
unlink(filename+".lock");
</code>```

Both of these rely on an additional file that will be left over if a process terminates before unlinking it, causing other processes to refuse to write to the original file.

In my opinion, these problems are brought on by the fact that the OS allows multiple writable file descriptors to be opened on the same file at the same time, instead of failing if a writable file descriptor is already open. It seems that O_CREAT|O_EXCL is the closest thing to a real solution for preventing filesystem race conditions, aside from POSIX record locks.

Another possible solution is to separate the file into multiple files and directories, so that more granular control can be gained over components (lines, fields) of the file using O_CREAT|O_EXCL. For example, "file/$id/$field" would contain the value of column $field of the line $id. It wouldn't be a CSV file anymore, but it might just work.

Yes, I know I should be using a database for this as databases are built to handle these types of problems, but the program is relatively simple and I was hoping to avoid the overhead.

So, would any of these patterns work? Is there a better way? Any insight into these kinds of problems would be appreciated.

答:
Don't reinvent the wheel. You'll get it wrong in subtle and frustrating ways.

Use a proper low-overhead database such as sqlite (as Zoredache or Chopper3 point out) made by people who have already done all the work for you.

Title: Editing files without race conditions?

OwnerDisplayName: MikeyB


答:
Clean code doesn't say checked exceptions are evil or forbidden. It just says that in most scenarios they are a burden and it is not necessary to take it.

All your examples are exceptional cases that should not happen, because you defined preconditions and assume they are met. Uncle Bob meant exactly such a case when he said you should favor unchecked exceptions over checked ones.

Nobody says you are not allowed to catch (unchecked) exceptions. So, you may wrap your call in a try-catch block and show the error message, or, more elegant, handle it on a higher level (most UI frameworks have a built in exception handler that shows a generic message).

Title: Layering Design Pattern in Java clean code style

Body:
As a Java developer, I am developing trying to use the clean code rules. But in my team we are facing a concrete problem:

We have a business layer offering a service called "createObject", this service makes a lot of operation which can result to problem. E.g: parentObjectDontExist, objectAlreadyExist, dontHaveAuthorizationToCreate, operationFailed...

and we want the UI using this service to display different information messages depending which error occurred.

In old java dev, we should have create all signed exception type and throw it in createObject.

As Clean code says, it is forbidden to use Exception for business logic AND signed exceptions are evil...
Why not...But i don't know how to solved this problem and i don't want to use return code.

How do you do?
Thanks for youre experience return.


问:
Display large amount of data to client through pagination
I have a web application in which i need to show a big number of data or records for clients. Now i 'll use pagination but i was wondering should I:

Load all the data once then pagination, sorting and sarching 'll be easy..But it 'll takes big time(using local DB it takes up to 9 sec.)

Or each time i show new page(from the pagination) i make a new request to server and then new request to DB to get the next records..But then what if the client click on Prev button, i 'll make a new request to get data that I had previously..Should i cach data that are loaded before and how if that's good technique?

So load all data once or make a new request every time i need data that maybe have been loaded before.

I'm using ASP.NET MVC SPA with durandaljs and knockoutjs

答:
You can have combined approach by taking best of both the worlds.

How? -->

Few weeks back I came across a library - oboe.js which loads the data in stream by giving parsed objects before the response completes.

So rather than waiting for 9 seconds to load the data you can stream it and use the parsed objects as soon as they are available. By this way, you will be able to load the whole data and also don't have to wait for long.


答: Another possibility is operator overloading. Once one part of the codebase starts to tinker with overloaded operators everyone tends to start second guessing just what exactly any given object they are working with is actually doing. It doesn't explicitly propagate through the codebase the way exceptions and const correctness do, but it's definitely something that can start to cause issues if the whole team isn't on the same page about when, how, and why to use it.

Title: "Whole-team" C++ features?

Body:
In C++, features like exceptions impact your whole program: you can either disable them in your whole program, or you need to deal with them throughout your code. As a famous article on C++ Report puts it:

Counter-intuitively, the hard part of coding exceptions is not the explicit throws and catches. The really hard part of using exceptions is to write all the intervening code in such a way that an arbitrary exception can propagate from its throw site to its handler, arriving safely and without damaging other parts of the program along the way.

Since even new throws exceptions, every function needs to provide basic exception safety — unless it only calls functions which guarantee throwing no exception — unless you disable exceptions altogether in your whole project.

Hence, exceptions are a "whole-program" or "whole-team" feature, since they must be understood by everybody in a team using them. But not all C++ features are like that, as far as I know.

A possible example is that if I don't get templates but I do not use them, I will still be able to write correct C++ — or will I not?. I can even call sort on an array of integers and enjoy its amazing speed advantage wrt. C's qsort (because no function pointer is called), without risking bugs — or not? It seems templates are not "whole-team".

Are there other C++ features which impact code not directly using them, and are hence "whole-team"? I am especially interested in features not present in C.

Update: I'm especially looking for features where there's no language-enforced sign you need to be aware of them. The first answer I got mentioned const-correctness, which is also whole-team, hence everybody needs to learn about it; however, AFAICS it will impact you only if you call a function which is marked const, and the compiler will prevent you from calling it on non-const objects, so you get something to google for. With exceptions, you don't even get that; moreover, they're always used as soon as you use new, hence exceptions are more "insidious". Since I can't phrase this as objectively, though, I will appreciate any whole-team feature.

Update 2: instead of C++ feature I should have written something like "C++-specific feature", to exclude things like multithreading which apply to a large amount of mainstream programming languages.

Appendix: Why this question is objective (if you wonder)

C++ is a complex language, so many projects or coding guides try to select "simple" C++ features, and many people try to include or exclude some ones according to mostly subjective criteria. Questions about that get rightfully closed regularly here on SO.

Above, instead, I defined (as precisely as possible) what a "whole-team" language feature is, provide an example (exceptions), together with extensive supporting evidence in the literature about C++, and ask for whole-team features in C++ beyond exceptions.

Whether you should use "whole-team" features, or whether that's a relevant concept, might be subjective — but that only means the importance of this question is subjective, like always.


问:
Is it possible to learn maths via programming, or you should learn maths for programming?
I am not the best in maths, not very horrid either, but lower than the average, I've always been thinking to improve my maths, but schools and books didn't do the job because I get bored too fast. The only thing I don't get bored with is coding and gaming, so I thought what if coding a program that solves mathematical problems will help me understand maths better, most of these problems are limits (calculus), functions, Differential calculus, and some other subjects (I already said am not that good) similar to the previous noted.

My question is: Am I able to achieve a better knowledge in maths if I do some specific program coding, and if possible, is physics possible that way too? Or am I wrong and Maths should be learned before programming to help improve my coding?

P.S : C++ is the preferred language.

答:
Another option is to use your love of programming to drive your desire to learn math. Just about anything tends to become easier to learn if you are learning it with a specific problem you want to apply it to and math is no exception. You just need to figure out math heavy programming problems that interest you and use them as a reason to learn the associated math. Learning Linear Algebra so you can play with graphics for example, or probability and statistics for image processing/computer vision type stuff.

I think your mileage is going to vary on this since different people have different ways of learning things, but sitting down and learning math in the abstract for the sake of learning math has simply never worked for me.


问:
Dependency injection: At what point am I allowed to create a new object?
I am refactoring a PHP application, and I am trying to do has much dependency injection (DI) as possible.

I feel like I've got a good grasp of how it works, and I can certainly see my classes becoming a lot leaner and more robust.

I'm refactoring so that I can inject a dependency rather than create a new object within the class, but at some point I am going to have to create some objects, that is, use the dreaded new keyword.

The problem I have now run into is at what point can I actually create new objects? It's looking like I'll end up at a top level class, creating loads of new objects as there is no where else to go. This feels wrong.

I've read some blogs that use factory classes to create all the objects, and then you inject the factory into other classes. You can then call the factory methods, and the factory creates the new object for you.

My concern with doing this is now my factory classes are going to be a new free-for-all! I guess this may be OK as they are factory classes, but are there some rules to stick to when using a factory pattern and DI, or am I going way off the mark here?

答:
My two cents here:

I am refactoring a php application and I am trying to do has much
  dependency injection as possible

You don't state if you are using a dependency injection framework. I think you definitely should. Use something that gives you the features you need: https://stackoverflow.com/questions/9348376/guice-like-dependency-injection-frameworks-in-php .

The problem I have now run into is at what point can I actually create
  new objects? Its looking like I'll end up at a top level class,
  creating loads of new objects as there is no where else to go. This
  feels wrong.

You normally use configuration or a central point for the instantiation of the initial objects that compose your application. The container will create the objects for you.

You then access objects (services, providers, controllers...) via the IoC container. It will transparently create an object for you if needed, or give you a reference to the appropriate existing instance.

Of course, inside your particular implementation of objects you can instantiate other objects on which you don't need DI (data structures, custom types, etc), but that's normal programming.

I've read some blogs that use factory classes to create all the
  objects, and then you inject the factory into other classes. You can
  then call the factory methods, and the factory creates the new object
  for you.

Normally, you use a Factory if you want the IoC framework to instantiate some IoC objects through your factories (this is needed when instantiating a particular object requires some extra work). If you can simply create your objects with "new Object()", and setting some properties, you don't necessarily want to use a Factory pattern.

In other words, I'd say that using a Factory pattern for a class or group of classes depends on how you want to model those classes, not on whether you use DI (unless your DI implementation explicitly requires factories, which is unusual).

You also configure your IoC framework to use a Factory when you are using a 3rd party lib that already requires the usage of a Factory. In this case you have no control about this and you need to tell your IoC container: "hey, when I ask for one of these interfaces, you have to use this factory to provide me with an appropriate instance".

My concern with doing this is now my factory classes are going to be a
  new free-for-all! I guess this may be ok as they are factory classes,
  but are there some rules to stick to when using factory pattern and
  DI, or am I going way off the mark here.

In this case, it sounds that you don't need to use Factory patterns for these objects/services/controllers/whatever, and you can simply configure your IoC to instantiate with "new" the appropriate class and inject everything else.

I hope it helps.


答: CLR also has value types (ie. structs on the stack) so one can argue it's a more efficient version of JVM. The implementation of generics is also better.</p>

Title: What is the advantage of a programmers VM apart from portability

Body:
I can understand the benefits of Java running on a JVM.  Portability.  Nice simple reason.  But I have always been puzzled as to why Microsoft brought out their own version of a JVM - .NET.  C# is supposed to be a fine language (haven't used myself) but could Microsoft have launched product to use native.  ie to generate an exe?

My colleague is learning F#.  The reason it has to be a language which runs on .NET is because the Microsoft Lync API which will be used is only available on .NET.  ie there is no C API for Lync.

A cynical view may be that the reason is vendor lockin.  F# will only run on a Microsoft platform (or C# for that matter) and so program is locked in.  But maybe I am missing some other benefit of a VM platform?


问:
Releasing a project under GPL v2 or later without the source code of libraries
I wrote a system in Java that I want to release under the terms of GPL v2 or later. I've used Apache Maven to deal with all the dependencies of the system, so I don't have the source code of any of the libraries used. I've already checked, all the libraries were released under GPL-compatible licenses (Apache v2, 3-clause BSD, MIT, LGPL v2 and v2.1).

Can I distribute my work under GPLv2 or later and provide the libraries on the same package as separate works, without having to apply GPL on them (as stated by GPLv2 sec 2), even if they are necessary to compile and run the system? If so, I know I am bound only by the original licenses of each one, and than I know what to do.

答:
Standard disclaimer: P.SE isn't the most appropriate place to ask for legal/license advice

1) Yes; 2) Yes; 3) Yes

You are not required to distribute any library code as long as you make it very clearly which libraries and versions you are using AND you did not make any modifications AND (as Ross pointed out) you provide explicit information on where to get the source for those libraries. If anyone wishes to see the source code for those libraries, they can always go to their respective websites and download them from there.  What I didn't know and just learned from others on this page (+1 to those answers) is that you are also responsible for making sure that source code accessible based on the information you provide.  And if third-party library website goes down, then it becomes YOUR RESPONSIBILITY to find another source or host the source yourself.

However, if you had to modify even a single line of code in a library (under both GPL and LGPL) you must distribute the library code that you modified. The motivation here is that if you are benefiting from using third-party code, the community should in return benefit if you find and fix bugs in that third-party code.

Under GPL you are required to make your own source code available, which looks like you are planning to do already, so you are good there. You do not have to package your source with the binaries, but your binaries distribution should reference a location from where your source code could be downloaded.


答:
In general, if your application depends on those libraries to work, you must license the entire application as GPL.  Since the libraries are already distributed under GPL, the source code for those libraries should already be publicly available, so in theory you shouldn't need to redistribute the source code for those libraries yourself.  The GPL concerns itself mostly with making your code public (including any modifications you made to the libraries), not code that is already public anyway.

There are a few caveats, however; the most important one is that the version of the library that your application works with might not be the same one that is in general distribution, either because you modified it, or it has been modified  by the original developers since you incorporated it in your application.  Consequently, it is more convenient for developers to have the entire body of actual code that is in use available in the project that you distribute, rather than going to several disparate places in an attempt to re-create the entire project, which might not even compile now.

Title: Releasing a project under GPL v2 or later without the source code of libraries

Body:
I wrote a system in Java that I want to release under the terms of GPL v2 or later. I've used Apache Maven to deal with all the dependencies of the system, so I don't have the source code of any of the libraries used. I've already checked, all the libraries were released under GPL-compatible licenses (Apache v2, 3-clause BSD, MIT, LGPL v2 and v2.1).

Can I distribute my work under GPLv2 or later and provide the libraries on the same package as separate works, without having to apply GPL on them (as stated by GPLv2 sec 2), even if they are necessary to compile and run the system? If so, I know I am bound only by the original licenses of each one, and than I know what to do.


问:
Is it possible to access javascript return value outside of function?
```<code>milkmachine = function(argument){
    var r=1, k=2;
    //.....
    return r;
}
milkmachine(); //returns r, good
milkmachine.set_return_to_another_variable('k');
milkmachine(); //this should return k
</code>```

答:
The short answer, as Greg Hewgill commented, is: no (to the best of my knowledge). There are a few shoddy ways you could get that behavior as well as a few recommended ways:

Shoddy Way #1:

One way is to have two versions of the function: one that returns r, the other that returns k. This is not recommended because it is duplicating the same code, just returning something different.

Shoddy Way #2:

Another option would be to add another parameter to the function which would specify the variable you want to be returned:

```<code>milkmachine = function(argument, retWhat){
    var r;
    var k;

    //do something with arguments and variables

    if (retWhat == "k")
        return k;
    else
        return r;
}
</code>```

This is also bad since you're using one function to do multiple things and a function should only do one thing; also, it gives external code more info about the inner workings of the function than is good. (There are probably other, better reasons this is bad, but I can't think of any at the moment.)

Recommended Way #1:

Instead of returning just one value, you could return both values wrapped in a container object:

```<code>milkmachine = function(argument){
    var r;
    var k;

    //do something with arguments and variables

    return new MilkMachineRetrunValue(r, k);
}

var retval = milkmachine("some arg");
// access retval.r here
// access retval.k here

// or you could directly access the variable
// that you wanted within the return wrapper
// after the call like so:
// milkmachine("some arg").k
</code>```

Recommended Way #2

Use an object:

```<code>function MilkMachine() {
    this.r;
    this.k;
}

MilkMachine.prototype.run = function(argument) {

    //do something with arguments and variables
}

var mm = new MilkMachine();
mm.run("some arg");
// access mm.r here
// access mm.k here
</code>```

Body:
The short answer, as Greg Hewgill commented, is: no (to the best of my knowledge). There are a few shoddy ways you could get that behavior as well as a few recommended ways:

Shoddy Way #1:

One way is to have two versions of the function: one that returns r, the other that returns k. This is not recommended because it is duplicating the same code, just returning something different.

Shoddy Way #2:

Another option would be to add another parameter to the function which would specify the variable you want to be returned:

milkmachine = function(argument, retWhat){
    var r;
    var k;

    //do something with arguments and variables

    if (retWhat == "k")
        return k;
    else
        return r;
}

This is also bad since you're using one function to do multiple things and a function should only do one thing; also, it gives external code more info about the inner workings of the function than is good. (There are probably other, better reasons this is bad, but I can't think of any at the moment.)

Recommended Way #1:

Instead of returning just one value, you could return both values wrapped in a container object:

milkmachine = function(argument){
    var r;
    var k;

    //do something with arguments and variables

    return new MilkMachineRetrunValue(r, k);
}

var retval = milkmachine("some arg");
// access retval.r here
// access retval.k here

// or you could directly access the variable
// that you wanted within the return wrapper
// after the call like so:
// milkmachine("some arg").k

Recommended Way #2

Use an object:

function MilkMachine() {
    this.r;
    this.k;
}

MilkMachine.prototype.run = function(argument) {

    //do something with arguments and variables
}

var mm = new MilkMachine();
mm.run("some arg");
// access mm.r here
// access mm.k here


答:
While I agree with the other two answers, keep in mind, that you are still in fact on the hook for providing sources to all the dependencies you use.

If you say "grab libBlah2.0" from libBlah.org, and the sources are easy to grab from there, no one is going to give you a hard time. But if libBlah.org shuts down and doesn't host the sources anymore, you are then still responsible for stepping up and making the sources available. Not stepping up in that circumstance is a violation of the terms of the GPL.

Edit: Additionally, not bothering to distribute binaries of the libraries does not get you off the hook. Your project is a derivative work of those libraries, and so you are responsible for providing source to the libraries whether you distribute them as binaries or not, because the GPL/copyright demands so.


问:
Tree position terminology/naming
This is a naming things question. I am processing trees (XML documents), and there are often special rules applied to nodes based on structure. It's been very difficult coming up with concise naming conventions for some cases, namely for nodes in the first position among their siblings, along with some recursive relationship:

Given an arbitrary node, I want to describe its first child, and then that node's first child, and so on recursively.

Given another arbitrary node, I want to describe its parent if the parent is first among its siblings, and that parent's parent if it's first, and so on recursively.

Is there existing terminology to describe these tree positions? How would you name a variable or function that captures one of these cases so that it's intuitive to an unfamiliar developer trying to understand an algorithm?

答:
I like to use the word Primary in situations where the word First isn't quite right, but is close.  It indicates that it's special in some way, without actually depending on an ordered enumeration.  First implies a Second, Third and so on, but Primary could be paired with everything else or Secondary, Tertiary, and only then everything else.

Given an arbitrary node, I want to describe its first child, and then that node's first child, and so on recursively.

I'd call this one PrimaryDescendant.  After all, if you enumerate every final descendant of a given node, in order, it's the one that will be first.  If you're referring to the "first child" status by itself, that'd just be FirstChild.

Given another arbitrary node, I want to describe its parent if the parent is first among its siblings, and that parent's parent if it's first, and so on recursively.

This one is harder, but I'd probably try to be consistent and call it PrimaryAncestor.

Title: Tree position terminology/naming