答:
What is happening during testing, and why does it takes so long?

It could be a resource issue (5 developers, one tester - not going to work)

Or maybe testing is overly thorough AND not finding any issue any way - in which case just test less and automate more?

Or maybe quality is poor and it takes a lot of time to test because there is a lot of rework/fixing required? In which case developers need to slow down and build better quality in (and eventually consider having QA work with them during development).

Someone smart (I'm too lazy to look it up) said that the job of a developer is to put QA out of business.

Title: Finishing an iteration early

Body:
I'd like some input on this on those working with agile methodologies...

A current project is finding that development on our planned user stories is finishing some time before the end of the iteration, and that the testing effort and business acceptance is what's actually dragging us out longer towards the end. This means that the devs in question have spare time, and they're essentially going out to the iteration+1 backlog and starting work on cards there before our current iteration cards are 'done'. As iteration manager, I want to put a stop to this - I want a more team-orientated approach where the group takes ownership of getting all the cards done, as opposed to "Well, dev's done so what do I dev next?"

The problem I face is convincing the team of this. On one hand, I understand why the devs don't want to test the code they've written (there are unit tests they write of course, but the manual testing to be done could be influenced by their bias). The team sees working ahead as making our next iterations easier, because a lot of the work is done before we start. I see this as screwing with the whole system of planning/actuals - but it's difficult to convince the team as to why this matters.

What advice can you guys and girls give? How do we stop devs reaching ahead? What should they be doing instead? How much of a problem is this in the scheme of things, if things are still getting done?


问:
Good Practices for development team in large projects
Since I started learning C a few years ago, I have never been a part of a team that worked on a project. I am very interested to know what are the best practices for writing large projects in C.

One of the things I want to know, is when (not how) do I split my project into different source files?  My previous experience is with writing a header-source duo (the functions defined in the header are written in the source).

I want to know what are the best practices for splitting a project, and some pointers on important things when writing a project as part of a team?

答:
C Modularization

There is a classic paper on modularization called "On the Criteria to be used in Decomposing Systems Into Modules."  Briefly summarized, the criteria are to make a data oriented, not functionally oriented decomposition of your project, and to use metrics to judge the success by how few modules must be touched per enhancement.

C is a structured programming language and some key concepts include creating low coupling (by avoiding globals and using parameters) and high cohesion (by grouping closely related functions and data together).

For C, what you describe for separating the .h (declaration) from the .c (definition, also called implementation) is good.  Some practical considerations arise with .c/.h files, but generally .h files should include very few global variables (i.e. externs) and prototypes for only those functions that will be used outside the .c.

There are many C programmers who talk don't use structured analysis or design.  Best Practices once involved making a Structure diagram that broke the problem a program was designed to solve into a top-down functional decomposition, that was transformed into a tree of modules using a technique called transform analysis.  This is no longer considered best practice, because data oriented and object oriented decomposition has proven itself superior.   However, C programmers often find what they do is a tough fit for object oriented design because the language features don't line up.

Team Best Practices

This is the subject of entire books.  Watts Humphrey wrote a technical report called "The Team Software Process" that is a classic and a free download. Skim over just pages 4-6, and 15 to get a really fast overview of what is important for the team and its leadership.  Other parts of the document also tell you a lot about the expectations of planned methodologies in terms of documentation including productivity and quality measurement.

Your team may pick a life cycle model that is either planned (more traditional waterfall, spiral, or feature oriented development) or Agile (iterative/incremental or perhaps lean).  Both will have many processes that overlap, although they might not be practiced exactly the same: documentation, source control, integrated tracking and planning with databases and chart editors, testing, and some kind of peer review.

If you think

We are uncovering better ways of developing
software by doing it and helping others do it.

you should consider what the Agile guys are saying because team process centered around Scrum or eXtreme Programming (XP), is later and reacts to what people felt didn't work before.

ContentLicense: CC BY-SA 3.0


答:
When to split your C source code in multiple files:

When the compile time starts slowing you down. Usually your compiler only builds the source files that have changed. If you put everything in a c+h duo, then the compiler will always compile it all.

When you work with more than one developer concurrently on the same project. Whether you use a version control system or not, it is not convenient when two developers want to edit the same source file. This is strong reason to group your functions in parts that belong together and split into separate files accordingly.

Title: Good Practices for development team in large projects

Body:
Since I started learning C a few years ago, I have never been a part of a team that worked on a project. I am very interested to know what are the best practices for writing large projects in C.

One of the things I want to know, is when (not how) do I split my project into different source files?  My previous experience is with writing a header-source duo (the functions defined in the header are written in the source).

I want to know what are the best practices for splitting a project, and some pointers on important things when writing a project as part of a team?


问:
What are the benefits of using the command line for software development?
What benefits are gained from using the command line for software development over using an alternative GUI? Is the command line faster for certain tasks? Are certain tools only available via the command line?</p>

答:
GUIs have the advantage of being able to use advanced visualisations. This can be extremely useful to make complex data meaningful.

Command lines, on the other hand, are often more powerful (e.g. fully scriptable) and also usually faster. The other answers have expanded on that – here I’d just like to mention that GUIs don’t offer an advantage for some tasks:

In development, many tasks don’t actually need any visualisation that cannot be done using a command line / text interface. Take compiling: good text editors (Vim, Emacs) readily support error message parsing and will jump directly to the error in the code. Graphical IDEs don’t offer more. Simply put, for such tasks there is no need for a graphical interface, and you’d lose the flexibility and efficiency of a command line interface.

On the other hand, an interactive visualisation can be very useful if you’re dealing with a complex data interaction. Version control software which can display branch graphs often beat text interfaces here. For instance, this is a snapshot from one of my repositories:

This is much more convenient than the text interface, even though this isn’t even a particularly powerful visualisation. But once again, note that actually manipulating the repository is faster using the command line (at least for me). I use the GUI just to display the branches.

Also note how Github has recently added a command line interface in recognition of the fact that many tasks can be accomplished faster by typing in a command than by clicking through a web page.


问:
"Do you have any questions for us?" In an interview
You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>

答:
I haven't interviewed lately, but a couple of questions I am sure I would now ask are:
    Do you practice test driven development?
If not:
    Do your developers write automated tests for your code?

Then I would probably get more details such as the types of automated testing they do and the tools they use.

ContentLicense: CC BY-SA 2.5


问:
Writing a desktop application for progammer from PHP background
I have a client who wants a tool for him to be able to upload his products, enter orders, and keep track of customer details. There are quite a few highly customised requests, which is why he wants the tool custum made.

He does not care much about the interface design - it just has to be usable and provide access to the databade. I've already designed the database.

I have no experience of desktop applications and usually write my web apps in PHP with the Yii framework. But hosting this on a server seems like overkill. I also have .net experience from a few years ago. What would be the best options for writing this as a desktop application?

答: Design a web application, and deploy it on his desktop by running apache and mysql locally.  It's actually a feature that this "local" web application will be accessible to his LAN too.</p>


问:
Scenarios for differences between UICulture and Culture
In .NET there are two "culture" values, UICulture and Culture. The first one is for localized texts on the UI, while the latter sets the culture for date and number formats.

I can't come up with any reason or scenario for those two values to be different. Is there some reason to do so?

答:
In some cases they can be different for example if you live in a foreign country and you want to change the UI language to a language that you are familiarly with, but you still want to use the date and number formats of that foreign country like:

```<code><globalization uiCulture="es" culture="en-US" />
</code>```

The other way around if you are doing business with an other country that your own, you probably want to use you own language, but change the date and number format.

And most of the time they are diffrent because you use the main culture (without the subculture) for the UI, en instead of en-US.

Body:
In some cases they can be different for example if you live in a foreign country and you want to change the UI language to a language that you are familiarly with, but you still want to use the date and number formats of that foreign country like:

<globalization uiCulture="es" culture="en-US" />

The other way around if you are doing business with an other country that your own, you probably want to use you own language, but change the date and number format.

And most of the time they are diffrent because you use the main culture (without the subculture) for the UI, en instead of en-US.


问:
Should I extract specific functionality into a function and why?
I have a large method which does 3 tasks, each of them can be extracted into a separate function. If I'll make an additional functions for each of that tasks, will it make my code better or worse and why?

Obviously, it'll make less lines of code in the main function, but there'll be additional function declarations, so my class will have additional methods, which I believe isn't good, because it'll make the class more complex.

Should I do that before I wrote all the code or should I leave it until everything is done and then extract functions?

答:
Yes, obviously. If it is easy to see and separate the different "tasks" of single function.

Readability - Functions with good names make it explicit what code does without need to read that code.

Reusability - It is easier to use function that does one thing in multiple places, than having function that does things you don't need.

Testability - It is easier to test function, that has one defined "function", that one that has many of them

But there might be problems with this:

It is not easy to see how to separate the function. This might require refactoring of the inside of the function first, before you move on to separation.

The function has huge internal state, that is passed around. This usually calls for some kind of OOP solution.

It is hard to tell what function should be doing. Unit test it and refactor it until you know.


答:
This is a book I often link to, but here I go again: Robert C. Martin's Clean Code, chapter 3, "Functions".

Obviously, it'll make less lines of code in the main function, but
  there'll be additional function declarations, so my class will have
  additional methods, which I believe isn't good, because it'll make the
  class more complex.

Do you prefer reading a function with +150 lines, or a function calling 3 +50 line functions? I think I prefer the second option.

Yes, it will make your code better in the sense that it will be more "readable". Make functions that perform one and only one thing, they will be easier to maintain and to produce a test case for.

Also, a very important thing I learned with the aforementioned book: choose good and precise names for your functions. The more important the function is, the most precise the name should be. Don't worry about the length of the name, if it has to be called FunctionThatDoesThisOneParticularThingOnly, then name it that way.

Before performing your refactor, write one or more test cases. Make sure they work. Once you're done with your refactoring, you will be able to launch these test cases to ensure the new code works properly. You can write additional "smaller" tests to ensure your new functions perform well separably.

Finally, and this is not contrary to what I've just written, ask yourself if you really need to do this refactoring, check out the answers to "When to refactor ?" (also, search SO questions on "refactoring", there are more and answers are interesting to read)

Should I do that before I write all the code or should I leave it
  until everything is done and then extract functions?

If the code is already there and works and you are short on time for the next release, don't touch it. Otherwise, I think one should make small functions whenever possible and as such, refactor whenever some time is available while ensuring that everything works as before (test cases).

Title: Should I extract specific functionality into a function and why?

Body:
I have a large method which does 3 tasks, each of them can be extracted into a separate function. If I'll make an additional functions for each of that tasks, will it make my code better or worse and why?

Obviously, it'll make less lines of code in the main function, but there'll be additional function declarations, so my class will have additional methods, which I believe isn't good, because it'll make the class more complex.

Should I do that before I wrote all the code or should I leave it until everything is done and then extract functions?


问:
What does (Lua) game scripting mean?
I've read that Lua is often used for embedded scripting and in particular game for scripting. I find it hard to picture how it is used exactly.
Can you describe why and for which features and for which audience it is used?

This questions isn't specifically addressing Lua, but rather any embedded scripting that serves a purpose similar to Lua scripting.

Is it used for end-users to make custom adjustments?
Is it used for game developers to speed up creation of game logic (levels, AI, ...)?
Is it used to script game framework code since scripting can be faster?

Basically I'm wondering how deep between plain configuration and framework logic such scripting usage goes. And how much scripting is done. A few configuration lines or a considerable amount?

答:
It can be used by people other than original game programmers to modify or extend game logic. Such people can be relatively non-technical, e.g. game designers or end-users (gamers).

Scripts are usually higher-level languages and as such Lua is easier than C++. Code written in scripts can usually be modified without recompiling the main application (game engine) which is useful for game designers to tweak game scenes quickly.

PS: better ask this question on gamedev.stackexchange.com

Title: What does (Lua) game scripting mean?


答:
A scripting language in a game engine is there to expose your game engine in a higher-level, interpreted manner.

Take a game like Skyrim, for example.  You'll notice that there are many quests and interactions that occur, and some of these have fairly impressive logic built into them, such as a guard reacting to you getting to close to an item during some scene.  These are things would be difficult to express in a pure data format, and for this reason, quests and custom behaviours are typically expressed as scripts.

There are also many practicalities to consider - the game designers who create these scripts often work at a higher level of abstraction than the game engine coders; they do not want to be worrying about memory allocation, etc.  A scripting language is a good fit for them, and with LUA, they're typically calling into a nice high level facade of the engine.  You also don't want to recompile your game every time you want to adjust some minute attribute in a script.

On top of all of this, they allow for easy debugging, modding, and all the other nice things you mentioned.

Title: What does (Lua) game scripting mean?

Body:
I've read that Lua is often used for embedded scripting and in particular game for scripting. I find it hard to picture how it is used exactly.
Can you describe why and for which features and for which audience it is used?

This questions isn't specifically addressing Lua, but rather any embedded scripting that serves a purpose similar to Lua scripting.

Is it used for end-users to make custom adjustments?
Is it used for game developers to speed up creation of game logic (levels, AI, ...)?
Is it used to script game framework code since scripting can be faster?

Basically I'm wondering how deep between plain configuration and framework logic such scripting usage goes. And how much scripting is done. A few configuration lines or a considerable amount?


问:
Unicode license
The Unicode Terms of Use state that any software that uses their data files (or a modification of them) should carry the Unicode license references. It seems to me that most Unicode libraries have functions to check whether a character is a digit, a letter, a symbol, etc., and so will contain a modification of the Unicode Data Files (usually in the form of tables). Does that mean the license applies and all applications that use such Unicode libraries should carry the license?

I've checked around, and it appears that very few Unicode programs do carry the license, though arguably most of those that didn't carry the license were from companies that were members of the Unicode consortium (do they get license exemptions?).

Some (e.g., Mozilla) are only "Liaison Members", and while their software do not carry the license (as far as I can tell), they do obviously rely on data derived from those data files. Is Mozilla in breach of the license?

Should we carry the license in all apps that include any form of advanced Unicode support (i.e., are bound to rely on the Unicode data files)? Or is there some form of broad exemption (since very very few programs out there carry the license)?

I've forwarded this question to Unicode staff. I'll post the reply here when/if I get one.

答:
Preliminary remark: I'm not a lawyer any longer, and never specialized myself in laws related to copyrights and intellectual property. If you want an unquestionable answer, you should consult a lawyer.

1. Data and data files are not the same

As it states, the exhibit 1 covers data files:

BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA FILES [...]

Data files and data itself are not the same. When Microsoft implements uppercase and lowercase methods in .NET Framework, the unicode standard is used, but this doesn't mean that .NET Framework contains, somewhere, the files downloaded from http://www.unicode.org/

Simple illustration of a difference between the data and the support:

Imagine that I create a database with a list of countries, cities and the corresponding post codes. I expose this data through a web service and on my website.

The data itself is in public domain: you can't reasonably copyright the list of countries and ask every person who use such list to pay you or to distribute a copy of your copyright.

On the other hand, nothing forbids for me to enforce a restrictive license on the usage of the web service or the website (especially since I invested a lot of effort while creating this set of data). If I find that an application is scraping my website to download the data, this would be a copyright infringement, and I would be able to sue the person who created the scraper.

2. Data is too vague

If http://www.unicode.org/ stated that the license covers the data itself, it would be very difficult for this organization to enforce such copyright.

Imagine the following method:

```<code>public char ToUpper(char c)
{
    string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if (upper.Contains(c))
    {
        return c;
    }

    string lower = "abcdefghijklmnopqrstuvwxyz";
    if (lower.Contains(c))
    {
        return upper[lower.IndexOf(c)];
    }

    throw new OutOfRangeException();
}
</code>```

Is this a violation of the copyright? Did I actually used the data from http://www.unicode.org/ and I should include the copy of the license in my answer below? Or maybe I just typed those letters myself?

In other words, if data itself was licensed, how far the license could go?

3. Copyright and data

Here are some interesting quotes:

http://www.lib.umich.edu/copyright/facts-and-data: University of Michigan

Copyright law does not apply to facts, data, or ideas. [...]

However, copyright may protect a collection of data as contained in a database or compilation, but only if it meets certain requirements. Simply working really hard to gather the data [...] is not enough. [...]

In order for a database to qualify for copyright protection, the author has to make choices about the selection, coordination, or arrangement of the facts or data, and those choices must be at least a little bit creative. [...]

It is important to remember that even if a database or compilation is arranged with sufficient originality to qualify for copyright protection, the facts and data within that database are still in the public domain.

http://www.ands.org.au/guides/copyright-and-data-awareness.html: Australian National Data Service

A table or compilation, consisting of words, figures or symbols (or a combination of these) is protected if it is

a literary work and

has the required degree of originality.

[...] Copyright applies not to the facts/information itself, but to the particular way the facts/information are presented in the dataset or database.

Those two examples, one concerning USA, the other one - Australia, clearly shows that the data itself, i.e. the unicode symbols with their respective numbers and the attributes such as "is this a digit?" or "is this a capital letter from Cyrillic alphabet?" is not covered by the copyright.

Data files, on the other hand, may be covered by the copyright, depending on their originality. For example, the PDFs you find on http://www.unicode.org/ would be very probably covered by a copyright. If, on the other hand, it is purely question of a CSV associating lowercase characters to uppercase or vice versa, the author of such data would hardly be able to enforce the copyright on it.

Clearly, the ToUpper method I put above is not a violation of http://www.unicode.org/ copyright. Nor the code used by .NET Framework or Firefox, unless those systems contain somewhere inside the data files which are clearly, undoubtedly copied from http://www.unicode.org/ with, optionally, some minor changes.

OwnerDisplayName: Eric Grange

Title: Unicode license

Body:
Preliminary remark: I'm not a lawyer any longer, and never specialized myself in laws related to copyrights and intellectual property. If you want an unquestionable answer, you should consult a lawyer.

1. Data and data files are not the same

As it states, the exhibit 1 covers data files:

BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA FILES [...]

Data files and data itself are not the same. When Microsoft implements uppercase and lowercase methods in .NET Framework, the unicode standard is used, but this doesn't mean that .NET Framework contains, somewhere, the files downloaded from http://www.unicode.org/

Simple illustration of a difference between the data and the support:

Imagine that I create a database with a list of countries, cities and the corresponding post codes. I expose this data through a web service and on my website.

The data itself is in public domain: you can't reasonably copyright the list of countries and ask every person who use such list to pay you or to distribute a copy of your copyright.

On the other hand, nothing forbids for me to enforce a restrictive license on the usage of the web service or the website (especially since I invested a lot of effort while creating this set of data). If I find that an application is scraping my website to download the data, this would be a copyright infringement, and I would be able to sue the person who created the scraper.

2. Data is too vague

If http://www.unicode.org/ stated that the license covers the data itself, it would be very difficult for this organization to enforce such copyright.

Imagine the following method:

public char ToUpper(char c)
{
    string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if (upper.Contains(c))
    {
        return c;
    }

    string lower = "abcdefghijklmnopqrstuvwxyz";
    if (lower.Contains(c))
    {
        return upper[lower.IndexOf(c)];
    }

    throw new OutOfRangeException();
}

Is this a violation of the copyright? Did I actually used the data from http://www.unicode.org/ and I should include the copy of the license in my answer below? Or maybe I just typed those letters myself?

In other words, if data itself was licensed, how far the license could go?

3. Copyright and data

Here are some interesting quotes:

http://www.lib.umich.edu/copyright/facts-and-data: University of Michigan

Copyright law does not apply to facts, data, or ideas. [...]

However, copyright may protect a collection of data as contained in a database or compilation, but only if it meets certain requirements. Simply working really hard to gather the data [...] is not enough. [...]

In order for a database to qualify for copyright protection, the author has to make choices about the selection, coordination, or arrangement of the facts or data, and those choices must be at least a little bit creative. [...]

It is important to remember that even if a database or compilation is arranged with sufficient originality to qualify for copyright protection, the facts and data within that database are still in the public domain.

http://www.ands.org.au/guides/copyright-and-data-awareness.html: Australian National Data Service

A table or compilation, consisting of words, figures or symbols (or a combination of these) is protected if it is

a literary work and

has the required degree of originality.

[...] Copyright applies not to the facts/information itself, but to the particular way the facts/information are presented in the dataset or database.

Those two examples, one concerning USA, the other one - Australia, clearly shows that the data itself, i.e. the unicode symbols with their respective numbers and the attributes such as "is this a digit?" or "is this a capital letter from Cyrillic alphabet?" is not covered by the copyright.

Data files, on the other hand, may be covered by the copyright, depending on their originality. For example, the PDFs you find on http://www.unicode.org/ would be very probably covered by a copyright. If, on the other hand, it is purely question of a CSV associating lowercase characters to uppercase or vice versa, the author of such data would hardly be able to enforce the copyright on it.

Clearly, the ToUpper method I put above is not a violation of http://www.unicode.org/ copyright. Nor the code used by .NET Framework or Firefox, unless those systems contain somewhere inside the data files which are clearly, undoubtedly copied from http://www.unicode.org/ with, optionally, some minor changes.


问:
How to setup the c++ rule of three in a virtual base class
I am trying to create a pure virtual base class (or simulated pure virtual)

my goal:

User can't create instances of BaseClass.

Derived classes have to implement default constructor, copy constructor, copy assignment operator and destructor.

My attempt:

```<code>class Base
{
public:
    virtual ~Base() {};
    /* some pure virtual functions */
private:
    Base() = default;
    Base(const Base& base) = default;
    Base& operator=(const Base& base) = default;
}
</code>```

This gives some errors complaining that (for one) the copy constructor is private. But i don't want this mimicked constructor to be called.

Can anyone give me the correct construction to do this if this is at all possible?

答:
As the Rule of the Three says...

If you need to explicitly declare either the destructor, copy constructor or copy assignment
   operator yourself, you probably need to explicitly declare all three
  of them.

In your example of abstract class with the inheritance hierarchy, you would have to make the destructor, copy constructor and the copy assignment operator your self. Do not declare either of them as private as you restrict their usage out of the class.

```<code>class Base
{
 /* some pure virtual functions */
 public:
     Base() ;
     Base(const Base& base) ;
     Base& operator=(const Base& base) = default;
     virtual ~Base() {};
} ;
</code>```

As a matter of fact, assignment operator is not passed on in inheritance.

Body:
As the Rule of the Three says...

If you need to explicitly declare either the destructor, copy constructor or copy assignment
   operator yourself, you probably need to explicitly declare all three
  of them.

In your example of abstract class with the inheritance hierarchy, you would have to make the destructor, copy constructor and the copy assignment operator your self. Do not declare either of them as private as you restrict their usage out of the class.

class Base
{
 /* some pure virtual functions */
 public:
     Base() ;
     Base(const Base& base) ;
     Base& operator=(const Base& base) = default;
     virtual ~Base() {};
} ;

As a matter of fact, assignment operator is not passed on in inheritance.


答:
These files legally form a database, which means many jurisdictions it's treated not as a copyrightable work but subject to other kinds of protection. In particular, such jurisdictions will consider the (quantitative and/or qualitative) effort necessary for the compilation of such databases. See e.g. the European Database Directive.

AS an example, there's no creative decision involved in defining the relation between uppercase and lowercase letters. That particular table is therefore not subject to copyright in the EU, and since the Unicode Consortium isn't European either, it's not covered under the database right laws either. (There's no equivalent of the Berne treaty for database rights)

