问:
What are some good assignments for an introductory course, to reach today's students?
I periodically teach an introduction to programming course using Java. I want to give my students some exciting assignments that they can relate to or find interesting. At the very least, I want assignments that make sense and have an internal cohesion (for example, some very bad programming exercises seem contrived just so that you have to use the most recent programming construct covered).

To give you an idea of scope, here's what's being covered:

The assignments must be in Java, using some external library can be done, but it would need to be a simple API and not a full framework

Variables, Primitives and Strings

Console input and output

if, for, while

Arithmetic and logical operators

Simple graphics with line and shape drawing

Static methods

One-dimensional arrays

The students will not go into advanced topics (e.g., no recursion, no emphasis on inheritance). Thus, I'm not looking for complex projects: "Have them write a C compiler. I did it when I was 5 and it was the only way I learned!"

If you have ideas that are more advanced than the scope, please post them on the "Challenging" question linked below, and not this one.

Instead, what I'm looking for are interesting ideas that can be accomplished in a short program. For example:

Students can write a console version of the "Star Wars Name" Generator. This is effectively reading Strings and using substring, but I think it's fun. A similar variation would be a "Mad Libs" program. I used this one five years ago, and perhaps it's already "stale."

Using some trig supplied to them, students can draw regular polygons, and create interesting spiral shapes.

It's also not out of the question to use some simple animation class with most of the code supplied to them. And if you know a Twitter or Facebook service that can be accessed with a simple API, I would be very interested to know.

Please note that this question is different from the "Challenging Java questions for beginners" Question. I'm not looking for challenging per se, just interesting. I think if students work on something where they can easily answer "why would anyone ever want to program that?" then they will learn better.

Even simple problems like computing Miles per Gallon can be good. Although, if there's a way to update it to be more relevant, all the better. If you have an exercise from somewhere else (a book or a website), please cite the source.

To help you think about the typical freshman today, check out the Beloit Mindset list, for many examples that will surely make you feel old.

答:
We created quite a few projects with just i/o, functions and conditional operators in school. All done before we learned about object oriented programming. These projects advanced slowly to be more and more difficult. Suffice to say, the 4 hours we had each week weren't nearly sufficient towards the end of the year.

All these projects were done with just functions & i/o:

A game that learns. You take a number of sticks, the pc takes a number of sticks. Repeat. The last one who holds a stick looses. We had to create a simple self learning program that got better after each game. Good example to learn 2D arrays.

A code breaker. You know the Caesar encryption, pick a letter and add the value of the letter to each letter of your word. E.g. key = 'a' and the word = "secret". This would become "tfdsfq". Can be done by reading in the file and then creating a frequency table for each letter. You also read in an English bible. Then you can simply see that the most used letter in the English alphabet is an 'e' and solve it. Added challenge: use a key like 'ab' which was our assignment. Good exercise to understand i/o.

A barcode maker. This program was an exercise to call an external library. You got a code and had to generate an image with the bar code. An external library was used to generate the image.

A genetic algorithm to solve the traveling salesmen problem. This was a more advanced project for 2 or 3 persons. You start with a random route and this route improves all the time until you have a "good route". Bonus: create a map with the route.

A working lzw compression program. This was the final, 4 people project. The parameters were quite simple. "Zip file.txt file.zip" or something similar. Fun project but understanding the lzw algorithm took a while.


问:
How do you test database abstraction in PHP?
I apologise in advance if this question is too subjective but I'm struggling to find a good answer, probably as there is not really a correct answer to give.

I'm currently writing a database abstraction layer to unify the use of a single API throughout my applications. Possibly re-inventing the wheel but I'm mainly doing it for my specific need of certain Oracle functionality that will eventually be migrated away from Oracle.

For the Oracle driver I'm finding it difficult to test the object due to the lack of an OO API in PHP, so to test I need to touch the database. There seems to be two schools of thought on testing database functionality.

Don't touch the database, mock it all away (obviously impossible without an OO API).

Allow the functionality to run and therefore feature test rather than unit test.

My question is two fold, has anyone done this before and how did you handle testing? If you haven't had cause to do this before, what are your thoughts on how you would handle it and why?

答:
If there is no way possible, set up a test database and have the test interact with it.  Since this is communication layer, you shouldn't be doing all together all that much.

There is a way to mock PHP functions if you are using PHP 5.3 or later via namespacing.  Basically, you place your code and test in the same namespace.  Then in your test you can mock the function calls.  PHP will check in your namespace and find the function and not call the internal function.

http://www.schmengler-se.de/-php-mocking-built-in-functions-like-time-in-unit-tests

This way you would be able to test your class, and mock the php internal functions and not have to touch any database.

OwnerDisplayName: happyaccidents

ContentLicense: CC BY-SA 3.0


问:
Versioning an API
I'm starting a side project, the first stage will be a building a web application with MVC, in later stages we will be adding clients for mobile platforms. My thought was to create one API that all of the applications (web and mobile) go through to get/save data.

Because these different platforms will be on different release cycles I'll need a way for, say IPhone, to work with one version of the API while the website is using an updated version. What's the best way to do that?

My ideas so far are:

Create a separate project to host the MVC Web API and host that in a subdomain or in a subfolder of the root site. Then either reference the DLL directly or reference it through the web (seems like an unnecessary http call)

House the API within the MVC project that will be the website and try to version it based on url in there. I did some quick testing with that this morning and wasn't able to get it to work, it always resided at \api (I couldn't get it to reside at \api_v2)

答: Your API shouldn't care about who/what is consuming it. The API provides a contract and fulfills it. It is up to the consumer to know what to do with the result. I don't see why your iPhone and web app would need a different contract.</p>

OwnerDisplayName: jrhutch

Title: Versioning an API

OwnerDisplayName: Jean-Bernard Pellerin


答:
I concur with what Jean-Bernard said. You should have one API so everybody can access it.

But that said, you will eventually have more than one version. You would manage that on different branches on your Source Control system. If you ever need to have more than one version published I recommend using subdomains:

http://api.yoursite.com

http://apiv2.yoursite.com

Title: Versioning an API

Body:
I'm starting a side project, the first stage will be a building a web application with MVC, in later stages we will be adding clients for mobile platforms. My thought was to create one API that all of the applications (web and mobile) go through to get/save data.

Because these different platforms will be on different release cycles I'll need a way for, say IPhone, to work with one version of the API while the website is using an updated version. What's the best way to do that?

My ideas so far are:

Create a separate project to host the MVC Web API and host that in a subdomain or in a subfolder of the root site. Then either reference the DLL directly or reference it through the web (seems like an unnecessary http call)

House the API within the MVC project that will be the website and try to version it based on url in there. I did some quick testing with that this morning and wasn't able to get it to work, it always resided at \api (I couldn't get it to reside at \api_v2)

OwnerDisplayName: amhed


答:
In a large service with multiple consumers and integrated services, here's some principles and guidelines we followed to be RESTful over our web api.  If you're not trying to be RESTful etc... and just want a simple http api, then it may not apply.

Key Principles:

A resource is identified by a RESTful URL (site.com/api/user/6).

That URL needs to be a permalink (always refers to that resource).  External services and consumers of the API can persist that permalink

Different versions of the client may ask for site.com/api/user/6 and depending on version, may get a different representation (version) of the resource.

We try hard to get it right, review APIs, etc... but we realize we won't get it right sometimes and want the ability to be able to version it and get it right.

We considered putting the version in the URL, but that breaks key RESTful principles.

https://stackoverflow.com/questions/389169/best-practices-for-api-versioning

Good read on web api design and versioning

What we did (basically, waving hands over details):

Put version of request in accept/content type header using MIME type properties: application/json;version=2 (we considered vendor MIME types which BTW, github uses).  We also support passing in querystring for web mashup scenarios.

We customized the routing so a request for version 2 of the resource request would route to the (Resource)2Controller.

On an http OPTIONS request, the server would iterate over the routes and expose the resources, available route templates and min/max version (our custom attribute put on the controller/classes).

The client knows what version it is so the first thing the client did is an OPTIONs request and negotiated the max version the client and server understands then it would send that in the header.

Since the server has multiple controllers, it's capable of handing back different versions of that resource.

Even though we're capable of versioning the resource, we refrain and take an purely additive approach if possible (older clients ignore extra properties on deserialization).  iOS will do this fine since it's just extra data in the dictionaries.

One benefit we got from the OPTIONs exposing routes, was we actually avoid path math on the client.  It knows what version it is - the http client passes in a dictionary and urls are formatted using the server advertised routes.

I am considering writing a blog and sharing how we integrated into web api to version our resources.  If I do, I will follow up here with a link.

Title: Versioning an API

OwnerDisplayName: bryanmac


问:
Stubbing and mocking boundaries
Suppose I'm building a JSON API and would like to include an endpoint that returns a list of recently created posts.  Somewhere in my system is an existing Post model with the following test:

create a few posts in the db (some new, some old)

posts = Post.recent

assert that posts only contains new posts

Now I want to test drive the JSON endpoint wrapping this functionality (the "controller").  The most obvious way to test this would be a full integration test like:

create a few posts in the db (some new, some old)

make a request to /posts

assert that only the new posts were returned in the response

This seems to duplicate much of what is already being tested in the model and will start to slow down the test suite as more code paths need to be tested (i.e. auth, query string params, etc.).  The alternatives…

Mock the model

mock Post.recent

make a request to /posts

assert that Post.recent was called

Stub the model

stub Post.recent

make a request to /posts

assert that the stubbed posts were return in the response

