问:
SQL W/ hibernate vs in-memory solution
I recently posted a question here: Methods to share memory or state across JVMs? and appreciate the answers.  However, as I read the code and learned the system better I learned I was over complicating the problem.  Only one of the JVM's really care about the dynamic data so there is no need to pass dynamic data across memory boundries.  However, we still have a problem that they are manually maintaining state between in-memory and sql; the manual code isn't perfect and doesn't protect against stale data, data races, etc etc and I want to remove it entirely one way or another so I can feel more secure about the overal stability.

Since only one JVM cares about dynamic data, and the dynamic data can be regenerated at bootup each time (with a small time penalty to do so) my inclination is to remove all the dynamic data from sql and just store everything in memory; why over complicate anything?

Howver, they liked the sql as a debugging tool.  This system is developed agile, it's on a live system but bugs and errors do come up due to the agile nature.  When that happens they ssh to the live system and debug it on the fly; often by viewing the database.  The SQL allows them to see the actual routes and pathing that are being used.  They can also see when a route looks wrong, change it, then restart the module so that the fixed path is loaded into memory and used from then on.  They like this ability to quickly fix bad routes don't want to lose it.

There is now talk of keeping the database but backing it with hybernate to avoid the nightmare of trying to keep JVM and sql sychronized manually.  There are some minor other gaines, but this is primarily so they can keep the sql and try to use it as a debug tool.

Something feels wrong about all of this, but I'm not entierly certain WHAT is so wrong about it.  If we droped the dynamic sql data I could partially emulate what they want by adding messages to print out the graph as it is, or to modify a graph on the fly, but obviously each message takes a bit of time to write.  Does keeping SQL rather then trying to write messages to allow changing of memory on the fly make sense?

I think using hibernate may make it a little harder to write our objects we use for generating and maintaining paths, having to keep the structor similar to a SQL database and all.  But I think my real issue is the idea of pushing changes to our in-memory state by changing our database.  That just feels dangerous to me; in much the same way improper encapsulation feels wrong.  I don't think I like the idea of fixing a broken route by just manually changing the route in sql feels safe.  But I don't know how to articulate why this all feels wrong.  Maybe I should be suggesting a better debugging solution?

So, am i right to worry or is hibernate really the best approch?

答:
What problems are you seeing in keeping your dynamic data in sync with the database?

The main benefit of Hibernate, being an object-relational mapping tool (ORM) is simplifying the mapping of rows in your database into domain objects. It does track the state of objects that were loaded from the database and can simplify committing those changes, but you'll still need to poll the database if you need to react to changes made there. In other words, I'm not sure how Hibernate is going to help with your problem, if I understand it correctly.

It sounds like your main concern is what happens if the data in memory gets out of sync with the database. Having a separate repository for the data does introduce that possibility, so another way to gain access to the in-memory state for debugging and corrections is to expose it through JMX MBeans; see the oracle docs for details. This would mean that the data only lives inside your running application, your developers could query the JMX interface to get the current state as needed, and when changes are made to an MBean, it could trigger system events (e.g. reloading a module) as needed.

By the way, the agile nature of your project's development doesn't cause bugs and errors to come up; they can be found in every software project.

Title: SQL W/ hibernate vs in-memory solution


问:
Should I test inherited methods?
Suppose I have a class Manager derived from a base class Employee, and that Employee has a method getEmail() that is inherited by Manager.  Should I test that the behaviour of a manager's getEmail() method is in fact the same as an employee's?

At the time these tests are written the behaviour will be the same, but of
course at some point in the future someone might override this method, change its behaviour, and therefore break my application.  However it seems a bit strange to essentially test for the absence of meddling code.

(Note that testing Manager::getEmail() method does not improve code coverage (or indeed any other code quality metrics (?)) until Manager::getEmail() is created/overridden.)

(If the answer is "Yes", some information about how to go about managing tests that are shared between base and derived classes would be useful.)

An equivalent formulation of the question:

If a derived class inherits a method from a base class, how do you express (test) whether you're expecting the inherited method to:

