问:
Reasons for the build-technological fork between Java and UNIX/C/Fortran
When Java was developed, it's designers chose to discard an unusual amount of the conventional wisdom established in the UNIX and C oriented toolchains. For one (and in my view) the most major example, they chose to discard the practice of header files and Makefiles and tried to build a monolithic, dependency-aware compiler instead. Later on, ant was developed to partially remedy the (obvious?) deficiencies of this process, and effectively re-implemented the makefile logic.

It's not like I resent old-style make and #include going overboard. However, their usage was reinvented in the Java world with ant and splitting each class into an Interface and an Implementation class, which is pretty close to the header file/source file pattern. I'm fairly sure the people behind Java knew of the existing tools and patterns and their purpose, so the decision to first do away with them and then reimplementing everything from scratch without even a hint of it in the language design is what astonishes me. Less costly ways would have been available (like parsing the source file and auto-generating a header file, which would have been fairly easy after pruning the C syntax a bit), but weren't taken, and I would love to know about the reason.

Similar forks were performed in most other places, at considerable development costs and the considerable cost of a splitted community. Nowadays, Java-world and C++-world developers often have a hard time communicating and collaborating due to a split that seems disproportionate to the actual differences between the C/C++ language and the Java language. While I can see the basic motivation behind the process (everyone loathes Makefile syntax and changing header files manually), I still can't grok the magnitude of the change.

Are there historical references about the motivation and reasons of this process? Are there any design documents or interviews with the people who drove this fork?

答:
You should actually look at it from a different perspective: In Java you can have header files in form of interfaces. Whereas you actually need header files in C/C++.

Later on, ant was developed to partially remedy the (obvious?) deficiencies of this process, and effectively re-implemented the makefile logic.

See ant as a tool to get things done, e.g. build your application, deploy it or publish Javadoc, instead of a necessary tool for building Java applications. Also, Java is not bound to ant. In a similar way, C/C++ is not bound to makefiles (although it's a de facto industry standard). In the Java world there is a noticeable movement towards other build tools, namely Maven and Gradle, which provide additional functionality like dependency management and configuration by exception.

I believe that the step from makefiles to ant has been driven by superior support for getting the tasks done. Additionally, why would you require header files when they are not required by compiler or developer?

This probably doesn't answer your request for design documents and interviews, but hopefully gives you some ideas why this has been a natural development.


问:
Is it an appropriate use of #define to make typing repeated code easier?
Is there any view on whether using the #define to define full lines of code for simplifying coding is good or bad programming practice? For example, if I needed to print a bunch of words together, I'd get annoyed typing

```<code><< " " <<
</code>```

To insert a space between words in a cout statement. I could just do

```<code>#define pSpace << " " <<
</code>```

and type

```<code>cout << word1 pSpace word2 << endl;
</code>```

To me this neither adds or subtracts from the clarity of the code and makes typing slightly easier. There are other cases that I can think of where typing will be much easier, usually for debugging.

Any thoughts on this?

EDIT: Thanks for all the great answers! This question just came to me after doing a lot of repetitive typing, but I never thought there would be other, less confusing macros to use. For those who don't want to read all the answers, the best alternative is to use the macros of your IDE to reduce repetitive typing.

答:
This question gives a clear example of how you can use macros badly.
To see other examples (and be entertained) see this question.

Having said that, I'll give real world examples of what I consider to be good incorporation of macros.

The first example appears in CppUnit, which is a unit testing framework. Like any other standard testing framework, you create a test class and then you have to somehow specify which methods should be run as part of the test.

```<code>#include <cppunit/extensions/HelperMacros.h>

class ComplexNumberTest : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE( ComplexNumberTest );
    CPPUNIT_TEST( testEquality );
    CPPUNIT_TEST( testAddition );
    CPPUNIT_TEST_SUITE_END();

 private:
     Complex *m_10_1, *m_1_1, *m_11_2;
 public:
     void setUp();
     void tearDown();
     void testEquality();
     void testAddition();
}
</code>```

As you can see, the class has a block of macros as it's first element. If I added a new method testSubtraction, it's obvious what you need to do to have it included in the test run.

These macro blocks expand out to something like this:

```<code>public:
  static CppUnit::Test *suite()
  {
    CppUnit::TestSuite *suiteOfTests = new CppUnit::TestSuite( "ComplexNumberTest" );
    suiteOfTests->addTest( new CppUnit::TestCaller<ComplexNumberTest>(
                                   "testEquality",
                                   &ComplexNumberTest::testEquality ) );
    suiteOfTests->addTest( new CppUnit::TestCaller<ComplexNumberTest>(
                                   "testAddition",
                                   &ComplexNumberTest::testAddition ) );
    return suiteOfTests;
  }
</code>```

Which would YOU prefer to read and maintain?

Another example is in the Microsoft MFC framework, where you map functions to messages:

```<code>BEGIN_MESSAGE_MAP( CMyWnd, CMyParentWndClass )
    ON_MESSAGE( WM_MYMESSAGE, OnMyMessage )
    ON_COMMAND_RANGE(ID_FILE_MENUITEM1, ID_FILE_MENUITEM3, OnFileMenuItems)
    // ... Possibly more entries to handle additional messages
END_MESSAGE_MAP( )
</code>```

So, what are the things which distinguish "Good Macros" from the horrible evil kind?

They perform a task which cannot be simplified any other way. Writing a macro to determine a maximum between two elements is wrong, because you can achieve the same using a template method. But there are some complex tasks (for example, mapping message codes to member functions) which the C++ language just doesn't handle elegantly.

They have an extremely strict, formal usage. In both of these examples the macro blocks are announced by starting and ending macros, and the inbetween macros will only ever appear inside these blocks.  You have normal C++, you briefly excuse yourself with a block of macros, and then you go back to normal again. In the "evil macros" examples, the macros are scattered throughout the code and the hapless reader has no way of knowing when the C++ rules apply and when they do not.

ContentLicense: CC BY-SA 3.0

Body:
This question gives a clear example of how you can use macros badly.
To see other examples (and be entertained) see this question.

Having said that, I'll give real world examples of what I consider to be good incorporation of macros.

The first example appears in CppUnit, which is a unit testing framework. Like any other standard testing framework, you create a test class and then you have to somehow specify which methods should be run as part of the test.

#include <cppunit/extensions/HelperMacros.h>

class ComplexNumberTest : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE( ComplexNumberTest );
    CPPUNIT_TEST( testEquality );
    CPPUNIT_TEST( testAddition );
    CPPUNIT_TEST_SUITE_END();

 private:
     Complex *m_10_1, *m_1_1, *m_11_2;
 public:
     void setUp();
     void tearDown();
     void testEquality();
     void testAddition();
}

As you can see, the class has a block of macros as it's first element. If I added a new method testSubtraction, it's obvious what you need to do to have it included in the test run.

These macro blocks expand out to something like this:

public:
  static CppUnit::Test *suite()
  {
    CppUnit::TestSuite *suiteOfTests = new CppUnit::TestSuite( "ComplexNumberTest" );
    suiteOfTests->addTest( new CppUnit::TestCaller<ComplexNumberTest>(
                                   "testEquality",
                                   &ComplexNumberTest::testEquality ) );
    suiteOfTests->addTest( new CppUnit::TestCaller<ComplexNumberTest>(
                                   "testAddition",
                                   &ComplexNumberTest::testAddition ) );
    return suiteOfTests;
  }

Which would YOU prefer to read and maintain?

Another example is in the Microsoft MFC framework, where you map functions to messages:

BEGIN_MESSAGE_MAP( CMyWnd, CMyParentWndClass )
    ON_MESSAGE( WM_MYMESSAGE, OnMyMessage )
    ON_COMMAND_RANGE(ID_FILE_MENUITEM1, ID_FILE_MENUITEM3, OnFileMenuItems)
    // ... Possibly more entries to handle additional messages
END_MESSAGE_MAP( )

So, what are the things which distinguish "Good Macros" from the horrible evil kind?

They perform a task which cannot be simplified any other way. Writing a macro to determine a maximum between two elements is wrong, because you can achieve the same using a template method. But there are some complex tasks (for example, mapping message codes to member functions) which the C++ language just doesn't handle elegantly.

They have an extremely strict, formal usage. In both of these examples the macro blocks are announced by starting and ending macros, and the inbetween macros will only ever appear inside these blocks.  You have normal C++, you briefly excuse yourself with a block of macros, and then you go back to normal again. In the "evil macros" examples, the macros are scattered throughout the code and the hapless reader has no way of knowing when the C++ rules apply and when they do not.


问:
How to trim all incoming values in an HTTP Post request?
I have an HTML form, with more than 30 fields in it. When this form is submitted to the server, all of the values of the fields should be trimmed. In other words, no value should start/end with any kind of whitespace (\b).

There are many options available for me:

Manually trim each value

Looping over values and trim each one