Either one of these options alone does not seem sufficient to fully test the controller but when combined seems fairly comprehensive.  The piece that remains untested is the agreement between the model and controller about Post.recent.  What if I decide to refactor my model and model tests and Post.recent no longer exists…my tests will still pass even though the production system will fail.

How does one address this?  Are integration tests the only answer?  If so, why bother stubbing and mocking at all?

答:
Integration tests help test that the interactions between all your objects work correctly.  And helps to outline the expected functionality of the entire system.  These tests are the similar to the ones where you actually try the system out and make sure that it works.  Or that QA would use to give the system a once over.

You are not concerned with any of the details in your controller and model with this test.  All you want is that when you make a given request to the system, a given response is returned by the system.  Having these tests would benefit you so that when you refactor your controller or model, you are able to verify that you have not broken any existing functionality.  Changes to the models that are being used are transparent to these tests.

Why bother with mocking/stubbing?  This is to verify that the individual components of your system work.  For example, with your controller, you would want to inject mock models into it so that you can control what they return.  This way you verify that an individual piece (the controller) works as intended.

By doing this, if there is a problem with your code (found either as a bug or failing integration test) you know that all your components are working correctly and only need to investigate the interactions between them.

When you are writing tests, you are not testing specific components per se.  Rather you are testing that specific results will happen for given inputs.

Title: Stubbing and mocking boundaries


问:
Can I charge for closed source J2EE .ear module relying on GPLed EJBs?
A customer asked me to add a (fairly generic monitoring and notifications) functionality to the in-house solution he has assembled on top of JBoss and couple of GPL-licensed components (downloadable from the open source vendor as EARs). I am using JMS and JMX to communicate with these components. Do I have to provide the source and redistribution rights to my customer to satisfy GPL restrictions? In other words, does configurable code that uses JMX and JMS mechanisms constitutes a derivative work? I would actually prefer to open source my code, but part of it relies on a patented third party logic that is unwilling to GPL it, but would gladly supply it to this customer. I am not asking for a legal advice, just for the opinion in terms of best practices / fair use.</p>

答:
Charging money has nothing to do with it.  Your real question is Do I have to provide the source and redistribution rights to my customer to satisfy GPL restrictions? In other words, does configurable code that uses JMX and JMS mechanisms constitutes a derivative work?

It's a gray area.  The FSF considers the manner in which one communicates with the GPL code relevant to its declaration as a derived work, but they are not specific about the manner in which that decision can be made, other than to say that the two programs must communicate "at arm's length," and that it must be apparent that the GPL program is not part of your work.

The relevant part of the GPL FAQ is here:

I'd like to incorporate GPL-covered software in my proprietary system. Can I do this?

In many cases you can distribute the GPL-covered software alongside
your proprietary system. To do this validly, you must make sure that
the free and non-free programs communicate at arms length, that they
are not combined in a way that would make them effectively a single
program.

The difference between this and “incorporating” the GPL-covered
software is partly a matter of substance and partly form. The
substantive part is this: if the two programs are combined so that
they become effectively two parts of one program, then you can't treat
them as two separate programs. So the GPL has to cover the whole
thing.

If the two programs remain well separated, like the compiler and the
kernel, or like an editor and a shell, then you can treat them as two
separate programs—but you have to do it properly. The issue is simply
one of form: how you describe what you are doing. Why do we care about
this? Because we want to make sure the users clearly understand the
free status of the GPL-covered software in the collection.

If people were to distribute GPL-covered software calling it “part of”
a system that users know is partly proprietary, users might be
uncertain of their rights regarding the GPL-covered software. But if
they know that what they have received is a free program plus another
program, side by side, their rights will be clear.


问:
MIT License: Why isn't it considered viral?
The first part of the license implies you can do basically whatever you want with it (copy, modify, sell etc).
But the second part says that these freedoms must propagate into all copies of the software.

My interpretation of that is, you can incorporate the software into your proprietary project, but that portion must remain open....so any modifications to the software must keep that license attached, forcing my changes to be open sourced.

Isn't this the reason people consider the GPL to be restrictive/viral? Because it forces modifications to be open sourced?

Here is a copy of the license:

Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

答:
The GPL is considered viral because, if you combine software that is licensed under it with proprietary code, you must also open-source your proprietary code under the GPL in order to remain compliant with the GPL.

The MIT license doesn't say that at all.

I think you might be interpreting the term "The Software" to include your proprietary portion.  It does not.  The MIT license only covers that part of the software which is licensed under the MIT license.

OwnerDisplayName: Kausheel


答:
Not quite.

Here's the basic idea. As you pointed out, "you can incorporate the software into your proprietary project, but that portion must remain open" under the MIT license.  If you have 100 features in your proprietary product, and one of them is based on MIT-licensed code, that's fine.

However, if you have 100 features in your product, and one of them is based on GPL-licensed code, the GPL forces you to open-source the entire rest of the product.  That's why it's called a viral license: it doesn't stay in its own code, but "infects" the rest of your codebase as well.

Title: MIT License: Why isn't it considered viral?

Body:
The first part of the license implies you can do basically whatever you want with it (copy, modify, sell etc).
But the second part says that these freedoms must propagate into all copies of the software.

My interpretation of that is, you can incorporate the software into your proprietary project, but that portion must remain open....so any modifications to the software must keep that license attached, forcing my changes to be open sourced.

Isn't this the reason people consider the GPL to be restrictive/viral? Because it forces modifications to be open sourced?

Here is a copy of the license:

Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


问:
Distributed SVN via file transfer?
I work for a large bureaucratic (and security paranoid) organisation that provides SVN for its development teams to use.

I am working with a 3rd party vendor (at their site) and we currently share code via SVN export and patch files. The only way I have for transferring files is by a FTP drop box or email. I would like a better way to work.

I am currently lobbying to get some kind of DCVS system setup, ideally cloud hosted. Failing that I want a better way to manage keeping SVN repositories in sync.

In the meantime (or if I fail to get DCVS) how do I keep two SVN repositories in sync?
How do I best manage exporting the repository?
How do I manage incoming changes?

答:
The SVK decentralized version control system uses the Subversion filesystem.

SVK can mirror and operate on Subversion repositories.

ContentLicense: CC BY-SA 4.0

Title: Distributed SVN via file transfer?


问:
What is a good license for community submissions to commercial partially closed source software?
I am maintaining a small code base that I am considering selling– but I want to allow developers that use it to submit code for addition to the trunk.  This way they can extend the framework and the community can benefit.

I want them to retain copyright to their code, but to allow me to use it however I desire, for commercial and non-commercial purposes.

I don't want to be obligated to release any submitted source(although as copyright holders they may).

The end user product will be binary distributions of the compiled code base.

Is there a good existing license for a project of this nature?  I could compromise a little to use an existing license which does not fully match this, if it will save me the legal headache.

答:
How exactly is the community benefiting from doing work to extend a product they can only get by buying it from you?

The only way I can see this working is a joint commercial/(L)GPL version. However even then you would need to get developers to assign any changes to you if you wanted to use it in the commercial version


问:
Is it possible in C++ to define several methods at once?
Sorry for the confusing title of this question, but I can't think of an exact way to word it. I have a very long class with hundreds of similar methods and I am trying to find a way to construct it without so many lines of code and so many DRY violations. Each time I add a new property to my class I have to write two methods and update the copy function. There are already over 80 properties.

Currently this class is written in Java but I was wondering if it were written in C++ if it could be done more efficiently. I think it can be done using preprocessor x-macros like described in wikipedia here but I am not a fan of macros and would prefer to do it using the language itself if possible.

Here is a simplified snippet of my Java class:

```<code>class InMemoryPerson implements Person {
    private HashMap<String,Object> values = new HashMap<String,Object>();

    public InMemoryPerson copyFrom(Person p) {
        setName(p.getName());
        // more code to copy all the properties...
    }

    public void setName(String name) {
        values.put("name",name);
    }

    public String getName() {
        return (String)map.get("name");
    }

    // many more methods for all the different properties...
    // each method may have a different type
}
</code>```

答:
In c++ it should be quite simple. Throw out setters and getters, and member variables, and use default copy constructors to copy objects of this class. Something like this :</p>

```<code>struct Person
{
    Person() : name("default name")
    {}

    std::string name;
    // etc
};

Person a;
// set fields of person a
Person b;
// set fields of person b
b = a;
</code>```

Body:
In c++ it should be quite simple. Throw out setters and getters, and member variables, and use default copy constructors to copy objects of this class. Something like this :

struct Person
{
    Person() : name("default name")
    {}

    std::string name;
    // etc
};

Person a;
// set fields of person a
Person b;
// set fields of person b
b = a;


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
In my life as C++ coder, two really nasty "rules" were enforced:

"We can not use the STL, because VC++ 4.1 does not support it (and we can't switch to VC++ 6.0 at this time)."

"Do not use QuickSort, because it can be O(n^2) in bad cases; use this implementation of the HeapSort algorithm I (name of project leader deleted) wrote as a student."

ContentLicense: CC BY-SA 2.5


问:
What are the 'must know' Emacs commands?
I'm a fairly new convert to Emacs and I really love it as an editor, primarily because I keep finding new and super-useful commands. Are there any other programmer 'must known' commands missing from my list?</p>

```<code>M-x replace-string     - Find and replace a given string.
M-x goto-line          - Goto a specific line
M-x column-number-mode - Show the current column number in text bar
</code>```

答:
M-x apropos

M-x describe-key

M-x describe-bindings

C-x C-f ~/.emacs (it helps if you know Elisp before running this one)

Pretty much everything else is personal preference. People sometimes talk about Emacs as though it's an editor.