Behave in exactly the same way as the base does right now (if the behaviour of the base changes, the behaviour of the derived method doesn't);

Behave exactly the same way as the base for all time (if the behaviour of the base class changes, the behaviour of the derived class changes as well); or

Behave however it wants to (you don't care about the behaviour of this method because you never call it).

答:
Robert Martin's rules for TDD are:

You are not allowed to write any production code unless it is to make a failing unit test pass.

You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.

You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

If you follow these rules, you wouldn't be able to get into a position to ask this question.  If the getEmail method needs to be tested, it would have been tested.

ContentLicense: CC BY-SA 3.0

Title: Should I test inherited methods?


问:
Why shouldn't a GET request change data on the server?
All over the internet, I see the following advice:

A GET should never change data on the server- use a POST request for that

What is the basis for this idea?

If I make a php service which inserts data in the database, and pass it parameters in the GET query string, why is that wrong? (I am using prepared statements, to take care of SQL Injection). Is a POST request in some way more secure?

Or is there some historic reason for this? If so how valid is this advice today?

答:
For your CRUD operations in a database-centric application use the following schema:

Use HTTP GET for Read Operations (SQL SELECT)

Use HTTP PUT for Update Operations (SQL UPDATE)

Use HTTP POST for Create Operations (SQL INSERT)

Use HTTP DELETE for Delete Operations (SQL DELETE)


问:
Where does the reporting function fit into Enterprise Software development Best Practices
At my company, I develop and maintain all the operational reporting used by management to run the business.  There is no reporting position on the application development team.  I've taken it upon myself to step in and attend design review meetings to give input to the development team on how changes will impact reporting, consult on how modify designs to avoid impacting existing reports and what I will need in new development to be able to report on the data.  It's been my experience that reporting is a key functional position on an enterprise application development team.  I'm hoping to find some documentation that supports that concept as an industry standard or Best Practice.  Can anyone help me there?</p>

答:
If you're describing reporting functionality that generates reports on the basis of data that the systems generate, then it sounds like you're describing BAM or "Business Activity Monitoring".

Searching the web provided these two links, although I'm sure you can find many more by searching for some combination of "best practices", "BAM" and "Business Activity Monitoring."

MSDN forum post on BAM best practices

InformationWeek article on BAM (2008)

BAM is often used together with a BPM engine, but that's only because BPM engines generate precisely the type of information that's meant for BAM.


答:
Yes, you should test inherited methods because in the future they may get overridden. Also, inherited methods may call virtual methods that are overridden, which would change the behavior of the non-overridden inherited method.

The way I test this is by creating an abstract class to test the (possibly abstract) base class or interface, like this (in C# using NUnit):

```<code>public abstract class EmployeeTests
{
    protected abstract Employee CreateInstance(string name, int age);

    [Test]
    public void GetEmail_ReturnsValidEmailAddress()
    {
        // Given
        var sut = CreateInstance("John Doe", 20);

        // When
        string email = sut.GetEmail();

        // Then
        Assert.IsTrue(Helper.IsValidEmail(email));
    }
}
</code>```

Then, I have a class with tests specific to the Manager, and integrate the employee's tests like this:

```<code>[TestFixture]
public class ManagerTests
{
    // Other tests.

    [TestFixture]
    public class ManagerEmployeeTests : EmployeeTests
    {
        protected override Employee CreateInstance(string name, int age);
        {
            return new Manager(name, age);
        }
    }
}
</code>```

The reason I can so this is Liskov's substitution principle: the tests of Employee should still pass when passed a Manager object, since it derives from Employee. So I have to write my tests only once, and can verify they work for all possible implementstions of the interface or base class.

Title: Should I test inherited methods?

Body:
Suppose I have a class Manager derived from a base class Employee, and that Employee has a method getEmail() that is inherited by Manager.  Should I test that the behaviour of a manager's getEmail() method is in fact the same as an employee's?

At the time these tests are written the behaviour will be the same, but of
course at some point in the future someone might override this method, change its behaviour, and therefore break my application.  However it seems a bit strange to essentially test for the absence of meddling code.

(Note that testing Manager::getEmail() method does not improve code coverage (or indeed any other code quality metrics (?)) until Manager::getEmail() is created/overridden.)

(If the answer is "Yes", some information about how to go about managing tests that are shared between base and derived classes would be useful.)

An equivalent formulation of the question:

If a derived class inherits a method from a base class, how do you express (test) whether you're expecting the inherited method to:

Behave in exactly the same way as the base does right now (if the behaviour of the base changes, the behaviour of the derived method doesn't);

Behave exactly the same way as the base for all time (if the behaviour of the base class changes, the behaviour of the derived class changes as well); or

Behave however it wants to (you don't care about the behaviour of this method because you never call it).

Body:
Yes, you should test inherited methods because in the future they may get overridden. Also, inherited methods may call virtual methods that are overridden, which would change the behavior of the non-overridden inherited method.

The way I test this is by creating an abstract class to test the (possibly abstract) base class or interface, like this (in C# using NUnit):

public abstract class EmployeeTests
{
    protected abstract Employee CreateInstance(string name, int age);

    [Test]
    public void GetEmail_ReturnsValidEmailAddress()
    {
        // Given
        var sut = CreateInstance("John Doe", 20);

        // When
        string email = sut.GetEmail();

        // Then
        Assert.IsTrue(Helper.IsValidEmail(email));
    }
}

Then, I have a class with tests specific to the Manager, and integrate the employee's tests like this:

[TestFixture]
public class ManagerTests
{
    // Other tests.

    [TestFixture]
    public class ManagerEmployeeTests : EmployeeTests
    {
        protected override Employee CreateInstance(string name, int age);
        {
            return new Manager(name, age);
        }
    }
}

The reason I can so this is Liskov's substitution principle: the tests of Employee should still pass when passed a Manager object, since it derives from Employee. So I have to write my tests only once, and can verify they work for all possible implementstions of the interface or base class.


问:
Optimal Data Structure for our own API
I'm in the early stages of writing an Emacs major mode for the Stack Exchange network; if you use Emacs regularly, this will benefit you in the end.

In order to minimize the number of calls made to Stack Exchange's API (capped at 10000 per IP per day) and to just be a generally responsible citizen, I want to cache the information I receive from the network and store it in memory, waiting to be accessed again.  I'm really stuck as to what data structure to store this information in.

Obviously, it is going to be a list.  However, as with any data structure, the choice must be determined by what data is being stored and what how it will be accessed.  What, I would like to be able to store all of this information in a single symbol such as stack-api/cache.  So, without further ado, stack-api/cache is a list of conses keyed by last update:

```<code>`(<csite> <csite> <csite>)
</code>```

where <csite> would be

```<code>(1362501715 . <site>)
</code>```

At this point, all we've done is define a simple association list.  Of course, we must go deeper.

Each <site> is a list of the API parameter (unique) followed by a list questions:

```<code>`("codereview" <cquestion> <cquestion> <cquestion>)
</code>```

Each <cquestion> is, you guessed it, a cons of questions with their last update time:

```<code>`(1362501715 <question>) (1362501720 . <question>)
</code>```

<question> is a cons of a question structure and a list of answers (again, consed with their last update time):

```<code>`(<question-structure> <canswer> <canswer> <canswer>
</code>```

and `

```<code>`(1362501715 . <answer-structure>)
</code>```

This data structure is likely most accurately described as a tree, but I don't know if there's a better way to do this considering the language, Emacs Lisp (which isn't all that different from the Lisp you know and love at all).  The explicit conses are likely unnecessary, but it helps my brain wrap around it better.  I'm pretty sure a <csite>, for example, would just turn into

```<code>(<epoch-time> <api-param> <cquestion> <cquestion> ...)
</code>```

Concerns:

Does storing data in a potentially huge structure like this have any performance trade-offs for the system?  I would like to avoid storing extraneous data, but I've done what I could and I don't think the dataset is that large in the first place (for normal use) since it's all just human-readable text in reasonable proportion. (I'm planning on culling old data using the times at the head of the list; each  inherits its last-update time from its children and so-on down the tree.  To what extent this cull should take place: I'm not sure.)

Does storing data like this have any performance trade-offs for that which must use it?  That is, will set and retrieve operations suffer from the size of the list?

Do you have any other suggestions as to what a better structure might look like?

答:
Emacs lisp is not optimized for data processing; you might find it advantageous to use a Common Lisp for the engine and Emacs for presentation only.

Even if you decide to stick with Emacs Lisp, I suggest that you use structured data (eieio) instead of lists, and hash tables instead of alists.

OwnerDisplayName: vermiculus

Title: Optimal Data Structure for our own API


问:
Is it wrong to use a boolean parameter to determine behavior?
I have seen a practice from time to time that "feels" wrong, but I can't quite articulate what is wrong about it. Or maybe it's just my prejudice. Here goes:

A developer defines a method with a boolean as one of its parameters, and that method calls another, and so on, and eventually that boolean is used, solely to determine whether or not to take a certain action. This might be used, for example, to allow the action only if the user has certain rights, or perhaps if we are (or aren't) in test mode or batch mode or live mode, or perhaps only when the system is in a certain state.

Well there is always another way to do it, whether by querying when it is time to take the action (rather than passing the parameter), or by having multiple versions of the method, or multiple implementations of the class, etc. My question isn't so much how to improve this, but rather whether or not it really is wrong (as I suspect), and if it is, what is wrong about it.

答:
Definitely a code smell. If it doesn't violate Single Responsibility Principle then it probably violates Tell, Don't Ask. Consider:

Can you summarize what your method does without using conjunctions (and, but, etc.)?

Are there subparts of your method that could easily be grouped into another smaller method? (This includes complex creation of a local variable.)

If your flag determines which method to call on a parameter, is your parameter doing too much?

Does this method belong in one of your parameters? (You might notice if it picks apart instance variables in your parameter using getters/setters.)

If it turns out not to violate one of those two principles, you should still use an enum. Boolean flags are the boolean equivalent of magic numbers. foo(false) makes as much sense as bar(42). Enums can be useful for Strategy Pattern and have the flexibility of letting you add another strategy. (Just remember to name them appropriately.)

Your particular example especially bothers me. Why is this flag passed through so many methods? This sounds like you need to split your parameter into subclasses.


问:
How can architects work with self-organizing Scrum teams?
An organization with a number of agile Scrum teams also has a small group of people appointed as "enterprise architects". The EA group acts as control and gatekeeper for quality and adherence to decisions. This leads to overlaps between the team decision and EA decisions.

For instance, the team might want to use library X or want to use REST instead of SOAP, but the EA does not approve of that.

Now, this can lead to frustration when team decisions are overruled. Taken far enough, it can potentially lead to a situation where the EA people "grabs" all power and the team ends up feeling demotivated and not very agile at all.

The Scrum guides has this to say about it:

Self-organizing: No one (not even the Scrum Master) tells the
  Development Team  how to turn Product Backlog into Increments of
  potentially releasable functionality.

Is that reasonable? Should the EA team be disbanded? Should the teams refuse or simply comply?

答:
Your Architect should not be overruling decisions made by your agile teams.  Your architect should include these in the requirements/stories passed to the teams.  They should keep teams updated when the landscape of the project changes & new interoperability requirements are introduced.

Architects giving out orders and vetting technical decisions is a cultural flaw.  They see themselves as the "boss" rather than simply maintaining a shared goal/vision & keeping separate teams on the same page.  Agile methodologies are based on communication & contact.  When your architects don't get involved until after decisions are made, they're failing at agile.


问:
How to license my closed source & freeware (donation ware) - using creative commons?
After doing a bit of research about licensing my free software, I reached this:

Attribution-NonCommercial-NoDerivs 3.0 Unported - http://creativecommons.org/licenses/by-nc-nd/3.0/

how do I include it in my software or website ?

going here: https://creativecommons.org/choose/

I see the text that I should include:

This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/.

答:
Creative Commons licenses should not be used for software. From the FAQ:

Can I apply a Creative Commons license to software?

We do not recommend it. Creative Commons licenses should not be used for software. We strongly encourage you to use one of the very good software licenses which are already available. We recommend considering licenses made available by the Free Software Foundation or listed at the Open Source Initiative. Unlike our licenses, which do not make mention of source or object code, these existing licenses were designed specifically for use with software. Furthermore, our licenses are not compatible with the GPL, the most frequently used free software license.

Note that the CC0 Public Domain Dedication is GPL-compatible and acceptable for software. For details, see the relevant CC0 FAQ entry.


问:
To be strict or pragmatic?
I'm beginning to realize that developing software is (amongst others) a process of constantly asking yourself questions. Questions regarding quality of code, separation of concerns, minimizing dependencies, ...

But the main question is: how far can you go without ending up in a mental hospital?

I'm applying for a new job. Yesterday I was with a possible future employer who wanted to test my programming capablities. One of the exercises was: explain what this code does. I went through some code of the application (winforms in vb.net) that they develop (it's an administrative application for a hospital). This gave me the opportunity to actually see how they approach things and it was rather disappointing.

Some examples:

I saw somewhere: Call [insert name of subroutine here] -> I was struck: isn't that something from VB6?

They have a separate datalayer, using ado.net, but one method I had to examine returns a dataset to the calling layer. So separate datalayer or not, the application is tied to ado.net (which could also never be a problem if they never switch to another data access approach).

That dataset is read as-is, so it still is a data-centric approach (of course, one can argue how much logic/behaviour you can put in classes like "Patient" or "LabAnalysisRequest".

I also believe to have seen the construction of an sql query by string concatenation.

They use stored procedures (which, to me, means: scattering of logic)

no mention of views/controllers: it's all form driven

The most ugly thing I saw was:
    ```
    If TestEnvironment.IsTesting then
       someVar = [some hard coded value]
    else
       someVar = [some dynamically retrieved value]
    end if
    [remainder of the function here]
```

It's all so different from what I learned in school: (persistence agnostic) domain layer, persistence layer, presentation layer, unit testing, ...

So I rephrase my question: how fundamental or dogmatic should one be? To what extent should a programmer stick to his or her principles or just write code that does the job?

答:
I think sticking to your principles is very important.  You should always strive to produce the best code possible within the constraints given.  However, if you add "should never have to read or change bad code" to your list of principles, you're going to have a lot of difficulty finding work.  Remember that 50% of programmers graduated in the bottom half of their class.  Even on a one man team, "today you" is better qualified to solve a problem than "last month you."  Being able to work with non-ideal code is just part of the job.

A lot of employers recognize that, so they code they give you to read may be representative of the worst code in their code base, rather than their best. If that's not clear from the context, you should ask.  One colleague I sometimes interview with has a page of code he purposely wrote poorly just to use as an interview question.

OwnerDisplayName: BartVG

Title: To be strict or pragmatic?


答:
Be strict when it matters.  Brace style (or other coding conventions)?  It doesn't matter.  Use the one the shop uses.  Breaking encapsulation (or other fundamental programming principles) for no good reason?  Not so trivial.

Stack Exchange uses tables for layout (as do many of the other major websites that are making money).  Does that make smoke come out of the purists ears?  Sure it does.  But pragmatism wins out over purity, every time.  Shipping product wins out over getting it perfect, every time.

The whole domain layer, persistence layer, presentation layer, unit testing thing is still relatively new, from a historical standpoint.  There are boatloads of software out there that still use a Client/Server model, and won't be changed to the latest architectural style just because it is "better."

Title: To be strict or pragmatic?

Body:
I'm beginning to realize that developing software is (amongst others) a process of constantly asking yourself questions. Questions regarding quality of code, separation of concerns, minimizing dependencies, ...

But the main question is: how far can you go without ending up in a mental hospital?

I'm applying for a new job. Yesterday I was with a possible future employer who wanted to test my programming capablities. One of the exercises was: explain what this code does. I went through some code of the application (winforms in vb.net) that they develop (it's an administrative application for a hospital). This gave me the opportunity to actually see how they approach things and it was rather disappointing.

Some examples:

I saw somewhere: Call [insert name of subroutine here] -> I was struck: isn't that something from VB6?

They have a separate datalayer, using ado.net, but one method I had to examine returns a dataset to the calling layer. So separate datalayer or not, the application is tied to ado.net (which could also never be a problem if they never switch to another data access approach).

That dataset is read as-is, so it still is a data-centric approach (of course, one can argue how much logic/behaviour you can put in classes like "Patient" or "LabAnalysisRequest".

I also believe to have seen the construction of an sql query by string concatenation.

They use stored procedures (which, to me, means: scattering of logic)

no mention of views/controllers: it's all form driven

The most ugly thing I saw was:
    ```
    If TestEnvironment.IsTesting then
       someVar = [some hard coded value]
    else
       someVar = [some dynamically retrieved value]
    end if
    [remainder of the function here]
```

It's all so different from what I learned in school: (persistence agnostic) domain layer, persistence layer, presentation layer, unit testing, ...

So I rephrase my question: how fundamental or dogmatic should one be? To what extent should a programmer stick to his or her principles or just write code that does the job?


问:
Is code ownership a code smell?
This is something I've been thinking about ever since I read this answer in the controversial programming opinions thread:

Your job is to put yourself out of work.

When you're writing software for your employer, any software that you create is to be written in such a way that it can be picked up by any developer and understood with a minimal amount of effort. It is well designed, clearly and consistently written, formatted cleanly, documented where it needs to be, builds daily as expected, checked into the repository, and appropriately versioned.

If you get hit by a bus, laid off, fired, or walk off the job, your employer should be able to replace you on a moment's notice, and the next guy could step into your role, pick up your code and be up and running within a week tops. If he or she can't do that, then you've failed miserably.

Interestingly, I've found that having that goal has made me more valuable to my employers. The more I strive to be disposable, the more valuable I become to them.

And it has been discussed a bit in other questions, such as this one, but I wanted to bring it up again to discuss from a more point blank "it's a code smell!!" point of view - which hasn't really been covered in depth yet.

I've been a professional developer for ten years. I've had one job where the code was well written enough to be picked up relatively quickly by any decent new developer, but in most cases in industry, it seems that a very high level of ownership (both individual and team ownership) is the norm. Most code bases seem to lack the documentation, process, and "openness" that would allow a new developer to pick them up and get working with them quickly. There always seem to be lots of unwritten little tricks and hacks that only someone who knows the code base very well ("owns" it) would know about.

Of course, the obvious problem with this is: what if the person quits or "gets hit by a bus"? Or on a team level: what if the whole team gets food poisoning when they go out on their team lunch, and they all die? Would you be able to replace the team with a fresh set of new random developers relatively painlessly? - In several of my past jobs, I can't imagine that happening at all. The systems were so full of tricks and hacks that you "just have to know", that any new team you hire would take far longer than the profitable business cycle (eg, new stable releases) to get things going again. In short, I wouldn't be surprised if the product would have to be abandoned.

Obviously, losing an entire team at once would be very rare. But I think there is a more subtle and sinister thing in all this - which is the point which got me thinking to start this thread, as I haven't seen it discussed in these terms before. Basically: I think a high need for code ownership is very often an indicator of technical debt. If there is a lack of process, communication, good design, lots of little tricks and hacks in the system that you "just have to know", etc - it usually means that the system is getting into progressively deeper and deeper technical debt.

But the thing is - code ownership is often presented as a kind of "loyalty" to a project and company, as a positive form of "taking responsibility" for your work - so it's unpopular to outright condemn it. But at the same time, the technical debt side of the equation often means that the code base is getting progressively less open, and more difficult to work with. And especially as people move on and new developers have to take their place, the technical debt (ie maintenance) cost starts to soar.

So in a sense, I actually think that it would be a good thing for our profession if a high level of need for code ownership were openly seen as a job smell (in the popular programmer imagination). Instead of it being seen as "taking responsibility and pride" in the work, it should be seen more as "entrenching oneself and creating artificial job security via technical debt".

And I think the test (thought experiment) should basically be: what if the person (or indeed, the whole team) were to vanish off the face of the Earth tomorrow. Would this be a gigantic - possibly fatal - injury to the project, or would we be able to bring in new people, get them to read the doccos and help files and play around with the code for a few days - and then be back in business in a few weeks (and back to full productivity in a month or so)?

答:
I define Code Ownership as taking personal responsibility for the code that you write, with the understanding that others will be working in your code in the future. If you think of things in this way, you'll be less likely to write a hack because a) bugs in that module could be traced back to you, and b) team members would likely have a hard time modifying the code in the future.

I wrote a blog post on this several months ago, where I argued that without code ownership, as I define it, a codebase often falls prey to the Tragedy of the Commons.

By your definition of code ownership, I agree that it's bad to have code that only the author can work in.

Title: Is code ownership a code smell?


问:
Max number of items mapped to same location in hashmap
I have a question about hashmaps.
If you have this hashmap with m slots, and need to map n items to it, and n > m. There will be collisions for sure. But assuming there is simple uniform hashing assumption, this means that the maximum amount of collisions in any spot is the load factor right? The load factor is n/m. But the load factor is probably going to be a decimal, does this mean its a ceiling of the n/m? So if n=6 and m=5, then load factor is 1.2, and the ceiling is 2, so that means the maximum collisions in one spot is 2.
Is this right?</p>

答:
No, the maximum number of collisions is the number of hash elements to be put into the hash.

From the wikipedia link on Simple Uniform Hashing Assumption:

Moreover, each item to be hashed has an equal probability of being placed into a slot, regardless of the other elements already placed.

The key word is "probability" - it is possible for all of them to hash to the same spot, and thus the maximum collisions is the size.  It is also possible for them to hash evenly, in which case it would be the ceiling of the load factor.

Particularlly relevant to this is:

Collision chain length Under the assumption of uniform hashing, the
  load factor A and the average chain length of a hash table of size m
  with n elements will be A = n/m

Where n is the number of elements and m is the size of the hash.  Key phrase again is the average chain length - not the maximum chain length.

Continuing to read the article, one will note phrases such as "on average" used regularly - this is about the probability of an uniform hash - not the guarantee of such.

An example of such a hash algorithm would be mod hashSize on integers.  If the hash size was 5 hash(x) = x % 5 would be a hash that fits this requirement - that each value hashed has an equal probability of being placed into a given slot.

However, if one was to hash into this size 5 hash the numbers: 5, 10, 15, 20, 25, 30 one would then have everything hash to the same location.


问:
Which framework should I learn if I want to do web development in Java? Any advice?
Well, I don't have a strong background in programming. I know C, C++, some C#, some vb, and some basic java and SQL, that's it. I don't have any work experience in web development, so just consider me as a completely new starter.

I would like to do web development, and I hope I can easily find a job in web development after I finish my current academic program. So I have started with asp.net MVC framework. But, at least it seems to me that many positions require java programming in web development, so I decide to learn java at the same time while learning .net. Well, there are a lot of frameworks out there. A friend of mine suggests Hibernate, some people say that play framework is good for small applications, whereas some guys recommend spring, which seems to be a very difficult one. I want to start with a framework which is relatively easy to pick up and popular in job market. So what should I start with? And aside from a framework, what else should I learn?

Besides, which one is more popular in terms of web programming, .net or Java? It seems that java is required by most employers, and I haven't found many positions indicating .net experience. Which of the two is actually more popular, and what about the trend in the future?

答:
I think you are asking many questions in one question.

There are lots of jobs for Java developers and .Net Developers. With experience and hard working you will be able to handle C# and Java both ecosystems are similar.

But first you need to settle in one. I suggest you keep using C# and Asp.Net MVC, Its a very nice stack with incredible potential and features.

If you really want to dig into Java ecosystem, I recommend Spring MVC with Spring Core, Spring Data and JPA2/Hibernate. For template FreeMarker is easy and fast.

Spring MVC is the View and Controller based on MVC pattern

Spring Core is used for DI and services

Spring Data JPA gives you the repository pattern and level of abstration from the models

JPA2/Hibernate for your models

Try to use Maven for all dependencies and this stack will give you everything for create powerful Java web applications.

About popularity on Dice.com Java is more popular than C# but I found more jobs as C# Web Developer than Java Web Developer but all depends.

Learn the tools you like most and really it does not matter, I was a Java developer and I got picked for a C# contract lately, I didn't not have deep knowledge in the tools but the import is your experience and that you are a fast learned and can pick up any tool right away.


问:
How does a concurrent garbage collector deal with variables?
Let's say it is a concurrent mark-and-sweep garbage collector.

When such GC handles constant pointers it just walks through them (starting from roots), and marks every encountered data block. Then sweeps everything unmarked. A client code should mark the data blocks it uses as roots.

But what to do with variables? Here is a situation:

V is a variable, which stores a pointer to object A.

Thread 1 reads V and suspends.

Thread 2 modifies V and makes it point to object B.

The garbage collector runs its "mark" phase and encounters that A is no longer referenced, then deallocates it during the "sweep" phase.

Thread 1 awakens and tries to use A (already read from V at step 2) by marking it as root. And fails, because A is no longer exists.

So, how to handle this?

The Thread 2 can mark the replaced object A with a special do-not-remove flag (similar flag is used for newly allocated objects). But when this flag should be removed? Of course Thread 1 could do that. But Thread 2 knows nothing about Thread 1, and thus can not be sure that this will be done ever. This may lead to A will never be freed. And if GC will remove that flag, then nothing prevents A from being removed when GC runs for the second time...

The on-the-fly mark-and-sweep garbage collector descriptions I've read just mention that the replaced object should be "grayed". But without any specifics. A link to a more detailed description of the solution would be highly appreciated.

答:
Depending on the precise details of the garbage collector implementation, this may not be a problem at all in your step 4. For example, in step 2, thread 1 presumably reads V into a register. The garbage collector will probably need to examine the contents of the registers for all active (running and suspended) threads to see if there is a reference to any object held in the registers.

Inevitably, a garbage collector implementation is tightly coupled to the operating (and threading) environment in which it runs. There are many implementation techniques for ensuring that all stored and transient references are considered.


问:
How to create a feature map?
I have a big side project that I do now for 3 years. It has a lot of extra small tools to help me do tasks. Most of those tools are so old that I forgot what I have there.

How to create a feature map to have easy reminder of what is possible ?

Is there some special UML diagram notation for it?

How to do it? I think graphic version would be better than a readme text file.

答:
Why not use mind maps.

Check this link for explanation of the concept
http://en.wikipedia.org/wiki/Mind_map

You can hand draw mind maps or use a software.

You can get free software from sites below:

Freeplane

Freemind

I have tried both and found that Freeplane has lot of features.

Title: How to create a feature map?


问:
Building a computer system with JS?
I recently finished this book called The Elements of Computing Systems where you build a working computer system from the ground up, starting from basic logic gates, to creating your own machine code and Assembly language, to intermediate code, and finally a simple object-oriented programming language that compiles down to VM code. I enjoyed it a lot and I'd like to create something similar in JavaScript, but with more features. I've already written an emulator for the Hack machine in JS:

```<code>  // Creates a new CPU object that is responsible for processing instructions
  var CPU = function() {

var D = 0;    // D Register
var A = 0;    // A Register
var PC = 0;   // Program counter

// Returns whether an instruction is valid or not
var isValidInstruction = function(instruction) {
    if (instruction.length != 32)
        return false;

    instruction = instruction.split("");

    for (var c = 0; c < instruction.length; c++)
    {
        if (instruction[c] != "0" && instruction[c] != "1")
            return false;
    }

    return true;
};

// Given an X and Y input and 6 control bits, returns the ALU output
var computeALU = function(x, y, c) {

    if (c.length != 6)
        throw new Error("There may only be 6 ALU control bits");

    switch (c.join(""))
    {
        case "000000": return 0;
        case "000001": return 1;
        case "000010": return -1;
        case "000011": return x;
        case "000100": return y;
        case "000101": return ~x;
        case "000110": return ~y;
        case "000111": return -x;
        case "001000": return -y;
        case "001001": return x+1;
        case "001010": return y+1;
        case "001011": return x-1;
        case "001100": return y-1;
        case "001101": return x+y;
        case "001110": return x-y;
        case "001111": return y-x;
        case "010000": return x*y;
        case "010001": return x/y;
        case "010010": return y/x;
        case "010011": return x%y;
        case "010100": return y%x;
        case "010101": return x&y;
        case "010110": return x|y;
        case "010111": return x^y;
        case "011000": return x>>y;
        case "011001": return y>>x;
        case "011010": return x<<y;
        case "011011": return y<<x;

        default: throw new Error("ALU command " + c.join("") + " not recognized");
    }
};

// Given an instruction and value of Memory[A], return the result
var processInstruction = function(instruction, M) {

    if (!isValidInstruction(instruction))
        throw new Error("Instruction " + instruction + " is not valid");

    // If this is an A instruction, set value of A register to last 31 bits
    if (instruction[0] == "0")
    {
        A = parseInt(instruction.substring(1, instruction.length), 2);

        PC++;

        return {
            outM: null,
            addressM: A,
            writeM: false,
            pc: PC
        };
    }

    // Otherwise, this could be a variety of instructions
    else
    {
        var instructionType = instruction.substr(0, 3);
        var instructionBody = instruction.substr(3);

        var outputWrite = false;

        // C Instruction - 100 c1, c2, c3, c4, c5, c6 d1, d2, d3 j1, j2, j3 (000..000 x16)
        if (instructionType == "100")
        {
            var parts = [ "a", "c1", "c2", "c3", "c4", "c5", "c6", "d1", "d2", "d3", "j1", "j2", "j3" ];
            var flags = {};

            for (var c = 0; c < parts.length; c++)
                flags[parts[c]] = instructionBody[c];

            // Compute the ALU output
            var x = D;
            var y = (flags["a"] == "1") ? M : A;
            var output = computeALU(x, y, [flags["c1"], flags["c2"], flags["c3"], flags["c4"], flags["c5"], flags["c6"]]);

            // Store the result
            if (flags["d1"] == "1") A = output;
            if (flags["d2"] == "1") D = output;
            if (flags["d3"] == "1") outputWrite = true;

            // Jump if necessary
            if ((flags["j1"] == "1" && output < 0) || (flags["j2"] == "1" && output == 0) || (flags["j3"] == "1" && output > 0))
                PC = A;
            else
                PC++;

            // Return output
            return {
                outM: output,
                addressM: A,
                writeM: outputWrite,
                pc: PC
            };
        }

        else throw new Error("Instruction type signature " + instructionType + " not recognized");
    }
};

// Reset the CPU by setting all registers back to zero
this.reset = function() {
    D = 0;
    A = 0;
    PC = 0;
};

// Set the D register to a specified value
this.setD = function(value) {
    D = value;
};

// Set the A register to a specified value
this.setA = function(value) {
    A = value;
};

// Set PC to a specified value
this.setPC = function(value) {
    PC = value;
};

// Processes an instruction and returns the result
this.process = function(instruction, M) {
    return processInstruction(instruction, M);
};
};
</code>```

I was thinking about adding things like a filesystem, sound, Internet connectivity, and an RGBA screen output (currently it's only black and white). But how feasible would this be, really?

Because what I'm thinking about doing is starting completely from scratch. And what I mean by that is create my own machine code, then work all the way up towards a C-like language and actually create working programs and stuff.

答:
You could certainly do it. You'd need to implement certain components of your operating system, such as the boot loader, and interrupts in a lower level language.

Have a look at the approach taken by the Singularity Operating System by Microsoft on how to develop an operating system that runs on Managed Code.

Of course, there is no requirement that you have to bolt on memory management to JavaScript, you could add an API for memory management to JavaScript. You could choose to write a compiler for JavaScript or write a virtual machine.

Singularity has source code available so you could gain valuable insight from looking at the design decisions that Microsoft made.

Title: Building a computer system with JS?


问:
Is a single object to be preferred over multiple variables?
It was quite hard to put what I meant into a title, but it's easy to put into code.

C++

Is this

```<code>int offset_x = 10;
int offset_y = 40;
...
element.move(offset_x, offset_y);
</code>```

To be preferred over this?

```<code>Vector<int> offset(10, 40);
...
element.move(offset.x, offset.y);
</code>```

(Note that Vector is not like std::vector, it's a 2D vector. This class has lots of methods I don't need here, like normalize() and scale(). Should I have a more basic Point class for this?)

JavaScript

Is this

```<code>var offsetX = 10;
var offsetY = 40;
...
element.move(offsetX, offsetY);
</code>```

To be preferred over this?

```<code>var offset = {x: 10, y: 40};
...
element.move(offset.x, offset.y);
</code>```

答:
I have "inherited" a lot of legacy code using your first variant, and also written lots of code by myself using Point2D and Point3D classes instead (essentially the same what your Vector<int> is about). The first variant leads always to functions with too many parameters and too many repeated constructs where simple vector addition or scalar multiplication is repeated again and again in several lines of code.

Using 2D point or vector classes, however, especially when you have the need for a lot of vector operations, makes the code much cleaner, concise, better readable and maintainable. If you should use an existing Vector<int>, or write your own Point class instead is impossible to say without knowing more about the details of your code, but in general, if an existing class suffers your need, why not reuse it? The additional methods you don't need typical don't hurt. But not using any 2D point/vector class is almost everytime the wrong decision. And in your example above: if you have influence on the element.move function, IMHO you are better off to design it in a way you can call element.move(offset) instead of element.move(offset_x, offset_y).

For example, say you need an array of point coordinates, and you are going to use a std::vector. In the first case, you will need two std::vector<int> variables, you have to make sure those two vector are "in sync" with each other, and all adding of new elements, finding existing elements, passing around of those elements needs two lines of code instead of one when you had choosen to use a std::vector<Point2D> instead.


问:
Entity Framework eager loading/reference data
I'm struggling to get my head around how best to eager load entities, and how to assign relationships when creating new entities. I'm using EF5 POCO, by the way.

I'm retreiving a large hierarchy of entities from a database, representing chemical analysis results. As a simple example I have an "AnalysisResult" entity with two generated properties that relate it to a "ChemicalElement" entity - ChemicalElement and ChemicalElementId. Standard stuff so far.

I started out by retrieving my AnalysisResults from the database and eager loading the related ChemicalElements using the .Include LINQ statement, meaning I could access a result's chemical element simply via AnalysisResult.ChemicalElement. This was fine for results loaded from the database, but what if I wanted to create a new AnalysisResult - how would I get the ChemicalElement entity that I wanted to assign to it?

As chemical elements never change, I decided to treat them as "reference/lookup data", so I dropped the eager loading, and I now retrieve all ChemicalElements into a separate collection that I can refer to whenever I need. The downside of dropping eager loading is that an AnalysisResult loaded from the database has a null .ChemicalElement property, so I have to use its .ChemicalElementId property to lookup the ChemicalElement entity in my "reference collection".

Have I overcomplicated the solution? Should I keep the idea of the ChemicalElement "reference collection" but also eager load them when retrieving existing AnalysisResults? It seems wasteful to (potentially) retrieve them twice - once when I retrieve them all, and again when eager loading during the AnalysisResults retrieval.

答:
Deciding if you should load some information (eager or lazy) depends mostly on your usage patterns.

I'm guessing the displaying the chemical information is the main scope of your application.

On a previous application that worked with cars we cached properties like car color and body types. We made the connection with the data coming from the database in the view (using controls/helpers).

This made sure that we didn't overburden the database with heavy handed joins.


答:
You have to mark local variables sometime during the mark phase. All local variables, including those that normally live on stack. Somehow.

I additionally think it has to be done during the synchronous (all mutators stopped) phase of scanning modified objects. In fact the same problem might arise even without considering local variables/registers. Consider object A pointing to null and object B pointing to C. Now you scan object A, a mutator thread comes, copies the reference to C from B to A, nulls out B. And now you get around to scanning B. And C slipped under your fingers.

I don't know about any way for dealing with this that wouldn't involve stopping the mutators. The usual technique is at the end of mark phase to stop all mutators and re-mark all objects that they mutated during the main marking phase. And include stacks and registers in that.

Marking registers is normally worked around by doing it synchronously by calling the collector in the thread sometimes. Inside the collector function, only it's own local variables (which are not roots) can be in registers, all other local variables in the call chain are on stack, so you can walk the stack.

Alternatively you can send a signal to the thread. The signal handler will again force all variables on the stack, so you can walk them. Disadvantage of this method is that it is platform dependent.

Title: How does a concurrent garbage collector deal with variables?

Body:
Let's say it is a concurrent mark-and-sweep garbage collector.

When such GC handles constant pointers it just walks through them (starting from roots), and marks every encountered data block. Then sweeps everything unmarked. A client code should mark the data blocks it uses as roots.

But what to do with variables? Here is a situation:

V is a variable, which stores a pointer to object A.

Thread 1 reads V and suspends.

Thread 2 modifies V and makes it point to object B.

The garbage collector runs its "mark" phase and encounters that A is no longer referenced, then deallocates it during the "sweep" phase.

Thread 1 awakens and tries to use A (already read from V at step 2) by marking it as root. And fails, because A is no longer exists.

So, how to handle this?

The Thread 2 can mark the replaced object A with a special do-not-remove flag (similar flag is used for newly allocated objects). But when this flag should be removed? Of course Thread 1 could do that. But Thread 2 knows nothing about Thread 1, and thus can not be sure that this will be done ever. This may lead to A will never be freed. And if GC will remove that flag, then nothing prevents A from being removed when GC runs for the second time...

The on-the-fly mark-and-sweep garbage collector descriptions I've read just mention that the replaced object should be "grayed". But without any specifics. A link to a more detailed description of the solution would be highly appreciated.


问:
How to approach the creation of a "Unit Outline" generator?
I am the Studies Coordinator at a College and we currently have somewhere in the order of 100-200 unit outlines that are created at the beginning of each semester. Those outlines need to have information like:

Unit Name

Unit Code

Course Type

Assessment Item 1 Name

Assessment Item 1 Distribution date...

And the list goes on and on. All up there are anywhere between 50-150 pieces of data that teachers enter into their outlines depending on the 10-20 different types of outline they might be creating.

Currently we have staff entering data into one of many different Word documents with editable fields. This works okay, but every time the outlines need to have a change made, you can imagine the work involved. The outlines also look poor because different table rows move across different pages...it's just messy.

We have tried using InfoPath files...maintaining those was a nightmare and the school won't go back to that.

I am contemplating a solution where teachers enter the unformatted/raw data into some kind of front-end (I was thinking an Excel file) and then I write a program that sweeps through the data and generates outlines for me.

I've been experimenting with simply using Mail Merge but this doesn't give me the flexibility to tailor the end result based on the data coming in (different numbers of Assessment Items for instance)

I am looking for ways to streamline the whole Unit Outline process.

答:
I see two main ways to develop this system.

Office solution

The first is to write some VBA that parses a file (such as an Excel worksheet or an Access database) and builds a Word document. I would suggest if you go down this path you use a properly designed database.

Pros

You can still edit the files in Office

Staff are familiar with the system

Cons

Ties you to a proprietary platform

Might be harder to find the expertise.

Web solution

The second proposition I would give to you is to have a simple web application developed using a MySQL database and a web interface to edit. You would have the page template defined and use PHP to "fill in the blanks". The pages could be printed and formatted easily as PDFs.

Pros

Easier to find developers able to do this sort of work

Available through a web browser

Cons

You won't be editing in word.

I also suggest you look at having students build the system. I know my university had it's own projects along with other commercial projects for students to choose from.


问:
Should I Use an ORM only when dealing with Data Model objects?
I am new to ORM, and we started developing a new system using NHibernate as the ORM.

I think this question may refer to any ORM and any language/platform.

The Team Leader has said we should use NHibernate only when retrieving our domain data model objects, ie, not to use any of the built in NHibernate selection or aggregations that will retrieve single primitives or a list of primitives.

The reason behind it was that we need to make a distinction between classic ORM and other abilities, so that usual select and select max will use a "classic" DAL project.

I think this is not so good, because we break the data access to two, and what's wrong using NHibernate abilities which gets checked compile time?

Are there any reasons to making this distinction?

答:
You are going to have the most luck using the functionality baked into the ORM. NHibernate is incredibly flexible and knows how many different databases work. Using it will allow your database layer to be easily portable.

I would say to your team leader:

NHibernate produces optimised queries

NHibernate does lazy loading

Will allow portability across various database platforms

Supports its own, powerful, querying language.

Don't "worry" about data access code and leave that to the ORM. Focus on your business logic and problem domain.

EDIT: One thing I just thought of is that if you are manually loading objects you're likely to miss the best features of NHibernate because your objects are going to be detached.


问:
How to make creating viewmodels at runtime less painful
I apologize for the long question, it reads a bit as a rant, but I promise it's not! I've summarized my question(s) below

In the MVC world, things are straightforward. The Model has state, the View shows the Model, and the Controller does stuff to/with the Model (basically), a controller has no state. To do stuff the Controller has some dependencies on web services, repository, the lot. When you instantiate a controller you care about supplying those dependencies, nothing else. When you execute an action (method on Controller), you use those dependencies to retrieve or update the Model or calling some other domain service. If there's any context, say like some user wants to see the details of a particular item, you pass the Id of that item as parameter to the Action. Nowhere in the Controller is there any reference to any state. So far so good.

Enter MVVM. I love WPF, I love data binding. I love frameworks that make data binding to ViewModels even easier (using Caliburn Micro a.t.m.). I feel things are less straightforward in this world though. Let's do the exercise again: the Model has state, the View shows the ViewModel, and the ViewModel does stuff to/with the Model (basically), a ViewModel does have state! (to clarify; maybe it delegates all the properties to one or more Models, but that means it must have a reference to the model one way or another, which is state in itself) To do stuff the ViewModel has some dependencies on web services, repository, the lot. When you instantiate a ViewModel you care about supplying those dependencies, but also the state. And this, ladies and gentlemen, annoys me to no end.

Whenever you need to instantiate a ProductDetailsViewModel from the ProductSearchViewModel (from which you called the ProductSearchWebService which in turn returned IEnumerable<ProductDTO>, everybody still with me?), you can do one of these things:

call new ProductDetailsViewModel(productDTO, _shoppingCartWebService /* dependcy */);, this is bad, imagine 3 more dependencies, this means the ProductSearchViewModel needs to take on those dependencies as well. Also changing the constructor is painful.

call _myInjectedProductDetailsViewModelFactory.Create().Initialize(productDTO);, the factory is just a Func, they are easily generated by most IoC frameworks. I think this is bad because Init methods are a leaky abstraction. You also can't use the readonly keyword for fields that are set in the Init method. I'm sure there are a few more reasons.

call _myInjectedProductDetailsViewModelAbstractFactory.Create(productDTO); So... this is the pattern (abstract factory) that is usually recommended for this type of problem. I though it was genius since it satisfies my craving for static typing, until I actually started using it. The amount of boilerplate code is I think too much (you know, apart from the ridiculous variable names I get use). For each ViewModel that needs runtime parameters you'll get two extra files (factory interface and implementation), and you need to type the non-runtime dependencies like 4 extra times. And each time the dependencies change, you get to change it in the factory as well. It feels like I don't even use a DI container anymore. (I think Castle Windsor has some kind of solution for this [with it's own drawbacks, correct me if I'm wrong]).

do something with anonymous types or dictionary. I like my static typing.

So, yeah. Mixing state and behavior in this way creates a problem which don't exist at all in MVC. And I feel like there currently isn't a really adequate solution for this problem. Now I'd like to observe some things:

People actually use MVVM. So they either don't care about all of the above, or they have some brilliant other solution.

I haven't found an in-depth example of MVVM with WPF. For example, the NDDD-sample project immensely helped me understand some DDD concepts. I'd really like it if someone could point me in the direction of something similar for MVVM/WPF.

Maybe I'm doing MVVM all wrong and I should turn my design upside down. Maybe I shouldn't have this problem at all. Well I know other people have asked the same question so I think I'm not the only one.

To summarize

Am I correct to conclude that having the ViewModel being an integration point for both state and behavior is the reason for some difficulties with the MVVM pattern as a whole?

Is using the abstract factory pattern the only/best way to instantiate a ViewModel in a statically typed way?

Is there something like an in depth reference implementation available?

Is having a lot of ViewModels with both state/behavior a design smell?

答:
I work daily with ASP.NET MVC and have worked on a WPF for over a year and this is how I see it:

MVC

The controller is supposed to orchestrate actions (fetch this, add that).

The view is responsible for displaying the model.

The model typically encompasses data (ex. UserId, FirstName) as well as state (ex. Titles) and is usually view specific.

MVVM

The model typically only holds data (ex. UserId, FirstName) and is usually passed around

The view model encompasses the behavior of the view (methods), its data (model) and interactions (commands) - similar to the active MVP pattern where the presenter is aware of the model. The view model is view specific (1 view = 1 view model).

The view is responsible for displaying data and data-binding to the view model. When a view is created, usually its associated view model is created with it.

What you should remember is that the MVVM presentation pattern is specific to WPF/Silverlight due to their data-binding nature.

The view typically knows which view model its associated with (or an abstraction of one).

I would advise that you treat the view model as a singleton, even though it's instantiated per view. In other words, you should be able to create it via DI via an IOC container and call appropriate methods upon it to say; load its model based on parameters. Something like this:

```<code>public partial class EditUserView
{
    public EditUserView(IContainer container, int userId) : this() {
        var viewModel = container.Resolve<EditUserViewModel>();
        viewModel.LoadModel(userId);
        DataContext = viewModel;
    }
}
</code>```

As an example in this case, you wouldn't create a view model specific to the user being updated - instead the model would contain user specific data that gets loaded via some call on the view model.

Body:
I work daily with ASP.NET MVC and have worked on a WPF for over a year and this is how I see it:

MVC

The controller is supposed to orchestrate actions (fetch this, add that).

The view is responsible for displaying the model.

The model typically encompasses data (ex. UserId, FirstName) as well as state (ex. Titles) and is usually view specific.

MVVM

The model typically only holds data (ex. UserId, FirstName) and is usually passed around

The view model encompasses the behavior of the view (methods), its data (model) and interactions (commands) - similar to the active MVP pattern where the presenter is aware of the model. The view model is view specific (1 view = 1 view model).

The view is responsible for displaying data and data-binding to the view model. When a view is created, usually its associated view model is created with it.

What you should remember is that the MVVM presentation pattern is specific to WPF/Silverlight due to their data-binding nature.

The view typically knows which view model its associated with (or an abstraction of one).

I would advise that you treat the view model as a singleton, even though it's instantiated per view. In other words, you should be able to create it via DI via an IOC container and call appropriate methods upon it to say; load its model based on parameters. Something like this:

public partial class EditUserView
{
    public EditUserView(IContainer container, int userId) : this() {
        var viewModel = container.Resolve<EditUserViewModel>();
        viewModel.LoadModel(userId);
        DataContext = viewModel;
    }
}

As an example in this case, you wouldn't create a view model specific to the user being updated - instead the model would contain user specific data that gets loaded via some call on the view model.


答:
Actually, I think the best way is to do this:

```<code>Vector<int> offset(10, 40);
element.moveBy(offset);
</code>```

This code abstracts away the dimensionality of your vectors, and the same line of code (element.moveBy(offset)) will work unchanged if you change your vectors to 3D, or doubles, or even polar coordinates, as long as your types implement the required operations correctly.

For example, consider the following code:

```<code>Vec wallBounce(Obj& o, cont Wall& w) {
    assert(isUnit(w.normal));
    Vec perp = dot(w.normal, o.velocity) * w.normal;
    o.velocity -= 2 * perp;
}
</code>```

Anyone with enough vector math clue will understand what happens here; additionally, the function is short, to the point. You can't see what Vec is typedef'd to, but that's usually not very interesting and also trivial to look up; the code clarity and brevity more than make up for it. After all, coding is all about making abstractions, and abstracting groups of scalars into vectors is a very powerful abstraction. For kicks, try and implement the above function without making this abstractions, for 2D vectors, 3D vectors, and scalars.

Title: Is a single object to be preferred over multiple variables?

Body:
It was quite hard to put what I meant into a title, but it's easy to put into code.

C++

Is this

```<code>int offset_x = 10;
int offset_y = 40;
...
element.move(offset_x, offset_y);
</code>```

To be preferred over this?

```<code>Vector<int> offset(10, 40);
...
element.move(offset.x, offset.y);
</code>```

(Note that Vector is not like std::vector, it's a 2D vector. This class has lots of methods I don't need here, like normalize() and scale(). Should I have a more basic Point class for this?)

JavaScript

Is this

```<code>var offsetX = 10;
var offsetY = 40;
...
element.move(offsetX, offsetY);
</code>```

To be preferred over this?

```<code>var offset = {x: 10, y: 40};
...
element.move(offset.x, offset.y);
</code>```

Body:
Actually, I think the best way is to do this:

Vector<int> offset(10, 40);
element.moveBy(offset);

This code abstracts away the dimensionality of your vectors, and the same line of code (element.moveBy(offset)) will work unchanged if you change your vectors to 3D, or doubles, or even polar coordinates, as long as your types implement the required operations correctly.

For example, consider the following code:

Vec wallBounce(Obj& o, cont Wall& w) {
    assert(isUnit(w.normal));
    Vec perp = dot(w.normal, o.velocity) * w.normal;
    o.velocity -= 2 * perp;
}

Anyone with enough vector math clue will understand what happens here; additionally, the function is short, to the point. You can't see what Vec is typedef'd to, but that's usually not very interesting and also trivial to look up; the code clarity and brevity more than make up for it. After all, coding is all about making abstractions, and abstracting groups of scalars into vectors is a very powerful abstraction. For kicks, try and implement the above function without making this abstractions, for 2D vectors, 3D vectors, and scalars.


答:
To give a more general answer, variables should be grouped into an object when it makes logical sense to do so.

Are the variables different aspects or properties of one "thing"?

Do they always belong together?

Will they be used enough to justify any extra work that may be involved in creating an object?

In your case, I would say that your code clearly improves when you group the variables together.

But if variables are slapped together in an object that is not well thought out, you can be stuck with an unwieldy design that is worse than using normal variables.

Conversely, it is possible to over-design: spending too much time thinking about and building the "perfect" object-oriented structure, to the point that it stops you from actually getting things done.


问:
Is there's a way to speed up my php code which parse XML files
I'm developing a web application and we are using XML as a database and I'm using Linux as a platform and centos 6.5 as a server. Changing some value would make a lot a lot of changes in about six XML files.

So here's the problem: Pressing button save after editing, adding, deleting takes about one or one and half minutes or more! This is because my code has to update about six XML files, log files and the crontab file. I wonder if there's any thing similar to threads in PHP?

I have my functions and all code I want, I just want to know how php can be used in a new way to make performance better. Can you guide me even by links to read?

I don't know what's exactly this problem is called to search about it. I'm still a beginner.

here's the update function I'm using :

```<code> public static function update($tableName, $fieldsToUpdate, $newValues, $value = NULL) {
        //Load XML file
        $fileName = G_APP_SCRIPTS_PATH . "/XMLS/xmls/" . $tableName . ".xml";
        $xml = new DOMDocument;
        $xml->load($fileName);
        //Load XSD file
        $xsdfileName = G_APP_SCRIPTS_PATH . "/XMLS/xsds/" . $tableName . ".xsd";
        $xsd = new DOMDocument;
        $xsd->load($xsdfileName);
        //Generate Xpath
        $path = c_XML::generateXPath($xml, $xsd, $fieldsToUpdate, $value);
        $xpath = new DOMXPath($xml);
        //Query nodes to update
        $nodes = $xpath->query($path);
//        print_r($nodes->item(0));
        //If number of new values < number of elements to update,means we have to update
        //all specified elements in the XML without any condition
        if (count($newValues) < $nodes->length) {
            for ($i = 0; $i < $nodes->length / count($newValues); $i++)
                $newValues = array_merge($newValues, $newValues);
        }
        //Iterate over the nodes to update
        for ($i = 0; $i < $nodes->length; $i++) {
            $oldNode = $nodes->item($i);
            for ($index = 0; $index < count($fieldsToUpdate); $index++) {
                //Find the associated index in the $fieldsToUpdate array
                if (strcmp($oldNode->nodeName, $fieldsToUpdate[$index]) === 0) {
                    break;
                }
            }
            //Create new node with the old node's name
            $newNode = $xml->createElement($oldNode->nodeName);
            //var_dump($newNode);
            //if the new value is an array,means we have to update an inner node
            if (is_array($newValues[$index])) {
                //go to the desired node in XSD and get its children elements,
                //to know their format
                $xsdxpath = new DOMXPath($xsd);
                $children = $xsdxpath->query("/xs:schema/xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType/xs:sequence/xs:element[@name='" . $oldNode->nodeName . "']/xs:complexType/xs:sequence/xs:element");
                //convert the $chlidren node list to an array to pass the createNode function.
                for ($c = 0; $c < $children->length; $c++) {
                    $childrenArray[$c] = $children->item($c);
                }
                //create the desired node
                c_XML::createNode($xml, $xsdxpath, $newNode, $childrenArray, $newValues[$index]);
            }
            //If the new value is not an array
            else
                $newNode->nodeValue = $newValues[$index];
            //Replace old node with new node
            $parent = $oldNode->parentNode;
            $parent->replaceChild($newNode, $oldNode);
        }
        //Validate & save XML
        $isValid = c_XML::validateXMLtoXSD($xml, $xsdfileName);
        if ($isValid == 1) {
            $xml->save($fileName);
            return true;
        }
        else
            return false;
    }
</code>```

and when user update a value I use this way in updating other xml files :

```<code>  private static function change_value_in_xml_file($old_value, $new_value) {
            $all_nodes = c_XML_h::select(tables::xmlfile, '*');
           $nodes = array();
            for ($i = 0; $i < count($all_nodes); $i++) {
               $nodes[$i] = array();
//just get the nodes i want
               $nodes[$i][0] = $all_nodes[$i][0];
               $nodes[$i][1] = $all_nodes[$i][3];
            }
            //find old value and replace it with new value
            foreach ($nodes as $node) {
                $newValues[0] = $new_value;

                if ($node[1] == $old_value) {
                    $id_to_update = $node[0];
                    $fieldsToSelect[0] = xmlfile:: value;
                    c_XML_h::update(tables::xmlfile, $fieldsToSelect, $newValues, $id_to_update);
                }

            }
        }
</code>```

答:
XML is not a very good choice for a database that needs a lot of updating, because text files are not random access:  you must parse the whole file every time you want to read or write a single element.  You might be able to improve your code slightly, but XML isn't going to be fast.

Some other problems you may have:

This will scale very poorly.  As the size of your database increases, your code will get much, much slower.

Concurrent updates will be a problem.  Could you have two people performing actions that will update the database at the same time?  If so, at best one action would fail to complete.  At worst, it could leave your data in a corrupt state.

I would suggest you bite the bullet and replace it with a real database.  You appear to have nicely abstracted your data access into functions, so all you have to do is rewrite those functions to access a database rather than read and write XML files.

(Also keep around the old XML functions to aid in moving the data.  Once you have written the database interface, you can make a little program that will read all of your data in XML using the old functions, then write it to the database using the new functions.)


问:
About the usage of assertions
I stumbled upon an article named Programming With Assertions.

And beside the mechanism of turning on and off assertions after compile time, I don't get it. Why were assertions introduced on language level, which is quite a big deal, isn't it?

I have never used assertions in production code, was never taught to use them in production code, and never saw assertions in production code. Beyond that, I would always prefer a more specific Exception over an AssertionError.

So here are my questions. Does anyone use assertions in production code, and what are the advantages of that usage?

答:
Assertions are used to assert that a condition is always true. They're used in code to ensure that an assumption is correct.

Generally if you see an assertion error something bad has gone wrong.

You can read all about them at Wikipedia.

When it comes to using your own assertions, don't use them in place of exceptions. Instead, use them wherever you feel the need to assert that a condition always holds true, for example a value you may rely on in an internal data structure.

Title: About the usage of assertions


问:
Is there a way to support different coding styles in a development team
The Problem: Two developers => three opinions on indention, braces on new line or not etc.

We usually work with three or four people on our projects and each of those has it's own code style. I know, the common solution is to agree on a code style, everybody has to use, but I don't want to force creative programmers in a suit that does not fit them.

So the question is: Is there a way to let each programmer live his/her own style, but having a common code base inside the repository? I think of some git/svn/whatever plugin, which changes between personal and common style on checkout and commit. It appears to me, that the tricky part in this approach is to support correct diffs between the versions of a file

答:
No, you will need to make a standard. If you have team member B change (either with an automated IDE tool, or manually) a whole heap of code team member A wrote, that will be committed and show as a change.

This is something almost every team faces and standards are "forced" for this very reason. I would suggest you follow the language authorities standards as a baseline and adopt them to suit your team.

Having a consistent coding style will also help in the maintainability of the project and reduce the barrier to entry for new people working on the code.


答: No, you will need to define a coding standard (preferrably one which already exists) and have your developers adhere to it. Being a professional programmer means that you are able to adapt to whatever coding standard is used in the project you're working on.</p>

Title: Is there a way to support different coding styles in a development team

Body:
The Problem: Two developers => three opinions on indention, braces on new line or not etc.

We usually work with three or four people on our projects and each of those has it's own code style. I know, the common solution is to agree on a code style, everybody has to use, but I don't want to force creative programmers in a suit that does not fit them.

So the question is: Is there a way to let each programmer live his/her own style, but having a common code base inside the repository? I think of some git/svn/whatever plugin, which changes between personal and common style on checkout and commit. It appears to me, that the tricky part in this approach is to support correct diffs between the versions of a file


问:
Which of these OOP examples demonstrate proper OOP concepts?
I'm still trying to wrap my head around OOP. All of the following examples work, of course, but is there one (or possibly another) that best exemplifies OOP concepts?

```<code>/**
 * For the following examples the Image class queries an image
 * and associated info from a database, which is passed on
 * instantiation via dependency injection.
 */

$image = new Image(new Db());
</code>```

Example 1:

```<code>if ($image->setImageId($id, $size)) {
    header('content-type: ' . $image->content_type);
    header('content-length: ' . $image->length);
    echo $image->getBytes();
}
</code>```

Example 2:

```<code>if ($image_info = $image->getImageInfoByIdAndSize($id, $size)) {
    header('content-type: ' . $image_info->content_type);
    header('content-length: ' . $image_info->length);
    echo $image->getImageBytesByIdAndSize($id, $size);
}
</code>```

Example 3:

```<code>$image->setImageIdAndSize($id, $size);

if ($image_info = $image->getImageInfo()) {
    header('content-type: ' . $image_info->content_type);
    header('content-length: ' . $image_info->length);
    echo $image->getImageBytes();
}
</code>```

答:
(my opinion, please do not be offended if you disagree)

None is good.

Method name does not indicate at all that headers are being sent or something is being echoed.

I would prefer something like following.

```<code>class Image {

public function __construct($id) {
#load, if fail throw exception
}

private function getHeaders() {
    return array(
        'content-type'   =>  $this->content_type,
        'content-length' => $this->length
    );
}

private function sendHeaders() {
    #calls function sendHeaders defined somewhere far away (usually it is 'app' object which has method like this)
    sendHeaders($this->getHeaders());
}

/** Sends image headers and content(bytes) */
public function sendImage() {
    $this->sendHeaders();
    echo $this->getBytes();
}
}
</code>```

If I am missing 'OOP way' please write in comments as I am also learning, and I would be thankful for directing me in right way :)

Body:
(my opinion, please do not be offended if you disagree)

None is good.

Method name does not indicate at all that headers are being sent or something is being echoed.

I would prefer something like following.

class Image {

public function __construct($id) {
#load, if fail throw exception
}

private function getHeaders() {
    return array(
        'content-type'   =>  $this->content_type,
        'content-length' => $this->length
    );
}

private function sendHeaders() {
    #calls function sendHeaders defined somewhere far away (usually it is 'app' object which has method like this)
    sendHeaders($this->getHeaders());
}

/** Sends image headers and content(bytes) */
public function sendImage() {
    $this->sendHeaders();
    echo $this->getBytes();
}
}

If I am missing 'OOP way' please write in comments as I am also learning, and I would be thankful for directing me in right way :)


答:
YES, it can work as long as the styles are all sensible and people don't go around changing other peoples' code to match their preferences and/or mix styles in a single code file.

It's not ideal, but it's no different from inheriting old code created to a different "standard" from your own and having to integrate it with your codebase.

So if you have to do it, some guidelines:

no changing differently styled code to match your preferences, it costs time and introduces bugs

remain consistent within any single file. So if style A was used to initially write it, everyone will use style A when modifying it

do create a common standard for your public interface, so for everything that is exposed to the outside (and yes, other subcomponents of a system are the outside).


答:
The short answer is No.

While opinions are to be valued in work especially in a knowledge based job such as Software Development, developers have to realise that an opinion is just that an opinion and that they are there to write software not argue over which line indentation standard is best.

The goal of a standards document should be to enforce/suggest a set of common coding standards/conventions that addresses

Layout Items such as tabbing, indentation, use of {,( ,

Variable, Object and Function name i.e. CamelCase, Hungarian notation

Exception Handling how/when/where is it to be performed

Code comments. Do you always reference a design doc, a bug number etc

The standards documents helps to ensure that the code is easy to read, maintain and consistent in its conventions.

This is invaluable when reviewing the code before checkins, debuging someone elses code or modifying the code several years after the original developer has left the company.

Normally when creating a Coding Standards document I review the industry standards for the language I am using (C, C#, SQL), use the most appropriate standards, circulate to the most senior/influential developers for comment, incorporate the comments where appropriate and then release the document.


答:
One-way automatically reformatting code may be a workable solution if you :

Find an autoformatter that actually works for the convention you want to implement and your programming language.

Can do it pre-commit so the reformatting doesn't show up in the change logs mixed with and indistinguishable from the actual functional changes.

Manage to get your team to agree on which convention should be applied (because generally speaking there is no "way back" on check-out to a developer's personal preference, at least not that I know of).

None of those are actually easy to do in many cases, so consider picking your battles here!  I've seen teams do this successfully for a C#/.NET project where the reformatting happened already on the developer's PC, so it is possible in some circumstances.


答:
Automatically reformatting code before it is committed to your version control system is possible in theory.

However, there is one big problem: automatic code formatting tools are not 100% reliable.  Thus, you could actually introduce problems in your code with this system. In my mind, that kills the idea.  It is always more important to have functional code than properly styled code!

If the project is compartmentalized, and most parts of the code tend to be "owned" by individual programmers, then it may be ok to let them use their own styles (within reason).  However, if several people are frequently working on the same piece of code, it is probably necessary to enforce a style.

Here is a similar discussion on Stack Overflow.


问:
Storage Client Library 2.0 - Why is the API not as intuitive to use as 1.7?
I am migrating to using the new Storage Client Library for my Azure Table Storage.

Querying with the previous Storage Client Library 1.7 namespace:

```<code>var orders = serviceContext
                 .CreateQuery<Order>(tableName)
                 .AsTableServiceQuery<Order>()
                 .Where(e => e.PartitionKey == partitionKey && e.RowKey == rowKey)
</code>```

Querying with the new Storage Client Library 2.0 classes:

```<code>string partitionKeyFilter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, partitionKey);
string rowKeyFilter = TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, rowKey);
string combinedFilter = TableQuery.CombineFilters(partitionKeyFilter, TableOperators.And, rowKeyFilter);

var query = new TableQuery<Order>().Where(combinedFilter);
var orders = table.ExecuteQuery<Order>(query);
</code>```

Please correct me if I'm wrong, but 1.7 is cleaner, uses strongly-typed entities, implements the IQueryable interface and utilizes the full power of LINQ.  Version 2.0 makes me feel like I'm working with ADO.NET Datasets again.

Am I completely missing the plot here?  I understand that there have been major performance improvements, but version 2.0 feels like a downgrade of an API.

Why isn't there a IQueryable<T> interface for 2.0?

答:
Asked the same question on Stackoverflow:

Storage Client Library 2.0 - Why is the API not as intuitive to use as 1.7?

See the above link for answer.


问:
Switching from ActionScript to JavaScript, tips for writing code?
I am quite comfortable with using actionscript3 and flash. I also have some experience with Java. But recently, I started learning JavaScript and node.js. I ultimately want to make a 3d game in threejs, but for now I simply want to make a chat application.

I want to get into the habit of using JavaScript. Unfortunately, I am finding it very difficult to start using JavaScript. The difficulties I am facing are

No suggestions for different methods and properties pop up, like they do in the Eclipse IDE and Flash Builder IDE. Like when you press dot after object, it shows all the methods and properties relating to that object and it becomes really easy to see what the parameters are and needed to be passed and stuff.

How to organize code? In ActionScript3, I could simply make different classes in different packages. I could then import and use those classes in one main file. How does it work in JavaScript?

Functions. I have seen people use anonymous functions in javascript. But I am compelled to write external functions as I am in the habit of it. What is better in JavaScript workflow? What do you advice?

How is code executed within a HTML file? So if I have several  tags and I declare a variable in one of them, can the tags below it and above it access that variable?

答:
For IDE:s consider using something that has good autocomplete support like visual studio, aptana or webstorm. These will make your life a lot easier.

For class-like structures consider Module pattern.

http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Check out Douglas Crockfords book good parts
and maybe check out some book on javascript patterns.

Because there aren't any classes don't mean that there aren't any good
solutions to organising code.


答:
Well technically speaking an assert normally gets compiled out of release builds so you wouldn't see them operate in code running in production. That said, you may still put them in to your application code as a kind of inline unit test so that they still do operate whilst your code is running in development/testing.

Normally unit tests run bits of application code and then check that certain things are true using asserts. That said there is still sometimes a reason to use an assert within the application code because, most importantly, a unit test can fail from an assert in the unit test code or an assert in the application code being tested.

Consider that you write a unit test that runs a contrived sequence of operations on your application that you suspect could theoretically cause bad things to happen. You might not have an easy way, from the scope unit test, to probe into your application classes to check if something is going wrong and there might be an easier alternative in adding the assert into the application code directly.
Sometimes I write unit tests without an assert in the unit test itself, simply to attempt (and hopefully fail) to invoke one that I put in the application.

And a final note - asserts are not the same as exceptions. Exceptions are used for still expected (rare) behaviour and this can still be tested for as unit tests can be written to expect exceptions. Assertions are used for impossible unexpected behaviour and hence associated with the core concept of unit testing.

Title: About the usage of assertions

Body:
I stumbled upon an article named Programming With Assertions.

And beside the mechanism of turning on and off assertions after compile time, I don't get it. Why were assertions introduced on language level, which is quite a big deal, isn't it?

I have never used assertions in production code, was never taught to use them in production code, and never saw assertions in production code. Beyond that, I would always prefer a more specific Exception over an AssertionError.

So here are my questions. Does anyone use assertions in production code, and what are the advantages of that usage?


问:
Barter vs. Cash for a Retailer's eCommerce Site
I am putting together a proposal for a local store with both a brick-n-mortar and web presence. It's an upscale shop that also happens to be one of my wife's favorites. I am considering offering the option of barter for part of the payment. I have two questions in this regard:

What would be a reasonable “exchange rate” for such a transaction? That is, in lieu of $1000 cash money, I should ask for about how much in store credit?

In your own experience, has using barter introduced any complications into the client relationship? Are there particular pitfalls to be concerned about?

答:
I'd stay away from "store credit" or anything out of the store's inventory because you don't really know what the true value of it is.

Let's say you do $1000 of work and accept $1000 of store credit. The goods you buy with that $1000 may have cost only $500 wholesale. Plus, you owe sales tax and income tax on that $1000 while the owner gets to write the whole thing off. You get the short end of the stick.

If you want tangible goods, get them to buy it at the same price you would pay or figure out what the actual wholesale price is.

Otherwise, trade like-for-like. If you do services for someone, have them to do a service for you.

I usually insist on cash. It keeps everyone honest.

ContentLicense: CC BY-SA 2.5


问:
How to avoid repetitively logging in to web site?
While developing web sites it can be annoying that I have to login to the site.
Every time the session runs out I have to go through a flow like...

Open logon page -> enter username/password -> click link to navigate to my page.

I sometimes use Selenium to record this flow, and then automate it.
But Selenium doesn't work in all browsers, and it still takes
too long to load etc.

I would like to be able to just refresh the page, exactly like I would if the
site didn't have a login page.

Does anyone use any strategies to achieve this?
Any way to disable login during development?
Or other tools which can help improve the situation?

答:
Rather than disable the login, manually invoke your login procedure on Session start.

For example, in pseudo code, do the following:

```<code>protected void Session_Start() {
    /* Login */
    LoginController.LogUserIn("myUsername", "myPassword");
}
</code>```

This, of course, holds true only for development systems with development passwords. If you need this for a production system I'd be looking for SSO options.

Body:
Rather than disable the login, manually invoke your login procedure on Session start.

For example, in pseudo code, do the following:

protected void Session_Start() {
    /* Login */
    LoginController.LogUserIn("myUsername", "myPassword");
}

This, of course, holds true only for development systems with development passwords. If you need this for a production system I'd be looking for SSO options.


问:
Using testing branches in Git
We have someone (let's call him Ted) that is responsible for testing new features and bug fixes.

We're using Git and GitHub. master should be/is always deployable and development is where we commit/merge new features or bug fixes, but only after they have been tested by Ted.

The project is in PHP.

I'd like the testing process to go like this:

A developer wants to work on a new feature (let's say the feature/bug #123 as Ted documented in the issue tracker), so he pulls origin/development to development on his local repository and creates a new branch (let's say issue-123) from there.

Once he's happy with his work, he commits and pushes his new branch to origin.

Ted connects to test.ourproject.com/choose-branch and sees a list of the branches on origin and chooses to switch on issue-123 (it should be doable through the webpage). He then goes on test.ourproject.com, tests the hell out of the web application (he's really pitiless) and after some back and forth with the developer, he's happy with the feature.

Ted tells the developer that he can merge issue-123 onto development on origin.

Rinse and repeat.

For the third step, I could hack something that does the job (showing and switching branches from a specific page), but I feel that what I've described is a very common pattern.

So my question is:
Is this a good / sustainable / maintainable workflow for branching? Can you back up your answer by citing some examples of other projects following this workflow?

答:
If your testing is done automatically rather than manually, I think Travis (a CI system for GitHub) will pretty much do what you want--it automatically runs tests on all pull requests.  (More information about this process, including screenshots.)

Note that tests are run not on the branch, but the branch after it's been merged into master.  (i.e. what you would get after merging the branch into master--you're guaranteed that tests will still run successfully post-merge.)

If commits are added to the branch, tests are re-run.  (Though for some reason adding commits to master doesn't seem to re-run the tests.)

Title: Using testing branches in Git


问:
Why does Resharper prefer "as" to "is"?
When I write code like this, where obj is a local variable:

```<code>if (obj is IMyInterface)
{
   var result = (IMyInterface)obj;
   // ....
}
</code>```

Resharper offers to change it into code like this:

```<code>var result = obj as IMyInterface;
if (result != null)
{
   // ...
}
</code>```

I prefer the former, as it offers no opportunity for accidental null reference exceptions.   What reasons are there for preferring the other form?

Why does Resharper recommend this?

答:
Firstly look at the Jon Skeet answer for general question about casting in C#:

Don't do this:

```<code>if (randomObject is TargetType)
{
    TargetType foo = (TargetType) randomObject;
    // Do something with foo
}
</code>```

Not only is this checking twice, but it may be checking different things, if randomObject is a field rather than a local variable. It's possible for the "if" to pass but then the cast to fail, if another thread changes the value of randomObject between the two.

(...)

If randomObject might be an instance of TargetType and TargetType is a reference type, then use code like this:

```<code>TargetType convertedRandomObject = randomObject as TargetType;
if (convertedRandomObject != null)
{
    // Do stuff with convertedRandomObject
}
</code>```

Then see similar topics:

What is the difference between the following casts in c#?

Casting vs using the 'as' keyword in the CLR

What is a difference between casts: (A) x and x as A?

Title: Why does Resharper prefer "as" to "is"?

Body:
Firstly look at the Jon Skeet answer for general question about casting in C#:

Don't do this:

if (randomObject is TargetType)
{
    TargetType foo = (TargetType) randomObject;
    // Do something with foo
}

Not only is this checking twice, but it may be checking different things, if randomObject is a field rather than a local variable. It's possible for the "if" to pass but then the cast to fail, if another thread changes the value of randomObject between the two.

(...)

If randomObject might be an instance of TargetType and TargetType is a reference type, then use code like this:

TargetType convertedRandomObject = randomObject as TargetType;
if (convertedRandomObject != null)
{
    // Do stuff with convertedRandomObject
}

Then see similar topics:

What is the difference between the following casts in c#?

Casting vs using the 'as' keyword in the CLR

What is a difference between casts: (A) x and x as A?