答:
if all or most of the coding is not done until the end of the sprint?

Why is it not finishing sooner? This key limitation is the source of your troubles, and I've seen two approaches be successful. One fits well into the agile approach (but not other common practices) and the other taints agile a bit (but is more common).

The first is that you don't code until the end of the sprint. Actually writing code is a relatively small part of development. If you finish about half way through the sprint, that provides plenty of time for QA to do their job. It also leaves you plenty of time to write documentation, clean up technical debt, do design for backlog items... All of the other stuff that you need to do for a quality product. The one downside to this I've seen is that it is nearly impossible to get the functionality and the unit tests done that quickly. Personally, I think it's completely fine to do unit tests after letting QA start to take a look at functionality, but TDD advocates (and others) will disagree.

The second option is to have QA operate a sprint behind the development staff like your PM hates. I also tend to dislike this. It eliminates the concept of "releasable product" at the end of the sprint, even if you have an escalation process for your releases. Worse, developers will be focused on "new" things when QA comes to them with questions or bugs from testing. Devs are also more unlikely to fix bugs in this arrangement. But I've seen it produce quality software on time.

Title: Coding and testing in the same sprint


问:
Source code modification and GPLv3 compatibility
Assume that the source file A contains the following license notice:

"This code is Copyright 1234 by XYZ. It may be freely redistributed in its entirety provided that this copyright notice is not removed."

Can I combine it with a project B published under the GPL version 3 license? In particular, does the lack of a permission to modify source file A ("redistributed in its entirety") prohibit that?

答:
For a formal answer on the compatibility of the two licenses, you need to ask a copyright lawyer or the FSF.

My, non-lawyer, take on it is that the two licenses are not compatible and that you can't use file A in a GPL project.