That's not true.

Emacs is a language designed to succinctly express editors (which is to say, Elisp is its best 'feature'). How much mileage you get out of it depends directly and entirely on how well you understand this principle.


问:
When to favor ASP.NET WebForms over MVC
I know that Microsoft has said

ASP.NET MVC is not a replacement for WebForms.

And some developers say WebForms is faster to develop on than MVC.  But I believe speed of coding comes down to comfort level with the technology so I don't want any answers in that vein.

Given that ASP.NET MVC gives a developer more control over their application, why isn't WebForms considered obsolete?  Alternatively, when should I favor WebForms over MVC for new development?

答: When faced with a programming problem I often look to the web for answers. Webforms has tons of information/components on doing just about anything. In MVC due to fewer sources online and the layers of abstractions needed to make something work has put a limit in things that I could once do. MVC total kills my productivity as a developer while with Webforms it ain't. So for now I'm sticking to webforms until MVC has matured enough to replace it.</p>

Title: When to favor ASP.NET WebForms over MVC


问:
Is it better to save output from command in memory and store later or save in a temporary file and then move to final location?
I hope this is not off topic.

I have to save output from a command to file, but only if length of this output is positive. I've thought about two solutions:

save output to a python variable, check length, if positive save to destination file;

save output to a temporary file, check length, if positive rename to destination file.

Is there any best practice for this little problem, or which one usually performs better between my proposed solutions?

Typical configuration:

file length is usually 1KB

we are not using ssds, usually 7200rpm hard disk

average RAM is usually 10-20 GB

I don't know if filesystem is important, anyway ext3

I know this is a bit unclear, but I was hoping there was some best practice to apply in this case.

Thanks

答:
I think the answer to this is: it depends.

If it is important that you do not lose this data, then my advice would be to get it onto the disk as soon as possible. Bear in mind that if something bad happens on the computer, anything in memory will be lost.

However if it is more important that your program runs in as performant a way as possible, then writing to memory is bound to be quicker than writing to disk.


答:
I've not seen this consideration put forward amongst the existing 15 answers to this thread yet, but I think it's worth considering.

From my experience Web Forms is more similar to Win Forms and WPF than MVC is. Given this, I think one might consider choosing Web Forms when the team has most experience in that kind of tech, or when the Web Forms project will deliver an interface on to the same data set as an existing (or concurrently developed) Win Forms or WPF project. Doing so allows developers to cross between projects more easily, since application logic may be quite similar between the two.

As other answers have pointed out, development on the MVC framework is more similar to web development in Ruby, PHP, Python etc than its Microsoft counterparts; so naturally the choice of MVC can be influenced by the teams experience in those areas, along with the factors submitted in other answers.

Title: When to favor ASP.NET WebForms over MVC

Body:
I know that Microsoft has said

ASP.NET MVC is not a replacement for WebForms.

And some developers say WebForms is faster to develop on than MVC.  But I believe speed of coding comes down to comfort level with the technology so I don't want any answers in that vein.

Given that ASP.NET MVC gives a developer more control over their application, why isn't WebForms considered obsolete?  Alternatively, when should I favor WebForms over MVC for new development?