Creating a framework (something like ASP.NET's HTTP Module) to sit at the way of any HTTP Post request, to trim the incoming value.

The third option seems the best one. However, I don't know if it is really the best one or not? And I also don't know how to do it. Is it possible at all? What are other solutions?

答:
If you don't really care about security you may consider trimming the fields with Javascript when the form submit button is clicked (event *onsubmit" to implement). Now, this is of course easily bypassable since it's client server code.

Otherwise, for a server-side solution, all your solutions work. I'm not sure about the module but I think it will perform this trimming for all applications on the server, right? So you may consider that factor if your application is not the only one deployed.

Finally, but you may have considered that already, you can properly do the trimming using HTTP request listeners.

In J2EE (or whatever it is called now), it would consist in implementing your own ServletRequestListener and requestInitialized method. The advantage here is that you can package this listener in a simple JAR and add it (and its configuration in web.xml) only for the applications that require that.

In .NET, it would consist in overriding the Application_BeginRequest method in Global.asax.cs. So it would work only for the application you wrote the code for.


答:
No other language beyond those that include C (C++ and Objective C) uses headers. Neither languages that predate C nor any of the newer ones.

It's because headers violate the very important "Don't Repeat Yourself" principle—all the information is actually there in the source file, so the compiler should just generate the information itself.

In fact, headers are probably an afterthought for C as well. In early versions of C you would just call functions without prototypes and C still caries rules on how arguments are marshalled in such case (and they are still important for variadic functions). Than prototypes were added and preprocessor was abused to pull them in and that stuck. Partly because it turned out to allow playing dirty tricks on the compiler that come in handy when doing low level work in the operating system and standard library. Those tricks are not generally useful for higher level programming.

Now if you don't have headers, you have three options:

generate all interfaces first and than compile the implementation bodies

compile in order of dependencies, but that precludes circular references

compile all modules in one compiler execution

Java chose the last one. C# did as well as did many other languages.

Title: Reasons for the build-technological fork between Java and UNIX/C/Fortran

Body:
When Java was developed, it's designers chose to discard an unusual amount of the conventional wisdom established in the UNIX and C oriented toolchains. For one (and in my view) the most major example, they chose to discard the practice of header files and Makefiles and tried to build a monolithic, dependency-aware compiler instead. Later on, ant was developed to partially remedy the (obvious?) deficiencies of this process, and effectively re-implemented the makefile logic.

It's not like I resent old-style make and #include going overboard. However, their usage was reinvented in the Java world with ant and splitting each class into an Interface and an Implementation class, which is pretty close to the header file/source file pattern. I'm fairly sure the people behind Java knew of the existing tools and patterns and their purpose, so the decision to first do away with them and then reimplementing everything from scratch without even a hint of it in the language design is what astonishes me. Less costly ways would have been available (like parsing the source file and auto-generating a header file, which would have been fairly easy after pruning the C syntax a bit), but weren't taken, and I would love to know about the reason.

Similar forks were performed in most other places, at considerable development costs and the considerable cost of a splitted community. Nowadays, Java-world and C++-world developers often have a hard time communicating and collaborating due to a split that seems disproportionate to the actual differences between the C/C++ language and the Java language. While I can see the basic motivation behind the process (everyone loathes Makefile syntax and changing header files manually), I still can't grok the magnitude of the change.

Are there historical references about the motivation and reasons of this process? Are there any design documents or interviews with the people who drove this fork?


问:
How to manage two major versions using SVN?
At the company I'm working we support two versions of the software we develop. One version is available for customers, and one version the developers are developing new functionality in.
The version available for customers is also changed by developers, to fix the bugs our customers have found.

So, for example we have a 4.1 version available for customers, and we are developing 4.2. As soon as we release 4.2, 4.1 gets closed, and we start developing on 4.3.

Currently we have two trunks, one for each version that is open for development. Every time a bug is fixed in the released version, we have to merge it in the new version too. This is extra work. Next to this, we would like to work in advance, and have a version already finished 'on the shelf', and already start on a new version. Which would mean if we fix a bug in the released version, we would have to merge it in three trunks!

Is there a better way of structuring this, and possibly eliminate the duplicate merges? Are we doing something completely wrong?

Thanks in advance.

答:
I don't understand why merging changes from one branch to another is extra work.

In the same way of thinking, you could say that fixing bugs is extra work and develop bug free code in the first place.

In other words a bug fix merge is normal work and is included in the bug fixing activity.

By the way, don't change your version control structure: it is perfectly OK.


答:
The usual terminology here would be that you have one trunk (the code leading to 4.3) and two branches (4.1 and 4.2), even though the branch for 4.1 will be closed according to your description when 4.2 is released (at the same time that the new 4.2 branch is created).

You can avoid the three-end situation when you do your "advance work" in a feature branch that is not intended to be bug free. That is, you'd have three open ends:

```<code>trunk (will be 4.2 some day)
branches/4.1
branches/conquer-the-world (a feature planned for 4.3)
</code>```

and only merge bugfixes from 4.1 into 4.2. When conquer-the-world is finished (some point after the release of 4.2, I presume), merge it into trunk.

Title: How to manage two major versions using SVN?

Body:
At the company I'm working we support two versions of the software we develop. One version is available for customers, and one version the developers are developing new functionality in.
The version available for customers is also changed by developers, to fix the bugs our customers have found.

So, for example we have a 4.1 version available for customers, and we are developing 4.2. As soon as we release 4.2, 4.1 gets closed, and we start developing on 4.3.

Currently we have two trunks, one for each version that is open for development. Every time a bug is fixed in the released version, we have to merge it in the new version too. This is extra work. Next to this, we would like to work in advance, and have a version already finished 'on the shelf', and already start on a new version. Which would mean if we fix a bug in the released version, we would have to merge it in three trunks!

Is there a better way of structuring this, and possibly eliminate the duplicate merges? Are we doing something completely wrong?

Thanks in advance.

Body:
The usual terminology here would be that you have one trunk (the code leading to 4.3) and two branches (4.1 and 4.2), even though the branch for 4.1 will be closed according to your description when 4.2 is released (at the same time that the new 4.2 branch is created).

You can avoid the three-end situation when you do your "advance work" in a feature branch that is not intended to be bug free. That is, you'd have three open ends:

trunk (will be 4.2 some day)
branches/4.1
branches/conquer-the-world (a feature planned for 4.3)

and only merge bugfixes from 4.1 into 4.2. When conquer-the-world is finished (some point after the release of 4.2, I presume), merge it into trunk.


问:
Newbie seeking advice on programming in general
need some of you to remember back to a time when you might have been bad at programming...

Been at my new job (as a software developer) for a couple of months now, passed probation period. Have very little programming experience (C++ only) and am currently working with asp.net MVC and silverlight. So there's a website the company has been working on and I am joining the effort to make it better, iron out bugs etc.

The problem is - learning about a system/website which has already been made, via visual studio. I ALWAYS feel HUGELY overwhelmed, never knowing which part of this line should I look up, and generally having lots of trouble getting the big picture. Visual studio itself is something I'm finding it difficult to get to grips with, let alone the asp.net framework.

I get the impression that because my coworkers have more experience than me, they are getting all the good jobs, and I am left with crap to do - stuff which is not even vaguely programming. Meaning they are learning/creating more, and I am learning/creating near nothing. I'm getting demoralised, and too scared to say anything.

I'm not stupid, I've read and practiced plenty of the fundamental programming concepts...I'm just bloody scared of this damn framework. I look at it and just feel paralyzed.

The result is that I keep asking the older veteran guy of questions, and he is getting irritated, and would rather give me easy/mindless/non programming jobs to avoid wasting time with helping me out. Then when I don't understand something, I'm hesitating about whether or not I should ask him yet, and trying to decide if it would be a waste of time.

I'm the kind of person who picks things up slowly, but with a lot of attention to detail. The former I think is making me look incompetent though.

Anyone get where I'm coming from please say something helpful....I'm scared of losing my job in a few months or something...

答:
Disclaimer: I am of the opinion that your problem, though programmer-specific, is faced by new professionals/practitioners in all fields. I mean, nobody knows anything for the first few months, and new guys always get the worst tasks (except maybe when these tasks are too critical).

A time when you might have been bad at programming

I still am bad at it. No second thoughts.

I get the impression that because my co-workers have more experience than me..

Again, remember that every player was a ball boy once. To get a good thing to work on, you first have to prove your worth in things you don't like, and this is common in all fields, not just programming.

I look at it and just feel paralysed.

What makes you feel paralysed? Do you dread getting back to the framework yet another time, or do you just hate looking at it altogether?

Always try to break your problems into one or more simple steps. Then go on to each one separately. There is no magic bullet here, except to keep hanging on, and that is what matters.

Getting into control

As the new guy, you will face problems in getting to know the tools you work with (VB, ASP etc.) and the things you work on (the framework). This is natural. We all face it. Your main priority should be to keep going on.

Keep learning the languages, keep asking questions, keep looking into the frameworks, and repeat!


问:
What can I do to prevent taking on an unethical development project?
Back in my self-employment days, I've once taken on a small and rather well-paid project: "A newsletter system", the spec stated.

Everything was fine, invoices were paid with each milestone reached, me was a happy developer …
Until Mr. Client started demanding mail header spoofing and a bunch of other functionality eventually leading me to the conclusion that I was building quite the sophisticated spam mailer.

To make a long story short: Financial considerations made me finish what I had started. I resent having taken on the job in the first place to this day – if I had bothered to google my client's name, I would've been warned.

What strategies can I use to avoid ending up coding stuff I'd rather not see in someone's hands?

答:
Warren Buffett was once told that he was an good and ethical man in an interview, and he said something to the effect of, "The world will never know.  I've always been well off in my life.  I've never had to steal to feed my family or make the choice between my ethics and poverty."  (paraphrasing, as I don't have his exact words)

I have had similar experiences.  Very luckily for me, I was in a position where I didn't have to do these unethical things.  I have had clients who have made decisions that about how they've wanted to run their business that I have disagreed with on ethical grounds, and I've finished out my contracts with them and bid them adieu.

The strategy for avoiding this has nothing to do with programming.  Get yourself in a financial position where you can survive well for a number of months with no pay.  Save enough money that you're not dependent upon one client's unethical demands to make ends meet.  Money is used all of the time by unethical people as a lever to get people to do something that they wouldn't otherwise do.

My limits are what I'm comfortable with.  I can't enumerate them all, but it would go something like the Code of Ethics for Professional Engineers.


问:
Why don't more languages support recursive/nested comments?

Possible Duplicate:

  Why do most programming languages not nest block comments?

Most languages I've worked with don't have support for recursive/nested comments.

Is there any reason why language designers would choose not to implement this?

Is it deceptively complex?

Would it have undesired results?

I know there could be issues such as:

```<code>/*
    string Str = "aslfkalfksnflkn/*aslkfasnflkn";

*/

Console.WriteLine("asdoadokn");
</code>```

However, we could still get the same issue with non-recursive ones (consider */ in a string in a comment) so i don't feel that's a good argument against.

答: I modified a C compiler to do this once, it wasn't terribly hard.  It's all taken care of in the lexical scanner, so you don't have to muck about with the guts of the parser.  It's really just a matter of keeping track of the nesting level and ignoring anything within string delimiters.</p>


答:
Some things to consider if you are financially obligated and already made the mistake of agreeing...

Try disassociating yourself with the project work.  Don't submit any code with your name or initials in comments.  Remove any public code repositories linked to your email.  In the event that legal actions are brought against this person you will still be linked by contract and financial transactions though.  Hope and pray that this person does nothing illegal.

On that note, you might want to consider reporting his IP address to a known public honeypot list that tracks such spammers.

Further, if you feel the client could be doing really bad things that might put you in legal jeopardy for aiding and abetting then code in a hidden remote kill switch.  Something where you can send a carefully worded HTTP header with the words, Alakazam for instance that will make everything grind to a halt.  If what the person is doing is illegal anyway then they can't really win in court over breach of contract.

EDIT: I am not condoning the actions I described, just offering suggestions if you have already made the mistake of associating with this person.  I understand the downvotes though.

Title: What can I do to prevent taking on an unethical development project?

Body:
Back in my self-employment days, I've once taken on a small and rather well-paid project: "A newsletter system", the spec stated.

Everything was fine, invoices were paid with each milestone reached, me was a happy developer …
Until Mr. Client started demanding mail header spoofing and a bunch of other functionality eventually leading me to the conclusion that I was building quite the sophisticated spam mailer.

To make a long story short: Financial considerations made me finish what I had started. I resent having taken on the job in the first place to this day – if I had bothered to google my client's name, I would've been warned.

What strategies can I use to avoid ending up coding stuff I'd rather not see in someone's hands?


答:
It's never appropriate to use #defines like that. In your case, you could do this:</p>

```<code>class MyCout
{
public:
  MyCout (ostream &out) : m_out (out), m_space_pending (false)
  {
  }

  template <class T>
  MyCout &operator << (T &value)
  {
    if (m_space_pending)
      m_out << " ";

    m_out << value;
    m_space_pending = false;
    return *this;
  }

  MyCout &operator << (const char *value)
  {
    if (m_space_pending)
      m_out << " ";

    m_out << value;
    m_space_pending = true;
    return *this;
  }

  MyCout &operator << (char *value) { return operator << (static_cast <const char *> (value)); }
  MyCout &operator << (ostream& (*fn)(ostream&)) { m_out << fn; return *this; }

private:
  ostream
    &m_out;

  bool
    m_space_pending;
};

int main (int argc, char *argv [])
{
  MyCout
    space_separated (cout);

  space_separated << "Hello" << "World" << endl;
}
</code>```

Title: Is it an appropriate use of #define to make typing repeated code easier?

Body:
Is there any view on whether using the #define to define full lines of code for simplifying coding is good or bad programming practice? For example, if I needed to print a bunch of words together, I'd get annoyed typing

```<code><< " " <<
</code>```

To insert a space between words in a cout statement. I could just do

```<code>#define pSpace << " " <<
</code>```

and type

```<code>cout << word1 pSpace word2 << endl;
</code>```

To me this neither adds or subtracts from the clarity of the code and makes typing slightly easier. There are other cases that I can think of where typing will be much easier, usually for debugging.

Any thoughts on this?

EDIT: Thanks for all the great answers! This question just came to me after doing a lot of repetitive typing, but I never thought there would be other, less confusing macros to use. For those who don't want to read all the answers, the best alternative is to use the macros of your IDE to reduce repetitive typing.

Body:
It's never appropriate to use #defines like that. In your case, you could do this:

class MyCout
{
public:
  MyCout (ostream &out) : m_out (out), m_space_pending (false)
  {
  }

  template <class T>
  MyCout &operator << (T &value)
  {
    if (m_space_pending)
      m_out << " ";

    m_out << value;
    m_space_pending = false;
    return *this;
  }

  MyCout &operator << (const char *value)
  {
    if (m_space_pending)
      m_out << " ";

    m_out << value;
    m_space_pending = true;
    return *this;
  }

  MyCout &operator << (char *value) { return operator << (static_cast <const char *> (value)); }
  MyCout &operator << (ostream& (*fn)(ostream&)) { m_out << fn; return *this; }

private:
  ostream
    &m_out;

  bool
    m_space_pending;
};

int main (int argc, char *argv [])
{
  MyCout
    space_separated (cout);

  space_separated << "Hello" << "World" << endl;
}


答:
No.

For macros intended to be used in code, a good guideline for testing appropriateness is to surround its expansion with parentheses (for expressions) or braces (for code) and see if it will still compile:

```<code>// These don't compile:

#define pSpace (<< " " <<)
cout << word1 pSpace word2 << endl;

#define space(x) (" " << (x))
cout << word1 << space(word2) << endl;

// These do:

#define FOO_FACTOR (38)
x = y * FOO_FACTOR;

#define foo() (cout << "Foo" << endl)
foo();

#define die(c) { if ((c)) { exit(1); } }
die(foo > 8);

#define space(x) (" " + string((x)))
cout << "foo" << space("bar") << endl;
</code>```

Macros used in declarations (like the example in Andrew Shepherd's answer) can get away with a looser set of rules as long as they don't upset the surrounding context (e.g. switching between public and private).

Body:
No.

For macros intended to be used in code, a good guideline for testing appropriateness is to surround its expansion with parentheses (for expressions) or braces (for code) and see if it will still compile:

// These don't compile:

#define pSpace (<< " " <<)
cout << word1 pSpace word2 << endl;

#define space(x) (" " << (x))
cout << word1 << space(word2) << endl;

// These do:

#define FOO_FACTOR (38)
x = y * FOO_FACTOR;

#define foo() (cout << "Foo" << endl)
foo();

#define die(c) { if ((c)) { exit(1); } }
die(foo > 8);

#define space(x) (" " + string((x)))
cout << "foo" << space("bar") << endl;

Macros used in declarations (like the example in Andrew Shepherd's answer) can get away with a looser set of rules as long as they don't upset the surrounding context (e.g. switching between public and private).


问:
Get 100 highest numbers from an infinite list
One of my friend was asked this interview question -

"There is a constant flow of numbers coming in from some infinite list
  of numbers out of which you need to maintain a datastructure as to
  return the top 100 highest numbers at any given point of time. Assume all the numbers are whole numbers only."

This is simple, you need to keep a sorted list in descending order and keep a track on lowest number in that list. If new number obtained is greater than that lowest number then you have to remove that lowest number and insert the new number in sorted list as required.

Then question was extended -

"Can you make sure that the Order for insertion should be O(1)? Is it possible?"

As far as I knew, even if you add a new number to list and sort it again using any sort algorithm, it would by best be O(logn) for quicksort (I think). So my friend told it was not possible. But he was not convinced, he asked to maintain any other data structure rather than a list.

I thought of balanced Binary tree, but even there you will not get the insertion with order of 1. So the same question I have too now. Wanted to know if there is any such data structure which can do insertion in Order of 1 for above problem or it is not possible at all.

答: Keep the list unsorted. Figuring out whether or not to insert a new number will take a longer time, but the insertion will be O(1).

OwnerDisplayName: Sachin Shanbhag


问:
Are there standard strategies for defining job flow and dependencies?
I'm working on a project that involves the chaining of separate jobs into a single master job, though there may be parallel paths in the chain leading up to the final output. Job and chain details will be stored in a database. Eventually what I want to end up with is a GUI in which blocks representing the individual jobs can be moved around and chained up, with the system definition stored in the DB for execution. This will be implemented as C# on top of SQL Server.

I don't want to reinvent the wheel if I can help it. I'm certain there must be some good patterns out there, particularly for how to represent the flow and dependencies in DB tables, but have been unable to find anything that fits the bill.

More than anything, I'm curious if there are any effective schemas people have used to define the jobs, dependencies, etc. Does anyone know of any commonly used strategies?

答:
I'm not sure if I got your question right, but it seems your are trying to build a tool to graphically specify a directed acyclic graph (DAG) for your atomic jobs, right? That is, a user should be providing dependencies between atomic jobs and your planned tool saves these dependencies to the backend database.

In this case, you could go with the classic DAG schema: One table with each row representing an atomic job, and one table with each row representing an edge in the graph (dependency). Then use a standard DAG visualization algorithm (like DAGmaps) to help in visualization.


问:
Should I be put off a junior role that uses an online development test?
I've applied for a junior development role, or rather been found by a recruiter looking for a developer. In order to get to a telephone interview stage I've been asked to sit one of those online coding assessments.

This wasn't quite what I expected. I consider myself a fairly good developer for my age and experience, but I've no illusions about being Don Knuth or anything. The test was a series of incredibly obtuse questions asking about the results of various obscure evaluations. About 30 minutes in I was thinking to myself I hadn't intended to enter an obfuscated code contest/code golf exercise.

After my last telephone interview I was asked to build something. I did. That seemed fair. Go away and work this out is more my in office experience of programming than "please evaluate this combination of lambdas, filters, maps, lists, tuples etc".

So I'm a little put off, to be honest. I never claimed to know the language inside out or all the little corner cases. My questions, then:

Should I be put off? Why? Why not?

Are these kinds of tests what I should be expecting for junior roles?

Should I learn stuff exam style? That seems to be the objective of these tests, for which you are timed and not supposed to use references or books? Normally, in the course of development I have a fairly good idea of basic types, rules, flow control and whatever. Occasionally I'll come up on something I need to use a regex for and have to go and remind myself of the exact piece of syntax I need if trying what I think should work doesn't. Or I'll come up against a module I've not used before and go and look it up. For example, if I wanted to write a server using sockets in C right now, I'd probably check the last piece of code I wrote doing that (and or the various books I have) and work from there. Chances are I probably couldn't do it exactly from scratch and from memory, although I can tell you you'd need a socket(), bind(), listen() and accept() call and you might also want select() depending on whether you intend to pthread_create or not. So I know what the calls are, but not their specific parameter list.

What are your experiences if you are a recruiting manager? Are you after programmers who can quote you the API or do you not mind if your programmers have a few books on their desk and google function calls every so often?

答: You mentioned this was through a recruiter.  Recruiters often require you to do a test ("Prove IT" or similar) so they have your results on file and can show it to the hiring company.  It's extremely annoying, and usually a waste of time, but I would consider it a necessary evil of dealing with recruiters and not something that should automatically put you off from a role.</p>

ContentLicense: CC BY-SA 2.5


答:
You did it for the money and we have to make these decisions all the time. Should I take a high paying job in an industry I don't agree with or help a greener company or non-profit?

I would not feel comfortable creating anything I would be ashamed to tell my friends and family about. It would be an uncomfortable interview discussing what I did with this application. These sound like more self-serving than ethical reasons but I've never claimed to be altruistic.


问:
Is there justification for leaving conflict markers in checked-in code?
Consider conflict markers. i.e.:

```<code><<<<<<< branch
blah blah this
=======
blah blah that
>>>>>>> HEAD
</code>```

In the particular case which has motivated me to post this question, the team member responsible had just completed a merge from upstream to our branch, and had in some cases left these in, as comments, as a sort of documentation over what had just been resolved. He left it in a compiled state, tests passing, so it's not as bad as you would think.

Instinctively though, I really took objection to this, however being devils advocate to myself I can see why he might have done it:

because it highlights to other team developers what has changed as a result of the merge.

because those who are more expert with the particular pieces of code can then address the concerns illustrated by the comments so that he doesn't have to guess.

because the upstream merge is a right pain and it can be difficult to justify the time to resolve everything well and completely, so some semi-complete FIXME notice is necessary, so why not use the original conflict as a comment to document this.

My objection was instinctive, but I'd like to be able to justify it rationally, or see my position more wisely. Can anyone give me some examples or even experiences where people have had a bad time with someone else doing this and/or reasons why it's bad practice (or you can play devil's advocate and support it).

My own immediate concern was that it would clearly have been annoying if I had been editing one of the files concerned, pulled the changes, got real conflicts, but also pulled in the commented ones. Then I would have had a very messy file indeed. Fortunately that didn't happen.

答:
I think comments should refer to the code that's there, not to code that has been there in the past, nor to events that happened to the code sometime in the past, nor to code that existed in a parallel universe (another branch) in the past. Leaving the markers in the way your team member did creates at least three problems:

The original code probably was something like blah blah null, and the bug report said "Can't use null there, use this or that, or whatever." So two people independently fixed the bug and when the fixes were merged, the conflict arose. Now the comment documents not what the problem was nor what the fix fixed, but only that there were two different fixes at some point in the past. That's not very helpful. A comment like //blah blah needs a non-null argument would at least give an indication what changed (and even that information is more easily available from the version control system's commit comment).

The merged version might not even look like one of the original lines. Maybe if you want blah blah to take this and that, the correct form is blah blah (this,that) or even something more complicated. In that case, leaving the conflict message in as a comment will surely confuse anybody trying to read the code later on.

Most version control systems give you access to the project history. For example, i can right click on a file in eclipse (with svn), say "Show History..." and then say "Compare Current with...' and get a diff window that highlights the differences. That information is way easier to grok if the diff highlights contain the actual differences, and not the comments around them. Every bit of non-functional change in the code makes that diff harder to read.


答:
Ethics are quite a bit subjective. Laws aren't. If you can show what you are demanded to do is illegal, you can use that as leverage. IANAL, but I am quite confident that withholding payment to coerce you to do something you think is illegal is really enough to be considered as duress.

As for your specific case: It appears that in Germany sending advertisement mails with misleading header/subject is actually illegal and can lead to a fine of up to 50000 EUR. Based on this you should have denied your client's request.

In general you might want to consider asking a lawyer in such a situation. Actions in our medium are sparsely covered by the law, which also means that the more general rules of conduct must be applied, which (depending on your country and your understanding of ethics) can tend towards what you consider ethical.

And I think most clients will back down if you tell them what they intend to do can be considered forgery (even if it's a whole different question whether it will be) or a similar crime.


问:
Shouldn't we count characters of code and comments instead of lines of code and comments?
Counting lines of code and comments is sometimes bogus, since most of what we write may be written in one or more lines, depending column count limitations, screen size, style and so forth.

Since the commonly used languages (say C, C++, C# and Java) are free-form, wouldn't it be more clever to count characters instead?

Edit: I'm not considering LOC-oriented programming where coders try to artificially match requirements by adding irrelevant comments or using multiple lines where less would be enough (or the opposite). I'm interested in better metrics that would be independent of coding style, to be used by honest programmers.

答:
Seeing LOC is a bad metric, I would say the number of characters and/or comments is just as bad, if not worse.

If you start measuring by number of characters, you will get very very long identifiers.

If you start measuring by number of comments (or characters in comments), you will get lots of irrelevant comments with loads of padding (I can imagine getting whole literary expositions).


答:
Not necessarily, since you would motivate people to write really, really, really, really long variable names and thereby obfuscate the code. A line maps to a statement in many coding styles, so it is often a better indicator of the amount of code.

You could of course go by words of code (WOC) to remedy that. But I don't think that any code metric based on the output of wc is any better than the other, and all are pretty bad.

Title: Shouldn't we count characters of code and comments instead of lines of code and comments?

Body:
Counting lines of code and comments is sometimes bogus, since most of what we write may be written in one or more lines, depending column count limitations, screen size, style and so forth.

Since the commonly used languages (say C, C++, C# and Java) are free-form, wouldn't it be more clever to count characters instead?

Edit: I'm not considering LOC-oriented programming where coders try to artificially match requirements by adding irrelevant comments or using multiple lines where less would be enough (or the opposite). I'm interested in better metrics that would be independent of coding style, to be used by honest programmers.


答:
Why does this matter, exactly?

Has anyone ever said an application sucks because it only has x number of lines? Neither matter unless for some reason writing MORE code is a bragging right I'm not aware of. Personally, the less code you write is a better practice, if it's just as readable.

Clever? Counting characters may be the least clever thing ever. Ever.


答:
Forget either approach. Count the number of user acceptance tests that pass.

Very clever.


问:
Why do people still say Java is slow?
For a long time in SO and in other places Java has the reputation of being slow. From jokes to many comments in questions and answers, people still believe Java is slow based solely on experience with it in the 90s.

This is my issue: we have disproved (most) of the reasons that people believe Java is slow. Outside of small things, Java is pretty fast.

So why is it that people still refuse to believe Java is fast now? Is it part of their mindset that anything thats not C/C++ is slow? Is it because people don't check over time? Is it because people are just biased?

答: Slow compared to what? I'm thinking of changing from ordinary Ruby to JRuby (Java based ruby) because I've heard it's faster.</p>

Title: Why do people still say Java is slow?


答:
Everyone knows that such metrics are flawed and can be cheated.

That said, when I count lines of code in my C programs, I actually count semicolons, i.e., actual number of statements.


答: Macros are evil and should be used only when you really have to. There are a few cases where macros are applicable (mainly debugging). But in C++ in most cases you can use inline functions instead.</p>


答:
Counting lines of code and comments is sometimes bogus, since most of
  what we write may be written in one or more lines, depending column
  count limitations, screen size, style and so forth.

When doing anything with lines of code, you need a consistent definition of what a "line of code" is, exactly. You need to know if you are counting physical lines of code or logical lines of code and what exactly makes up a "line of code".

As an example:

```<code>for (int i = 0; i < array.length; i++) {
  boolean truthValue = processElement(array[i]);

  if (truthValue) {
    break;
  }
}
</code>```

That could be considered 6 physical lines, 4 logical lines, or something else entirely.

In addition, you need rules on a per-language basis, based on coding style that can be consistently applied across projects. It's a fact that 3 lines of Python is not equal to 3 lines of Java is not equal to 3 lines of Objective-C. However, 3 lines of Python always needs to be 3 lines of Python, 3 lines of Java always needs to be 3 lines of Java, and 3 lines of Objective-C always needs to be 3 lines of Objective-C.

Also, comments and code should be counted separately. For example, in a comment, I mentioned that a line of code can be used in Six Sigma as an "opportunity". A non-executable component should not be included in that. In addition, comparing a ratio of comments/lines of code isn't necessarily meaningful as well-organized code should need fewer comments to begin with. I'd be much more careful with counting comments than counting code, other than identifying a distinct lack of comments (especially in public APIs or systems that use automatic documentation generation) or excessive comments as those are opportunities to improve documentation or refactor (or remove useless, potentially out-of-date comments).

Since the most used languages (say C, C++, C# and Java) are free-form,
  wouldn't it be more clever to count characters instead?

I don't think so. Cleverness buys you nothing - if you try something clever, you are likely shooting yourself in the foot, either with other people trying to understand your intentions. You should keep it simple. The line and the statement are the most fundamental building blocks of a unit of code. Every language has a concept of a statement - a single, meaningful, block. Your coding style should specify how to format your statements into lines. Thus, making both statements and lines consistent measurements across projects (written in the same language) to compare.

Body:
Counting lines of code and comments is sometimes bogus, since most of
  what we write may be written in one or more lines, depending column
  count limitations, screen size, style and so forth.

When doing anything with lines of code, you need a consistent definition of what a "line of code" is, exactly. You need to know if you are counting physical lines of code or logical lines of code and what exactly makes up a "line of code".

As an example:

for (int i = 0; i < array.length; i++) {
  boolean truthValue = processElement(array[i]);

  if (truthValue) {
    break;
  }
}

That could be considered 6 physical lines, 4 logical lines, or something else entirely.

In addition, you need rules on a per-language basis, based on coding style that can be consistently applied across projects. It's a fact that 3 lines of Python is not equal to 3 lines of Java is not equal to 3 lines of Objective-C. However, 3 lines of Python always needs to be 3 lines of Python, 3 lines of Java always needs to be 3 lines of Java, and 3 lines of Objective-C always needs to be 3 lines of Objective-C.

Also, comments and code should be counted separately. For example, in a comment, I mentioned that a line of code can be used in Six Sigma as an "opportunity". A non-executable component should not be included in that. In addition, comparing a ratio of comments/lines of code isn't necessarily meaningful as well-organized code should need fewer comments to begin with. I'd be much more careful with counting comments than counting code, other than identifying a distinct lack of comments (especially in public APIs or systems that use automatic documentation generation) or excessive comments as those are opportunities to improve documentation or refactor (or remove useless, potentially out-of-date comments).

Since the most used languages (say C, C++, C# and Java) are free-form,
  wouldn't it be more clever to count characters instead?

I don't think so. Cleverness buys you nothing - if you try something clever, you are likely shooting yourself in the foot, either with other people trying to understand your intentions. You should keep it simple. The line and the statement are the most fundamental building blocks of a unit of code. Every language has a concept of a statement - a single, meaningful, block. Your coding style should specify how to format your statements into lines. Thus, making both statements and lines consistent measurements across projects (written in the same language) to compare.


问:
How to handle manipulation of data after a db record is written from outside my program
I have written a warehouse management web app. The application handles batch picking, warehouse routing, packing, and the final piece is handled by UPS worldship to "ship" the packages. Worldship will write a record to my postgres db after every shipment or void. I need a way to cleanly see that the record was written/deleted and then "do stuff".

The easy answer is to have a program just monitor the database and when it sees a record written to do its thing but something is nagging at me that there is probably a better way to go about this that doesn't have a program polling the table and comparing it to what was there last.

EDIT: How i was going to approach this...
The table is setup with a status field. My program would on intervals read the table for any records that have a null status, if records are found "do stuff" then mark the status as complete.

TIA

答:
There's at least two other effective means to handle this type of problem.

A. Use triggers.  Set them to fire on the appropriate operations.

B. Expose a service.  The client program goes through the service instead of directly hooking into the database.  This gives you full control over which tables can be updated.  The extra layer gives you the ability to handle operations in an imperative language as well.  In other words, C#/Java is usually a better choice for item manipulation such as iterating individual rows as opposed to SQL which is best suited for set operations.


答:
It's very common to "clean/rinse" incoming data. This is best handled server-side, typically by the method you are POSTing to (you may have a static helper to do the actual work).

Writing a module to intercept all requests seems like overkill (but effective if you need this application- or server-wide).

You don't mention a technology but in ASP.NET MVC, it would look something like:

```<code>[HttpPost]
public ActionResult Index(FormCollection form)
{
    foreach (var field in form.AllKeys)
        form[field] = form[field].Trim();

    return View();
}
</code>```

So, I guess I'm going with option #2, server-side!

Edit: just changed my bogus Regex.Replace() call to String.Trim()

Title: How to trim all incoming values in an HTTP Post request?

Body:
I have an HTML form, with more than 30 fields in it. When this form is submitted to the server, all of the values of the fields should be trimmed. In other words, no value should start/end with any kind of whitespace (\b).

There are many options available for me:

Manually trim each value

Looping over values and trim each one

Creating a framework (something like ASP.NET's HTTP Module) to sit at the way of any HTTP Post request, to trim the incoming value.

The third option seems the best one. However, I don't know if it is really the best one or not? And I also don't know how to do it. Is it possible at all? What are other solutions?

Body:
It's very common to "clean/rinse" incoming data. This is best handled server-side, typically by the method you are POSTing to (you may have a static helper to do the actual work).

Writing a module to intercept all requests seems like overkill (but effective if you need this application- or server-wide).

You don't mention a technology but in ASP.NET MVC, it would look something like:

[HttpPost]
public ActionResult Index(FormCollection form)
{
    foreach (var field in form.AllKeys)
        form[field] = form[field].Trim();

    return View();
}

So, I guess I'm going with option #2, server-side!

Edit: just changed my bogus Regex.Replace() call to String.Trim()


问:
What are your thoughts about the Actor Model?
The Actor Model which is used by Erlang seems to be a very different way to do concurrent programming. What are your thoughts about the Actor Model? Will it be a popular solution for concurrency?</p>

答:
"Popular" isn't a terribly important metric. "Useful" or "powerful" is.

The Actor model's been around for about 35 years now, at least in academia, and it has been adopted by more and more real-world languages as time passes. (OK, Erlang didn't adopt the Actor model, it reinvented the Actor model. Still.)

So, given that it's survived several decades in academia, and it's moving into the mainstream, I'd say it's going to be around for a good while.


答:
Database triggers will allow you to do this most efficiently. Create a trigger on the insert/delete operations in the relevant table so you capture the event you're talking about. Use the trigger to insert a row into a table just for your application to mark when a record has been changed.

Triggers were designed to do this and are very fast, but be careful when writing them; if the trigger's statement fails (e.g. you violate a UNIQUE constraint) the whole operation can fail, not just the triggered action.

Title: How to handle manipulation of data after a db record is written from outside my program

Body:
I have written a warehouse management web app. The application handles batch picking, warehouse routing, packing, and the final piece is handled by UPS worldship to "ship" the packages. Worldship will write a record to my postgres db after every shipment or void. I need a way to cleanly see that the record was written/deleted and then "do stuff".

The easy answer is to have a program just monitor the database and when it sees a record written to do its thing but something is nagging at me that there is probably a better way to go about this that doesn't have a program polling the table and comparing it to what was there last.

EDIT: How i was going to approach this...
The table is setup with a status field. My program would on intervals read the table for any records that have a null status, if records are found "do stuff" then mark the status as complete.

TIA


问:
What's the best way to learn code if you are just starting out?
I'm just starting out with some articles and tutorials.

I am looking for some guidance on which languages to start with and what is the best way to go about learning code, books, tutorials, classes.

Which tutorials or books are best?

Is it possible to learn this stuff online? If so how?

Thanks for any help!

答:
There is a resource I found few days ago http://www.codecademy.com/, there are two courses introduction to programming and javascript.

I test it and the level is for beginners, I like the way that the system allow interacts in the browser.


问:
What is the good explanation of Tennent's Correspondence Principle?
I found myself struggling to see what is this principle about and why is it so important for language design.

Basically, it states, that for every expression expr in language should be exactly the same as this construct:

```<code>(function () { return expr; })()
</code>```

Also, I have heard that Ruby obeys this principle, while Python doesn't. I don't understand why this is true, or if it is true at all.

答:
To answer the question why Tennent's CP is so important for language design, I'd like to quote Neal Gafter:

Tennent's principles are very powerful because violations of them tend to show up in the language as flaws, irregularities, unnecessary restrictions, unexpected interactions or complications, and so on.

Any violation of TCP is likely to hurt some programmer in the future when he expects closures to work like non-closure code but finds that, in violation of TCP, they don't.

OwnerDisplayName: Andrew


问:
What language should be used to teach object-oriented design and development in university?
My understanding is that C++ is usually offered as the 1st OOP language, and as the 2nd programming language (after C) in my country (Bangladesh). I've taught it several times, and the problem I've run into is that students often tend to think C++ as an extension of C, i.e. C with cin and cout!
This has lead me to think about teaching Java as the first OOP language in the upcoming semester.

What is your opinion? I would like some suggestions from professional programmers as well as academics.

答:
C++ is often chosen as the OO language in classrooms mainly because it is one of the more useful languages to know. Lots of work for C++ programmers. But, as stated before, it can easily lead people into trap of coding in it as C, and barely touching the OO piece of it.

I believe one language that might be suitable would be Ruby, which is somewhat desirable, and highly OO. I usually recommend Python over Ruby, as I prefer it, but in this case it may be better, due to everything inherently being an object. It is useful, has quite a bit of libraries to build on, and quite a bit of activity.

I believe that if you want to avoid the C trap, you have to remove them from the world of C/C++ so they are forced to learn a new language, as well as the OO concepts that come with it.


答:
Use a min-priority queue implemented with a Fibonacci heap, which has constant insertion time:</p>

```<code>1. Insert first 100 elements into PQ
2. loop forever
       n = getNextNumber();
       if n > PQ.findMin() then
           PQ.deleteMin()
           PQ.insert(n)
</code>```

Title: Get 100 highest numbers from an infinite list

Body:
One of my friend was asked this interview question -

"There is a constant flow of numbers coming in from some infinite list
  of numbers out of which you need to maintain a datastructure as to
  return the top 100 highest numbers at any given point of time. Assume all the numbers are whole numbers only."

This is simple, you need to keep a sorted list in descending order and keep a track on lowest number in that list. If new number obtained is greater than that lowest number then you have to remove that lowest number and insert the new number in sorted list as required.

Then question was extended -

"Can you make sure that the Order for insertion should be O(1)? Is it possible?"

As far as I knew, even if you add a new number to list and sort it again using any sort algorithm, it would by best be O(logn) for quicksort (I think). So my friend told it was not possible. But he was not convinced, he asked to maintain any other data structure rather than a list.

I thought of balanced Binary tree, but even there you will not get the insertion with order of 1. So the same question I have too now. Wanted to know if there is any such data structure which can do insertion in Order of 1 for above problem or it is not possible at all.

Body:
Use a min-priority queue implemented with a Fibonacci heap, which has constant insertion time:

1. Insert first 100 elements into PQ
2. loop forever
       n = getNextNumber();
       if n > PQ.findMin() then
           PQ.deleteMin()
           PQ.insert(n)


答:
One reason is probably compatibility with existing codebases; C-like languages typically do everything just like C did, even stupid things like 031==25 (octal literals, who ever needed them?)

Another reason is more philosophical: A comment starts with (e.g.) /* and ends with the next */, and whatever is in between those, doesn't matter at all. Nested comments require defining a syntax for comments, too.

BTW, if you don't need that piece code anymore, why not just remove it entirely and leave it to the VCS to keep the older version? Commented code is a code smell.

Title: Why don't more languages support recursive/nested comments?

Body:
Possible Duplicate:

  Why do most programming languages not nest block comments?

Most languages I've worked with don't have support for recursive/nested comments.

Is there any reason why language designers would choose not to implement this?

Is it deceptively complex?

Would it have undesired results?

I know there could be issues such as:

```<code>/*
    string Str = "aslfkalfksnflkn/*aslkfasnflkn";

*/

Console.WriteLine("asdoadokn");
</code>```

However, we could still get the same issue with non-recursive ones (consider */ in a string in a comment) so i don't feel that's a good argument against.


问:
What can and can't the Garbage Collector do?
Will the GC take care of all memory management issues (memory leaks) ?

Is there any case where you don't want the GC to take control of some part of your code ?

答:
It will take care of the classical memory management issues (allocated memory not getting deacllocated when no longer in use), though it is still possible to have memory leaks with a GC system - this will be more subtle and will occur when objects still hold references to other objects, even when they no longer need to.

See the question Why can .NET not have memory leaks? and it's answers on StackOverflow.

There may x. situations when you want full control over memory allocation, but frankly, the benefits of a GC system are such that you will normally not need to.


答:
How annoying are conflict markers in checked-in code?

So annoying.

Title: Is there justification for leaving conflict markers in checked-in code?

Body:
Consider conflict markers. i.e.:

```<code><<<<<<< branch
blah blah this
=======
blah blah that
>>>>>>> HEAD
</code>```

In the particular case which has motivated me to post this question, the team member responsible had just completed a merge from upstream to our branch, and had in some cases left these in, as comments, as a sort of documentation over what had just been resolved. He left it in a compiled state, tests passing, so it's not as bad as you would think.

Instinctively though, I really took objection to this, however being devils advocate to myself I can see why he might have done it:

because it highlights to other team developers what has changed as a result of the merge.

because those who are more expert with the particular pieces of code can then address the concerns illustrated by the comments so that he doesn't have to guess.

because the upstream merge is a right pain and it can be difficult to justify the time to resolve everything well and completely, so some semi-complete FIXME notice is necessary, so why not use the original conflict as a comment to document this.

My objection was instinctive, but I'd like to be able to justify it rationally, or see my position more wisely. Can anyone give me some examples or even experiences where people have had a bad time with someone else doing this and/or reasons why it's bad practice (or you can play devil's advocate and support it).

My own immediate concern was that it would clearly have been annoying if I had been editing one of the files concerned, pulled the changes, got real conflicts, but also pulled in the commented ones. Then I would have had a very messy file indeed. Fortunately that didn't happen.


答:
GC systems is a software that attempts to optimize the usage of memory for a running program.

GS system is the responsibility of and is a component of the framework (JVM/.NET).

It can free memory for some objects that it predicts as not going to be needed by an application after a given point in the processing.

In .NET it can only free memory for some .NET native objects and not for MS COM object.

MS COM objects used in .NET must be freed explicitly.

References:

MSDN: Garbage Collection

Wikipedia: Gabage Collection

Title: What can and can't the Garbage Collector do?

Body:
Will the GC take care of all memory management issues (memory leaks) ?

Is there any case where you don't want the GC to take control of some part of your code ?


答:
First step is to make sure your contract fully documents what features would be included.  If you see questionable features up front, don't take the job.  If the client tries to add questionable features later, they are not covered by the current contract, so you can refuse the new contract and client is still obligated to pay for the original contract work (and you obligated to complete it).

If you already have a contract that is too vague, you are in a tough spot.  You can either surrender the contract and deal with the legal and financial outcomes or complete the work per contract.  YMMV and IANAL, but I believe you don't have much of a legal position to fight from in your current situation.  While it may be illegal to send spam in your country, I don't think it would be illegal to build software that could be used to send spam so you can't use the illegality to get out of the contract.  Building a gun is not illegal, even though shooting someone with a gun almost always is.


答:
It depends on your goal. If you want the students to come out of the program with real-world marketable skills, then C# and Java are both good candidates.

However, if you want to teach your students a language that is easy to learn, has good OO properties, and easy to teach, I strongly recommend Python. I've taught Python to people with no programming experience, and they pick it up very quickly. The syntax is simple, and very close to natural language prose. The OO capabilities are not as robust as C#, but there's enough fundamentals in there for teaching purposes.

Title: What language should be used to teach object-oriented design and development in university?

Body:
My understanding is that C++ is usually offered as the 1st OOP language, and as the 2nd programming language (after C) in my country (Bangladesh). I've taught it several times, and the problem I've run into is that students often tend to think C++ as an extension of C, i.e. C with cin and cout!
This has lead me to think about teaching Java as the first OOP language in the upcoming semester.

What is your opinion? I would like some suggestions from professional programmers as well as academics.


问:
How to make security usable in a web application?
I'm in the planning stages of developing a web application that I want to make as secure as possible. I'm pretty clear about how to do that from a technical point of view, but there is one massive potential security hole: I want the site to have users.

As anyone who has ever been a user knows, users forget usernames, forget passwords, sometimes forget that they even had an account with your site. Users respond to phishing emails and give away their credentials. If you do anything that they find too complicated they won't use your site, it has to be simple and all happen in as few clicks as possible, but we have to balance that out by making it as hard as possible for users to accidentally give away their credentials and to keep access to the service as secure as possible.

What I'm particularly interested in are strategies that go beyond the standard username and password combination and ways of recovering or resetting passwords that make things easy for users but hard for anyone trying to steal their account. I know a lot of sites provide an extra user-set security question, but because I don't trust users not to create a stupid question like "what is 1+1" I don't see how this can guarantee security.

Are there strategies that could be useable to the most clueless user but challenging to a determined and targetted attack aiming to break into their account? If not what are the closest things we could get? As a user what are the best/worst sites for this you have encountered and why?

答:
I think you shouldn't reinvent the wheel. Most websites have a solution that works for forgotten passwords, and that's sending a link to the user's e-mail account. The only way that plan goes haywire is if the e-mail account has been compromised.

It's obvious that the more important the user data on your website is, the more security measures you should have, but these extra security measures have an impact on your site's usability. How critical is the data on your site? Should you have 2 or 3 authentication systems like sometimes e-banks do?

The most important aspect is "don't trust user input". If you do this, most security problems won't exist and there won't be an impact on the usability. If you want to be paranoid, go ahead and build a fancy security system, but don't forget that it might impact the way users use your site (for the worst). You have to find a balance between these 2 things.


答:
Once you pass 100 numbers, the maximum cost you'll ever incur for the next number is the cost to check if the number is in the highest 100 numbers (let's label that CheckTime) plus the cost to enter it into that set and eject the lowest one (let's call that EnterTime), which is constant time (at least for bounded numbers), or O(1).

```<code>Worst = CheckTime + EnterTime
</code>```

Next, if the distribution of numbers is random, the average cost decreases the more numbers you have.  For example, the chance you will have to enter the 101st number into the maximum set is 100/101, the chances for the 1000th number would be 1/10, and the chances for the nth number would be 100/n.  Thus, our equation for average cost will be:

```<code>Average = CheckTime + EnterTime / n
</code>```

Thus, as n approaches infinity, only CheckTime is important:

```<code>Average = CheckTime
</code>```

If the numbers are bound, CheckTime is constant, and thus it is  O(1) time.

If the numbers are not bound, the check time will grow with more numbers.  Theoretically, this is because if the smallest number in the maximum set gets big enough, your check time will be greater because you'll have to consider more bits.  That makes it seem like it will be slightly higher than constant time.  However, you could also argue that the chance that the next number is in the highest set approaches zero as n approaches infinity and so the chance you'll need to consider more bits also approaches 0, which would be an argument for O(1) time.

I'm not positive, but my gut says that it is O(log(log(n))) time.  This is because the chance that the lowest number increases is logarithmic, and the chance that the number of bits you need to consider for each check is logarithmic as well.  I'm interested in other peoples takes on this, because I'm not really sure...

Body:
Once you pass 100 numbers, the maximum cost you'll ever incur for the next number is the cost to check if the number is in the highest 100 numbers (let's label that CheckTime) plus the cost to enter it into that set and eject the lowest one (let's call that EnterTime), which is constant time (at least for bounded numbers), or O(1).

Worst = CheckTime + EnterTime

Next, if the distribution of numbers is random, the average cost decreases the more numbers you have.  For example, the chance you will have to enter the 101st number into the maximum set is 100/101, the chances for the 1000th number would be 1/10, and the chances for the nth number would be 100/n.  Thus, our equation for average cost will be:

Average = CheckTime + EnterTime / n

Thus, as n approaches infinity, only CheckTime is important:

Average = CheckTime

If the numbers are bound, CheckTime is constant, and thus it is  O(1) time.

If the numbers are not bound, the check time will grow with more numbers.  Theoretically, this is because if the smallest number in the maximum set gets big enough, your check time will be greater because you'll have to consider more bits.  That makes it seem like it will be slightly higher than constant time.  However, you could also argue that the chance that the next number is in the highest set approaches zero as n approaches infinity and so the chance you'll need to consider more bits also approaches 0, which would be an argument for O(1) time.

I'm not positive, but my gut says that it is O(log(log(n))) time.  This is because the chance that the lowest number increases is logarithmic, and the chance that the number of bits you need to consider for each check is logarithmic as well.  I'm interested in other peoples takes on this, because I'm not really sure...


问:
Should we hire one consultant for website design and another for development or find someone who will do both?
We've outsourced our app development, and they've created a DB hosted on Amazon-EC2.

For the UI we're in talks with a web designer, but they don't do any of the coding to integrate the website with the DB created by the app developers.

Is it a good idea to have one person do the website design, and another to do the DB integration coding? What issues or complications could come up?

Should we instead go with a designer who provides the complete package?

答:
This might be helpful.

In an organization there are 2 types of coders : Frontend - UI and Backend coders.
You SHOULD get the UI done by an expert (web designer) and leave the geeky stuff for another expert (web developer). This is a different food entirely so if your worry is "too many cooks spoil the food" then, you shouldn't be worrying :)

The people who give COMPLETE package WILL be costly.
It is as good as saying... Tailor-made holiday is better than package holiday (in terms of pricing).

OwnerDisplayName: chimps


问:
How to design a performance comparison between two data structures
I want to compare the performance of two search trees of integers (an AVL tree and a RedBlack tree). How should I design/engineer the tests to accomplish this? For example, let's consider the insert operation; what steps should I follow in order to state that on average this operation is faster in the RB case? What considerations should I take to correctly measure CPU time? Should both implementations be optimized, or may I compare an optimized implementation of AVL vs a straightforward implementation of RB?

Any links or papers would be very helpful.

答:
Algorithms can be compared by identifying some basic operation, such as comparisons, and counting them, as a function of the amount of input data.

Programs are much more difficult to compare, because you can't make a fair comparison without controlling all sorts of extraneous variables.
On top of that, if any two programmers write programs to do the same thing, one will take longer than the other, by reason of silly little design decisions.
I've never seen a significant program that, as first written, didn't have a lot of room for speedup.
It's like dipping a towel in water.
It comes out sopping wet.
If you squeeze it (tune it) you can get a lot of the water out.
If you squeeze it harder, you can get more water out.
If you squeeze it really hard, you can get most of the water out, but it will still be damp.
There's a tradeoff between the program's speed and how hard you try to tune it,
and that's a variable that's hard to control between programs.


问:
Why it is important to include definition of success/failure in specification?
I've read Steve McConnell's "Code Complete" and one of items in checklist for requirements is: "Is the definition of success included? Of failure?".

Why is this important? Can you write any examples of those definitions? Can anybody provide examples of good requirements specification?

答:
A good requirement is something that is by its very nature Testable.  The requirement itself defines its own metric of success or failure, was the requirement met or not?

There may be 1...n test cases for a single requirement but if the requirement is ambiguous, subjective, or conjunctive (combining multiple requirements using conjunctions) then it is no longer Testable.

Success or Failure are attributes one would apply to a Test Case for a requirement not the requirement itself.

The System shall display an error alert to the user if the credential job queue contains 80% or more un-audited documents.


问:
Help me classify this type of software architecture
I read some books about software architecture as we are using it in our project but I can't classify the architecture properly. It's some kind of Enterprise Architecture, but what exactly... SOA, ESB (Enterprise Service Bus), Message Bus, Event Driven SOA, there are so many terms in Enterprise software....

The system is based on custom XML messages exchanges between services. (it's not SOAP, nor any other XML based standard, just plain XML). These messages represent notifications (state changes) that are applied to the Domain model, (it's not like CRUD when you serialize the whole domain object, and pass it to service for persistence). The system is centralized, and system participants use different programming languages and frameworks (c++, c#, java). Also, messages are not processed at the moment they are received as they are stored first and the treatment begins on demand.

It's called SOA+EDA -:)

答:
That sounds like Event Sourcing, which "Capture[s] all changes to an application state as a sequence of events" coupled with a Message Bus, which solves the problem of "several existing systems that must be able to share data and operate in a unified manner in response to a set of common business requests."

On event sourcing:

The key to Event Sourcing is that we guarantee that all changes to the domain objects are initiated by the event objects.

In the article, the use of the term "application state" appears to mean "the state of the domain model."

On message bus:

A Message Bus is a combination of a common data model, a common command set, and a messaging infrastructure to allow different systems to communicate through a shared set of interfaces.

I don't think the ESB pattern is being used, since it:

transforms messages depending on the client and

has mutually interacting clients

From what you've said, your clients all process the same message type and they are not peers but have the event change notifications published to them by the centralized server.


答:
"Complete" implies "does not need a couple more hours/days/weeks/months fussing about it until it's perfect". It's hard to know when to move on to the next thing in the pile if you never know when you're done - which requires knowing exactly what "done" is. (And moving to the next thing is a good thing because that's how you end up delivering what you promised).

It is actually very hard to describe exactly what's needed for something to be "complete" - but having a list of success (if it doesn't do that it isn't complete) and failure (if it does that it fails) is a good way to get there.

Title: Why it is important to include definition of success/failure in specification?

Body:
I've read Steve McConnell's "Code Complete" and one of items in checklist for requirements is: "Is the definition of success included? Of failure?".

Why is this important? Can you write any examples of those definitions? Can anybody provide examples of good requirements specification?


问:
Get 100 highest numbers from an infinite list
One of my friend was asked this interview question -

"There is a constant flow of numbers coming in from some infinite list
  of numbers out of which you need to maintain a datastructure as to
  return the top 100 highest numbers at any given point of time. Assume all the numbers are whole numbers only."

This is simple, you need to keep a sorted list in descending order and keep a track on lowest number in that list. If new number obtained is greater than that lowest number then you have to remove that lowest number and insert the new number in sorted list as required.

Then question was extended -

"Can you make sure that the Order for insertion should be O(1)? Is it possible?"

As far as I knew, even if you add a new number to list and sort it again using any sort algorithm, it would by best be O(logn) for quicksort (I think). So my friend told it was not possible. But he was not convinced, he asked to maintain any other data structure rather than a list.

I thought of balanced Binary tree, but even there you will not get the insertion with order of 1. So the same question I have too now. Wanted to know if there is any such data structure which can do insertion in Order of 1 for above problem or it is not possible at all.

答:
You could use a Binary Max-Heap.  You'd have to keep track of a pointer to the minimum node (which could be unknown/null).

You start by inserting the first 100 numbers into the heap.  The max will be at the top.  After this is done, you will always keep 100 numbers in there.

Then when you get a new number:

```<code>if(minimumNode == null)
{
    minimumNode = findMinimumNode();
}
if(newNumber > minimumNode.Value)
{
    heap.Remove(minimumNode);
    minimumNode = null;
    heap.Insert(newNumber);
}
</code>```

Unfortunately findMinimumNode is O(n), and you do incur that cost once per insert (but not during the insert :).  Removing the minimum node and inserting the new node are, on average, O(1) because they'll tend towards the bottom of the heap.

Going the other way with a Binary Min-Heap, the min is at the top, which is great for finding the min for comparison, but sucks when you have to replace the minimum with a new number that's > min.  That's because you have to remove the min node (always O(logN)) and then insert the new node (average O(1)).  So, you still have O(logN) which is better than Max-Heap, but not O(1).

Of course, if N is constant, then you always have O(1).  :)

Body:
You could use a Binary Max-Heap.  You'd have to keep track of a pointer to the minimum node (which could be unknown/null).

You start by inserting the first 100 numbers into the heap.  The max will be at the top.  After this is done, you will always keep 100 numbers in there.

Then when you get a new number:

if(minimumNode == null)
{
    minimumNode = findMinimumNode();
}
if(newNumber > minimumNode.Value)
{
    heap.Remove(minimumNode);
    minimumNode = null;
    heap.Insert(newNumber);
}

Unfortunately findMinimumNode is O(n), and you do incur that cost once per insert (but not during the insert :).  Removing the minimum node and inserting the new node are, on average, O(1) because they'll tend towards the bottom of the heap.

Going the other way with a Binary Min-Heap, the min is at the top, which is great for finding the min for comparison, but sucks when you have to replace the minimum with a new number that's > min.  That's because you have to remove the min node (always O(logN)) and then insert the new node (average O(1)).  So, you still have O(logN) which is better than Max-Heap, but not O(1).

Of course, if N is constant, then you always have O(1).  :)


问:
When learning JS, what was your your Aha-moment?
Do you remember when you were learning JavaScript? What was the moment that you suddenly "got it"? (For example, my CSS aha-moment was when I learnt about the box model...)

The reason I´m asking is that I´m learning JS for 6 weeks, but I still find it quite confusing. Here´s a quote from something I read recently on SO:

"..functions act similar to values, as
  method is a property of the object
  that has a value of a function (which
  is also an object)."

I´m curious if you were confused as well in the beginning and what was it that made you understand it.

(I´m reading the Sitepoints "Simply JavaScript", the book "Eloquent JavaScript" and following Lynda´s Essential JavaScript tutorial. I don´t have any programming expeirence and was terrible at math ;)

Thanks!

答:
When I realized that you could set a property on a function object.

Also when I finally understood what the prototype was.

```<code>function Alpha(){
    return 'aplha';
}
Alpha.Beta = function(){
    return 'beta';
}
Alpha.prototype.Delta = function(){
    return 'delta';
}

Alpha(); // 'alpha'
Alpha.Beta(); // 'beta'
new Alpha().Delta(); // 'delta'
</code>```

OwnerDisplayName: Mattvic

Body:
When I realized that you could set a property on a function object.

Also when I finally understood what the prototype was.

function Alpha(){
    return 'aplha';
}
Alpha.Beta = function(){
    return 'beta';
}
Alpha.prototype.Delta = function(){
    return 'delta';
}

Alpha(); // 'alpha'
Alpha.Beta(); // 'beta'
new Alpha().Delta(); // 'delta'


问:
Why would a video game need main(String[] args) in its own class?
My teacher just told me that whenever I create a class to run something for a video game company that uses Eclipse, I should make a run class with the main and any outputs. He says any arithmetic should then be put in its own class. Here's the example he gave us.

//triangle

import java.util.Scanner;
import java.lang.Math.*;
import java.lang.String;
public class Lab03a {  //this class is used to test Triangle
    public static void main( String[] args ) {
        Scanner keyboard = new Scanner(System.in);

        //ask for user input
        System.out.print("Enter side A ::  ");
        int a = keyboard.nextInt();

        System.out.print("Enter side B ::  ");
        int b = keyboard.nextInt();

        System.out.print("Enter side C ::  ");
        int c = keyboard.nextInt();

        Triangle test = new Triangle(a, b, c);
        test.calcPerimeter();
        test.calcArea();
        test.toString();
        System.out.println("Area "+test.toString());

        //ask for user input
        System.out.print("Enter side A ::  ");
        a = keyboard.nextInt();

        System.out.print("Enter side B ::  ");
        b = keyboard.nextInt();

        System.out.print("Enter side C ::  ");
        c = keyboard.nextInt();

        test.setSides(a,b,c);
        test.calcPerimeter();
        test.calcArea();
        test.toString();
        System.out.printf("%.3f\n",(test.toString()));

        //add one more input section

}
}
```

<p>The other class:</p>

<pre class="lang-java prettyprint-override"><code>import java.util.Scanner;
import java.lang.Math.*;

public class Triangle {
    private int sideA, sideB, sideC;
    private double perimeter;
    private double theArea;
    private double s;

    public Triangle() {
        setSides(0,0,0);
        perimeter=0;
        theArea=0;
        s=0;
    }

    public Triangle(int a, int b, int c) {
        sideA=a;
        sideB=b;
        sideC=c;
    }

    public void setSides(int a, int b, int c) {
        sideA=a;
        sideB=b;
        sideC=c;
    }

    public void calcPerimeter( ) {
        perimeter=sideA+sideB+sideC;
    }

    public void calcArea() {
         s=perimeter/2;
         theArea=(Math.sqrt(s*(s-sideA)*(s-sideB)*(s-sideC)));
    }

    public String toString() {
        String output = ""+theArea+"\n\n";
        return output;
    }
}
</code>```

Is this universally true for gaming companys? True for some? Or would most accept this?

答:
This is universally true for any Java program.

Since a class is not a program it cannot run, think of the Main class and run method as the entry point to the program.

In response to your comment read up on SRP from the SOLID principles: http://en.wikipedia.org/wiki/Single_responsibility_principle.

For example, your triangle class will contain all of its logic and nothing else, it should be really good at that job and not be responsible for anything else. So you will need a class for the entry/execution to the application, which is the Main class.

Also, i simply have the first class with all the methods then have the main at the end, so your program would be a single object, this isn't OO and is a particular "anti-pattern", see: http://en.wikipedia.org/wiki/God_object

In learning OO, this is where you make the jump from thinking about functionality at the method level and start thinking about the object level.


答:
I see this as part of a general rule that a well designed language does what a programmer would naturally expect. If I have a block of code that I want to refactor into a closure, and I wrap that block with the appropiate syntax without really thinking about the individual lines of code, then I expect that block to do the same thing in the closure as it did inline. If some statements use the keyword "this" (perhaps implicitly) and the language makes "this" used inside the closure refer to an anonymous class used to represent it rather than the class that defines the method that defines the closure, then the meaning of those statements has changed, my block of code no longer does what I think it does, and I have to track down a bug and figure out how to change my code to work in the closure. A language that prevents me from having such problems is helpful.

The problem could also be mitigated with an IDE with smart refactoring tools, that could extract closures, detect potential problems, and even automatically adjust the extracted code to solve the problems.

Title: What is the good explanation of Tennent's Correspondence Principle?

Body:
I found myself struggling to see what is this principle about and why is it so important for language design.

Basically, it states, that for every expression expr in language should be exactly the same as this construct:

```<code>(function () { return expr; })()
</code>```

Also, I have heard that Ruby obeys this principle, while Python doesn't. I don't understand why this is true, or if it is true at all.


答:
It sounds like some form of a context aware broker architecture. Found two research papers(pdf) referencing these as a COBRA architecture.

http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.13.3938&rep=rep1&type=pdf

http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.105.9899&rep=rep1&type=pdf

Title: Help me classify this type of software architecture

Body:
I read some books about software architecture as we are using it in our project but I can't classify the architecture properly. It's some kind of Enterprise Architecture, but what exactly... SOA, ESB (Enterprise Service Bus), Message Bus, Event Driven SOA, there are so many terms in Enterprise software....

The system is based on custom XML messages exchanges between services. (it's not SOAP, nor any other XML based standard, just plain XML). These messages represent notifications (state changes) that are applied to the Domain model, (it's not like CRUD when you serialize the whole domain object, and pass it to service for persistence). The system is centralized, and system participants use different programming languages and frameworks (c++, c#, java). Also, messages are not processed at the moment they are received as they are stored first and the treatment begins on demand.

It's called SOA+EDA -:)


答:
We just started using scrum, so this idea of having a definition of done is new to us, but has been very useful.  For just one example, we had a user story to get a build compilable.  It seems apparent what that means, but having a definition spelled out really helped us.  One part of that definition was to have another developer check it out from source control and verify it compiled without errors or warnings from a clean build.  That caught a problem where I forgot to add some files in source control, so it built on my machine but not others.

Other things that came up were what should be included in the build for it to be called "done."  Can we temporarily leave out modules with a lot of compile errors that are time consuming to reconcile?  That led to a discussion about what we really need it for at this point in our development cycle.  Without that discussion, we might either wait too long for a "perfect" build, or erroneously call a build done that is completely unusable by the rest of the team.

In other words, a definition of success makes sure we all know what to expect and what not to expect when we are finished.  If it makes a difference in something as simple as compiling a build at the start of a project, it will make that much more of a difference on requirements the customer really cares about.


答:
Why it's important? Can you write any examples of those definitions?

When you specify a requirement, it's important that it meets certain qualities, such as cohesiveness (only address a single thing), complete (does not lack any information needed to fulfill the desired outcome), traceable (it is documented and can be tracked through design, implementation, and maintenance in both directions), up-to-date, feasible (it can actually be implemented), unambiguous (multiple people reading it will have the same idea of the desired outcome), and verifiable (it can be tested and easily seen whether the requirement is complete).

Defining success or failure criteria for a requirement allows it to be complete, traceable, feasible, unambiguous, and verifiable. How can you know if the requirement can be met now or in the future? How can you know when you have implemented the feature or aspect of the system? How can you point to specific modules at any level that implement the requirement, either in a representation of the design or the implementation?

This is somewhat related to the concept of "definition of done" in the agile community, as well.

Can anybody provide examples of good requirements specification?

You can find a lot of information about requirements, including examples, in Karl Wiegers' Software Requirements and More About Software Requirements: Thorny Issues and Practical Advice. In addition, Wiegers' site Process Impact provides a number of goodies, such as sample documents and templates.


答: That's a manual form of unit testing.  Most people in industry nowadays feel that if you're going to go through the trouble to write extra code for it, you may as well do some sort of automated unit tests using a unit testing framework like JUnit.</p>

Title: Why would a video game need main(String[] args) in its own class?

Body:
My teacher just told me that whenever I create a class to run something for a video game company that uses Eclipse, I should make a run class with the main and any outputs. He says any arithmetic should then be put in its own class. Here's the example he gave us.

//triangle

import java.util.Scanner;
import java.lang.Math.*;
import java.lang.String;
public class Lab03a {  //this class is used to test Triangle
    public static void main( String[] args ) {
        Scanner keyboard = new Scanner(System.in);

        //ask for user input
        System.out.print("Enter side A ::  ");
        int a = keyboard.nextInt();

        System.out.print("Enter side B ::  ");
        int b = keyboard.nextInt();

        System.out.print("Enter side C ::  ");
        int c = keyboard.nextInt();

        Triangle test = new Triangle(a, b, c);
        test.calcPerimeter();
        test.calcArea();
        test.toString();
        System.out.println("Area "+test.toString());

        //ask for user input
        System.out.print("Enter side A ::  ");
        a = keyboard.nextInt();

        System.out.print("Enter side B ::  ");
        b = keyboard.nextInt();

        System.out.print("Enter side C ::  ");
        c = keyboard.nextInt();

        test.setSides(a,b,c);
        test.calcPerimeter();
        test.calcArea();
        test.toString();
        System.out.printf("%.3f\n",(test.toString()));

        //add one more input section

}
}
```

<p>The other class:</p>

<pre class="lang-java prettyprint-override"><code>import java.util.Scanner;
import java.lang.Math.*;

public class Triangle {
    private int sideA, sideB, sideC;
    private double perimeter;
    private double theArea;
    private double s;

    public Triangle() {
        setSides(0,0,0);
        perimeter=0;
        theArea=0;
        s=0;
    }

    public Triangle(int a, int b, int c) {
        sideA=a;
        sideB=b;
        sideC=c;
    }

    public void setSides(int a, int b, int c) {
        sideA=a;
        sideB=b;
        sideC=c;
    }

    public void calcPerimeter( ) {
        perimeter=sideA+sideB+sideC;
    }

    public void calcArea() {
         s=perimeter/2;
         theArea=(Math.sqrt(s*(s-sideA)*(s-sideB)*(s-sideC)));
    }

    public String toString() {
        String output = ""+theArea+"\n\n";
        return output;
    }
}
</code>```

Is this universally true for gaming companys? True for some? Or would most accept this?