Title: Unicode license

Body:
The Unicode Terms of Use state that any software that uses their data files (or a modification of them) should carry the Unicode license references. It seems to me that most Unicode libraries have functions to check whether a character is a digit, a letter, a symbol, etc., and so will contain a modification of the Unicode Data Files (usually in the form of tables). Does that mean the license applies and all applications that use such Unicode libraries should carry the license?

I've checked around, and it appears that very few Unicode programs do carry the license, though arguably most of those that didn't carry the license were from companies that were members of the Unicode consortium (do they get license exemptions?).

Some (e.g., Mozilla) are only "Liaison Members", and while their software do not carry the license (as far as I can tell), they do obviously rely on data derived from those data files. Is Mozilla in breach of the license?

Should we carry the license in all apps that include any form of advanced Unicode support (i.e., are bound to rely on the Unicode data files)? Or is there some form of broad exemption (since very very few programs out there carry the license)?

I've forwarded this question to Unicode staff. I'll post the reply here when/if I get one.


答:
TCP is a stream protocol, usually on top of IP (IPv4 or 6).It doesn't cover file transmission. Instead, this is typically delegated to other protocols such as FTP, HTTP, HTTPS, NFS, CIFS or rsync.

You are apparently removing the IP and TCP headers from the data, but not the metadata added by the other protocol(s) you're using. Since you haven't told us what those are, we can't specifically address them, but in general you'll have to implement a protocol handler for that.