答:
The need for updating the copy function can be avoided by using default copy ctors, as @BЈовић has pointed out. For getters and setters, however, I would bite the bullet and use X-macros (if you don't want to write an external code generator for this).

Whatever you do, you need a place where you associate the hash key "name" with the associated data type String and the corresponding getter/setter names (the names of these methods may follow a strict convention, but AFAIK there is no easy uppercase/lowercase conversion within the preprocessor). So defining that list using X-macros will at least give you a very compact and easy-to-extend solution (EDIT: see @petrch's post for an example).

Title: Is it possible in C++ to define several methods at once?

Body:
Sorry for the confusing title of this question, but I can't think of an exact way to word it. I have a very long class with hundreds of similar methods and I am trying to find a way to construct it without so many lines of code and so many DRY violations. Each time I add a new property to my class I have to write two methods and update the copy function. There are already over 80 properties.

Currently this class is written in Java but I was wondering if it were written in C++ if it could be done more efficiently. I think it can be done using preprocessor x-macros like described in wikipedia here but I am not a fan of macros and would prefer to do it using the language itself if possible.

Here is a simplified snippet of my Java class:

```<code>class InMemoryPerson implements Person {
    private HashMap<String,Object> values = new HashMap<String,Object>();

    public InMemoryPerson copyFrom(Person p) {
        setName(p.getName());
        // more code to copy all the properties...
    }

    public void setName(String name) {
        values.put("name",name);
    }

    public String getName() {
        return (String)map.get("name");
    }

    // many more methods for all the different properties...
    // each method may have a different type
}
</code>```


答:
In C++ this is possible to do, using old style C macros.

```<code>// method is get/set method suffix
// name is the key in hash table
#define POINTER_PROPERTY(type,method,name) \
        type get##method(){return (type)_pointer_map[name];} \
        void set##method(type value){_pointer_map[name]=value;}

class InMemoryPerson : Person {
public:
    POINTER_PROPERTY(char *,Name,"name")

private:
    std::map<const char *,void *> _pointer_map;
};
</code>```

Value types would have to be handled by different macro and (easiest way) by different hash for each type. Not sure though this code is more readable and manageable than 80 different get/set functions.

Body:
In C++ this is possible to do, using old style C macros.

// method is get/set method suffix
// name is the key in hash table
#define POINTER_PROPERTY(type,method,name) \
        type get##method(){return (type)_pointer_map[name];} \
        void set##method(type value){_pointer_map[name]=value;}

class InMemoryPerson : Person {
public:
    POINTER_PROPERTY(char *,Name,"name")

private:
    std::map<const char *,void *> _pointer_map;
};

Value types would have to be handled by different macro and (easiest way) by different hash for each type. Not sure though this code is more readable and manageable than 80 different get/set functions.


问:
Multiple SSH keys for different organizations
I can see that GitHub allows you to have multiple mail account and associate every organization you are part of with a different address.

Can this be done also for SSH keys?

What I would like to do is having two different keys, one to push on my private repository, another to push on an organization repository.

答:
On Github, you can add several ssh keys to your account, simply go to your profile/ssh and click "Add SSH key".

But as far as I know the permissions for a repository is associated to the account, not the key. So if you are trying to limit the damage done by someone stealing your key, I believe you will need to create two accounts.


问:
Is there any design pattern to remove elements from a hash map?
In my application I keep track of the running threads via a hash map, in that way I can retrieve the correct thread and do any actions. The app evolved in a way that new threads are created and old threads must be destroyed. My concern is if I'm removing the elements of the hash correctly, or if there's any efficient pattern.

I'm developing in Java but I'll share the pseudo code:

```<code># HashMap mainHashmap already initialized
List toDelete = new List();
# First step, stop the threads
For (each element in HashMap)
{
  if (element.value is ThreadA)
  {
    element.value.stopThread();
    toDelete.add(element.key);
  }
 }
 # Then remove the element from the array
 For (each key in toDelete)
 {
    mainHashmap.remove(key);
 }
</code>```

Thanks

答:
A couple problems I can see with this are the following:

Stopping a thread like this is dangerous since you have no idea what it is doing in that particular moment.  Usually in a situation like this you'd send it a message asking it to stop when it's convenient, and the thread can stop in its own way (closing resources and connections, etc.).  Once each thread is stopped (when the callback indicating that it has stopped is called), then you can take the proper action of removing it from your hash map.

The second problem is a little more subtle.  I see no locks here, so I have to assume there are none.  You have to be sure that this method cannot be run while another thread is running it or you get all sorts of problems which seem to happen only once in a while in random moments.  In general, any access to this hash map should be locked or should not be public and the methods you use to access it are locked.

If the threads being run are your own, and you're fairly confident that these threads can be stopped on a dime, then #1 is not a problem, however know that it is an anti-pattern.  Most languages support stopping a thread abruptly only because it should still exist as a last resort option, but you would normally ask nicely if the thread could please stop for you.  If the thread ignores the request (especially these threads are not running code you've made yourself), you can then consider the possibility of outright stopping the thread.

I can't get too specific because it really depends on the language that you're using, but most languages have a proper "done" method which gets executed upon finish (or halt), and you could take advantage of this method by calling the thread pool with that instance to indicate that the thread is stopped and can be removed.


问:
What are the worst false economies in software development?
What are the worst false economies (that is ways of saving money that ultimately cost more than they save) prevalent in the software industry and how do you combat them?</p>

答: "Throw (enough) bodies at the problem" may still be used in some places, unfortunately.  Brook's Law does counter this from The Mythical Man-Month, though some require experience to learn this lesson.  Generally this isn't something within my power to stop as management may believe the false statement about adding people and not having to pay a price for it.


问:
How did they debug segmentation faults before protected memory?
Now, when I make a programming mistake with pointers in C, I get a nice segmentation fault, my program crashes and the debugger can even tell me where it went wrong.

How did they do that in the time when memory protection wasn't available? I can see a DOS programmer fiddling away and crashing the entire OS when he made a mistake. Virtualization wasn't available, so all he could do was restart and retry. Did it really go like that?

答:
Once I was working on bugfixing on a then famous Windows 3.1 Presentation software.

I had a bug which, when it occurred, caused the Blue Screen of Death.

The bug only occurred when a certain loop had been executed over 1000 times. I used the advanced features of the debugger to let a break point pass 1000 times and then I carefully stepped through the program. Every time I went too far or skipped over a function call which contained the bug Windows Blue Screened.

Finally, after several days of work, I narrowed it down to a function that was running out of memory and instead of displaying an error message, appended the error message to a buffer. With every subsequent iteration it trashed more memory until something crucial was overwritten and Windows was trashed.

Debugging skills and perseverance was the solution.


问:
Feature boundaries in functional programming
I very much enjoy the functional programming paradigm, but I am still not sure how to go about designing a small/medium project with it.

When using OO, I have a set of labelled entities (classes) with clearly defined boundaries. I can reason about stuff like:

what is this class doing?

should I put this code inside or outside a class?

should I split this class in two?

how would a client like to use this class?

So one big benefit of classes is that they provide boundaries for a piece of functionality. I find that this helps a lot when designing an application.

In functional programming, everything seems to be about composing and abstracting functions and data structures. Type classes in haskell are mainly there to offer polymorphism. Same for prototypes in clojure.

When designing an application written in a functional style, what is a good "unit of feature" one can define, label, and reason about?

答:
Actually, it doesn't have to be that different.

You need to identify the core data structures you need to work with. (That's what classes are in OOP). You write functions that deal with various aspects of that data structure, and group it in a module, or compilation unit.

Finally, you use the functions and data you have in other parts of your program.

Of course, the questions you're asking sound a bit different in FP:

What is this data structure doing? Nothing, it just is. Since you (hopefully) write code as pure as possible, only minimal parts of your code are actually doing something.

Should I put this code inside or outside the data structure? This is merely a syntactical question. In languages like Haskell, you have no choice: outside.

Should I split this class in two? This is a hard question, and it is independent of programming paradigm. Yet, in FP, you tend naturally to do things "bottom up", so you start out with easy, almost trivial data and combine that into more complex.

How would a client like to use this? Through the functions provided (same as OOP).


问:
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?

答: Certainly -- why would visual studio's fundamental unit be a solution if this weren't the case?</p>


问:
What's the difference between recursion and corecursion?
What's the difference between these?

Recursion

Corecursion

On Wikipedia, there is little information and no clear code explaining these terms.

What are some very simple examples explaining these terms?

How is corecursion the dual of recursion?

Are there any classic corecusive algorithms?

答:
Basically, corecursion is recursion accumulator-style, building its result on the way forward from the starting case, whereas regular recursion builds its result on the way back from the base case.

(speaking Haskell now). That's why foldr (with a strict combining function) expresses recursion, and foldl' (with strict comb. f.) / scanl/ until/ iterate/ unfoldr/ etc. express corecursion. Corecursion is everywhere. foldr with non-strict comb. f. expresses tail recursion modulo cons.

And Haskell's guarded recursion is just like tail recursion modulo cons.

This is recursion:

```<code>fib n | n==0 = 0
      | n==1 = 1
      | n>1  = fib (n-1) + fib (n-2)

fib n = snd $ g n
  where
    g n | n==0 = (1,0)
        | n>0  = let { (b,a) = g (n-1) } in (b+a,b)

fib n = snd $ foldr (\_ (b,a) -> (b+a,b)) (1,0) [n,n-1..1]
</code>```

(read $ as "of"). This is corecursion:

```<code>fib n = g (0,1) 0 n where
  g n (a,b) i | i==n      = a
              | otherwise = g n (b,a+b) (i+1)

fib n = fst.snd $ until ((==n).fst) (\(i,(a,b)) -> (i+1,(b,a+b))) (0,(0,1))
      = fst $ foldl (\(a,b) _ -> (b,a+b)) (0,1) [1..n]
      = fst $ last $ scanl (\(a,b) _ -> (b,a+b)) (0,1) [1..n]
      = fst (fibs!!n)  where  fibs = scanl (\(a,b) _ -> (b,a+b)) (0,1) [1..]
      = fst (fibs!!n)  where  fibs = iterate (\(a,b) -> (b,a+b)) (0,1)
      = (fibs!!n)  where  fibs = unfoldr (\(a,b) -> Just (a, (b,a+b))) (0,1)
      = (fibs!!n)  where  fibs = 0:1:map (\(a,b)->a+b) (zip fibs $ tail fibs)
      = (fibs!!n)  where  fibs = 0:1:zipWith (+) fibs (tail fibs)
      = (fibs!!n)  where  fibs = 0:scanl (+) 1 fibs
      = .....
</code>```

Folds: http://en.wikipedia.org/wiki/Fold_(higher-order_function)

Body:
Basically, corecursion is recursion accumulator-style, building its result on the way forward from the starting case, whereas regular recursion builds its result on the way back from the base case.

(speaking Haskell now). That's why foldr (with a strict combining function) expresses recursion, and foldl' (with strict comb. f.) / scanl/ until/ iterate/ unfoldr/ etc. express corecursion. Corecursion is everywhere. foldr with non-strict comb. f. expresses tail recursion modulo cons.

And Haskell's guarded recursion is just like tail recursion modulo cons.

This is recursion:

fib n | n==0 = 0
      | n==1 = 1
      | n>1  = fib (n-1) + fib (n-2)

fib n = snd $ g n
  where
    g n | n==0 = (1,0)
        | n>0  = let { (b,a) = g (n-1) } in (b+a,b)

fib n = snd $ foldr (\_ (b,a) -> (b+a,b)) (1,0) [n,n-1..1]

(read $ as "of"). This is corecursion:

fib n = g (0,1) 0 n where
  g n (a,b) i | i==n      = a
              | otherwise = g n (b,a+b) (i+1)

fib n = fst.snd $ until ((==n).fst) (\(i,(a,b)) -> (i+1,(b,a+b))) (0,(0,1))
      = fst $ foldl (\(a,b) _ -> (b,a+b)) (0,1) [1..n]
      = fst $ last $ scanl (\(a,b) _ -> (b,a+b)) (0,1) [1..n]
      = fst (fibs!!n)  where  fibs = scanl (\(a,b) _ -> (b,a+b)) (0,1) [1..]
      = fst (fibs!!n)  where  fibs = iterate (\(a,b) -> (b,a+b)) (0,1)
      = (fibs!!n)  where  fibs = unfoldr (\(a,b) -> Just (a, (b,a+b))) (0,1)
      = (fibs!!n)  where  fibs = 0:1:map (\(a,b)->a+b) (zip fibs $ tail fibs)
      = (fibs!!n)  where  fibs = 0:1:zipWith (+) fibs (tail fibs)
      = (fibs!!n)  where  fibs = 0:scanl (+) 1 fibs
      = .....

Folds: http://en.wikipedia.org/wiki/Fold_(higher-order_function)


答:
This isn't really an answer because of the following constraint from a comment...

Because I am implementing an interface this is not possible, there are several other implementations and my class must be compatible with the interface.

However, it might be an answer for someone else, so...

One option is to provide one getter and setter for each type and to use a parameter to identify which property. I can think of two ways to handle this...

Use an enumerate to provide all your property names, and store those properties in an array.

Use a separate struct to define all the member data, possibly as a public member of your class. Store the properties using in a private instance of that struct inside your class. Pass member pointers to your getters and setters to identify the property.

Either way allows the getters and setters to handle particular properties specially if needed. The member pointer method is only really mentioned for completeness, though - I'd prefer the enumerate method.

Once you can identify which property using a parameter, you still need different getters and setters for each property datatype. This can be avoided by specifying your getter and setter as member template functions. You still need some checks, though, to ensure that the property for the current call has the correct type. This is actually easier if you used the member pointer approach (the template can require that the member type for the member pointer matches the get/set type) though you'll probably get other problems later.

The most obvious case where something like this is justified is if you're developing a RAD-style tool.


答:
Incredibly handy while coding:

```<code>M-; : comment-dwim
</code>```

comment-dwim will toggle commenting on the current region; commenting if it's not commented, and vice versa.  Your current language mode lets emacs know how to do the commenting.

By default, if there's no active region and there's text on the line, it will insert a comment at the end of the line.  Personally, I prefer to have it comment the entire current line, which this accomplishes:

```<code>      ;; Original idea from
      ;; http://www.opensubscriber.com/message/emacs-devel@gnu.org/10971693.html
      (defun comment-dwim-line (&optional arg)
        "Replacement for the comment-dwim command.
        If no region is selected and current line is not blank and we are not at the end of the line,
        then comment current line.
        Replaces default behaviour of comment-dwim, when it inserts comment at the end of the line."
          (interactive "*P")
          (comment-normalize-vars)
          (if (and (not (region-active-p)) (not (looking-at "[ \t]*$")))
              (comment-or-uncomment-region (line-beginning-position) (line-end-position))
            (comment-dwim arg)))
      (global-set-key "\M-;" 'comment-dwim-line)
</code>```

Stole it myself from http://www.emacswiki.org/emacs/CommentingCode

Title: What are the 'must know' Emacs commands?

Body:
I'm a fairly new convert to Emacs and I really love it as an editor, primarily because I keep finding new and super-useful commands. Are there any other programmer 'must known' commands missing from my list?</p>

```<code>M-x replace-string     - Find and replace a given string.
M-x goto-line          - Goto a specific line
M-x column-number-mode - Show the current column number in text bar
</code>```

Body:
Incredibly handy while coding:

M-; : comment-dwim

comment-dwim will toggle commenting on the current region; commenting if it's not commented, and vice versa.  Your current language mode lets emacs know how to do the commenting.

By default, if there's no active region and there's text on the line, it will insert a comment at the end of the line.  Personally, I prefer to have it comment the entire current line, which this accomplishes:

      ;; Original idea from
      ;; http://www.opensubscriber.com/message/emacs-devel@gnu.org/10971693.html
      (defun comment-dwim-line (&optional arg)
        "Replacement for the comment-dwim command.
        If no region is selected and current line is not blank and we are not at the end of the line,
        then comment current line.
        Replaces default behaviour of comment-dwim, when it inserts comment at the end of the line."
          (interactive "*P")
          (comment-normalize-vars)
          (if (and (not (region-active-p)) (not (looking-at "[ \t]*$")))
              (comment-or-uncomment-region (line-beginning-position) (line-end-position))
            (comment-dwim arg)))
      (global-set-key "\M-;" 'comment-dwim-line)

Stole it myself from http://www.emacswiki.org/emacs/CommentingCode


答:
There was a three-part series on Embedded.com about X-macros, that gives a cleaner result than what the Wikipedia article describes.

```<code>#define EXPAND_AS_ENUMERATION(a,b) a,
#define EXPAND_AS_JUMPTABLE(a,b) b,
#define STATE_TABLE(ENTRY)     \
        ENTRY(STATE_0, func_0) \
        ENTRY(STATE_1, func_1) \
        ENTRY(STATE_2, func_2) \
        ...                    \
        ENTRY(STATE_X, func_X)

/* declare an enumeration of state codes */
enum{
    STATE_TABLE(EXPAND_AS_ENUMERATION)
    NUM_STATES
}

/* declare a table of function pointers */
p_func_t jumptable[NUM_STATES] = {
    STATE_TABLE(EXPAND_AS_JUMPTABLE)
}:
</code>```

Here's Part 1.

Here's Part 2.

They blew the in-article link to Part 3.  Here it is.

They require you to create a free account and profile, so they can spam you, if you want to read more than 2 articles per day.  (BOO!  HISS!)  The 2-article limit is a fairly recent change to what used to be a really good site.

Body:
There was a three-part series on Embedded.com about X-macros, that gives a cleaner result than what the Wikipedia article describes.

#define EXPAND_AS_ENUMERATION(a,b) a,
#define EXPAND_AS_JUMPTABLE(a,b) b,
#define STATE_TABLE(ENTRY)     \
        ENTRY(STATE_0, func_0) \
        ENTRY(STATE_1, func_1) \
        ENTRY(STATE_2, func_2) \
        ...                    \
        ENTRY(STATE_X, func_X)

/* declare an enumeration of state codes */
enum{
    STATE_TABLE(EXPAND_AS_ENUMERATION)
    NUM_STATES
}

/* declare a table of function pointers */
p_func_t jumptable[NUM_STATES] = {
    STATE_TABLE(EXPAND_AS_JUMPTABLE)
}:

Here's Part 1.

Here's Part 2.

They blew the in-article link to Part 3.  Here it is.

They require you to create a free account and profile, so they can spam you, if you want to read more than 2 articles per day.  (BOO!  HISS!)  The 2-article limit is a fairly recent change to what used to be a really good site.


问:
Boolean Method Naming Affirmative vs Negative
Should boolean methods always take the affirmative form, even when they will only ever be used in the negative form?

Say I wanted to check whether an entity exists before creating one, my argument is that the first form below is better than the second form, whether or not the method is ever used in the affirmative form.

In summary, I find if(!affirmative) easier to read than if(negative). I have a colleague who disagrees, thoughts?

First Form:

```<code>int entity_id = 42;
if(!entity_exists(entity_id)) create_entity(entity_id);
</code>```

Second Form:

```<code>int entity_id = 42;
if(entity_not_exist(entity_id)) create_entity(entity_id);
</code>```

答:
I agree that the affirmative is easier to read.  You might try

Third Form

```<code>int entity_id = 42;
if (entity_is_missing(entity_id)) create_entity(entity_id);
</code>```

or

Fourth Form

```<code>int entity_id = 42;
if (is_entity_missing(entity_id)) create_entity(entity_id);
</code>```

Body:
I agree that the affirmative is easier to read.  You might try

Third Form

int entity_id = 42;
if (entity_is_missing(entity_id)) create_entity(entity_id);

or

Fourth Form

int entity_id = 42;
if (is_entity_missing(entity_id)) create_entity(entity_id);


答:
Should boolean methods always take the affirmative form, even when
  they will only ever be used in the negative form?

Making rules about such things seems a little much -- I wouldn't want to see a guideline in a coding standards document that says thou shalt not use negative names for boolean properties. But as a matter of personal style, I think trying to keep the names positive could be a fine ideal. However, I think it's also good to avoid the need for that skinny and easily-missed !. One can often find ways to turn a negative name into a positive one:

accountHasCharges

accountIsClear (same as !accountHasCharges)

Clarity is the most important consideration, and a good reason for avoiding negative method names is that they can lead to double negatives or worse:

isComplete // okay

isNotComplete // !isComplete is usually better

isIncomplete // could make sense if 'incomplete' is a known state of the object

!isNotComplete // horrible

!isNotComplete == 0 // may lead to permanent vacation

Title: Boolean Method Naming Affirmative vs Negative

Body:
Should boolean methods always take the affirmative form, even when they will only ever be used in the negative form?

Say I wanted to check whether an entity exists before creating one, my argument is that the first form below is better than the second form, whether or not the method is ever used in the affirmative form.

In summary, I find if(!affirmative) easier to read than if(negative). I have a colleague who disagrees, thoughts?

First Form:

```<code>int entity_id = 42;
if(!entity_exists(entity_id)) create_entity(entity_id);
</code>```

Second Form:

```<code>int entity_id = 42;
if(entity_not_exist(entity_id)) create_entity(entity_id);
</code>```


问:
What are some good assignments for an introductory course, to reach today's students?
I periodically teach an introduction to programming course using Java. I want to give my students some exciting assignments that they can relate to or find interesting. At the very least, I want assignments that make sense and have an internal cohesion (for example, some very bad programming exercises seem contrived just so that you have to use the most recent programming construct covered).

To give you an idea of scope, here's what's being covered:

The assignments must be in Java, using some external library can be done, but it would need to be a simple API and not a full framework

Variables, Primitives and Strings

Console input and output

if, for, while

Arithmetic and logical operators

Simple graphics with line and shape drawing

Static methods

One-dimensional arrays

The students will not go into advanced topics (e.g., no recursion, no emphasis on inheritance). Thus, I'm not looking for complex projects: "Have them write a C compiler. I did it when I was 5 and it was the only way I learned!"

If you have ideas that are more advanced than the scope, please post them on the "Challenging" question linked below, and not this one.

Instead, what I'm looking for are interesting ideas that can be accomplished in a short program. For example:

Students can write a console version of the "Star Wars Name" Generator. This is effectively reading Strings and using substring, but I think it's fun. A similar variation would be a "Mad Libs" program. I used this one five years ago, and perhaps it's already "stale."

Using some trig supplied to them, students can draw regular polygons, and create interesting spiral shapes.

It's also not out of the question to use some simple animation class with most of the code supplied to them. And if you know a Twitter or Facebook service that can be accessed with a simple API, I would be very interested to know.

Please note that this question is different from the "Challenging Java questions for beginners" Question. I'm not looking for challenging per se, just interesting. I think if students work on something where they can easily answer "why would anyone ever want to program that?" then they will learn better.

Even simple problems like computing Miles per Gallon can be good. Although, if there's a way to update it to be more relevant, all the better. If you have an exercise from somewhere else (a book or a website), please cite the source.

To help you think about the typical freshman today, check out the Beloit Mindset list, for many examples that will surely make you feel old.

答:
Are all of the students in the class CS majors? My guess would be not. I would come up with assignments that are tailored to the majors in the class.

Examples:

Art students could write a program that takes the dimensions of a piece of canvas and a frame to calculate the amount of the canvas would be unavailable for painting (due to wrapping and stapling the canvas around the frame).

Econ students could calculate compound interest on an item.

Math students could choose problems from Project Euler.


问:
Quicksort and middle pivot
I am having a head ache understanding quicksort with middle pivot. I found lot of explanations about using left most or right most, but not many about a middle one.

Can I safely assume these?:

If left and right pointers meet at the same position, means that the
element at that position is at its final sorted position, so I can split the list in two without including that element (list1 length + list2 length = list length -1).

If left and right cross each other ( so left > right), means that no
element is at its final sorted position yet, so I must split the list in two using left and right as boundaries ( list1 length + list2 length = list length).

Is this right?

Thanks.

Update : The reason why I want to use a middle pivot, is to implement the "median algorithm" that increases QS speed. In this techique, the pivot is selected by approximating the list middle value: http://www.brpreiss.com/books/opus4/html/page500.html

答:
If the array is randomly shuffled, then in theory, one item in the list is as good as another, which means we can pick according to what is most convenient for us.  However, it should be said that a middle item would be better suited when the array is almost sorted (or otherwise quicksort would take O(n^2) time).  The reason for us to take the middle item is because it is likely representative of an item in which half is less and half is more in this case, and if it were random, it wouldn't make much difference otherwise, would it?

For the sake of this example, lets assume the array is randomly shuffled and so we arbitrarily name the right-most item in the list as the pivot.  Starting from the left, compare that number with the pivot.  If the number is less than the pivot, go to the next number.  If the number is greater than the pivot then you do the following:

If the pivot is not adjacent to the current number, then the pivot switches with its left neighbor.  The current number then swaps with the new slot created to the right of the new pivot.  If the pivot is adjacent to the current number, then it simply switches position with the current number.

Continue these steps until the index of the current number is equal to or greater than the index of the pivot.  Once this is done, perform a recursive call to a sublist of everything on the left side of the pivot and another call to a sublist of everything on the right side of the pivot (assuming length of sublist is 2 or greater).

Lets look at an example:

```<code>1 4 8 9 2 3 5
</code>```

5 is our pivot.  Starting with index 0, we get the following operations:

```<code>1 4 8 9 2 3 5
^           *
1 4 8 9 2 3 5
  ^         *
1 4 3 9 2 5 8
    ^     *
1 4 3 9 2 5 8
    ^     *
1 4 3 2 5 9 8
      ^ *
1 4 3 2 5 9 8
      ^ *
</code>```

End of first pass:  Recursive call to left-hand sublist:

```<code>1 4 3 2
^     *
1 3 2 4
  ^ *
1 2 3 4
  ^ *
</code>```

And recursive call to right-hand sublist:

```<code>9 8
^ *
8 9
* ^
</code>```

I hope that clarifies things.  Notice how if the current number was greater than the pivot, the current number did not increment.  This is because it is replaced with another number which has not yet been handled, and so it too must be checked.   I know it isn't exactly what you were doing with middle pivot, but this works just as well.

Title: Quicksort and middle pivot

Body:
If the array is randomly shuffled, then in theory, one item in the list is as good as another, which means we can pick according to what is most convenient for us.  However, it should be said that a middle item would be better suited when the array is almost sorted (or otherwise quicksort would take O(n^2) time).  The reason for us to take the middle item is because it is likely representative of an item in which half is less and half is more in this case, and if it were random, it wouldn't make much difference otherwise, would it?

For the sake of this example, lets assume the array is randomly shuffled and so we arbitrarily name the right-most item in the list as the pivot.  Starting from the left, compare that number with the pivot.  If the number is less than the pivot, go to the next number.  If the number is greater than the pivot then you do the following:

If the pivot is not adjacent to the current number, then the pivot switches with its left neighbor.  The current number then swaps with the new slot created to the right of the new pivot.  If the pivot is adjacent to the current number, then it simply switches position with the current number.

Continue these steps until the index of the current number is equal to or greater than the index of the pivot.  Once this is done, perform a recursive call to a sublist of everything on the left side of the pivot and another call to a sublist of everything on the right side of the pivot (assuming length of sublist is 2 or greater).

Lets look at an example:

1 4 8 9 2 3 5

5 is our pivot.  Starting with index 0, we get the following operations:

1 4 8 9 2 3 5
^           *
1 4 8 9 2 3 5
  ^         *
1 4 3 9 2 5 8
    ^     *
1 4 3 9 2 5 8
    ^     *
1 4 3 2 5 9 8
      ^ *
1 4 3 2 5 9 8
      ^ *

End of first pass:  Recursive call to left-hand sublist:

1 4 3 2
^     *
1 3 2 4
  ^ *
1 2 3 4
  ^ *

And recursive call to right-hand sublist:

9 8
^ *
8 9
* ^

I hope that clarifies things.  Notice how if the current number was greater than the pivot, the current number did not increment.  This is because it is replaced with another number which has not yet been handled, and so it too must be checked.   I know it isn't exactly what you were doing with middle pivot, but this works just as well.


问:
What needs to change for Software Engineering to become a formal profession?
Unlike other professions (such as Accounting, Law, Medicine, etc.), there is no profession-wide certification for Software Engineering.

I am well aware of the multitude of technology and methodology specific certifications that aim to serve as proof of specialisation and experience, but there is no public Software Engineering society / governing body that sets (and has the power to legally assess) generally accepted professional standards.

I understand that software is a dynamic beast - that is part art, part science - but I'm wondering whether Software Engineering has the potential to become a formal profession.

What needs to change for this to happen, and would it even be a good thing?

(If anybody knows of formal research into this topic I'd greatly appreciate references)

Update

I agree with many of the good points raised below regarding the current level of certification in Software Engineering. I also find it very interesting that some countries treat Software Engineering as a profession whilst others don't.

There does however seem to be a bit of shroud surrounding the term "formal profession", and how it would apply to Software Engineering. I think the key issue with Software Engineering - and the primary reason it is not a full-blown profession - is that if you're a certified Software Engineer, and - for example - some software you wrote for an elevator malfunctions and kills people, your certification and / or membership to a formal professional body won't get revoked.

Sure, your company might get sued for millions, and you personally might lose your job and earn a bad reference, but generally speaking, you personally are protected by the shield of limited liability as a result of being employed by said company. In other words, and as far as I know, there is no legal assessment / enforcement in place (unlike other formal professions and their governing societies) which have the mandate to officially bar you from trading once you've made a colossal stuff-up.

I quite liked the answer that touched on the fact that Software Engineering - as it stands - is a meritocracy, which doesn't need to be a formal profession, and that this is a good thing that shouldn't change. At the same time, I think we need to make a clear distinction between Software Engineers of mission-critical software versus developers of miscellaneous / non-critical software.

To those of you who work / have worked on mission-critical software - is there any personal liability? Surely there is a need for formal repercussions in the event of the Software Engineer making a costly mistake?

答:
Based on available information, I believe that Software Engineering is already a formal profession. It may not be widely accepted as such, but it is meeting the generally accepted criteria for the characteristics of a profession.

From Wikipedia's article on Profession:

There is considerable agreement about defining the characteristic
  features of a profession. They have a "professional association,
  cognitive base, institutionalized training, licensing, work autonomy,
  colleague control... (and) code of ethics,"[18] to which Larson then
  also adds, "high standards of professional and intellectual
  excellence," (Larson, p. 221) that "professions are occupations with
  special power and prestige," (Larson, p.x) and that they comprise "an
  exclusive elite group," (Larson, p. 20) in all societies.

This quotes Magali Sarfatti Larson's The Rise of Professionalism: A Sociological Analysis extensively. Searching for "characteristics of a profession" tend to lead similar results.

How does Software Engineering stack up against these characteristics?

Professional Association There are numerous professional associations for software engineers. The IEEE and more specifically the IEEE Computer Society serve professionals working in engineering around the world, with the IEEE Computer Society focusing specifically on computer and software engineers. The ACM is another professional organization for professionals working in computing, generally in the Americas. There's also the British Computer Society, which caters to various aspects of professions in information and communication technology, generally in the UK.

Cognitive Base The Software Engineering Body of Knowledge is sponsored by the IEEE, Boeing, National Research Council Canada, Raytheon, Construx Software, Canadian Council of Professional Engineers, the MITRE Corporation, NIST, Rational, SAP (for the 2004 version). It was started specifically as a step toward "making software engineering a legitimate engineering discipline and a recognized profession".

Institutionalized Training In the United States, Information Technology, Computer Science, and Software Engineering programs can be accredited by ABET. In Canada, Computer Science and Software Engineering programs are accredited by CIPS. These organizations define minimum standards and expected outcomes for students graduating from an accredited program to enable them to function in a professional environment. The IEEE also offers two exams based on the Software Engineering Body of Knowledge - the Certified Software Development Associate exam for undergraduates (or recently graduated undergraduates) and the Certified Software Development Professional exam for mid-career professionals.

Licensing As of April 2013, NCEES offers a Professional Engineering exam in Software Engineering. It is offered on a state-by-state basis in the United States. However, the Software Engineering PE exam is not currently offered by every state, and even fewer require the license. This article, published in the November/December 1999 issue of IEEE Software, discusses licensing requirements in the state of Texas and a brief discussion of licensing in Ontario and British Columbia, Canada and the UK. In Texas, a license is only required to work on the design, testing, or implementation of embedded or real-time systems that "require a detailed understanding of the engineered electrical or mechanical components" and for software systems for "mechanical devices, electrical devices, and power systems" - a relatively small amount of software development work. In states that offer licensing, the worst case scenario is disciplinary action, sanctions, or loss of your license should a client or employer file a complaint. However, the only real harm comes in states that require a license - unless the license is required to do the work, losing it doesn't mean anything.

Code of Ethics The ACM and IEEE Computer Society created a Software Engineering Code of Ethics and Professional Practice. In the United States, graduates of ABET accredited engineering programs, including Software Engineering programs, can also join the Order of the Engineer, which maintains a code of ethics that generally applies to professional engineers.

Work Autonomy, Colleague Control, High Standards of Professional and Intellectual Excellence These are frequently visible in an environment where software engineering is treated as an engineering discipline. That is to say that not all employers (or freelancers) treat software development as engineering.


答:
It never will, at least not entirely. Software is a medium, like paint. There are people who do industrial scale painting jobs of large structures, there are people that design new paints to perform to high standards, but there are also people who buy paint to do small scale jobs like paint their shed, and still others who might mix their own paint but just use it to paint pictures of cats. </p>

<p>Similarly while I could see a future where safety critical and/or financial software needs accredited engineers working on it, there will never be a need for people producing art or entertainment software. What needs to change to get safety or financial software required to have accredited engineers? Well much like those other professions it would require a law to mandate it. </p>

Title: What needs to change for Software Engineering to become a formal profession?

Body:
Unlike other professions (such as Accounting, Law, Medicine, etc.), there is no profession-wide certification for Software Engineering.

I am well aware of the multitude of technology and methodology specific certifications that aim to serve as proof of specialisation and experience, but there is no public Software Engineering society / governing body that sets (and has the power to legally assess) generally accepted professional standards.

I understand that software is a dynamic beast - that is part art, part science - but I'm wondering whether Software Engineering has the potential to become a formal profession.

What needs to change for this to happen, and would it even be a good thing?

(If anybody knows of formal research into this topic I'd greatly appreciate references)

Update

I agree with many of the good points raised below regarding the current level of certification in Software Engineering. I also find it very interesting that some countries treat Software Engineering as a profession whilst others don't.

There does however seem to be a bit of shroud surrounding the term "formal profession", and how it would apply to Software Engineering. I think the key issue with Software Engineering - and the primary reason it is not a full-blown profession - is that if you're a certified Software Engineer, and - for example - some software you wrote for an elevator malfunctions and kills people, your certification and / or membership to a formal professional body won't get revoked.

Sure, your company might get sued for millions, and you personally might lose your job and earn a bad reference, but generally speaking, you personally are protected by the shield of limited liability as a result of being employed by said company. In other words, and as far as I know, there is no legal assessment / enforcement in place (unlike other formal professions and their governing societies) which have the mandate to officially bar you from trading once you've made a colossal stuff-up.

I quite liked the answer that touched on the fact that Software Engineering - as it stands - is a meritocracy, which doesn't need to be a formal profession, and that this is a good thing that shouldn't change. At the same time, I think we need to make a clear distinction between Software Engineers of mission-critical software versus developers of miscellaneous / non-critical software.

To those of you who work / have worked on mission-critical software - is there any personal liability? Surely there is a need for formal repercussions in the event of the Software Engineer making a costly mistake?

Body:
It never will, at least not entirely. Software is a medium, like paint. There are people who do industrial scale painting jobs of large structures, there are people that design new paints to perform to high standards, but there are also people who buy paint to do small scale jobs like paint their shed, and still others who might mix their own paint but just use it to paint pictures of cats.

Similarly while I could see a future where safety critical and/or financial software needs accredited engineers working on it, there will never be a need for people producing art or entertainment software. What needs to change to get safety or financial software required to have accredited engineers? Well much like those other professions it would require a law to mandate it.


问:
Handling compiler bugs in Continuous Integration
I believe that warnings should be treated as errors. If you start ignoring warnings you'll start missing "important" warnings among the "unimportant" ones. So my Continuous Integration system fails a build if there are warnings.

One of my compilers has a bug that causes it to raise a warning when it shouldn't. My code is valid and compiles correctly, and I can't disable this particular warning.

How should my CI system handle this? Should I temporarily disable "warnings as errors", until the compiler is patched?

答:
For Visual C++ 2012 (and probably earlier) I use

```<code>#pragma warning(push)
#pragma warning(disable: XYZW)
  // Code causing spurious XYZW warning here.
#pragma warning(pop)
</code>```

It's not particularly pretty and sometimes you have to be rather broad in the scope of the warning, e.g. when inside a shared library, deriving from a template class that doesn't have an export statement, I haven't found any other way than disabling that warning for the whole file.

I only do this when the warning appears in the build logs, I've double-checked that it is spurious, and I have determined the absolute minimum amount of code necessary to disable the warning for so that it goes away.  I do not disable the warning globally for the whole project.

Body:
For Visual C++ 2012 (and probably earlier) I use

#pragma warning(push)
#pragma warning(disable: XYZW)
  // Code causing spurious XYZW warning here.
#pragma warning(pop)

It's not particularly pretty and sometimes you have to be rather broad in the scope of the warning, e.g. when inside a shared library, deriving from a template class that doesn't have an export statement, I haven't found any other way than disabling that warning for the whole file.

I only do this when the warning appears in the build logs, I've double-checked that it is spurious, and I have determined the absolute minimum amount of code necessary to disable the warning for so that it goes away.  I do not disable the warning globally for the whole project.


问:
Task Planning on an Agile Team
At the beginning of each sprint our team will pull in a handful of user stories and then, one by one, write slightly more detailed tasks for them as well as assign specific hours to each task.

Having individual tasks helps us establish our sprint burn-down by having a specific total number of hours up front, as well as make it more feasible to keep track of who's working on what and what all has been completed.

However, I recently read that some mature Agile teams have eliminated the use of writing tasks altogether and head right into their sprints armed only with their user stories as the modularized sources of work for the sprint.

I'm having a hard time seeing how eliminating task planning could still provide an Agile team with small enough units of work so as to keep the sprint organized and transparent. Has anyone here tried or use this approach and if so how do you keep track of exactly who is working on what?

答:
I've worked on the 'big picture' thing with an Agile team before - work beautifully. We spent all our time doing work, rather than doing the process planning and task creation and project organisation.

You should try it, its amazing what you can do when you step away from the proscribed processes.

Naturally, it depends on you though - if you need tasks to make you productive, then keep doing them. If you don't need tasks to be productive, scrap them immediately. Isn't that the spirit of Agile?

Title: Task Planning on an Agile Team


问:
Are there any well-known quantitative approaches to evaluate a particular design whether it satisfies or violates the SOLID design principles?
I designed an application framework by considering the SOLID design principles and supported by design patterns. However, I wonder if there are any automated tools or well-known approaches to evaluate whether the SOLID design principles are satisfied or violated in the proposed design?</p>

答:
Even if it were possible, I think the effort might be wasted. What you can do is measure the impact of adherence to the principles has on the maintainability of your code. Coupling, cohesion, and cyclomatic complexity can all be measured by static analysis tools.

Also, if you're using .NET, you might be able to leverage StyleCop to create rules for adherence to certain guidelines. Again that might be more effort than it's worth. Either way, it can't hurt to use it.


答:
When the compiler 'misbehaves' one could wrap it just as any other misbehaving application.

Depending on the build script and how it works, this can be done in one of two ways.

The ideal way, however, is to address the in the code rather than the compiler (thus the 0th way).  If it is possible, this should be investigated first as it minimizes differences in build environments which can make it difficult to do a build on a different system.

Way 0 - ignore it from the compiler

This option should certainly be considered because while it makes the code slightly messier, it keeps the number of 'moving parts' in the build process lower, and thus less likely to have errors.

This has the significant advantage of that it keeps the build environment the same (compared to way 2).  One wouldn't want to go and create a new Jenkins server and then have a bit of WTF time spent trying to figure out why it breaks the build to discover on the old build server, the compiler had a wrapper that the new one doesn't.

This is compiler and language dependant.  MadKeithV mentioned the approach for Visual C++.

The SO question Selectively disable GCC warnings for only part of a translation unit? goes into it a bit for gcc which can be "summarized" as:

```<code>#pragma GCC diagnostic error "-Wuninitialized"
    foo(a);         /* error is given for this one */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
    foo(b);         /* no diagnostic for this one */
#pragma GCC diagnostic pop
    foo(c);         /* error is given for this one */
#pragma GCC diagnostic pop
    foo(d);         /* depends on command line options */
</code>```

The docs for this can be seen in GCC 4.6 diagnostic pragmas

Clang uses a similar approach, though instead of GCC, its clang as specified in Ignore all warnings in a specific file using LLVM/Clang:

```<code>#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmultichar"

char b = 'df'; // no warning.

#pragma clang diagnostic pop
</code>```

One can see that this could get very confusing if compiling the same source with gcc and clang...

In Java, one has the @SupressWarnings annotation.

Way 1 - filter through a pipe

```<code>gcc args file.c | supresswarning.pl
</code>```

The supresswarning.pl script would then filter the output from gcc to identify if that specific error occurred and just take it out of the output. One could also pass in the file.c to the script and identify the line number where the annotation or macro occurs to avoid filtering real errors.

Note that this isn't quite as simple as it is shown - errors may come out on standard error rather than standard out, and the pipe would need to be adjusted appropriately.  To maintain it that errors go out on the correct file handle, suppresswarning.pl would need to identify the errors and write them again to the proper file handle.

Way 2 - filter though a wrapper

If the build script doesn't like dealing with compilers in this way (think ant and maven style environments where it invokes the compiler itself), one could write a wrapper.

A wrapper for javac would call itself javac, invoke javac_real (the real javac that has been renamed), pass all of the options through to the real invocation and process the output and adjust return code and messages itself.

This can also be used the other way (to make it error out on warnings) if the compiler is returning warnings, and you want to fail on warnings, and the CI environment will do it if the compiler returns a non-zero exit code... but it isn't.  The wrapper script could examine the output of the compiler and again, adjust the return code of the wrapper to be appropriate to the environment.

Title: Handling compiler bugs in Continuous Integration

Body:
I believe that warnings should be treated as errors. If you start ignoring warnings you'll start missing "important" warnings among the "unimportant" ones. So my Continuous Integration system fails a build if there are warnings.

One of my compilers has a bug that causes it to raise a warning when it shouldn't. My code is valid and compiles correctly, and I can't disable this particular warning.

How should my CI system handle this? Should I temporarily disable "warnings as errors", until the compiler is patched?

Body:
When the compiler 'misbehaves' one could wrap it just as any other misbehaving application.

Depending on the build script and how it works, this can be done in one of two ways.

The ideal way, however, is to address the in the code rather than the compiler (thus the 0th way).  If it is possible, this should be investigated first as it minimizes differences in build environments which can make it difficult to do a build on a different system.

Way 0 - ignore it from the compiler

This option should certainly be considered because while it makes the code slightly messier, it keeps the number of 'moving parts' in the build process lower, and thus less likely to have errors.

This has the significant advantage of that it keeps the build environment the same (compared to way 2).  One wouldn't want to go and create a new Jenkins server and then have a bit of WTF time spent trying to figure out why it breaks the build to discover on the old build server, the compiler had a wrapper that the new one doesn't.

This is compiler and language dependant.  MadKeithV mentioned the approach for Visual C++.

The SO question Selectively disable GCC warnings for only part of a translation unit? goes into it a bit for gcc which can be "summarized" as:

#pragma GCC diagnostic error "-Wuninitialized"
    foo(a);         /* error is given for this one */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuninitialized"
    foo(b);         /* no diagnostic for this one */
#pragma GCC diagnostic pop
    foo(c);         /* error is given for this one */
#pragma GCC diagnostic pop
    foo(d);         /* depends on command line options */

The docs for this can be seen in GCC 4.6 diagnostic pragmas

Clang uses a similar approach, though instead of GCC, its clang as specified in Ignore all warnings in a specific file using LLVM/Clang:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmultichar"

char b = 'df'; // no warning.

#pragma clang diagnostic pop

One can see that this could get very confusing if compiling the same source with gcc and clang...

In Java, one has the @SupressWarnings annotation.

Way 1 - filter through a pipe

gcc args file.c | supresswarning.pl

The supresswarning.pl script would then filter the output from gcc to identify if that specific error occurred and just take it out of the output. One could also pass in the file.c to the script and identify the line number where the annotation or macro occurs to avoid filtering real errors.

Note that this isn't quite as simple as it is shown - errors may come out on standard error rather than standard out, and the pipe would need to be adjusted appropriately.  To maintain it that errors go out on the correct file handle, suppresswarning.pl would need to identify the errors and write them again to the proper file handle.

Way 2 - filter though a wrapper

If the build script doesn't like dealing with compilers in this way (think ant and maven style environments where it invokes the compiler itself), one could write a wrapper.

A wrapper for javac would call itself javac, invoke javac_real (the real javac that has been renamed), pass all of the options through to the real invocation and process the output and adjust return code and messages itself.

This can also be used the other way (to make it error out on warnings) if the compiler is returning warnings, and you want to fail on warnings, and the CI environment will do it if the compiler returns a non-zero exit code... but it isn't.  The wrapper script could examine the output of the compiler and again, adjust the return code of the wrapper to be appropriate to the environment.


答:
At least the S, O, and L in SOLID stand for semantic principles - one has to understand what the code does and what its purpose is to validate those things. I am pretty sure A.I. research has not gotten so far (at least, not yet) to make a computer really understand the meaning of programs. So don't expect anything automatic nowadays.

But you have also asked for "well-known approaches" - well, there is one very well-known approach, it is called "code review by an expert" and I am pretty sure you have heard of it ;-) So the best suggestion I can give you is to post some parts of your code at https://codereview.stackexchange.com/ and discuss it there.

Title: Are there any well-known quantitative approaches to evaluate a particular design whether it satisfies or violates the SOLID design principles?

Body: I designed an application framework by considering the SOLID design principles and supported by design patterns. However, I wonder if there are any automated tools or well-known approaches to evaluate whether the SOLID design principles are satisfied or violated in the proposed design?</p>


答:
Our team actually does it both ways, depending on the user story.  Well, we actually still do one big task called "Fix it" or something, so the burndown chart will still work on our tool.

The difference for us is how easy it is to predict the tasks in advance.  For example, we do embedded software, and whenever we have a brand new board to get booting it's very difficult to predict the individual parts, but by experience we know how long it usually takes for everything together.  One time the clocks might be perfect but some power rails are unstable, the next time it might be the other way around.

Also, some teams break their user stories down into smaller parts than others.  Our team averages around 12 per sprint.  Other teams at my company average 3 or 4 per sprint.  The smaller your stories, the less you need tasks.

It boils down to choosing what works best for the style of your individual team.  If you can't imagine working without tasks, that shouldn't make you feel inferior.  On the other hand, if you feel like tasks are a hindrance, you should feel free to discard them.

Title: Task Planning on an Agile Team

Body:
At the beginning of each sprint our team will pull in a handful of user stories and then, one by one, write slightly more detailed tasks for them as well as assign specific hours to each task.

Having individual tasks helps us establish our sprint burn-down by having a specific total number of hours up front, as well as make it more feasible to keep track of who's working on what and what all has been completed.

However, I recently read that some mature Agile teams have eliminated the use of writing tasks altogether and head right into their sprints armed only with their user stories as the modularized sources of work for the sprint.

I'm having a hard time seeing how eliminating task planning could still provide an Agile team with small enough units of work so as to keep the sprint organized and transparent. Has anyone here tried or use this approach and if so how do you keep track of exactly who is working on what?


问:
Resources for learning common algorithms by Lisp
Many books about algorithms and data structures are coded by imperative languages. Is there any book that can show functional programming languages can do the same thing or do them better?

In particular I am interested in sorting, searching, data structures and graph.

答:
A  Haskell-based book:

Algorithms: A Functional Programming Approach, by Fethi Rabhi and Guy Lapalme

ISBN 0-201-59604-0

http://www.iro.umontreal.ca/~lapalme/Algorithms-functional.html

Also, this one seems like a nice little paper. Available online, too:

Jamie Snape, Loopless Functional Algorithms,

Master's thesis, Computing Laboratory, University of Oxford, 2005, advised by Richard S. Bird

http://wwwx.cs.unc.edu/~snape/publications/msc/


问:
What to expect from a 'peer interview' for a new grad position?
I apologize if something like this has been asked, I did try to look for something similar.

I am graduating May 16th, and I applied for a position posted as '.NET Application Developer' requiring 1-2 years experience and a Bachelor's in CIS. I had the phone screen, which went well. They brought me in Friday for an interview with the head managers which consisted of a written 20 question test, and other behavioral like questions and oddball ones such as "How would you make an M&M?"

That seemed to go well too, they took me on a tour of the campus and said they usually will get back to the candidate, if they decide to proceed, in a week or so. Well, that following Monday at 9:00 am sharp they called me back for a third and final 'peer interview'. This is where I am stuck - I have no idea what to expect here? How do I prepare? Is this like the 'Hey let's see if you are culture fit" or "Lets put him through the paces with whiteboard coding" or what?

Any advice would be HIGHLY appreciated. I have been practicing whiteboard coding just in case, and will come in with a humble, "I want to learn from you guys" kind of attitude.

答:
If I were interviewing a graduate I'd mainly be looking to see how they think, how they approach problems etc. I wouldn't expect them to actually know a great deal (i.e. in terms of giving them a technical grilling), but I would need to satisfy myself that they could think rationally and learn.

For example, did you do some kind of final year project? I'd ask about this, what problems did you encounter, how did you overcome them, that kind of thing.

Possibly things like how do you think working professionally may be different to college. I'm thinking here stuff like quality, e.g. coding standards, code reviews, source control, testing...... I mean, presumably what you did at college was as a one-man band?

On top of all of this they will of course be asking themselves whether you would fit in. But they would have been asking themselves this from first the moment they met you, and they now want to meet you for a third time - so you must have given off positive vibes to get this far. So I wouldn't worry about this, just be yourself.

Dress smart, don't be late, and good luck!


答:
A widely established and accepted professional body for software developers/engineers/architects/etc would not be a good thing.

Currently, this is one of the few fields that can act as a meritocracy. As in, I don't care what degree you have (or if you have one at all), how much seniority you have, which languages you know, etc. It is relatively easy to figure out if you are a good developer or not, and at the end of the day that is the only thing that matters. i.e. Can you get things done?

Currently you are gauged by your ability, not by some accreditation that someone awarded you. And this is a fair, Good Thing (tm).


问:
What Http verb should the route to log out of your web app be?
Browser support issues aside, if you're being an Http/hateoas stickler what verbs should the request to log into/out of a site be?

DELETE would seem like the obvious choice but I'm not sure what the resource you're deleting would be.

答:
The common choice is POST, and it makes sense. The 'safe' verbs (GET, HEAD, OPTIONS, TRACE) are out, because they cannot have semantic side effects that change the observable state of the application (and logging in and out is such a state).

PUT and DELETE are theoretical possibilities; the resource you are creating (PUT) and removing (DELETE) would be the user's session. However, there are a few oddities about this: first of all, PUT and DELETE, while not safe like HEAD, are still supposed to be idempotent, that is, logging out several times in a row without logging back in would have to be valid, and so would logging in again while still logged in. Furthermore, such a double login cannot alter the state of the application beyond what the first login does, which, considering things like session IDs and such, is problematic. Also, strictly speaking, the URL you are PUTting to is supposed to uniquely identify the resource you are pushing, so in order to be semantically correct, you'd have to PUT to http://example.com/sessions/a8edjn239sd8h2er instead of http://example.com/login, that is, a unique identifier for the session would have to be encoded in the URL - but then, the session ID is generated along with the session, so the ID does not exist yet until after successful login.

The semantics of POST are a much better fit: your login URL (say, http://example.com/login) identifies a resource (the application's 'login functionality') that you are about to "annotate", that is, it changes an aspect of that resource. Unlike PUT and DELETE, POST requests do not have to be idempotent, which means multiple identical POST requests can continue to change the application state - this is exactly what you want.

Wikipedia's description of the various verbs is actually quite revealing in this regard:

https://en.wikipedia.org/wiki/HTTP_Verbs#Request_methods


答:
HTTP is stateless, so you're never logging in/out of a website, those are just clever names we use for the cookie implementation.

What you actually do is GET an authentication token (cookie), after you POST authentication details. That your browser stores that cookie for you is just a convenience. Finally, after you're done with your authentication token, you POST that token to the server to let it know that it can be destroyed. Again, this all happens with cookies in the browser as a convenience.

If you want to be an HTTP stickler, your HTTP needs to be stateless (and maybe RESTful).

Title: What Http verb should the route to log out of your web app be?

Body:
Browser support issues aside, if you're being an Http/hateoas stickler what verbs should the request to log into/out of a site be?

DELETE would seem like the obvious choice but I'm not sure what the resource you're deleting would be.