The licenses are incompatible because the license on file A gives you fewer rights than the GPL (you don't have the right to modify), and the GPL requires that the rights given by the GPL must be valid for the entire program that uses the GPL code, even the portions of the program that aren't licensed under the GPL.

ContentLicense: CC BY-SA 3.0


问:
Coding and testing in the same sprint
How is testing handled within the same sprint as coding, if all or most of the coding is not done until the end of the sprint? (I'm referring to the "soup-to-nuts" development and testing of a single PBI within a sprint.)

Most of the answers I've seen online involve QA automation, but even that isn't really possible since you generally need a functional UI to record or create automated tests from. I only have storyboards that continue to evolve as I develop features and discover new requirements.

In my case, I am developing a new desktop application. Desktop apps don't generally lend themselves to automated testing very well. I have some automated unit tests, but they are not the manual functional/integration tests that a QA professional would perform.

So, where I'm at now is that my sprint ends tomorrow, I still have coding to finish, and my QA folks have nothing to test yet, and no idea how to test whatever I'd give them without me holding their hands.

I'm sure I'm not the first person to have this dilemma.

In the past, I've done a pipeline: in the current sprint the test team tests the features that have been implemented during the previous sprint. At my current job, the PM refers to this approach as "waterfall", and as such, unacceptable.

答:
The essential problem is that you have programmers who code but don't test and testers who test but not code.

Solve that problem and you will not have this problem, and an arguably more efficient team.

One way that worked for me in the past was to suggest coders and testers to pair on stories with the explicit task of delivering a fully tested story. Together with that I've erased all forms of "dev complete" thinking: no "dev complete" columns on the scrum/kanban/trello board, no "dev done" attitude by coders.

What happened was:

Pairs were responsible for delivering stories and they would both fail if a story was not completed. They were treated as responsible professionals in charge of delivering software and they did, in most cases.

There was much less testing work done because testers were exposed to unit and integration tests, so they didn't repeat the same test manually.

Some testing got automated when the devs understood better what the testers needed.

Some people got upset.

Stories got delivered quicker on average because the code-commit-pull-test cycle became almost instant

Of course, this is only my anecdotal experience, but you might want to try that yourself if you can.

In your case, given your comment that testers and developers are authoritatively separated in your company, the message seems clear to me. There's an obvious barrier to communication and collaboration put up by company rules.

This is a communication problem, not an agile problem. Adopting an agile methodology is simply making it evident. Silo'd teams are a known management anti-pattern, so embrace the non-adaptability of agile in this case!

Title: Coding and testing in the same sprint


问:
Is Visual Studio just an IDE?
For Windows Development I mean.

Looking over other questions there are alternatives to VS, but they seem to be web based ones, which is fine, or you could program an entire .net website in notepad, should the urge drive you to.

But is there more to it than just an IDE for Windows Development? I.E. Is it possible for me to create an application in just notepad, is the compiler part of Visual Studio, or is it separate, which could be called via command line or something?

I don't want to not use VS, I'm happy with it, does what I need etc etc, just more a facet I'm curious about.

答:
Not only is the compiler completely separate, so is anything else you might need to build a .net project.  Visual Studio solution and project files are just XML that is understood by MSBuild (another command line tool), which in turn calls the relevant compiler.

Yes, Visual Studio is just an IDE.  That integrates most of the individual tools that you might use during the SDLC (SQL Server, StyleCop, etc.) into a single application.

That's all!

ContentLicense: CC BY-SA 2.5

Title: Is Visual Studio just an IDE?


问:
Why would a C executable be smaller when compared to C++ executable
I'm trying to understand why the output file sizes are significantly different when using a C and a C++ compiler.

I was writing a small hello world program in C and C++, I noticed that in C version, the size of the executable was 93.7KB and in C++, the size of the same hello world program was 1.33MB. I am not sure why that is. I think it may be because C++ has more libraries and namespaces to use so I removed the using namespace std line and simply used std::cout and still the result was the same.

C

```<code>#include <stdio.h>

int main()
{
    printf("hello world");
    return 0;
}
</code>```

// size 93.7KB

C++

```<code>#include <iostream>

int main()
{
    std::cout<<"Hello world";
    return 0;
}
</code>```

// size 1.33MB

There doesn't seem to be much difference in the code above.  Is there some sort of compiler difference that creates the differing file sizes?

答:
Most of the C++ standard library, including all the streams which cout is part of, are inline template classes. Whenever you #include one of these inline library components, the compiler will copy and paste all that code to the source file that is including it. This will help the code to run faster, but will also add a lot of bytes to the final executable. This is likely the reason for the results you got.

Doing a similar test with the clang compiler on OSX (Apple LLVM version 5.1), using default flags, I got comparable results:

hello_cpp_cout:

```<code>#include <iostream>
int main()
{
    std::cout << "Hello world" << std::endl;
    return 0;
}
</code>```

Size: 14,924 bytes

hello_c:

```<code>#include <stdio.h>
int main()
{
    printf("hello world\n");
    return 0;
}
</code>```

Size: 8,456 bytes

And, as a bonus, I tried to compile a .cpp file with the exact same code as hello_c, i.e.: using printf instead of cout:

hello_cpp_printf:

```<code>#include <stdio.h>
int main()
{
    printf("hello world\n");
    return 0;
}
</code>```

Size: 8,464 bytes

As you can see, the executable size is hardly related to the language, but to the libraries you include in your project.

Update:

As it was noted by several comments and other replies, the choice of compiler flags will also be influential in the size of the compiled executable. A program compiled with debug flags will be a lot larger than one compiled with release flags, for example.

Body:
Most of the C++ standard library, including all the streams which cout is part of, are inline template classes. Whenever you #include one of these inline library components, the compiler will copy and paste all that code to the source file that is including it. This will help the code to run faster, but will also add a lot of bytes to the final executable. This is likely the reason for the results you got.

Doing a similar test with the clang compiler on OSX (Apple LLVM version 5.1), using default flags, I got comparable results:

hello_cpp_cout:

#include <iostream>
int main()
{
    std::cout << "Hello world" << std::endl;
    return 0;
}

Size: 14,924 bytes

hello_c:

#include <stdio.h>
int main()
{
    printf("hello world\n");
    return 0;
}

Size: 8,456 bytes

And, as a bonus, I tried to compile a .cpp file with the exact same code as hello_c, i.e.: using printf instead of cout:

hello_cpp_printf:

#include <stdio.h>
int main()
{
    printf("hello world\n");
    return 0;
}

Size: 8,464 bytes

As you can see, the executable size is hardly related to the language, but to the libraries you include in your project.

Update:

As it was noted by several comments and other replies, the choice of compiler flags will also be influential in the size of the compiled executable. A program compiled with debug flags will be a lot larger than one compiled with release flags, for example.


问:
How could an expert system get some meaning from a sentence?
How could an expert system tell following scenarios apart? How could we include some meaning of a sentence, if at all?

```<code>A machine needs 1 day to produce x units, and,

we know that two machines like the first would need 1/2 day for x units.
</code>```

However, if:

```<code>a truck transports a container from a to b in 1 day,

but two trucks won't transport the same container in half the time.
</code>```

But how to establish a logical rule to exclude attaching a truth value to the second sentence? Hoe to process sentences that depict a process that can not be divided in pieces (that means, include the meaning of 'divisible'/'non-divisible'), and therefore, an expert system can't assign automatically a time value to a process that has to be performed. The enhanced expert system would then be able to avoid scheduling failures.

答:
It seems to me that you're comparing apples & oranges.

A machine needs 1 day to produce x units, so,
  this implies that two machines like the first would need 1/2 day.

No, it implies 2 machines can produce 2x units in 1 day.  We don't have enough information to know if x is divisible, if the machines can cooperate, if there are external constraints (incoming resources), etc.

Think about babies - one woman can produce a baby in 9 months but that does not imply 9 women working in tandem can produce one in a single month.

On the other hand, while one woman can theoretically produce 10 babies in 10 years, 10 women can produce 10 babies in one year.

My point is that you need more information to make the inferences you're looking for.  The one sentence examples only work if the reader can supply additional supporting information from experience, education, etc.


答:
If you don't test a User Story (US) and verify that the acceptance criteria are met this story is not done. If its not done this US goes to the next sprint of course. And if all your US are in this state you sprint has ended with no value added to the project. From the client point of view I cannot distinguish this from the entire development team going on vacation.

One of the lean principles (agile doesn't end with scrum) says "quality is built in". Something is only done if it meets the quality criteria you define. This is crucial to have a real agile process, ending spring with zero value or separate testing from development are symptoms of a big problem.

There are a lot of things you can do:

automation is key to success. At least at unit test level, and some other practices like CI are important too. This is not enough, but if done well these types of testing result in few or no bugs discovered in manual testing (usually minor UI things). If you have dedicated QA people they can be the ones who automate the acceptance testing, and some of this automation can start before you finish a sprint.

Look at the size of your User Stories. If you have a US that is finished the two first days of the sprint the third day a QA person can test it.  In my opinion having small (SMART) user histories one of the most important things to success in agile development, and a lot of people seems to no t realize this.

Collaboration between tester and developers is another key part of success. In my previous project when a US its finished by a developer a QA person do "pair testing" with the developer (can be manual, can be via launching some automated, or better, both), this works pretty well.

Title: Coding and testing in the same sprint

Body:
How is testing handled within the same sprint as coding, if all or most of the coding is not done until the end of the sprint? (I'm referring to the "soup-to-nuts" development and testing of a single PBI within a sprint.)

Most of the answers I've seen online involve QA automation, but even that isn't really possible since you generally need a functional UI to record or create automated tests from. I only have storyboards that continue to evolve as I develop features and discover new requirements.

In my case, I am developing a new desktop application. Desktop apps don't generally lend themselves to automated testing very well. I have some automated unit tests, but they are not the manual functional/integration tests that a QA professional would perform.

So, where I'm at now is that my sprint ends tomorrow, I still have coding to finish, and my QA folks have nothing to test yet, and no idea how to test whatever I'd give them without me holding their hands.

I'm sure I'm not the first person to have this dilemma.

In the past, I've done a pipeline: in the current sprint the test team tests the features that have been implemented during the previous sprint. At my current job, the PM refers to this approach as "waterfall", and as such, unacceptable.


答:
The difference in executable sizes will be heavily dependent on what type of linkage is specified, optimisations and the compiler(s) being used.

Given the significant difference in final sizes, it looks like the C++ variant is being statically linked with the runtime. Remove or change that and you should see a drop in the C++ size; for gcc (g++) look for --static* et. al and for msvc /MD and /MT

Title: Why would a C executable be smaller when compared to C++ executable

Body:
I'm trying to understand why the output file sizes are significantly different when using a C and a C++ compiler.

I was writing a small hello world program in C and C++, I noticed that in C version, the size of the executable was 93.7KB and in C++, the size of the same hello world program was 1.33MB. I am not sure why that is. I think it may be because C++ has more libraries and namespaces to use so I removed the using namespace std line and simply used std::cout and still the result was the same.

C

```<code>#include <stdio.h>

int main()
{
    printf("hello world");
    return 0;
}
</code>```

// size 93.7KB

C++

```<code>#include <iostream>

int main()
{
    std::cout<<"Hello world";
    return 0;
}
</code>```

// size 1.33MB

There doesn't seem to be much difference in the code above.  Is there some sort of compiler difference that creates the differing file sizes?


答:
There doesn't seem to be much difference in the code above.

Yes there is. It's a totally different code. The c++ iostream library relies heavily on template which creates more inline code and so the C++ executable is bigger.

Another reason is that you did not remove debug sympols from the executable files, and for C++ the symbols are quite verbose. If you are under linux, you can use the "strip" command to remove those symbols and the executable size will shrink.


问:
Choosing a functional programming language
I have read a lot of threads about functional programming languages lately (almost in the past year, in fact). I would really like to pick one and learn it thoroughly.

Last [course] semester, I have been introduced to Scheme. I loved it. Loved the extreme simplicity of syntax, the homoiconicity principle, the macros (hygienic and non-hygienic), the n-arity of procedures, etc.

The problem with Scheme is it's an academic language. I don't think it is really used in production environments. I don't believe either that it is particularly good to have on our resume. So, I have been looking around for alternatives. There are many of them and they somehow all seem to have a similar level of popularity.

Some thoughts about some other functional languages I have considered yet:

Clojure: It sounds great because it can access the Java world, it is oriented towards scalability and concurrency, but isn't the Java world on an edge right now? I already know Java pretty well, but would it be wise to add even more energy on depending on the JVM?

Haskell: Looks like a very appreciated language, but from what I have read, it's also more of an academic language.

Lisp: It's been around since forever. It seems to have most of what I like from Scheme. It has a big community. For what I [think I] know, it is probably the most widely used functional programming language in industry(?).

F#: Didn't really consider it. I'm not a big fan of MS stuff. I don't have the money to pay for their softwares (I could have them free from university alliances, but I'm more inclined to go with community-driven solutions). Though... I guess it would be the best career-oriented choice.

Tonight, I'm leaning towards Lisp. One week ago, it was Haskell. Before that it was Clojure. In the past year, I was doing some Scheme for fun, not pushing it for the reason you know. Now I would like to get serious (about learning one, about doing real projects with it, about maybe eventually professionally working with it). My problem is I would need to learn them all in depth before being able to choose one.

答:
If you want to learn functional programming, you might be better served to learn Haskell first, then use whichever language you want. You can learn functional programming using the other languages, but they still allow for imperative and object-oriented code. If you write a real program in Haskell, you will learn functional programming faster because the other paradigms won't be available to fall back on.

After writing your Haskell program, you will have tools like monads and techniques like point-free coding to bring to the language of your choice. The concepts seem to map especially well to Scheme.


问:
Caching large amount of ajax returned objects
I'm building an application which fetches large amount of items with ajax requests via other application API. It returns me 6k - 30k js objects which are used multiple times across various application views (sorting, filtering etc.). I would like to avoid querying API every time for such big list so I decided to cache this data somehow.

I was thinking about various solutions:

saving it to localstorage,

using some caching library (e.g. locachejs),

storing in js var.

I'm not an expert so I would like to hear Your suggestions about each (or one of these) solution, about its pros and cons.

Every help will be very appreciated.

答:
Unfortunately, the "right" answer here would depend on the size (complexity) of those objects.

I have found from experience that 25.000-50.000 of objects of most common complexity is the limit that keeps browser behaving within limits of usability.

There are some useful results here, that match with mine, and you can compare the sample object with yours:

http://www.ziggytech.net/technology/web-development/how-big-is-too-big-for-json/

Having that in mind, caching this data could be a viable approach with following considerations:

will waiting for ~4MB of data to load be justified by the increased responsiveness of the app later?

localstorage is limited to 5MB

If the wait is justified, I would recommend to either:

store data in a var (memory consumption is not that bad), if you just need to access parts of it by keys and use it directly

use IndexedDB, if you need to query the data, its structure is more complex or you need to manipulate it in different ways on the client side - it is a somewhat more involved approach, but libraries can help (https://github.com/aaronpowell/db.js served me well)

Best of luck!


问:
Algorithm for percentage without knowing total number
Suppose there are n lines for a hotline.

Whenever a customer calls the hotline, the call is forwarded to one of the n lines. And I want to assign  percentage of calling to each of the n lines. Suppose there are two lines and one line is assigned 60% and other is 40%, the total number of calls is 10 so the first line would receive 6 calls and second will get 4 calls.

I know the percentage of calling to each line in advance but the problem is that I don't know the number of calls that would be received in a day.

How can I distribute the number of calls without knowing the total calls?

答:
Do some bookkeeping about the already taken calls and calculate their distribution over the n lines. This gives you n percentage values (your already achieved distribution), which can be compared to the n percentages you want to achieve. Whenever a new call comes in, assign that call to the line with the highest deviation from the target value (note that as long as you don't hit the given distribution exactly, there is always a line which has too few calls so far, when compared to the target distribution).

For example: after assigning the first call to line 1:

```<code> total calls line1      total calls line2    perc.line 1    perc. line 2
 1                      0                    100%             0%
                                             *above 60%      *below 40% <- next call to 2
 1                      1                    50%             50%
                                             * below 60%:    *above40% next to line1
 2                      1                    66%             33%
                                             *above 60%      *below 40% <- next to line 2
 2                      2                    50%             50%
                                             * below 60%:    *above40% next to line1
 3                      2                    60%             40%
                                             * both hit the mark: next call arbitrary
 4                      2                    66%             33%
                                             *above 60%      *below 40% <- next to line 2
 4                      3                    57.1%             42.85%
                                             *below 60%      *above 40% <- next to line 1
</code>```

...

EDIT: This approach could be further improved by not using the absolute difference, but choosing the line which minimizes the sum-of-squares of all deviations. That would also give you a better result in case you reach the target values exactly.

Body:
Do some bookkeeping about the already taken calls and calculate their distribution over the n lines. This gives you n percentage values (your already achieved distribution), which can be compared to the n percentages you want to achieve. Whenever a new call comes in, assign that call to the line with the highest deviation from the target value (note that as long as you don't hit the given distribution exactly, there is always a line which has too few calls so far, when compared to the target distribution).

For example: after assigning the first call to line 1:

 total calls line1      total calls line2    perc.line 1    perc. line 2
 1                      0                    100%             0%
                                             *above 60%      *below 40% <- next call to 2
 1                      1                    50%             50%
                                             * below 60%:    *above40% next to line1
 2                      1                    66%             33%
                                             *above 60%      *below 40% <- next to line 2
 2                      2                    50%             50%
                                             * below 60%:    *above40% next to line1
 3                      2                    60%             40%
                                             * both hit the mark: next call arbitrary
 4                      2                    66%             33%
                                             *above 60%      *below 40% <- next to line 2
 4                      3                    57.1%             42.85%
                                             *below 60%      *above 40% <- next to line 1

...

EDIT: This approach could be further improved by not using the absolute difference, but choosing the line which minimizes the sum-of-squares of all deviations. That would also give you a better result in case you reach the target values exactly.


答:
The Scrum Guide requires that teams be cross-functional. All team members are considered developers, irrespective of their individual specialisation. Silo'd individuals (coder, tester, qa, ux, etc) are unhelpful in Scrum. Team members help each other wherever they can. There is no concept of 'passing the item to qa'.

In your situation, it sounds as if you may have an estimating problem. When estimating product backlog items, you need to consider all activities, ie: Coding, Testing, Peer Review, Deployment, Integration - whatever your definition of done demands.

As a rough rule of thumb, expect to bring between 5 and 15 product backlog items in to a sprint. This gives you an idea of how large each product backlog item should be. It also gives you an excellent chance to get work 'done' within the sprint.

Finally, the task of the team is to move one product backlog item to 'done' and then move on to the next one. Sometimes, doing this means that people are treading on each others toes and so it makes sense to spin up more than one product backlog at a time. Your guideline though should be to reduce your work in progress (WIP) and move product backlog items to done.

Title: Coding and testing in the same sprint


问:
Web Services and code lists
Our team heavily discuss the issues how to handle code list in a web service definition. The design goal is to describe a provider API to query a system using various values. Some of them are catalogs resp. code lists. A catalog or code list is a set of key value pairs. There are different systems (at least 3) maintaining possibly different code lists. Each system should implement the provider API, whereas each system might have different code list for the same business entity eg. think of colors. One system know [(1,'red'),(2,'green')] and another one knows [(1,'lightgreen'),(2,'darkgreen'),(3,'red')] etc.

The access to the different provider API implementations will be encapsulated by a query service, but there is already one candidate which might use at least one provider API directly.

The current options to design the API discussed are:

use an abstract code list in the interface definition: the web service interface defines a well known set of code list which are expected to be used for querying and returning data. Each API provider implementation has to mapped the request and response values from those abstract codelist to the system specific one.

let the query component handle the code list: the encapsulating query service knows the code list set of each provider API implementation and takes care of mapping the input and output to the system specific code lists of the queried system.

do not use code lists in the query definition at all: Just query code lists by a plain string and let the provider API implementation figure out the right value. This might lead to a loose of information and possibly many false positives, due to the fact that the input string could not be canonical mapped to a code list value (eg. green -> lightgreen or green -> darkgreen or both)

What are your experiences resp. solutions to such a problem? Could you give any recommendation?

答:
How do you map what the client might send you to the data the API requires?

I mean if I've understood the question correctly, its about providing a webservice that wraps several other APIs, eg a pizza delivery service that passes requests on to either Tony's or John's pizza parlours, only Tony does Deep Pan and Thin Crust, and John does Traditional,  Stuffed Crust and Wholemeal.

You could implement a method that returns these options to the client, so they can ask "what choices do I have" and then can use these options in subsequent calls.

Title: Web Services and code lists


问:
Could taking design lightly be a pitfall of agile methodologies causing constant rework or is it a misunderstanding of the methodology?
I've been working for a year now in an agile project to redesign an insurance application.
I really like working in an agile environment, although management and analysts I work with still have waterfall thinking ingrained and makes it a little complicated to embrace the new paradigm shift to agile.

From a developer standpoint sometimes I feel like since we're doing "agile" we don't over-think or think enough our designs and just go with the flow and refactor later. Many times that ends up in rework because we never put enough though to certain pieces of the application. As far as I understand, agile is like having small waterfalls and deliver small pieces at a time (iterations), but sometimes we lose the big picture and end up paying for it later with rework.

Are agile methodologies encouraging or tolerating procrastination more than traditional waterfall? Is this constant rework for pieces of software with defined requirements acceptable?

Is anyone else experiencing something similar in their projects?

答:
All mature engineering disciplines include a design/systems engineering style phase (or multiple iterative phases).

The problem with software is that the design space is not as constrained as most engineering problems, so there is a lot of uncertainty/many ways to accomplish an engineering task, this is why Agile was developed.

Agile is good for some things, like customers who want websites, but don't really have a good idea of exactly what website they want.

Test driven development (TDD) and Agile, are however, poor (or poorly implemented) at other things, especially things which require actual engineering like :

Mathematical modeling

Algorithms

Constrained or task specific systems

Mission critical systems

etc.  Any engineering solution requires some iteration, this includes disciplines outside of software, but we absolutely cannot disregard design entirely.  Design is necessary to achieve efficient, robust, and scalable solutions.

Agile has been useful for the problem spaces where constraints are not defined or are not even known, but even in these situations design still needs to be included in the iterative process.  Recently I have encountered what I consider to be too great of a swing to minimize all design, and this is especially prevalent among Agile evangelists in my experience.

A parable of what can go wrong if you swallow too much Agile/TDD koolaid : http://ravimohan.blogspot.com/2007/04/learning-from-sudoku-solvers.html


问:
Is there a known standard data structure which is a hash table that resolves collisions using a binary tree?
Is there a known standard data structure which is a hash table that resolves collisions using a binary tree?
If so what is the name of this data structure?
I imagine such a structure would be useful as it should reduce the worst case search time down to O(log(n)) compared to O(n) in a hash table, and the best case would still be O(1).</p>

答:
Yes, but there isn't a standard name for it shorter than what you've already written.

Wikipedia says:

[...] by using a self-balancing tree, the theoretical worst-case time of common hash table operations (insertion, deletion, lookup) can be brought down to O(log n) rather than O(n). However, this approach is only worth the trouble and extra memory cost if long delays must be avoided at all costs (e.g. in a real-time application), or if one must guard against many entries hashed to the same slot [...]

and that's pretty much the reason why.


问:
Minimize travel distance of n people to n locations
The problem:

Given the coordinates of N people on a regular 2-dimensional plane and N target points-of-interest (POI) on the same plane, determine the set of pairs of people and POIs that minimize the sum of straight-line distances between the locations in each pair.  No two people can go to the same POI, and all POIs must be covered.

In other words, if I have 5 trucks that need to go to 5 locations and trucks are interchangeable, where do I send the trucks so that the least amount of fuel is used (assuming fuel use is proportional to distance traveled)?

Discussion:

Brute force would take N factorial.  Is there a better way?  This would seem to be a pretty common operations research problem, but my google-fu is insufficient.

答:
Copying the comments to get the problem out of the unanswered problems queue, and making it community wiki.

This sounds like the travelling salesman problem. See Algorithm for an exact solution to the Travelling Purchaser Problem

This is known as the assignment problem: en.wikipedia.org/wiki/Assignment_problem - Wikipedia lists some algorithms to solve it in polynomial time.

You're right! More specifically, it is exactly the transportation problem.


答:
I agree with @DocBrown's solution.  Placing it into an algorithm form:

```<code>for each incoming call:
    sort lines ascending by delta* (see footnote below)

    // first element in array gets the call
    increase number of calls for first element by 1
</code>```

Delta is determined by the actual percentage minus the expected percentage of a line.  In this way, those with the biggest negative delta are the ones which most require a call to conform with the expected percentage.

For example, in the case in which expected percentages for lines 1 and 2 are respectively 60% and 40%, and their actual percentages are 50% and 50%, you'd see the ordering line 1 followed by line 2, since -10% is less than 10%.  Hence line 1 would get the call.

I highly recommend using insertion sort since it performs best when the array is already mostly sorted.

Also, as a minor optimization, if you keep track of the total number of calls thus far, rather than having to calculate the actual percentage of each line, you can simply calculate the total number of calls for that line minus the expected percentage for that line times the total number of calls (delta = t_i - p_i*T).  In this case the delta is simply the negative number of calls to achieve the expected percentage.

I hope that clarifies any other doubts.

Title: Algorithm for percentage without knowing total number

Body:
Suppose there are n lines for a hotline.

Whenever a customer calls the hotline, the call is forwarded to one of the n lines. And I want to assign  percentage of calling to each of the n lines. Suppose there are two lines and one line is assigned 60% and other is 40%, the total number of calls is 10 so the first line would receive 6 calls and second will get 4 calls.

I know the percentage of calling to each line in advance but the problem is that I don't know the number of calls that would be received in a day.

How can I distribute the number of calls without knowing the total calls?

Body:
I agree with @DocBrown's solution.  Placing it into an algorithm form:

for each incoming call:
    sort lines ascending by delta* (see footnote below)

    // first element in array gets the call
    increase number of calls for first element by 1

Delta is determined by the actual percentage minus the expected percentage of a line.  In this way, those with the biggest negative delta are the ones which most require a call to conform with the expected percentage.

For example, in the case in which expected percentages for lines 1 and 2 are respectively 60% and 40%, and their actual percentages are 50% and 50%, you'd see the ordering line 1 followed by line 2, since -10% is less than 10%.  Hence line 1 would get the call.

I highly recommend using insertion sort since it performs best when the array is already mostly sorted.

Also, as a minor optimization, if you keep track of the total number of calls thus far, rather than having to calculate the actual percentage of each line, you can simply calculate the total number of calls for that line minus the expected percentage for that line times the total number of calls (delta = t_i - p_i*T).  In this case the delta is simply the negative number of calls to achieve the expected percentage.

I hope that clarifies any other doubts.

ContentLicense: CC BY-SA 4.0


问:
Passing central objects around or having global instances?
Having a larger WinForms application with several classes I currently pass references to several "central" objects around to function calls.

This leads to more method parameters.

Example:

```<code>public static class Program
{
    private static MyCentral _central;

    ...
}

...

public class SomeController
{
    public object SomeFunction(MyCentral central)
    {
        // Do something with the MyCentral instance.
    }
}
</code>```

Now I'm asking myself whether I should ditch this approach and instead use singletons for those central objects so that everyone can always access these objects and I do not need to pass them around anymore.

Example:

```<code>public static class Program
{
    public static MyCentral Central { get; private set; }

    ...
}

...

public class SomeController
{
    public object SomeFunction()
    {
        // Do something with the Program.Central singleton.
    }
}
</code>```

My question:

Are there any rules-of-thumb whether the singleton approach or the "passing objects around" approach should be prefered?

答:
The rule of thumb is:

Always pass around, never use the traditional singleton pattern approach.

The problem kind of solves itself if you use a dependency injection framework.

Using public statics will make testing harder, strongly couple your components, and make dependencies between your classes harder to see.


问:
Is Python Interpreted or Compiled?
This is just a wondering I had while reading about interpreted and compiled languages.

Ruby is no doubt an interpreted language since the source code is processed by an interpreter at the point of execution.

On the contrary C is a compiled language, as one have to compile the source code first according to the machine and then execute. This results is much faster execution.

Now coming to Python:

A python code (somefile.py) when imported creates a file (somefile.pyc) in the same directory. Let us say the import is done in a python shell or django module. After the import I change the code a bit and execute the imported functions again to find that it is still running the old code. This suggests that *.pyc files are compiled python files similar to executable created after compilation of a C file, though I can't execute *.pyc file directly.

When the python file (somefile.py) is executed directly ( ./somefile.py or python somefile.py ) no .pyc file is created and the code is executed as is indicating interpreted behavior.

These suggest that a python code is compiled every time it is imported in a new process to create a .pyc while it is interpreted when directly executed.

So which type of language should I consider it as? Interpreted or Compiled?
And how does its efficiency compare to interpreted and compiled languages?

According to wiki's Interpreted Languages page, it is listed as a language compiled to Virtual Machine Code, what is meant by that?

答:
It's worth noting that languages are not interpreted or compiled, but rather language implementations either interpret or compile code. You noted that Ruby is an "interpreted language", but you can compile Ruby à la MacRuby, so it's not always an interpreted language.

Pretty much every Python implementation consists of an interpreter (rather than a compiler). The .pyc files you see are byte code for the Python virtual machine (similar to Java's .class files). They are not the same as the machine code generated by a C compiler for a native machine architecture. Some Python implementations, however, do consist of a just-in-time compiler that will compile Python byte code into native machine code.

(I say "pretty much every" because I don't know of any native machine compilers for Python, but I don't want to claim that none exist anywhere.)

Title: Is Python Interpreted or Compiled?


问:
When does extracting methods from code stop to make sense?
I am currently studying the refactoring methods defined by Marting Fowler (http://refactoring.com/catalog/).

He states a tip for replacing chunks of code by a single method that does that job. So far, I agree, as we all learned about the downsides of Spaghetti-code. But the example for this rule looks as follows:

Replacing

```<code>    void printOwing() {
      printBanner();

      //print details
      System.out.println ("name:  " + _name);
      System.out.println ("amount " + getOutstanding());
    }
</code>```

by

```<code>    void printOwing() {
      printBanner();
      printDetails(getOutstanding());
    }

    void printDetails (double outstanding) {
      System.out.println ("name:  " + _name);
      System.out.println ("amount " + outstanding);
    }
</code>```

Is the readability and thus, the immediate understanding of the code really better in the latter example? There is no indication about what "details" are in reference to "owing". For example, will the name be listed or is there another method printName()? Is the interest listed as well? I would need to search for the printDetail() method's implementation to find out about that.

The method printOwing() itself is already a print-method. Would it not be easier for maintaining the code to just list the  System.out.println()'s in this method commenting the purpose as in the first example instead of "scattering" the code this way?

Is there a rule of thumb about when to stop "methodizing" and when it still makes sense?

答:
One thing to understand is that the examples in books are there to illustrate techniques, not necessarily to show the pinnacle of best practice. So if the sweet spot in refactoring was actually to extract 50-line functions from 500-line functions, every example in the book would take several pages and obscure the actual point.

What matters is not necessarily the size of the example, but that you can see and understand the technique used.

In the specific example, the "print details" comment suggests a smell that can be removed by extracting a print_details() function - better to make the functionality explicit and self-documenting rather than rely on comments.

However, unless print_details() had other uses, my personal opinion is that refactoring this would be make-work that takes time away from more important things.

That IS just my opinion : however I'm reading Code Complete at the moment and finding a lot to agree with in it : one point he makes is that studies actually show lower error rates in medium sized functions (50-150 lines) than in either many tiny functions or a few huge functions.

This jives with my own (mainly non-C++) experience though it's at odds with a lot of advice. To see data supporting such large functions is quite a surprise ... "it's not just me then".

Take this too with a pinch of salt :

C++ may be different from other languages in optimum function size

If your experience suggests a different optimum : 10 or 20 line functions, say, then I wouldn't waste time aggregating them on my or Steve McConnell's say so

but I would agree that breaking a 4-line function for the sake of refactoring is unlikely to be worth it (unless each line is very hard to understand!)


问:
How should I test boolean function with many possible permutations
When I write an unit test I usually provide a context (plain object or mocked/stubbed object) that I setup in some ways and then I can run assert statement on the context:

note: code is in pseudo-code; groovy like syntax:

```<code>test myTest() {
  def o = getTestContext();
  o.string = "testme"
  o.number = "2"
  assert o.mult() == "testme testme"
}
</code>```

But how to organize the test when you need to test a complex boolean expression that takes many parameters ?

EDIT: I have replaced the one line expression with something more readable to avoid confusion.

```<code>//this is not a real class, this is an example. Naming is bad, for conciseness sake
//the expression is coming from randomness realm, so it is probably refactorable and simplifiable, but complex real world expression still exists.
enum Type {X,Y,Z}
class C {
  boolean a,b,c,d;
  Type t;

  boolean isEnabled(boolean anotherFlag) {

    def condition1 = (a || b)
    def condition2 = (c && d)
    def goodType1 = t == X || t == Y
    def goodType2 = anotherFlag && t == Z || t == Z && !condition1

    return (  condition1  || condition2 ) && (goodType1 || goodType2)
  }
}
</code>```

All tests for this kind of methods I've read so far are very verbose, not complete and hard to understand.

And it is quite a shame that such a small line of code, even if it is 'complex', generates awful tests.

I've tried to break the boolean expression into smaller sub methods, but sometime it is not so convenient and the permutation count is still high. I also usually break the expression into intermediate variables, but this is not helping in unit test world...

How should I test something like this to have test code matching the briefness of the tested code and the completeness that must assert that my code works as expected ?

Edit: about the retained solution.

Refactoring is indeed a way to go, but I really don't want to 'unroll' all combinations manually in my tests: it is verbose, ugly and hard to understand.

However I'll keep this answer as a preliminary mandatory step: break the expression into smaller pieces before anything else.

Once the refactoring is done and the test still result in combinatory tests, then I'll use the TruthTable solution proposed. I'll just generate the combinations and not declare everything.

I found this interesting, but outdated, article about test combination in Groovy.

The tool they spoke about is out of search engine radar, so it must be dead !

However I'll use the same pattern:

```<code>assertThat(permutations, expectations, instanceObject)
</code>```

Where

permutation is all possible values to assign to properties in a 'condensed map': (a:[true, false], b:[true, false], ...)

expectation is all combinations that return a specific value, all other combination will be checked against a default value.

答:
Let me present another perspective. If your real code block is as complex as your example, it is not really good practice to write it that way.

"Concise" does not always mean "elegant". Sometimes, it just means "hard to debug".

Imagine if that complex condition was somehow failing - it would be downright annoying to figure out the problem. A better way is to have intermediate variables storing the values of the individual condition blocks. Of course, those intermediate variables need proper names to help readability.

Expand that "brief" code block into the corresponding nested if-else series. Every little if and else in that expanded block is a potential test condition. Now you will see that it is not brief after all. It is complex logic that must be treated with due respect.

With regards to your question, it would help to separate out each of these test conditions into its own test. They can share common setup, etc. using functions. At the unit test level, simpler individual tests are better because they help you pin-point the problem to the exact failure condition.

Organize each test as per the 3A pattern. This makes the tests readable and also independent of each other. Here's an example:

```<code>void testSummation()
{
    // ARRANGE
    Calculator testObject = new Calculator();

    // ACT
    int sum = testObject.add(1, 2);

    // ASSERT
    Assert.equals(3, sum);
}
</code>```

Arrange:

Set up the environment for the condition to be tested. This might include setting up some initialization parameters, mocks, etc.

Act:

Run an action on the object. A good practice is to make sure that this action is an independent operation as seen from the API of the object.

Assert:

Check whether the action had the intended effect. Validate the output variables, object state, etc. to make sure that the expected behavior was met.

Body:
Let me present another perspective. If your real code block is as complex as your example, it is not really good practice to write it that way.

"Concise" does not always mean "elegant". Sometimes, it just means "hard to debug".

Imagine if that complex condition was somehow failing - it would be downright annoying to figure out the problem. A better way is to have intermediate variables storing the values of the individual condition blocks. Of course, those intermediate variables need proper names to help readability.

Expand that "brief" code block into the corresponding nested if-else series. Every little if and else in that expanded block is a potential test condition. Now you will see that it is not brief after all. It is complex logic that must be treated with due respect.

With regards to your question, it would help to separate out each of these test conditions into its own test. They can share common setup, etc. using functions. At the unit test level, simpler individual tests are better because they help you pin-point the problem to the exact failure condition.

Organize each test as per the 3A pattern. This makes the tests readable and also independent of each other. Here's an example:

void testSummation()
{
    // ARRANGE
    Calculator testObject = new Calculator();

    // ACT
    int sum = testObject.add(1, 2);

    // ASSERT
    Assert.equals(3, sum);
}

Arrange:

Set up the environment for the condition to be tested. This might include setting up some initialization parameters, mocks, etc.

Act:

Run an action on the object. A good practice is to make sure that this action is an independent operation as seen from the API of the object.

Assert:

Check whether the action had the intended effect. Validate the output variables, object state, etc. to make sure that the expected behavior was met.


答:
Your mistake is to assume that the code is short. The fact that it's one-liner doesn't mean it's simple to test, to debug and to maintain. If I had to maintain this code, I would have WTFed quite a lot about people who like writing cryptic, condensed code (also, I hope your a, b etc. variables are just for an example, and in real life, you use more meaningful names).

Here's what it looks like when refactored, isSomething, isAlso and isSomethingElse should be replaced by meaningful names which document your code:

boolean isSomething() {
    return (a || b) || (c && d)
}

boolean isAlso() {
    return t == X || t == Y
}

boolean isSomethingElse(boolean anotherFlag) {
    return anotherFlag && t == Z && a
}

boolean isEnabled(boolean anotherFlag) {
    if isSomething() && isAlso() {
        return true
    }

    return isSomethingElse(anotherFlag)
}
```

<p>This code is much <em>simpler</em> than the one-liner, but it also makes it clearer that you'll need more than two-three unit tests to test it.</p>

<h2>Number of permutations</h2>

<p>Talking about the high number of permutations you would expect:</p>

```return a
```

<p>needs <strong>two tests</strong>: one where the statement returns true, and one where it returns false.</p>

```return a && b
```

needs either three or four tests, depending on the language. Most languages would be lazy and avoid evaluating b when a is false, knowing that anyway, the result will be false, meaning that you have only to test:

a is true and b is true,

a is false,

a is true and b is false.

Now imagine the number of tests you need for your one-liner. That explains the verbosity.

All tests for this kind of methods I've read so far are very verbose, not complete and hard to understand.

I explained the verbosity.

As for complete, I imagine you're talking about what I illustrated with three tests instead of four.

Finally, it's obvious that your tests are hard to understand, since your one-liner is too complex. Do some refactoring, and test separate methods, eventually using Dependency Injection or moving those separate methods to dedicated classes, if appropriate.

Title: How should I test boolean function with many possible permutations

Body:
When I write an unit test I usually provide a context (plain object or mocked/stubbed object) that I setup in some ways and then I can run assert statement on the context:

note: code is in pseudo-code; groovy like syntax:

```<code>test myTest() {
  def o = getTestContext();
  o.string = "testme"
  o.number = "2"
  assert o.mult() == "testme testme"
}
</code>```

But how to organize the test when you need to test a complex boolean expression that takes many parameters ?

EDIT: I have replaced the one line expression with something more readable to avoid confusion.

```<code>//this is not a real class, this is an example. Naming is bad, for conciseness sake
//the expression is coming from randomness realm, so it is probably refactorable and simplifiable, but complex real world expression still exists.
enum Type {X,Y,Z}
class C {
  boolean a,b,c,d;
  Type t;

  boolean isEnabled(boolean anotherFlag) {

    def condition1 = (a || b)
    def condition2 = (c && d)
    def goodType1 = t == X || t == Y
    def goodType2 = anotherFlag && t == Z || t == Z && !condition1

    return (  condition1  || condition2 ) && (goodType1 || goodType2)
  }
}
</code>```

All tests for this kind of methods I've read so far are very verbose, not complete and hard to understand.

And it is quite a shame that such a small line of code, even if it is 'complex', generates awful tests.

I've tried to break the boolean expression into smaller sub methods, but sometime it is not so convenient and the permutation count is still high. I also usually break the expression into intermediate variables, but this is not helping in unit test world...

How should I test something like this to have test code matching the briefness of the tested code and the completeness that must assert that my code works as expected ?

Edit: about the retained solution.

Refactoring is indeed a way to go, but I really don't want to 'unroll' all combinations manually in my tests: it is verbose, ugly and hard to understand.

However I'll keep this answer as a preliminary mandatory step: break the expression into smaller pieces before anything else.

Once the refactoring is done and the test still result in combinatory tests, then I'll use the TruthTable solution proposed. I'll just generate the combinations and not declare everything.

I found this interesting, but outdated, article about test combination in Groovy.

The tool they spoke about is out of search engine radar, so it must be dead !

However I'll use the same pattern:

```<code>assertThat(permutations, expectations, instanceObject)
</code>```

Where

permutation is all possible values to assign to properties in a 'condensed map': (a:[true, false], b:[true, false], ...)

expectation is all combinations that return a specific value, all other combination will be checked against a default value.

Body:
Your mistake is to assume that the code is short. The fact that it's one-liner doesn't mean it's simple to test, to debug and to maintain. If I had to maintain this code, I would have WTFed quite a lot about people who like writing cryptic, condensed code (also, I hope your a, b etc. variables are just for an example, and in real life, you use more meaningful names).

Here's what it looks like when refactored, isSomething, isAlso and isSomethingElse should be replaced by meaningful names which document your code:

boolean isSomething() {
    return (a || b) || (c && d)
}

boolean isAlso() {
    return t == X || t == Y
}

boolean isSomethingElse(boolean anotherFlag) {
    return anotherFlag && t == Z && a
}

boolean isEnabled(boolean anotherFlag) {
    if isSomething() && isAlso() {
        return true
    }

    return isSomethingElse(anotherFlag)
}

This code is much simpler than the one-liner, but it also makes it clearer that you'll need more than two-three unit tests to test it.

Number of permutations

Talking about the high number of permutations you would expect:

return a

needs two tests: one where the statement returns true, and one where it returns false.

return a && b

needs either three or four tests, depending on the language. Most languages would be lazy and avoid evaluating b when a is false, knowing that anyway, the result will be false, meaning that you have only to test:

a is true and b is true,

a is false,

a is true and b is false.

Now imagine the number of tests you need for your one-liner. That explains the verbosity.

All tests for this kind of methods I've read so far are very verbose, not complete and hard to understand.

I explained the verbosity.

As for complete, I imagine you're talking about what I illustrated with three tests instead of four.

Finally, it's obvious that your tests are hard to understand, since your one-liner is too complex. Do some refactoring, and test separate methods, eventually using Dependency Injection or moving those separate methods to dedicated classes, if appropriate.


答:
One quite intuitive way to handle this is to code a truth table into your test so you have something like:

```<code>//last in tuple is expected result, rest are inputs
test date = new List<Tuple<bool,bool,bool,bool,string>>()
{
   {true,true,true,true,"foo"}
   {true,true,true,false,"bar"}
   etc...
}
</code>```

i.e. a data driven test.
For big table you can move this to a data file which you slurp up.
The test itself then simply needs to iterate over the table and plug the inputs in and check the expected output.

This also hints at a possible refactoring of the code. An input of Tuple<bool,bool> is essentially the same as an enum with 4 possible values.

Body:
One quite intuitive way to handle this is to code a truth table into your test so you have something like:

//last in tuple is expected result, rest are inputs
test date = new List<Tuple<bool,bool,bool,bool,string>>()
{
   {true,true,true,true,"foo"}
   {true,true,true,false,"bar"}
   etc...
}

i.e. a data driven test.
For big table you can move this to a data file which you slurp up.
The test itself then simply needs to iterate over the table and plug the inputs in and check the expected output.

This also hints at a possible refactoring of the code. An input of Tuple<bool,bool> is essentially the same as an enum with 4 possible values.


问:
Is it ok to start with templates in MVC development?
I'm new to web development and I've started working on a project in my company that uses DJANGO. I feel it flexible to start my development straight first from the templates. I think it will be easier if I visualize things first. So my question: Is it okay to start with a template rather than starting with models first? Will I stumble on to any sort of confusions if I go by this method of development? </p>

答:
Starting with the user experience and how that works is actually a good way to start off.

It ensures that what you build is fit for purpose and that you end up building what needs to be built and not things you think you will need.

See User Centered Design on Wikipedia.


问:
Any real use of pointers in C#?
What is a situation while coding in C# where using pointers is a good or necessary option? I'm talking about unsafe pointers.

答:
yes, there are real uses, when performance is critical and the operations are low-level

for example, i've only needed to use pointers in C# once, for image comparison. Using GetPixel on a pair of 1024x1024x32 images took 2 minutes to do the comparison (Exact match). Pinning the image memory and using pointers took less than 1 second (on the same machine of course).

Title: Any real use of pointers in C#?


问:
Continuous integration policy problems
Currently our model, with respect to SVN and automated build, looks like

Which, as far as I know, wasn't the way SVN was meant to be used. But the process works okay from a technical standpoint. The goal is to be able to run these chains in parallel, with different people working on new features, others fixing new bugs and regressions, and somehow responding to client feedback.

The difficulty comes in explaining it, even to people who have been around for a while, and usually after someone messes it up and changes one of these steps to something that makes more sense to them (ie using the latest release build for internal testing and sending archived releases to client QA).

I didn't set the policy but I understand what it is, so I'm one of the people who has to explain/maintain it. Having done so many times over the last year, it seems like it doesn't meet the principle of least astonishment.

How could we make this process more obvious/boring?

答:
I'll try keep my answer focused on the

How could we make this process more obvious?

part of the question you asked. Simpler processes do tend to get a "that's obvious" response from users, but are difficult to articulate and develop.

Some things I don't see in the diagram or don't know if they exist in your documentation;

How code changes flow through the process w.r.t. the repository. We use SVN, but we've modelled a lot of our internal code flows on the git flow with a lot of success. I'm not advocating a change in repository or a work flow for you, but there a number of neat ideas on how to document your code flows and where each build needs to come from in the codebase.

That said, a change in your code workflows may help. Depending on your specific time and other physical constraints, performing the internal test and QA cycle before the client cycles should help. The artefacts of your internal cycles will then be the inputs to the clients' cycles. These can still be run in parallel, being that they can be physically worked on at the same time. But they wouldn't be parallel, in that what is produced in one will only be available later to the other - as you pretty mush have it now. I think this will be a trade off between your resources, time and unique business and technology issues. I can think of scenarios where both would work.

Further process changes;

Simplify the documentation, even if it is just to reduce the volume of it. Part of the problem here will be user education. Making it easier for people to understand and use the process properly will reduce the burden on you.

Short definitive lists of the artefacts from each stage, these can be used as check-lists for conformance and query resolution.

Define as clearly as possible the parallel chains of the process and the separation between them. How does information (and code) flow between them, if at all? What is the difference between the two acceptance phases at the end of each of them? And so on.

Define useful "reset" points; if any step fails does the process go back to the previous step or the beginning of the process or are the better more meaningful points to return to, fix and continue. Define how those fixes get back to dev.

Producing a process that is simple and intuitive is hard, changing it in place is even harder. In general, removing un-needed, confusing or unintuitive steps is better to changing them, and even that is better than adding anything.

I believe it was Antoine de Saint-Exupéry that originally said (it has repeated in several forms over the years);

It seems that perfection is attained not when there is nothing more to add, but when there is nothing more to remove.

From wikiquote

Title: Continuous integration policy problems


答:
Why not

```<code>public static class Program
{
    private static MyCentral _central;

    ...
    var controller = new SomeController(_central);
}

...

public class SomeController
{
    MyCentral _central;
    public SomeController(MyCentral myCentral)
    {
        _central=myCentral;
    }

    public object SomeFunction()
    {
        // Do something with _central
    }
}
</code>```

This is called "constructor injection". The central object has only to be passed once to your controller, it can be "mocked out" for testing purposes, and if you decide later that you need to have more than one central object, it won't become a problem.

Title: Passing central objects around or having global instances?

Body:
Having a larger WinForms application with several classes I currently pass references to several "central" objects around to function calls.

This leads to more method parameters.

Example:

```<code>public static class Program
{
    private static MyCentral _central;

    ...
}

...

public class SomeController
{
    public object SomeFunction(MyCentral central)
    {
        // Do something with the MyCentral instance.
    }
}
</code>```

Now I'm asking myself whether I should ditch this approach and instead use singletons for those central objects so that everyone can always access these objects and I do not need to pass them around anymore.

Example:

```<code>public static class Program
{
    public static MyCentral Central { get; private set; }

    ...
}

...

public class SomeController
{
    public object SomeFunction()
    {
        // Do something with the Program.Central singleton.
    }
}
</code>```

My question:

Are there any rules-of-thumb whether the singleton approach or the "passing objects around" approach should be prefered?

Body:
Why not

public static class Program
{
    private static MyCentral _central;

    ...
    var controller = new SomeController(_central);
}

...

public class SomeController
{
    MyCentral _central;
    public SomeController(MyCentral myCentral)
    {
        _central=myCentral;
    }

    public object SomeFunction()
    {
        // Do something with _central
    }
}

This is called "constructor injection". The central object has only to be passed once to your controller, it can be "mocked out" for testing purposes, and if you decide later that you need to have more than one central object, it won't become a problem.


答:
Is the readability and thus, the immediate understanding of the code really better in the latter example?

I think it is. By looking at it, you can see that printOwing "prints a banner and some details".

There is no indication about what "details" are in reference to "owing".

If it is not clear or known when reading the API name, then the API should not be called printDetails in the first place (printDebtByName maybe?)

For example, will the name be listed or is there another method printName()?

You should see this by looking at the API or the API docs.

I would need to search for the printDetail() method's implementation to find out about that.

You should actually just choose a better name (than printDetails). This is the reason why naming things is hard in API design. This is also why it is critical. (Stepanov stated in a lecture that for good design to be achieved, you should spend about ten times as much on API design as you spend on the implementation).

The method printOwing() itself is already a print-method. Would it not be easier for maintaining the code to just list the System.out.println()'s in this method commenting the purpose as in the first example instead of "scattering" the code this way?

Not really, though it is easier to write in a single function in the first place (just write everything there, and you're finished). For long-term maintenance though, it is vital that the code is easy to read and understand, not (necessarily) to write.

When doing long term maintenance though, it is easier to refactor if you have such a small change, than it is if you have code that could have been refactored a number of times, but people figured "it's fine where it is" every one of those times (such code becomes bigger and bigger, and then you have to refactor a large method, that would have been naturally broken n times).

The larger the project is, the more critical it is to minimize the comprehension effort.

Is there a rule of thumb about when to stop "methodizing" and when it still makes sense?

The design guide lines that (probably) applied in the decision to refactor:

keeping similar abstraction levels for similar APIs (both printHeader and printDetails are at a similar abstraction level); printOwed no longer calls APIs with different abstraction levels.

SRP: printOwned doesn't "print the header and then print the name and then the amount". Instead, it prints "parts of Owned"; Conceptually, it is a different thing.

Law of Demeter: you minimize the amount of knowledge necessary for each API (printOwned doesn't need to know that something like System.out.println exists at all).

Title: When does extracting methods from code stop to make sense?

Body:
I am currently studying the refactoring methods defined by Marting Fowler (http://refactoring.com/catalog/).

He states a tip for replacing chunks of code by a single method that does that job. So far, I agree, as we all learned about the downsides of Spaghetti-code. But the example for this rule looks as follows:

Replacing

```<code>    void printOwing() {
      printBanner();

      //print details
      System.out.println ("name:  " + _name);
      System.out.println ("amount " + getOutstanding());
    }
</code>```

by

```<code>    void printOwing() {
      printBanner();
      printDetails(getOutstanding());
    }

    void printDetails (double outstanding) {
      System.out.println ("name:  " + _name);
      System.out.println ("amount " + outstanding);
    }
</code>```

Is the readability and thus, the immediate understanding of the code really better in the latter example? There is no indication about what "details" are in reference to "owing". For example, will the name be listed or is there another method printName()? Is the interest listed as well? I would need to search for the printDetail() method's implementation to find out about that.

The method printOwing() itself is already a print-method. Would it not be easier for maintaining the code to just list the  System.out.println()'s in this method commenting the purpose as in the first example instead of "scattering" the code this way?

Is there a rule of thumb about when to stop "methodizing" and when it still makes sense?


问:
How to store Role Based Access rights in web application?
Currently working on a web based CRM type system that deals with various Modules such as Companies, Contacts, Projects, Sub Projects, etc.  A typical CRM type system (asp.net web form, C#, SQL Server backend).  We plan to implement role based security so that basically a user can have one or more roles.

Roles would be broken down by first the module type such as:

-Company

-Contact

And then by the actions for that module for instance each module would end up with a table such as this:

```<code>Role1 Example:

    Module   Create  Edit        Delete   View
    Company   Yes    Owner Only    No     Yes
    Contact   Yes    Yes           Yes    Yes
</code>```

In the above case Role1 has two module types (Company, and Contact).  For company, the person assigned to this role can create companies, can view companies, can only edit records he/she created and cannot delete.  For this same role for the module contact this user can create contacts, edit contacts, delete contacts, and view contacts (full rights basically).

I am wondering is it best upon coming into the system to session the user's role with something like a:

List<Role> roles;

Where the Role class would have some sort of List<Module> modules; (can contain Company, Contact, etc.).?  Something to the effect of:

```<code>class Role{
string name;
string desc;
List<Module> modules;
}
</code>```

And the module action class would have a set of actions (Create, Edit, Delete, etc.) for each module:

```<code>class ModuleActions{
List<Action> actions;
}
</code>```

And the action has a value of whether the user can perform the right:

```<code>class Action{
string right;
}
</code>```

Just a rough idea, I know the action could be an enum and the ModuleAction can probably be eliminated with a List<x, y>.  My main question is what would be the best way to store this information in this type of application: Should I store it in the User Session state (I have a session class where I manage things related to the user).  I generally load this during the initial loading of the application (global.asax).  I can simply tack onto this session.

Or should this be loaded at the page load event of each module (page load of company etc..).  I eventually need to be able to hide / unhide various buttons / divs based on the user's role and that is what got me thinking to load this via session.

Any examples or points would be great.

答:
Well, I think your design is fine I would only recommend you only a simple thing on how to store the roles. I have here a system that has almost the same concepts. It is not based on roles as per the name.

So I have a user session object with objects of type Map that store the permissions that the user has. And this Map objects is filled on demmand It will be something like:

```<code>public class UserSession {
    HashMap<Application, Action> map;

    public boolean hasPermissionApp( Application app ){
        if ( !map.containsKey(app) ){
            //check if the user has the permission on the DB or whatever you store it
            //if it has add it to the map with the action that
            //it came along and return true
            //if it hasn't return false
        }
        return true;
    }

    public boolean hasPermissionAction( Application app, Action act ) {
        if ( hasPermissionApp(app) ){
            if ( !map.get(app).containsKey(act) ){
                //check if the user has permission to that action of the app
                //if it has add to the map and return true
                //if not return false
            }
        }
        return false;
    }
}
</code>```

That way you load the user permisson and store it by demmand and don't overload the session object with the full set of permissions that the user has.

EDIT

As OP asked on the comments:

Do you fill this hashmap at every sort of click event that requires role permissions?

The answer is almost this. When the user logs in an application the user session object is empty, so for the Application that He is logging in I would check if He has access and if so, I add it to the map with the first Action that was called by that Application lets say 'View'. And with this Action the user can see the search form.

Here you can have two approach. Which is what you asked!

Check permissions when the user fire the events like with this 'View' Action it can see the entire form with the buttons search, add, cancel (or whatever others) But the permission will be checked only when the user press the button. Then it if have you add to the map or send him a message saying that it does not have that permission.

Check the permission when rendering the actions. You only show the buttons on the form if the user has that appropriate Action associated to it. So lets say you are using a component library like Richfaces it would be like this:

<a4j:commandButton rendered="#{userSessionObject.hasPermissionAction('appBla','search')}" ..... />

And since this is created on the construction of the page the map would be filled on every check permission that is made on the page or other resources.

And on my application i choose for the second approach, because I don't think that make sense to show a button to a user that does not have the access to it.

Edit 2

A thing that maybe is usefull is that I associate a thread timing (configurable time) to the user session that clean up the maps on the userSessionObject, so if some administrator change permissions to that user at some point it will have his permissions updated automatically, not exactly at prompt but this was a acceptable requirement to this particular system.

Body:
Well, I think your design is fine I would only recommend you only a simple thing on how to store the roles. I have here a system that has almost the same concepts. It is not based on roles as per the name.

So I have a user session object with objects of type Map that store the permissions that the user has. And this Map objects is filled on demmand It will be something like:

public class UserSession {
    HashMap<Application, Action> map;

    public boolean hasPermissionApp( Application app ){
        if ( !map.containsKey(app) ){
            //check if the user has the permission on the DB or whatever you store it
            //if it has add it to the map with the action that
            //it came along and return true
            //if it hasn't return false
        }
        return true;
    }

    public boolean hasPermissionAction( Application app, Action act ) {
        if ( hasPermissionApp(app) ){
            if ( !map.get(app).containsKey(act) ){
                //check if the user has permission to that action of the app
                //if it has add to the map and return true
                //if not return false
            }
        }
        return false;
    }
}

That way you load the user permisson and store it by demmand and don't overload the session object with the full set of permissions that the user has.

EDIT

As OP asked on the comments:

Do you fill this hashmap at every sort of click event that requires role permissions?

The answer is almost this. When the user logs in an application the user session object is empty, so for the Application that He is logging in I would check if He has access and if so, I add it to the map with the first Action that was called by that Application lets say 'View'. And with this Action the user can see the search form.

Here you can have two approach. Which is what you asked!

Check permissions when the user fire the events like with this 'View' Action it can see the entire form with the buttons search, add, cancel (or whatever others) But the permission will be checked only when the user press the button. Then it if have you add to the map or send him a message saying that it does not have that permission.

Check the permission when rendering the actions. You only show the buttons on the form if the user has that appropriate Action associated to it. So lets say you are using a component library like Richfaces it would be like this:

<a4j:commandButton rendered="#{userSessionObject.hasPermissionAction('appBla','search')}" ..... />

And since this is created on the construction of the page the map would be filled on every check permission that is made on the page or other resources.

And on my application i choose for the second approach, because I don't think that make sense to show a button to a user that does not have the access to it.

Edit 2

A thing that maybe is usefull is that I associate a thread timing (configurable time) to the user session that clean up the maps on the userSessionObject, so if some administrator change permissions to that user at some point it will have his permissions updated automatically, not exactly at prompt but this was a acceptable requirement to this particular system.


问:
IllegalStateException vs. IllegalArgumentException
In have written a function which expects the caller to pass in a configuration file like XML. Then I parse this given file and extract something which i then return.

In this function (at least) two "bad" things can happen:

The given file does not exist or is not accessible in any way

While parsing/validating the file some unexpected content is found

The first thing is clearly an IllegalArgumentException. I am however not sure what kind of exception the second case would be. Is that also an IllegalArgumentException because i expect (by documentation-contract) that the input is in a valid form? Or is it rather an IllegalStateException as the given parameter is formal correct but only after parsing I can't do any further steps as it would result in unwanted behaviour?

Or is it even something else?

答:
The Javadocs of IllegalStateException say

Signals that a method has been invoked at an illegal or inappropriate time

I would argue, that it does not matter when your method is called or in what state the JVM or your context is - the parsing error will remain as long as the file is not correct. So it seems to me, that an IllegalArgumentException is more appropriate.


答:
Doesn't seem so bad all in all.

Ok, so you want feature branches in your repository workflow. Simple:

Where it says 'release build', you need to make a tag with the appropriate version number and use that to build the releases. It allows you to respond to feedback from Integration and QA testing by applying changes to the tag (and passing the changes back to dev for a future fix)

Where it says "dev" you need a branch per feature. These are the builds that go through internal testing, when they are passed they get merged onto trunk. Once merged, the branch gets deleted (any fixes that you find after this must be fixed as new dev branches or you'll get into a pickle given your overall process).

I don't think that's so hard all in all. Basically the arrows pointing from the Repository to Integration box should become many arrows, one for each branch or tag that you have. Then you have parallel development and the problem becomes one of managing all the different builds and configuration that goes with them... but that's a different story.

Title: Continuous integration policy problems

Body:
Currently our model, with respect to SVN and automated build, looks like

Which, as far as I know, wasn't the way SVN was meant to be used. But the process works okay from a technical standpoint. The goal is to be able to run these chains in parallel, with different people working on new features, others fixing new bugs and regressions, and somehow responding to client feedback.

The difficulty comes in explaining it, even to people who have been around for a while, and usually after someone messes it up and changes one of these steps to something that makes more sense to them (ie using the latest release build for internal testing and sending archived releases to client QA).

I didn't set the policy but I understand what it is, so I'm one of the people who has to explain/maintain it. Having done so many times over the last year, it seems like it doesn't meet the principle of least astonishment.

How could we make this process more obvious/boring?


问:
Is there a benefit in compiling your code as you go along?
I recently had a job interview in which they gave me an hour to write some real code.  It wasn't a huge amount, probably less than 100 lines.  After about 45 minutes, I compiled, ran it, and got it to work.  I may have spent 5-10 minutes working out compile errors and a couple minor bugs, but overall it was very smooth.  (Incidentally, I did get an offer from them.)

However, what puzzled me was that after I handed over the completed code, the interviewer told me that the only thing I did wrong was "not compiling as I go along".  I asked him what the difference is, and he said "what would you have done if you finished the code and it didn't compile in time".

In my understanding that's an invalid argument, because "getting code to compile" for a given length of code generally involves fixing a constant number of compile errors and takes a fairly constant amount of time, which should be the same whether you do it after you finish writing the code, or if you interleave it with your coding time.  If anything, interrupting your coding to search for missing semicolons would probably be detrimental to your efficiency.  Except in extreme circumstances when I'm experimenting with obscurities around edge-cases on things like virtual functions in derived classes, etc. it seems reasonable to expect that code written by a an experienced developer will compile, minus the occasional typing error, and even if it doesn't, it's not as if I would have to rewrite a portion of the code in order to fix the compile error.

In another similar incident, I was given an incomplete codebase in an interview, and asked to finish it and make necessary modifications to get it running.  I started by reading through the existing code, and then after a few minutes (even before I had finished looking at the code), the interviewer told me that's enough.  When I asked him what he would have done (i.e. "what did I do wrong"), he told me that he would have started by immediately getting the code to compile.

Why is that even relevant?  In my opinion and in my experience, whether or not a piece of code compiles is essentially random, involving things like whether or not semicolons are missing, and has little to do with the correctness of the underlying program.  (To me, focusing on compiling is like running an article through a spell-check without proofreading to check the grammar.)

If you give me a piece of incomplete code, the first thing I do will be to read it.  I won't even try to compile it until I know what the code is doing and I know the algorithm is correct.

Anyway, these have been just a couple recent incidents, but in general I've heard many developers talk about compiling their code as they go along, and yet nobody has been able to tell me the benefit of doing so.  I understand the benefits of testing your code as you go along, but why compiling?

So my question is this: Is there something I missed?  Is there actually a benefit to compiling as you go along?  Or is this some sort of myth propagated by the software community that you must compile your code frequently?

答:
I thought a bit longer about this, because I felt that there is something very, very wrong with the interviewer and couldn't exactly point out what it is. Here's the problem: For any code that I have written in the last twenty years, the amount of time needed to turn a workable algorithm into code that compiles has been minimal. Any gain in efficiency in that area has so little impact on total development time that it is totally negligible, and an interviewer who rejects a candidate for perceived inefficiencies in that area has no idea what makes a good developer.

Most time should be spent on gathering information what the code is supposed to do, gathering information and specs about outside services that need to be used, creating a global design that will lead to correct and maintainable code instead of hacked together code, and finding algorithms that will lead to working code instead of code that is patched together until it happens to work (code that has obviously no errors vs. code that has no obvious errors).

Then come a tiny amount of time writing code that compiles.

Then comes a larger amount of time spent to make sure that the code works, and to make sure that we know that the code works and will stay working. Which is done by writing unit tests, stepping through code, and to a large extent by having well-designed code in the first place.

This interviewer concentrated on something that is covered by ten words in my reply. Which represent 10 percent or less of the actual working time. And has almost zero influence on the ability of that developer to produce reliable and working code.


问:
Adding a Short-Term Developer to a Rework of an Old Project

Background

I work in the Language Resource Center on my campus. It's a relatively small lab, and our job is to help students, not code software. Being a Computer Science student, I took the initiative to start coding useful utilities to make our jobs as lab assistants easier.

Recently, Google declared a shut-down of our data storage mechanism, so I decided that it was time to completely rework the entire system that I've built (alone) over the past year. I have more experience now, and I want to do it correctly with the (better) tools that are now available to us.

There is another CS student that works with me in this lab, who will continue working with me for one more semester (e.g. a 4-month period). I never asked him to contribute to the original project because I started it last summer when he wasn't scheduled to work.

The goal of this project is to build an integrated 'manager' application for our staff and my boss; the utility is a web service built using HTML/CSS/JavaScript. My coworker doesn't have any experience with JavaScript, HTML nor CSS. This developer also has no experience with the code base that I built previously (purely JavaScript), which would need to be re-worked (albeit slightly) to work with the new system.

Again, this is not a required duty in our positions. I enjoy coding things to automate menial tasks, and to make our jobs easier. It was never a requirement.

Deadlines

There is a hard deadline of mid-August, when faculty will start submitting requests to us again. The old system has to be rebuilt (some parts retrofitted) before then.

Why ask?

My boss suggested that this coworker of mine contribute to the new project to speed up development. I worry that my coworker (and boss, for that matter) might take it as a slight if he doesn't help develop this system. On the other hand, there was a 9-month period where he could have contributed to the previous project, and a 4-month period that he could have taken over management of said project (I was in France) - he has never shown interest in actively contributing to the previous project, and I have no problem with that.

I'm concerned because I feel that helping him learn HTML, CSS and JS, as well as Google's API and toolset will really slow things down. We essentially have two months to re-construct the old system, and I feel that the time it would take to get him acquainted with the tools and languages used in this project, I could have built it myself.

Is there a protocol?

I've come up with the following as my options in this situation:

Just start working on the new project alone, assuming that my coworker does not want and/or never wanted to contribute.

Ask my coworker if he wants me to help him learn HTML/CSS/JS and start showing him the previous code base as well as the current project's plan.

Ask my coworker if he has any interest in helping with the new project (he doesn't need to have an interest, but would he take that as You must work on this!?)

The question

Is it worth the time/effort, given the deadline, to have my coworker work on this project with me? Or would I detriment progress by having him co-develop?

答:
No-one can really say, given the details provided. Your co-worker might want to help but felt it wasn't part of his job so never offered, or didn't want to tread on your toes.

So, easiest thing to do is to find a self-contained piece of work that you can offer him to help you, and if it turns out to be poor, the worst thing that can happen is that you have to re-do it, which you would have had to do if he wasn't there at all.

Never hurts to offer, and in 4 months time, you can do what you like with his code without any fear of offence (as he won't be there any more). There doesn't seem to be a downside, and there is the great possibility of an upside if he excels at his task.


问:
Is Visual Studio just an IDE?
For Windows Development I mean.

Looking over other questions there are alternatives to VS, but they seem to be web based ones, which is fine, or you could program an entire .net website in notepad, should the urge drive you to.

But is there more to it than just an IDE for Windows Development? I.E. Is it possible for me to create an application in just notepad, is the compiler part of Visual Studio, or is it separate, which could be called via command line or something?

I don't want to not use VS, I'm happy with it, does what I need etc etc, just more a facet I'm curious about.

答:
I would like to add my two cents. I would say you can't use the words "just an IDE". The way you word your question it's almost that you are saying "is Visual Studio just a fancy text editor?". Remember it has a debugger, tools for SQL, a visual designer, tools for mobile development, viewers for inspecting memory, etc. Visual Studio is an IDE and an IDE is a suite of development/debugging tools.

I think you got the answer you were searching for, which was compilers can be downloaded separately, but I want develpors to realize how much an IDE brings to the table. Even the ability to organize your project is a beautiful thing. I guess this soap box is more "please learn the tools" than anything else. You could use visual studio to debug system problems as well.

Title: Is Visual Studio just an IDE?


问:
Is this a good task for machine learning - grouping pieces of DNA based on sequence?
Say I have a list of 50 DNA sequences all of the same length (6, 8 or 16 bps/ chars).

I want to group these to sets of say 5 or 6 sequences per set.
I have some criteria that need to be met based on the sequence:

1) There has to be at least three mismatches (different characters),

```<code>ACGTAC
ACTTAT
</code>```

has 2 mismatches - positions 3, and 6 , so would not meet the criteria

2)  if we say A and C are red C and T are green (the laser colours on the sequencing machines), then we must have a green and red laser in each position.

```<code>ACACTG
AATGAC
CCATGC
</code>```

is equivalent to (r is RED, g is green)

```<code>RRRRGG
RRGGRR
RRRGGG
</code>```

So the last four positions match the criteria (we have a red and a green in each position), but the first two positions are all red, so this set would not meet the criteria.

I have tried brute forcing this, and it works, but after the set size gets big enough, the number of combinations needed to check gets huge. So would this be a suitable task for some "machine learning" algorithms. Is there a type of algorithm / process that I should be looking at in particular?

(I just started a Coursera course, but the problems being discussed just now are linear regression, which seems to be a different class of problem).

答: There are lots of different algorithms that get classified as machine learning, but most of them have the flavor of "discover the imperfect pattern in the noisy data". It sounds like you already have an exact pattern, and you just want to count how many instances of it are in your data. That sounds like more like a combinatorics problem.</p>