Note that with advanced protocols such as HTTPS, you obviously and by design cannot recover a file from only the server side packets.

Title: Reconstruct a file from a TCP stream

Body:
I have a client and a server and a third box which sees all packets from the server to the client (but not the other way around). Now when the client requests a file from the server (over HTTP), the third box sees the response. I am trying to reconstruct the file there. I am using libpcap to capture TCP datagrams and trying to reconstruct the file there. Here is what I did

Listen for packets on an interface

Group all packets which have the same ACK number

Sort the group based on SEQ number

Extract data from each packet and combine them and write to the disk

The problem is, the file thus generated is not exactly the same as the original file. Their sizes are the same each, but when I open the images in an image viewer, they look different. time Does everything sound correct here?

EDIT

Hexdump of first 512 bytes of the recovered file

```<code>0000000 009a 0095 0090 008b 0086 0081 007c 0077
0000010 0072 006d 0068 0063 005e 0059 0054 004f
0000020 004a 0045 0040 003b 0037 0032 002d 0028
0000030 0023 001e 0019 0014 000f 000a 0005 0000
0000040 0400 0000 0000 0000 7276 6375 5420 4352
0000050 0000 0000 6720 7369 0000 0000 0000 0000
0000060 0000 0000 0002 0000 028f 0000 0000 0000
0000070 0001 0000 0000 0000 6173 6d65 1fe7 0057
0000080 0000 0050 0956 004c 0000 0000 5a20 5859
0000090 0001 0000 5c9e 0003 130b 0004 edcc 0003
00000a0 cf14 0010 5f2e 0014 a4fe 0013 0000 0000
00000b0 6577 7669 0000 0000 0000 0000 0000 0000
00000c0 0000 0000 0000 0000 0000 0000 2e31 2d32
00000d0 3636 3139 4336 4945 6e20 2069 6f6e 7469
00000e0 6469 6f6e 2043 6e67 7769 6965 2056 6365
00000f0 656e 6572 6566 2c52 0000 0000 0000 0000
0000100 0000 3100 322e 362d 3936 3631 4543 2049
0000110 696e 6e20 696f 6974 6e64 436f 6720 696e
0000120 6577 5669 6520 6e63 7265 6665 5265 002c
0000130 0000 0000 0000 7363 6465 0000 0000 0000
0000140 0000 0000 0000 0000 0000 0000 0000 0000
0000150 4742 7352 2d20 6520 6163 7370 7220 6f75
0000160 6f6c 2063 4742 2052 6c74 6175 6566 2044
0000170 2e31 2d32 3636 3139 2036 4543 2e49 0000
0000180 0000 0000 0000 0000 4200 5247 2073 202d
0000190 6365 7061 2073 7572 6c6f 636f 4220 5247
00001a0 7420 756c 6661 4465 3120 322e 362d 3936
00001b0 3631 4320 4945 002e 0000 0000 0000 7363
00001c0 6465 0000 0000 0000 0000 0000 0000 0000
00001d0 0000 0000 0000 0000 0000 0000 0000 0000
*
00001f0 6368 632e 6965 772e 7777 2f2f 703a 7474
0000200
</code>```

Hexdump of first 512 bytes of the original file:

```<code>0000000 d8ff e0ff 1000 464a 4649 0100 0101 2c01
0000010 2c01 0000 e2ff 6d1c 4349 5f43 5250 464f
0000020 4c49 0045 0101 0000 5d1c 694c 6f6e 1002
0000030 0000 6e6d 7274 4752 2042 5958 205a ce07
0000040 0200 0900 0600 3100 0000 6361 7073 534d
0000050 5446 0000 0000 4549 2043 5273 4247 0000
0000060 0000 0000 0000 0000 0000 0000 d6f6 0100
0000070 0000 0000 2dd3 5048 2020 0000 0000 0000
0000080 0000 0000 0000 0000 0000 0000 0000 0000
*
00000a0 0000 0000 0000 0000 1100 7063 7472 0000
00000b0 5001 0000 3300 6564 6373 0000 8301 0000
00000c0 6c00 7477 7470 0000 ef01 0000 1400 6b62
00000d0 7470 0000 0302 0000 1400 5872 5a59 0000
00000e0 1702 0000 1400 5867 5a59 0000 2b02 0000
00000f0 1400 5862 5a59 0000 3f02 0000 1400 6d64
0000100 646e 0000 5302 0000 7000 6d64 6464 0000
0000110 c302 0000 8800 7576 6465 0000 4b03 0000
0000120 8600 6976 7765 0000 d103 0000 2400 756c
0000130 696d 0000 f503 0000 1400 656d 7361 0000
0000140 0904 0000 2400 6574 6863 0000 2d04 0000
0000150 0c00 5472 4352 0000 3904 0000 0c08 5467
0000160 4352 0000 450c 0000 0c08 5462 4352 0000
0000170 5114 0000 0c08 6574 7478 0000 0000 6f43
0000180 7970 6972 6867 2074 6328 2029 3931 3839
0000190 4820 7765 656c 7474 502d 6361 616b 6472
00001a0 4320 6d6f 6170 796e 6400 7365 0063 0000
00001b0 0000 0000 7312 4752 2042 4549 3643 3931
00001c0 3636 322d 312e 0000 0000 0000 0000 0000
00001d0 1200 5273 4247 4920 4345 3136 3639 2d36
00001e0 2e32 0031 0000 0000 0000 0000 0000 0000
00001f0 0000 0000 0000 0000 0000 0000 0000 0000
0000200
</code>```

Some more details:

I am using C++

The packet data is being stored as std::vector<char>

I did change the byte order while reading the ack number and seq number from the packet using ntohl

I am not sure if I need to change the byte order for the data as well. I tried to reverse the data from each packet before combining them, even that did not work.

Is there something I am missing?

EDIT

Original file:

Recovered file:


问:
Should I add parameters to instance methods that use those instance fields as parameters?
I have an instance method that uses instance fields in its work. I can leave the method without that parameters as they're available to me, or I can add them to the parameter list, thus making my method more "generic" and not reliable on the class. On the other hand, additional parameters will be in parameters list. Which approach is preferable and why?

Edit: at the moment I don't know if my method will be public or private.

Edit2: clarification: both method and fields are instance level.

答:
Every interface you offer to outside clients gives you restrictions. For example, if you have a method

```<code>    public double computeMean(double[] values) {
    ...
    }
</code>```

You give a promise that you accept double[] arrays, but what if you deliverd the code to customers and suddenly realize that ArrayList<Double> would be better? And maybe you don´t know if there are clients who call your method, so you can not just change it to ArrayList.

If it is public and the values are already known to the class, you don´t need the parameters. This gives you the freedom to change from double[] to whatever you want, without changing your interface.

If it is a private method, you don´t need the parameters, they would be boilerplate code since you already know the values as you said.

If you want a really generic function that does not depend on the class at all (which means there is no state to keep track of) you can make a static method that gets all information it needs from the parameters, if you don´t keep any state in your class at all you don´t even need an instance of this class. Like in Java Collections.sort(...).

So it depends on your clients if you should add the parameters.

Body:
Every interface you offer to outside clients gives you restrictions. For example, if you have a method

    public double computeMean(double[] values) {
    ...
    }

You give a promise that you accept double[] arrays, but what if you deliverd the code to customers and suddenly realize that ArrayList<Double> would be better? And maybe you don´t know if there are clients who call your method, so you can not just change it to ArrayList.

If it is public and the values are already known to the class, you don´t need the parameters. This gives you the freedom to change from double[] to whatever you want, without changing your interface.

If it is a private method, you don´t need the parameters, they would be boilerplate code since you already know the values as you said.

If you want a really generic function that does not depend on the class at all (which means there is no state to keep track of) you can make a static method that gets all information it needs from the parameters, if you don´t keep any state in your class at all you don´t even need an instance of this class. Like in Java Collections.sort(...).

So it depends on your clients if you should add the parameters.


答:
Well, unless you need to interface with the outer world, it is not useful to add parameters, neither if in view of needing it later.

If you should realize at a certain time you need to provide this method with parameters, then you may overload this method at that moment, accepting parameters in the new signature and manage it out that way.

Generally speaking I tend to consider a good design approach leaving eventual 2nd generation changes out of scope, if my specification is well-defined.

It is better to keep design as minimal as possible, but open to later eventual changes.

This means that, given a situation like yours, it is not useful to trust program evolution immediately; instead stick to actual specifications, designing with an eye to what it is reasonable to be expected.

Title: Should I add parameters to instance methods that use those instance fields as parameters?

Body:
I have an instance method that uses instance fields in its work. I can leave the method without that parameters as they're available to me, or I can add them to the parameter list, thus making my method more "generic" and not reliable on the class. On the other hand, additional parameters will be in parameters list. Which approach is preferable and why?

Edit: at the moment I don't know if my method will be public or private.

Edit2: clarification: both method and fields are instance level.


问:
Evaluating mean and std as simulations are added
I have simulations that evaluate a certain value X. I run the simulations several times and save the value of X in a vector V. When all the runs have finished I evaluate the mean and standard deviation for the vector V.

This approach works, but implies saving all the values for X. As my computer is quite old and with limited ram, I was wondering if there is a way to update the mean value M and the standard deviation S, knowing the value of X at the (n+1)-th run, and the values of M and S after n runs.

How can I update the mean value and the standard deviation as simulations are added to the set?

Please note that this is just a conceptual example, I don't save only one number X but thousands at each simulations, so I really have problems running a big number of runs if I have to keep all the past values into the memory.

答:
For the mean, it is enough to save the sum and a counter of how many values you added. For the standard deviation, you need an online algorithm like this one:
http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm

Or here:
https://stackoverflow.com/questions/11978667/online-algorithm-for-calculating-standard-deviation


答:
I think you should build the application for the web, but host it on his machine. Everything from the code to the database. This does have it's quirks, as the client has to do the maintenance. </p>

<p>I also suggest you talk to the client about the pros and cons of running it locally. It saves you from unnecessary headache. </p>

Title: Writing a desktop application for progammer from PHP background

Body:
I have a client who wants a tool for him to be able to upload his products, enter orders, and keep track of customer details. There are quite a few highly customised requests, which is why he wants the tool custum made.

He does not care much about the interface design - it just has to be usable and provide access to the databade. I've already designed the database.

I have no experience of desktop applications and usually write my web apps in PHP with the Yii framework. But hosting this on a server seems like overkill. I also have .net experience from a few years ago. What would be the best options for writing this as a desktop application?

Body:
I think you should build the application for the web, but host it on his machine. Everything from the code to the database. This does have it's quirks, as the client has to do the maintenance.

I also suggest you talk to the client about the pros and cons of running it locally. It saves you from unnecessary headache.


问:
Would a typical corporate firewall block a Java applet having the following behaviour
I'm thinking of developing a proxy-like program to forward ports on a remote PC to a local PC (for example SSH).
Assume that both local and remote PCs are running behind typical firewalls (i.e. consumer broadband router firewall, Windows firewall or corporate firewalls).

The program will be a Java program which the user will run on both the remote and local PC.
The remote client will periodically poll a central server to determine whether there are pending client connections. A session could be initiated as follows:

The local client contacts the central server and request the current connection details for a specific remote client.

The central server responds with the remote server's last received IP address and port.

The next time the remote server polls the central server, the
    client's IP address and port are returned. The remote server
    initiates a connection to the local client using the IP address and
    port returned by the central server and listens for a response on a
    random port. The remote server will pass the value of the port it's
    listening on to central server.

Goto 1, if client fails to connect to server.

All coomunication with the central server will be via HTTP/HTTPS on ports 80 & 443.

Would this work or will a typical firewall block the interactions.

答: In addition to pdr's answer, some firewalls are capable of packet inspection.  Just because you are using 80 / 443 doesn't mean that you are replicating http(s) traffic. </p>


问:
A way to return multiple return values from a method: put method inside class representing return value. Is it a good design?
I need to return 2 values from a method. My approach is as follows:

create an inner class with 2 fields that will be used to keep those 2 values

put the method inside that class

instantiate the class and call the method.

The only thing that will be changed in the method is that in the end it will assign those 2 values to the fields of the instance. Then I can address those values by referencing to the fields of that object.

Is it a good design and why?

答:
It seems that this class is taking responsibility away from another class, and this makes me think that this design isn't great.

For a method that returns multible values, I would rather

return a generic containter (e.g. a List or Map) containing the return values

or

create a Class for the return value, which contains just of the necessary fields + getters + a constructor with all fields

Example for the second option:

```<code>public Class FooBarRetval {
   private String foo;
   private int bar;

   public FooBarRetval (String foo, int bar) {
      this.foo = foo;
      this.bar = bar;
   }

   public String getFoo() {
      return foo;
   }

   public int getBar() {
      return bar;
   }
}
</code>```

Body:
It seems that this class is taking responsibility away from another class, and this makes me think that this design isn't great.

For a method that returns multible values, I would rather

return a generic containter (e.g. a List or Map) containing the return values

or

create a Class for the return value, which contains just of the necessary fields + getters + a constructor with all fields

Example for the second option:

public Class FooBarRetval {
   private String foo;
   private int bar;

   public FooBarRetval (String foo, int bar) {
      this.foo = foo;
      this.bar = bar;
   }

   public String getFoo() {
      return foo;
   }

   public int getBar() {
      return bar;
   }
}


答:
I would argue this along the following lines:

Why exactly does your method return multiple values?  What kind of cohesion are we talking about - should those values actually be fields on a single class, or are they just coincidentally returned by the same method, but otherwise unrelated?  If it's the latter, you might want to consider splitting the method into two methods, rather.  Edit: use your judgement here; sometimes a type of "coincidental" cohesion may be the best option.  Another option is to use a pair or tuple construct, although in OOP, these are usually not seen in public APIs (some notable exceptions being standard collections, etc).

If the values do deserve to form a class, I would probably advise against using an inner class.  Inner classes are typically used as internal implementation details, which are hidden from the outside.  Is there any reason why this result shouldn't be a "full-blown" class, in its own right?

Other than holding data, what operations are applicable to this new class?  In object oriented design, you want to have the related behaviour close to the relevant data (which seem to be your intentions, too).  Should the method you are referring to not live on this class rather?

To summarise, I would see if I can turn this "data object" into a fledged-out class with both data and behaviour.  As an additional comment, you may want to make the class immutable, since its state is set once.  Making it immutable will help prevent it being incorrectly set, or modified later (say, someone setting one of the fields to null and passing it along).

Edit: As Patkos Csaba correctly points out, the principle being applied here is the Single Responsibility Principle (SRP) - the class you are trying to create should really have one responsibility (defined as a reason for changing).  This design guideline should help you figure out whether your two fields belong in a single class, or not.  To stick with the Wikipedia example, your class could be a seen as a type of report, in which case it's conforming to SRP, but it's difficult to comment without further information.

Title: A way to return multiple return values from a method: put method inside class representing return value. Is it a good design?

Body:
I need to return 2 values from a method. My approach is as follows:

create an inner class with 2 fields that will be used to keep those 2 values

put the method inside that class

instantiate the class and call the method.

The only thing that will be changed in the method is that in the end it will assign those 2 values to the fields of the instance. Then I can address those values by referencing to the fields of that object.

Is it a good design and why?


答:
IMO, "making my method more "generic" and not reliable on the class" is not a good goal, since it promotes classes with low cohesion.

If your method is generic enough to serve for other classes, too, then take it out of the class and move it to a "function library" class. (But beware of the functional decomposition antipattern).


问:
Is mocking for unit testing appropriate in this scenario?
I have written around 20 methods in Java and all of them call some web services.
None of these web services are available yet. To carry on with the server side coding, I hard-coded the results that the web-service is expected to give.

Can we unit test these methods? As far as I know, unit testing is mocking the input values and see how the program responds. Are mocking both input and ouput values meaningful?

Edit :

The answers here suggest I should be writing unit test cases.

Now, how can I write it without modifying the existing code ?

Consider the following sample code (hypothetical code) :

```<code>    public int getAge()
    {
            Service s = locate("ageservice"); // line 1
            int age = s.execute(empId); // line 2
             return age; // line 3

 }
</code>```

Now How do we mock the output ?

Right now , I am commenting out 'line 1' and replacing line 2 with int age= 50. Is this right ? Can anyone point me to the right way of doing it ?

答:
Yes.

Use mocks and stubs to simulate the web services' expected behavior. Validate that your code functions correctly under all expected boundary values and equivalence classes.

EDIT:

No, you should not be manually editing the unit test with int age= 50. You should be using dependency injection so that you can easily replace the Service with a mock object.

```<code>public int getAge(Service s)
{
    int age = s.execute(empId); // line 2
    return age; // line 3
}
</code>```

Your unit test should look something like the following pseudo-code:

```<code>public int getAgeMinimumValueTest()
{
    ClassUnderTest uut = new ClassUnderTest();
    MockService service = new MockService();
    service.age = 10;
    int age = uut.getAge(service);
    Assert(age == 10);
}
</code>```

Body:
Yes.

Use mocks and stubs to simulate the web services' expected behavior. Validate that your code functions correctly under all expected boundary values and equivalence classes.

EDIT:

No, you should not be manually editing the unit test with int age= 50. You should be using dependency injection so that you can easily replace the Service with a mock object.

public int getAge(Service s)
{
    int age = s.execute(empId); // line 2
    return age; // line 3
}

Your unit test should look something like the following pseudo-code:

public int getAgeMinimumValueTest()
{
    ClassUnderTest uut = new ClassUnderTest();
    MockService service = new MockService();
    service.age = 10;
    int age = uut.getAge(service);
    Assert(age == 10);
}


答:
Yes, it is. Your job is to demonstrate that your code does the right thing, given its environment. The external web services are part of the environment; it's not your job to test their proper functioning, it's the job of the people who write the services. The input/output mapping that the tests should check is the input/output to your code; if the code produces input for another collaborator to do its job, that's strictly incidental.

In fact, even after the web services are available it is probably a good idea to keep your unit tests using a mock environment rather than the real one. It makes the tests simpler, less fragile with respect to the expected system context, and probably faster as well.

Title: Is mocking for unit testing appropriate in this scenario?

Body:
I have written around 20 methods in Java and all of them call some web services.
None of these web services are available yet. To carry on with the server side coding, I hard-coded the results that the web-service is expected to give.

Can we unit test these methods? As far as I know, unit testing is mocking the input values and see how the program responds. Are mocking both input and ouput values meaningful?

Edit :

The answers here suggest I should be writing unit test cases.

Now, how can I write it without modifying the existing code ?

Consider the following sample code (hypothetical code) :

```<code>    public int getAge()
    {
            Service s = locate("ageservice"); // line 1
            int age = s.execute(empId); // line 2
             return age; // line 3

 }
</code>```

Now How do we mock the output ?

Right now , I am commenting out 'line 1' and replacing line 2 with int age= 50. Is this right ? Can anyone point me to the right way of doing it ?


答:
Old time calculators with statistics functions saved only the number of items, the sum of the items and the sum of the squares of the items.

mean is the sum of the items divided by their number:

standard deviation is the square root of the variance:

variance is obtained by substracting the square of the mean from the mean of the squares:

Title: Evaluating mean and std as simulations are added

Body:
I have simulations that evaluate a certain value X. I run the simulations several times and save the value of X in a vector V. When all the runs have finished I evaluate the mean and standard deviation for the vector V.

This approach works, but implies saving all the values for X. As my computer is quite old and with limited ram, I was wondering if there is a way to update the mean value M and the standard deviation S, knowing the value of X at the (n+1)-th run, and the values of M and S after n runs.

How can I update the mean value and the standard deviation as simulations are added to the set?

Please note that this is just a conceptual example, I don't save only one number X but thousands at each simulations, so I really have problems running a big number of runs if I have to keep all the past values into the memory.


问:
Is taking frequent breaks really that beneficial when programming?
I keep reading that it is recommended for a programmer to take frequent breaks while programming, and the usual recommendation I see is 5 minutes every half hour or 10 minutes every hour.

I gave it a try, but quite often I find something interesting during those 5 minutes, and it takes me away from what I was working on for longer than I planned. Either that, or my mind gets focused on something else and I find it hard to get back into my work and don't focus very well.

Is it really that beneficial to take frequent breaks while programming? Am I doing something wrong for it to be decreasing my productivity instead of increasing it?

答: If you're really stuck, sometimes instead of taking a break, you can release your rage and break a take, like the teeth of the annoying co-worker who is distracting you by babbling loudly on the phone to all of his living relatives back in the hole he crawled out from and into the urban areas.


答:
The requirement looks wrong. The reason is that virtual methods and copy constructors don't work together. Virtual methods are useful if you use the object polymorphically, that is via reference/pointer to a base class. But copy constructor always constructs object of the static type it is written as, so if you give it polymorphic object, it will only create the base class, not the subclass you wanted. This is called slicing.

So you want to either:

Have a templated framework that knows the type at compile time and uses copy-constructor. But this does not need any virtual methods, nor for that matter a common base type, since the code will be compiled with the specific template parameter. Compiler will complain if the type substituted does not support the operations the template tries to use, but you can slightly improve diagnostics by using some explicit checks, e.g. from Boost.Concept Check.

Have a framework using polymorphic objects with base class, but that can't create copies with copy constructor, because it does not know the type to construct. There are three ways out:

Have a pure virtual Base *clone() method, that will be implemented to do return new Derived(this) in each concrete subclass. You should probably wrap that in unique_ptr or shared_ptr immediately to avoid leaking the copies.

Instead of copies, hand out references or smart pointers, probably shared_ptr in this case. It would probably be either const references/smart pointers or typed with interface that only contains methods that can't affect invariants in the framework.

Make the method that inserts the objects a template, that would construct a cloner and store it along with the object. Cloner is a function template<typename T> Base *clone(const Base *obj) { return new T(dynamic_cast<const T &>(*obj); } (you can have a functor or a class with multiple helper methods like this). To ensure you really have correct type, the insert method should probably wrap the call to new as well similar to e.g. make_shared.

By the way, nothing of this has anything to do with rule of three. Because rule of three says that if default copy constructor, default assignment operator or default destructor are not good enough for the class, than none of them is. But not because compiler would require it, but because the logic probably does. But for most classes that want to be copyable they are good enough. Because in most cases you hide the resource handling in some smart pointer and just let the default copy/assignment/destructor call to it.

Title: How to setup the c++ rule of three in a virtual base class

Body:
I am trying to create a pure virtual base class (or simulated pure virtual)

my goal:

User can't create instances of BaseClass.

Derived classes have to implement default constructor, copy constructor, copy assignment operator and destructor.

My attempt:

```<code>class Base
{
public:
    virtual ~Base() {};
    /* some pure virtual functions */
private:
    Base() = default;
    Base(const Base& base) = default;
    Base& operator=(const Base& base) = default;
}
</code>```

This gives some errors complaining that (for one) the copy constructor is private. But i don't want this mimicked constructor to be called.

Can anyone give me the correct construction to do this if this is at all possible?


答:
Short anwer: If the instance method has access to the instances variables then there is no need to pass those same values as parameters.

If you want to create a class (static) methods, then such a method will no have access to any state, so you have to pass the values as parameters.


答:
Are mocking both input and ouput values meaningful?

No, but you're not mocking the input value. Your test is being run, and the mock service verifies that the right part of the contract is accessed. That you happen to return a particular value is irrelevant.

On the otherside, if your method does any logic at all, then the return value matters. Here you're mocking the inputs to the logic (the result of the web service) and testing the output.


答:
Yes you should be mocking your service. Mocking is the practice of using mock objects to replace the real objects you would normally use at runtime. Most of the time you would want to use a mocking framework to easily and dynamically create mock objects.

If you use mock objects, you would probably write code that looked more like this:

```<code>public int getAge(ServiceInterface service)
{
    return service.execute(empId);
}
</code>```

where service is the actual service you're going to use at runtime, but during a unit test it is a mock object with mock behavior. Notice the parameter for getAge is no longer a concrete class, but instead is an interface. This allows you to use any object as a parameter as long as it implements the interface, instead of just one specific class. Your unit test would then take the following steps:

Create the mock object

Tell it to return a certain age when execute is called

Call getAge with the mock object as a parameter

Verify getAge returns the correct age.

For a good list of Java mocking frameworks, check out this stackoverflow question.

EDIT

Don't comment out your code and replace it with a constant just for your unit tests. The problem with this is that you'll have to make sure the right thing is commented when running unit tests, and the right thing is commented when releasing to the customer. This would turn into a nightmare for long-term maintenance purposes, especially if you intend on writing more than a 2 unit tests that require mocks. Aside from that, your tests should be run against the finished product; if not, that means you're not testing the actual code that is being released, which negates the purpose of having tests in the first place.

Body:
Yes you should be mocking your service. Mocking is the practice of using mock objects to replace the real objects you would normally use at runtime. Most of the time you would want to use a mocking framework to easily and dynamically create mock objects.

If you use mock objects, you would probably write code that looked more like this:

public int getAge(ServiceInterface service)
{
    return service.execute(empId);
}

where service is the actual service you're going to use at runtime, but during a unit test it is a mock object with mock behavior. Notice the parameter for getAge is no longer a concrete class, but instead is an interface. This allows you to use any object as a parameter as long as it implements the interface, instead of just one specific class. Your unit test would then take the following steps:

Create the mock object

Tell it to return a certain age when execute is called

Call getAge with the mock object as a parameter

Verify getAge returns the correct age.

For a good list of Java mocking frameworks, check out this stackoverflow question.

EDIT

Don't comment out your code and replace it with a constant just for your unit tests. The problem with this is that you'll have to make sure the right thing is commented when running unit tests, and the right thing is commented when releasing to the customer. This would turn into a nightmare for long-term maintenance purposes, especially if you intend on writing more than a 2 unit tests that require mocks. Aside from that, your tests should be run against the finished product; if not, that means you're not testing the actual code that is being released, which negates the purpose of having tests in the first place.


答:
Mocking isn't about inputs or outputs its about replacing external dependencies. So yes it is appropriate to write unit tests and mock out the external web services.

Now for the bad news: depending on the language and tooling available to you you may not be able to mock out the external dependencies unless the code has been designed to allow you to. If this is the case then you will find your tests actually turn into little integration tests rather then pure unti tests.

On the plus side it looks like you are alowed to modify the code (else how are you commenting it out) pass in an interface to your service to allow it to be mocked out (or use some other form of dependency injection)

Finally, what you are wanting to test appears to be a pure wrapper around the external service, there is almost nothing to unit test here other than that you call the service. As this is fundamentally an interface most of the testing will have to be done later at a higher level (integration testing)


答:
Now, how can I write it without modifying the existing code ?

you can-t. But you can create an interface "IMyService" that you can program against that contains all webservice methods-signatures.

```<code>public int getAge()
{
        IMyService s = getService();
        int age = s.execute(empId);
         return age; // line 3

}
</code>```

In Production mode getService(); will return a reference to a full functional webservice and in testmode an alternative implemention (or mock) that returns your fake data.

Body:
Now, how can I write it without modifying the existing code ?

you can-t. But you can create an interface "IMyService" that you can program against that contains all webservice methods-signatures.

public int getAge()
{
        IMyService s = getService();
        int age = s.execute(empId);
         return age; // line 3

}

In Production mode getService(); will return a reference to a full functional webservice and in testmode an alternative implemention (or mock) that returns your fake data.


问:
What causes overtime and how can it be avoided?
Today, my manager told me that I must work over time to make up for a lack of planning and project management. Instead of incentivizing this unpaid mandatory overtime, my manager has made it clear I have no choice in the matter.

This isn't a single project. We currently have a dozen projects all on the go at one time, and I simply can't get them all done. Therefore, I must work overtime so we don't have to push deadlines.

Is this a sign of an ignorant or disrespectful manager, or simply an inexperienced one?

I'm in this position because of a lack of planning and project management (I think). How might I avoid this in the future? I'm no Project Manager, it isn't my strength.

What are good ways to get an employee to work overtime if you can't directly pay them? Good incentives, etc.

From what I hear, gaining your employee's respect is the single best way to get your employees to work over time, although you should never make a habit of it.

答:
You do have a choice in the matter - you can leave if it's not worth it !

To answer the question: If you had promised a certain project by a certain date, and it is running late even though there were no forces outside your control why it may be late - then perhaps said manager may have a point. That is about the only reason I can think of that overtime could be 'expected' since its just about making good on a promise.

Any other reason and it sounds like the manager is on a power trip.

As a side question, what are good ways to get an employee to work overtime if you can't directly pay them?

Gain respect, and people will do things for you and actually enjoy it.


问:
Is ASP.NET MVC completely (and exclusively) based on conventions?
--TL;DR

Is there a "Hello World!" ASP.NET MVC tutorial out there that doesn't rely on conventions and "stock" projects?

Is it even possible to take advantage of the technology without reusing the default file structure, and start from a single "hello_world.asp" file or something (like in PHP)?

Am I completely mistaken and I should be looking somewhere else, maybe this?

I'm interested in the MVC framework, not Web Forms

--Background

I've played a bit with PHP in the past, just for fun, and now I'm back to it since web development became relevant for me once again. I'm no professional, but I try to gain as much knowledge and control over the technology I'm working with as possible.

I'm using Visual Studio 2012 for C# - my "desktop" language of choice - and since I got the Professional Edition from Dreamspark, the Web Development Tools are available, including ASP.NET MVC 4. I won't touch Web Forms, but the MVC Framework got my attention because the MVC pattern is something I can really relate to, since it provides the control I want but... not quite.

Learning PHP was easy - and right form the start I could just create a "hello_world.php" file and just do something like this for immediate results:

```<code><!-- file: hello_world.php -->
<?php>
    echo "Hello World!";
<?>
</code>```

But I couldn't find a single ASP.NET (MVC) tutorial out there (I'll be sure to buy one of the upcoming MVC 4 books, only a month away or so) that would start like that. They all start with a sample project, building up knowledge from the basics and heavily using conventions as they go along. Which is fine, I suppose, but it's now the best way for me to learn things.

Even the "Empty" project template for a new ASP.NET MVC 4 Application in VS2012 is not empty at all: several files and folders are created for you - much like a new C# desktop application project, but with C# I can in fact start from scratch, creating the project structure myself.

It is not the case with PHP:

I can choose from a plethora of different MVC frameworks

I can just create my own framework

I can just skip frameworks altogether, and toss random PHP along with my HTML on a single file and make it work

I understand the framework needs to establish some rules, but what if I just want to create a single page website with some C# logic behind it? Do I really need to create a whole bloat of files and folders for the sake of convention?

Also, please understand that I haven't gotten far on any of those tutorials mainly because of this reason, but, if that's the only way to do it, I'll go for it using one of the books I've mentioned before. This is my first contact with ASP.NET but from the few comparisons I've read, I believe I should stay the hell away from Web Forms.

Thank you.
(Please forgive the broken English - it is not my primary language.)

答:
If you are looking for simple C# backed pages, look into ASP.NET Web Pages.  These are designed to be "framework-less" type way of building ASP.NET MVC style web applications, like would be done in raw PHP.

The full ASP.NET MVC framework does rely heavily on conventions, but it is itself a framework, not "raw" ASP.NET.


答:
To add on to emddudley's excellent answer the biggest gain you can get in mocking the service is being able to test what should happen the service doesn't function correctly. The test pseudo-code could look something like this:

```<code>public int AgeMinimumValue_LogsServiceError_Test()
{
    ClassUnderTest uut = new ClassUnderTest();
    MockService service = new MockService();
    service.Throws(new TimeoutException());

    MockLogger logger = new MockLogger();

    try {
        int age = uut.getAge(service, logger);
        Assert.Fail("Exception was not raised by the class under test");
    }
    catch (TimeoutException) {
        Assert(logger.LogError().WasCalled());
    }
}
</code>```

And now your implementation has been edited with this new requirement

```<code>public int getAge(Service s, Logger l)
{
    try {
        int age = s.execute(empId);
        return age;
    }
    catch(Exception ex) {
        l.LogError(ex);
        throw;
    }
}
</code>```

In other scenarios it is more likely that you would need to respond to more complicated responses. If the service provided credit card processing you would need to respond to Success, Service Unavailable, Expired Credit Card, Invalid Number, etc. By mocking the service you can ensure you respond to these scenarios in a way that is proper for your situation. In this case you must mock the input/output from the service and the feedback you get from knowing that the consuming code will work for all known outputs is indeed meaningful and valuable.

EDIT: I just noticed you want to be able to mock without modifying the existing method. To do this the locate("ageservice"); method would need to be changed to support mock objects in tests, and locating the real service once it is ready. This is a variation of the service locator patter which abstracts away the logic to retrieve the implementation of the service you are using. A quick version of that may look like this:

```<code>public Service locate(string serviceToLocate) {
    if(testEnvironment) // Test environment should be set externally
        return MockService(serviceToLocate);
    else
        return Service(serviceToLocate);
}
</code>```

My recommendation however would be to move the service dependencies into the Constructors:

```<code>public int AgeMinimumValue_LogsServiceError_Test()
{
    MockService service = new MockService();
    service.Throws(new TimeoutException());

    MockLogger logger = new MockLogger();

    ClassUnderTest uut = new ClassUnderTest(service, logger);

    try {
        int age = uut.getAge();
        Assert.Fail("Exception was not raised by the class under test");
    }
    catch (TimeoutException) {
        Assert(logger.LogError().WasCalled());
    }
}
</code>```

Now the getAge method no longer has the responsibility of looking up the service as it has been abstracted out of the class completely leaving an implementation similar to this:

```<code>public int getAge()
{
    try {
        // _service is a private field set by the constructor
        int age = _service.execute(empId);
        return age;
    }
    catch(Exception ex) {
         // _logger is a private field set by the constructor
        _logger.LogError(ex);
        throw;
    }
}
</code>```

Body:
To add on to emddudley's excellent answer the biggest gain you can get in mocking the service is being able to test what should happen the service doesn't function correctly. The test pseudo-code could look something like this:

public int AgeMinimumValue_LogsServiceError_Test()
{
    ClassUnderTest uut = new ClassUnderTest();
    MockService service = new MockService();
    service.Throws(new TimeoutException());

    MockLogger logger = new MockLogger();

    try {
        int age = uut.getAge(service, logger);
        Assert.Fail("Exception was not raised by the class under test");
    }
    catch (TimeoutException) {
        Assert(logger.LogError().WasCalled());
    }
}

And now your implementation has been edited with this new requirement

public int getAge(Service s, Logger l)
{
    try {
        int age = s.execute(empId);
        return age;
    }
    catch(Exception ex) {
        l.LogError(ex);
        throw;
    }
}

In other scenarios it is more likely that you would need to respond to more complicated responses. If the service provided credit card processing you would need to respond to Success, Service Unavailable, Expired Credit Card, Invalid Number, etc. By mocking the service you can ensure you respond to these scenarios in a way that is proper for your situation. In this case you must mock the input/output from the service and the feedback you get from knowing that the consuming code will work for all known outputs is indeed meaningful and valuable.

EDIT: I just noticed you want to be able to mock without modifying the existing method. To do this the locate("ageservice"); method would need to be changed to support mock objects in tests, and locating the real service once it is ready. This is a variation of the service locator patter which abstracts away the logic to retrieve the implementation of the service you are using. A quick version of that may look like this:

public Service locate(string serviceToLocate) {
    if(testEnvironment) // Test environment should be set externally
        return MockService(serviceToLocate);
    else
        return Service(serviceToLocate);
}

My recommendation however would be to move the service dependencies into the Constructors:

public int AgeMinimumValue_LogsServiceError_Test()
{
    MockService service = new MockService();
    service.Throws(new TimeoutException());

    MockLogger logger = new MockLogger();

    ClassUnderTest uut = new ClassUnderTest(service, logger);

    try {
        int age = uut.getAge();
        Assert.Fail("Exception was not raised by the class under test");
    }
    catch (TimeoutException) {
        Assert(logger.LogError().WasCalled());
    }
}

Now the getAge method no longer has the responsibility of looking up the service as it has been abstracted out of the class completely leaving an implementation similar to this:

public int getAge()
{
    try {
        // _service is a private field set by the constructor
        int age = _service.execute(empId);
        return age;
    }
    catch(Exception ex) {
         // _logger is a private field set by the constructor
        _logger.LogError(ex);
        throw;
    }
}


答:
EDIT:  To summarise, I think understand where you're coming from - at first glance, the ASP.Net MVC framework seems to have (too) many parts, and it's difficult to start understanding it.  Having said this, I'd argue that you're looking at this wrong.  ASP.Net MVC is not a particularly heavy MVC framework (you should compare it to PHP MVC frameworks to be fair), but yes, it is very much conventions-based.  There is a lot of good reasoning behind that design choice, and your first priority in learning the framework would be to learn its conventions, and perhaps the reasoning for them.  If for some reason you absolutely want to go deeper, the framework is open source, and you can dig into it here.

I can just skip frameworks altogether, and toss random PHP along with my HTML on a single file and make it work

Well, not with an MVC framework (even in PHP).  You're going to at least have a model, a view, and a controller.  Those are a bit of a minimum, so I'm not really sure what you're looking for here; it's an apples and oranges comparison.

After that, there's going to be a few other files that you will probably need; such as configuration for the routing, etc.  This is fairly standard and comparable to PHP MVC frameworks.

If you want a "single page" model, you could try WebForms, although that technology typically tries to move logic into a separate "code behind" page.  I'm pretty sure you could skip the latter, however, and have .aspx files logically identical to .php files sitting there.

Do I really need to create a whole bloat of files and folders...

The default VS project template does tend to copy a lot of potentially unnecessary stuff (scripts, etc), but you could remove most of those.  Again, you will probably have a minimum number of things there.  Do these really cause you major worry?  Have you seen what a Symfony installation looks like?

... for the sake of convention?

Convention is a great thing.  The concept is called "convention over configuration", and for most non-trivial projects, it is wonderful thing.  It stops people from reinventing things, and gives standards that should be followed.

Since you mention this is a learning exercise, I would suggest that you stop worrying about these things too much.  ASP.Net MVC is very much about convention, and you are doing yourself a disservice by trying to work around those.  In fact, to learn MVC, you should learn the conventions as much as any of the internals.

Title: Is ASP.NET MVC completely (and exclusively) based on conventions?

Body:
--TL;DR

Is there a "Hello World!" ASP.NET MVC tutorial out there that doesn't rely on conventions and "stock" projects?

Is it even possible to take advantage of the technology without reusing the default file structure, and start from a single "hello_world.asp" file or something (like in PHP)?

Am I completely mistaken and I should be looking somewhere else, maybe this?

I'm interested in the MVC framework, not Web Forms

--Background

I've played a bit with PHP in the past, just for fun, and now I'm back to it since web development became relevant for me once again. I'm no professional, but I try to gain as much knowledge and control over the technology I'm working with as possible.

I'm using Visual Studio 2012 for C# - my "desktop" language of choice - and since I got the Professional Edition from Dreamspark, the Web Development Tools are available, including ASP.NET MVC 4. I won't touch Web Forms, but the MVC Framework got my attention because the MVC pattern is something I can really relate to, since it provides the control I want but... not quite.

Learning PHP was easy - and right form the start I could just create a "hello_world.php" file and just do something like this for immediate results:

```<code><!-- file: hello_world.php -->
<?php>
    echo "Hello World!";
<?>
</code>```

But I couldn't find a single ASP.NET (MVC) tutorial out there (I'll be sure to buy one of the upcoming MVC 4 books, only a month away or so) that would start like that. They all start with a sample project, building up knowledge from the basics and heavily using conventions as they go along. Which is fine, I suppose, but it's now the best way for me to learn things.

Even the "Empty" project template for a new ASP.NET MVC 4 Application in VS2012 is not empty at all: several files and folders are created for you - much like a new C# desktop application project, but with C# I can in fact start from scratch, creating the project structure myself.

It is not the case with PHP:

I can choose from a plethora of different MVC frameworks

I can just create my own framework

I can just skip frameworks altogether, and toss random PHP along with my HTML on a single file and make it work

I understand the framework needs to establish some rules, but what if I just want to create a single page website with some C# logic behind it? Do I really need to create a whole bloat of files and folders for the sake of convention?

Also, please understand that I haven't gotten far on any of those tutorials mainly because of this reason, but, if that's the only way to do it, I'll go for it using one of the books I've mentioned before. This is my first contact with ASP.NET but from the few comparisons I've read, I believe I should stay the hell away from Web Forms.

Thank you.
(Please forgive the broken English - it is not my primary language.)


问:
What are the problems python 3 new features solve?
Python 3 new features say:

we’re mostly fixing well-known annoyances and warts, and removing a
  lot of old cruft

It mentions what is different (the fix) but not why (the problems). I have have not found what were the problems. What were the problems the fixes solve?

答:
I'll just name the ones that come to mind immediately.

Keyword-only arguments: Described in the rationale of the PEP.

nonlocal: Without this, closures can't overwrite variables closed over. This need arises from time to time with decorators and other higher-order functions. The only reasonable workaround (without switching the external API), storing whatever mutable state you want in a mutable object, is excessively ugly.

Dictionary and set comprehensions: Creating dictionaries and sets in a manner similar to list comprehensions is less pretty and slightly slower when done via generator comprehensions. It enables us to use these types where they are appropriate, without extra cost. Ditto for set literals, especially for in tests (as of Python 3.2, these are also optimized by the peephole optimizer).

Octal literals existed in Python 2, but the 0777 notation is a pitfall for those not used to it (in other contexts, adding a leading zero changes neither value nor base).

Binary literals are useful for bit fiddling, even moreso than hexadecimal literals.

Byte literals are a symptom of the enforced distinction between unicode strings and byte strings, and string literals being unicode. These changes force you to think about the difference between text and uninterpreted binary data and about encodings. This matters because otherwise you need extensive testing (with inputs us English-speaking, Europe/America-centric fools rarely ever think about) to find encoding-related errors.

except ex, var -> except ex as var fixes the common error except ValueError, IndexError (ought to catch both, but only catches the first and overwrites the name IndexError with the caught exception).

List comprehension scoping: Avoid polluting namespaces, and allow thinking of them in terms of generator expressions.

Removed syntax and modules: Bring us closer to "There should be one-- and preferably only one --obvious way to do it." and avoids people with poor tutorials sticking to the old & busted way of fixing things.


答:
Think of it this way. If the instance variables are more related to the class as a whole, leave them in the class. If they are not related to the class but much more to a single method, make them parameters.

If you think this way, you will have a higher cohesion also, which one of the basic concepts of OO.


答:
There's the concept of a Tuple which is featured in other languages, such as Python.

One could return an instance of this genericized class which is easily re-usable:

```<code>public class TypedTuple<L, R> implements Serializable {
private static final long serialVersionUID = 1L;

  protected L left;
  protected R right;

  protected TypedTuple() {
    // Default constructor for serialization
  }

  public TypedTuple(L inLeft, R inRight) {
    left = inLeft;
    right = inRight;
  }

  public L getLeft() {
    return left;
  }

  public R getRight() {
    return right;
  }
}
</code>```

Body:
There's the concept of a Tuple which is featured in other languages, such as Python.

One could return an instance of this genericized class which is easily re-usable:

public class TypedTuple<L, R> implements Serializable {
private static final long serialVersionUID = 1L;

  protected L left;
  protected R right;

  protected TypedTuple() {
    // Default constructor for serialization
  }

  public TypedTuple(L inLeft, R inRight) {
    left = inLeft;
    right = inRight;
  }

  public L getLeft() {
    return left;
  }

  public R getRight() {
    return right;
  }
}


问:
What are the pros and cons of a language using whitespace vs. {}'s to indicate scope?
There seems to be a conflict over whether its better to use whitespace or tokens like brackets to indicate scope. I've seen many praise python's solution to the inconsistent indentation problem, but many disagree:

Any language that has whitespace as tokens needs to die.

posted later on the same answer:

I was sortof anti-whitespace-as-tokens, until I actually tried it. It probably helped that my personal white-space layout pretty much matches what everyone in python-land uses. Perhaps it's that I am a bit minimalist, but if you're going to indent anyways, why bother with the {}s?

I can see some clear arguments for each side:

using whitespace:

helps reduce inconsistent indentation in code

clears the screen by replace visible tokens with whitespace to serve the same purpose

using tokens:

much easier to cut and paste code to different levels (you don't have to fix the
indentation)

more consistent. Some text editors display whitespace differently.

more popular currently.

Are there any points I missed? Which do you prefer? Any words of wisdom after having worked with one or the other for a long time?

PS. I hate it when languages don't use the same token for each control structure. VB is really annoying with its End If and End While statements, most other languages just use {}'s for everything. But maybe that's a topic for a different question...

答:
Pro: There are no indentation/curly-brace-placement holy wars in the Python world as far as I know. Making this decision on behalf of developers has probably saved some pain.

Con: Anonymous functions are limited to one line. Sounds ok, but I frequently find myself writing up multi-line lambdas in Scheme (mostly to feed to map or apply in exactly one place, so it wouldn't make sense to declare separately).


答:
Short answer: You can return an array or a List with the two values.

I personally would write two distinct methods, like

```<code>int x = obj.getX();
int y = obj.getY();
</code>```

Body:
Short answer: You can return an array or a List with the two values.

I personally would write two distinct methods, like

int x = obj.getX();
int y = obj.getY();


答:
Putting multiple return values from a method into its own class/structure is often used in message based systems that have one class for
Request and response. An example of this is  Simple Object Access Protocol (SOAP).

Is it a good design and why?

At least it is quite common. If this is good or bad depends on your special usecase.


答:
I am trying to create a pure virtual base class (or simulated pure virtual)

Sure:

User can't create instances of BaseClass.

Easy make the destructor virtual and pure

```<code>class Base
{
    public:
       virtual ~Base() = 0;
};
Base::~Base(){}
</code>```

Now you can not instantiate a member of Base.

Derived classes have to implement default constructor, copy constructor, copy assignment operator and destructor.

You can't force any of that.

If the user does not provide any of the above the compiler will automatically generate public versions for you. But by making them private you have basically made any derived class non copyable (even if the create their own versions).

But in g++ there are some warnings to help you.

If you set -Weffc++ and also set -Werror It should generate a compile time error if you do not obey the rule of three.

Body:
I am trying to create a pure virtual base class (or simulated pure virtual)

Sure:

User can't create instances of BaseClass.

Easy make the destructor virtual and pure

class Base
{
    public:
       virtual ~Base() = 0;
};
Base::~Base(){}

Now you can not instantiate a member of Base.

Derived classes have to implement default constructor, copy constructor, copy assignment operator and destructor.

You can't force any of that.

If the user does not provide any of the above the compiler will automatically generate public versions for you. But by making them private you have basically made any derived class non copyable (even if the create their own versions).

But in g++ there are some warnings to help you.

If you set -Weffc++ and also set -Werror It should generate a compile time error if you do not obey the rule of three.


问:
Programmaticaly finding the Landau notation (Big O or Theta notation) of an algorithm?
I'm used to search for the Landau (Big O, Theta...) notation of my algorithms by hand to make sure they are as optimized as they can be, but when the functions are getting really big and complex, it's taking way too much time to do it by hand. it's also prone to human errors.

I spent some time on Codility (coding/algo exercises), and noticed they will give you the Landau notation for your submitted solution (both in Time and Memory usage).

I was wondering how they do that...
How would you do it?

Is there another way besides Lexical Analysis or parsing of the code?

This question concerns mainly PHP and or JavaScript, but I'm opened to any language and theory.

答: My intuition is that a general solution to this problem is impossible; asserting, as it does, a priori facts about the runtime of algorithms without running them (you allude to lexical analysis). That said, it is possible for some heuristic algorithm for a (probably large) class of algorithms (since we do it all the time), but a general algorithm to do this would be equivalent to solving the Entscheidungsproblem which is well known not to be possible (cf. Church, Turing, et al.). I’m ~99.9% sure of this now that I think about it…


答:
Is this a sign of an ignorant manager or just a disrespectful one?

It's a sign of an ignorant, disrespectful asshole who is pushing your limits (and probably other developers too) to see how far he can abuse you for his own interest (promotion in the company, salary bonus..).

Either say no, or leave the company. Oh, and make sure you leave a letter for the upper mgmt. (the guys above your mgr.) explaining why exactly you left.

Title: What causes overtime and how can it be avoided?

Body:
Today, my manager told me that I must work over time to make up for a lack of planning and project management. Instead of incentivizing this unpaid mandatory overtime, my manager has made it clear I have no choice in the matter.

This isn't a single project. We currently have a dozen projects all on the go at one time, and I simply can't get them all done. Therefore, I must work overtime so we don't have to push deadlines.

Is this a sign of an ignorant or disrespectful manager, or simply an inexperienced one?

I'm in this position because of a lack of planning and project management (I think). How might I avoid this in the future? I'm no Project Manager, it isn't my strength.

What are good ways to get an employee to work overtime if you can't directly pay them? Good incentives, etc.

From what I hear, gaining your employee's respect is the single best way to get your employees to work over time, although you should never make a habit of it.


问:
Dependency injection and IOC containers in a closed project
Does it make sense to assemble my project with dependency injection containers if I am the only one who will use the code of that project?

The question came up when I read this IOC Article http://martinfowler.com/articles/injection.html

The justification for using dependency injection in this article is that friends can reuse a class, and replace depending classes with their own classes because they get injected and not instantiated in the class.

I would only use it to inject objects where they are needed instead of passing them through layers to their target. (Which is not so bad I learned here: Is it bad practice to pass instances through several layers?)

(Maybe I will reuse parts of the project, who knows, but I don´t know if that is a good justification)

答:
How the code is consumed and how many people are working on the project are orthogonal to the decision to use IoC containers or not.

They're a mechanism for providing unknown (and possibly changing post-deploy) implementations for a given interface, often via configuration. Do you need that mechanism? Then consider using them. If not, then don't.

Personally I find Spring-like containers to be oftentimes more trouble than the problem they're solving. Supplying dependencies via a constructor parameter or simple factory are often good enough. They tend to be easier to debug, and a lot less error-prone due to the lack of configuration.