问:
Coding Guideline : Methods shouldn't contain more than 7 statements?
I was looking through the AvSol Coding Guidelines for C# and I agree with nearly everything but I'm really curious to see what other think of one specific rule.

AV1500

Methods should not exceed 7 statements  A method that requires more
  than 7 statements is doing too much, or has too many responsibilities.
  It also requires the human mind to analyze the exact statements to
  understand what the code is doing. Break it down in multiple small and
  focused methods with self-explaining names.

Do most of you follow this rule? Even if there's little to be saved from creating a new method (Your code is still DRY) aside from greatly increasing readability?  And is your number still as low as 7?    I would tend more toward 10.

I'm not saying I violate this rule all over the place--on the contrary, my methods are 95% small and focused but saying you should never violate this rule really blew me away.

I really just want to know what everyone thinks of NEVER violating this rule (It's a '1' on the coding standard--meaning NEVER do this).  But I think you'd have trouble finding a codebase that doesn't.

答:
It is usually a good idea to split stuff into little methods. But the important thing is to split things where it make sense.

If it doesn't make sense to split, then don't split. This is often the case for some procedures or GUI code.

Steve McConnell stated in Code Complete that you aren't always more productive when using short methods. If you split when it doesn't make sense, you add complexity to the code for no benefit.

As always with guidelines, it is good to remember why the constraints exist, so you can learn when it doesn't apply. In most of the code the methods will be short, or you probably have a problem with DRY or separation of concerns. But if isn't the case, then fine.


问:
What's the difference between computer science and programming?
I'm new at computer science and programming, and I was wondering, is there a difference between computer science and programming? and do you get to choose to study only one of them at the university, or both of them?</p>

答: Programming (development) is about making money. Science is about discovering new things.</p>

ContentLicense: CC BY-SA 3.0


问:
How do you integrate Testing into a Scrum process?
This is really perplexing me. We have a 'definition of done' and it includes dev 'done', unit tests 'done', dev test 'done'. However we also have a user acceptance test that needs to be 'done' but the business wants to know when users stories are complete so that they can see stuff (the uat really isnt a priority until release). But because this is outside of the initial done (where we pass our user stories) how can we say its done? And where does this fit into estimating?

Where can I find information on integrating testing with a scrum process? I think I need to read up this...

答:
I'd recommend sitting with the users or appropriate management and going over this issue in a lot more detail.  Professional Software development means that you do testing, including for user stories.

You have to make this a priority.  It's always easier to not address the issue and just keep writing more code and delivering more functionality.  However this is not software that counts, and can be counted on, if part of the QA process is not working.

Focus on process and long-term benefits.  "Changing your oil takes time" but you don't put it off forever or suddenly, one day, you get a nasty surprise!  So you schedule maintenance, testing, whatever as just part of the software development process.  Since you are trying to change an existing system I would recommend making this a bit more formal initially to get the process going.  Focus on benefits (people like to hear) rather than current issues (people get defensive and question).

If the organization doesn't fully understand about professional software development you can either educate them or seek another place that does.


答: I've never taken the time to actually count the number of statements in my methods, but I do strive to write methods that cleanly perform a single, clear purpose.  As long as your code is clean, readable, and follows the DRY and Single Responsibility principles, you've probably done your job.  I think that arbitrarily splitting a method apart just to enforce the seven-statement limit could make your code less readable/maintainable.</p>

Title: Coding Guideline : Methods shouldn't contain more than 7 statements?

Body:
I was looking through the AvSol Coding Guidelines for C# and I agree with nearly everything but I'm really curious to see what other think of one specific rule.

AV1500

Methods should not exceed 7 statements  A method that requires more
  than 7 statements is doing too much, or has too many responsibilities.
  It also requires the human mind to analyze the exact statements to
  understand what the code is doing. Break it down in multiple small and
  focused methods with self-explaining names.

Do most of you follow this rule? Even if there's little to be saved from creating a new method (Your code is still DRY) aside from greatly increasing readability?  And is your number still as low as 7?    I would tend more toward 10.

I'm not saying I violate this rule all over the place--on the contrary, my methods are 95% small and focused but saying you should never violate this rule really blew me away.

I really just want to know what everyone thinks of NEVER violating this rule (It's a '1' on the coding standard--meaning NEVER do this).  But I think you'd have trouble finding a codebase that doesn't.


问:
Rigorous Definition of Syntactic Sugar?
It seems like in language holy wars, people constantly denigrate any feature they don't find particularly useful as being "just syntactic sugar".  The line between "real features" and "syntactic sugar" tends to get blurred in these debates.  What do you believe is a reasonable and unambiguous definition of syntactic sugar that avoids it being defined as any feature the speaker/writer doesn't find useful?</p>

答:
To answer my own question, a feature is syntactic sugar if and only if it it was included primarily to enhance aesthetics and readability and can be trivially translated in a roughly one-to-one fashion into the de-sugared version.  (By roughly one-to-one I mean modulo trivial things like the order of commutative operations, variable names and whitespace.)

Any feature that could only be de-sugared with a significant amount of programmer discipline is not syntactic sugar.  As a subset of this, any feature that increases type safety is not syntactic sugar, since manually enforcing type safety via programmer discipline is highly non-trivial.  For example, C++'s object system is more than syntactic sugar on top of C pointer cast polymorphism.

Any feature that would require either significant code duplication or a major redesign if removed is not syntactic sugar, since neither of these is a trivial undertaking.  For example, templates are not just syntactic sugar because getting the equivalent functionality without them would require tons of clone-and-modify.

Example of things that are syntactic sugar:

a[i] instead of *(a + i)

a -> b instead of (*a).b

foreach syntax instead of manually typing out iterator syntax.

All operator overloading is pure syntactic sugar.

Does this sound like a fair and reasonably unambigous definition?

ContentLicense: CC BY-SA 2.5

Title: Rigorous Definition of Syntactic Sugar?


问:
Business Objects within a Data Access Layer
So I've been creating a data access layer via TDD and have approached somewhat of a concern. I'd rather not start down the wrong path, so I figured I'd ask you guys to see if my thoughts were in line with a clean architecture.

The methods within my Data Access Layer (DAL for short), are pretty simple. They are in line with the stored procedures in the database (no other way to call into it to keep things clean), and they contain those same parameters that the procedures do. They then just connect to the database, and return the query result. Here's one example:

```<code>public int DeleteRecord(int recordId)
{
    recordId.RequireThat("recordId").NotZeroOrLess();

    List<SqlParameter> parameters = new List<SqlParameter>();
    parameters.Add(new SqlParameter { ParameterName = "@RecordId", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Input, Value = recordId});

    return this.ExecuteNonQuery("DeleteRecord", parameters.ToArray());
}
</code>```

This works perfectly for this type of method because I am not doing anything meaningful with the result set. I just want to make sure the command worked, so I will return the result of the non-query, which is just the rows affected, and I can verify the logic using that number.

However, say in another DAL method, I want to load a record. My load procedure is going to be executing selects against a bunch of tables and returning a DataSet, but I am battling with whether my DAL should create the Business Objects within the method using the DataSet, or if my Business Objects themselves should just have a Load() method that gets the DataSet from the DAL, and then basically fills itself in.

Doing it through the DAL would result in less logic in the Business Objects (even though this is just select logic, it's still logic), but would crowd the DAL a little bit and make it feel like it really is doing something that it shouldn't be doing.

What do you guys think?

答:
My method, even prior to LINQ-To-SQL and Entity Framework, was to have an interface and abstract class library that provided a "written contract" for communication between different layers of the app. This is sometimes called an ontology, a definition for a work domain. Anything that passed between layers used this 'contract'.

I don't like the idea of passing raw Dataset objects from the data layer to the business layer. I've seen this result in a number of problems, especially when integrating legacy data sources. It can also make it very difficult for new people coming into a project to understand where data is coming from. Lastly, it requires your business layer to be in the business of handling data directly from the DB, which can lead to complications down the road.

The example code you had looks similar to code I had prior to LINQ. I had a common DB function class that I used inside my DAL objects. The DAL classes would read the data and fit it into the 'contract' objects. Scalar results, like your delete example, would return a value, usually a boolean.


答: This is a "standards smell" to me.  Whenever I see coding standards with specific limits in them, I worry.  You almost always run into a case where a method needs to be bigger than the standard allows (whether it's line length/count, number of variables, number of exit points, etc). Standards should be more like guidelines, and allow sufficient leeway for exercising good judgement.  Don't get me wrong, it's good to have standards, but they shouldn't become "micromanagement by proxy".</p>


答: Well, it depends a bit. I write a lot of code that accesses databases. The  boiler plate code for exception handling is more that seven statements long in a lot of cases.  I'd say teh best guideline is to make sure your function has one purpose </p>


问:
python login form vulnerability?
```<code><HTML>
<HEAD><TITLE>Login Page</TITLE></HEAD>
<BODY>
<CENTER>
<FORM method="POST" action="http://yourserver/cgi-bin/login.py">
<paragraph> Enter your login name: <input type="text" name="login">
<paragraph> Enter your password: <input type=password name="password">
<paragraph> <input type="submit" value="Connect">
</FORM>
</CENTER>
<HR>

</form>
</BODY>
</HTML>
</code>```

login.py:

```<code>#!/usr/local/bin/python
import cgi

def header(title):
   print "Content-type: text/html\n"
   print "<HTML>\n<HEAD>\n<TITLE>%s</TITLE>\n</HEAD>\n<BODY>\n" % (title)

def footer():
   print "</BODY></HTML>"

form = cgi.FieldStorage()
password = "python"

if not form:
   header("Login Response")
elif form.has_key("login") and form["login"].value != "" and form.has_key("password")       and form["password"].value == password:
header("Connected ..." )
   print "<center><hr><H3>Welcome back," , form["login"].value, ".</H3><hr></center>"
   print r"""<form><input type="hidden" name="session" value="%s"></form>""" % (form["login"].value)
   print "<H3>Click here to start browsing</H3>"

else:
   header("No success!")
   print "<H3>Please go back and enter a valid login.</H3>"

footer()
</code>```

I would like to make this login form vulnerable to RCE (remote code execution), is this possible with the function eval() or exec().

I am looking for functions that introduce a vulnerability within the login form. Are there whole classes/modules that contain dangerous functionally? Also would it be possible to make this login form vulnerable to remote code execution?

答:
I would like to make this login form vulnerable to RCE ( remote code execution), is this possible with the function eval() or exec()?

Yes. If you pass unchecked user input to either of those functions then you are allowing remote code execution.

I am looking for functions that introduce a vulnerability within the login form.I am particularly interested in Remote Code Execution vulnerabilities. Are there whole classes/modules that contain dangerous functionally?

Yes. Python can open files/delete files/connect to databases/etc. So yes there is plenty of bad things that could happen if you can execute arbitrary code.

Also would it be possible to make this login form vulnerable to remote code execution?

Yes. See above.

Title: python login form vulnerability?

Body:
```<code><HTML>
<HEAD><TITLE>Login Page</TITLE></HEAD>
<BODY>
<CENTER>
<FORM method="POST" action="http://yourserver/cgi-bin/login.py">
<paragraph> Enter your login name: <input type="text" name="login">
<paragraph> Enter your password: <input type=password name="password">
<paragraph> <input type="submit" value="Connect">
</FORM>
</CENTER>
<HR>

</form>
</BODY>
</HTML>
</code>```

login.py:

```<code>#!/usr/local/bin/python
import cgi

def header(title):
   print "Content-type: text/html\n"
   print "<HTML>\n<HEAD>\n<TITLE>%s</TITLE>\n</HEAD>\n<BODY>\n" % (title)

def footer():
   print "</BODY></HTML>"

form = cgi.FieldStorage()
password = "python"

if not form:
   header("Login Response")
elif form.has_key("login") and form["login"].value != "" and form.has_key("password")       and form["password"].value == password:
header("Connected ..." )
   print "<center><hr><H3>Welcome back," , form["login"].value, ".</H3><hr></center>"
   print r"""<form><input type="hidden" name="session" value="%s"></form>""" % (form["login"].value)
   print "<H3><a href=browse.html>Click here to start browsing</a></H3>"

else:
   header("No success!")
   print "<H3>Please go back and enter a valid login.</H3>"

footer()
</code>```

I would like to make this login form vulnerable to RCE (remote code execution), is this possible with the function eval() or exec().

I am looking for functions that introduce a vulnerability within the login form. Are there whole classes/modules that contain dangerous functionally? Also would it be possible to make this login form vulnerable to remote code execution?


问:
How do you keep track of large projects?
When dealing with a project that has many different files, I always seem to loose track of how the parts interact with one another. I've never really had much of a problem understanding smaller components in isolation, but as the complexity of the project increases, I find myself unable to mentally construct an understanding of what is going on. I notice this especially with OOP projects, as the number of methods and source files increase.

My background:
I'm a self-taught web programmer. I've dealt mostly with python for quick and dirty scripts, but I've also done a few basic django projects. I like web frameworks such as flask, because in the simplicity of a single-file layout, I can easily keep track (mostly) of what is going on.

I now find myself in a situation where I need to interact with a large Zend Framework PHP project that someone else developed, and I'm overwhelmed with trying to understand the code spread out to numerous files.

What techniques and processes have you found useful to understand a large code base that someone else has developed? Is there any particular diagram that you find helps you grasp the larger picture?

答:
I am actually going to start doing this during the course of this week where a new client needs enhancements for a product that was left by another developer. Below are the steps to be followed:

a) Identify the programming framework used, which helps in knowing how the application flows.

b) Identify common services - logging, exception handling, MVC, database connection, auditing, view (page generation) since these are the parts where we shall be using the most.

c) Run through common user flows (in the application) then try to align them to how the code is laid out

d)Try to make some changes and see how they come out. This is the biggest step because until you start making changes the code is still a black box ....

I will let you know what other ideas I get over the course of the next two weeks


问:
In integration testing, do you use the data access objects for setup and validation or a different data access method?
When writing integration tests for business logic objects and data access objects, what makes the most sense to use for setup and validation?  In my case, I'm using an ORM in the implementation of my data access interface that will be used in production, and I plumb that ORM implementation together with the business logic objects for integration testing.  Given that the ORM implementation is tested separately using INSERT and SELECT statements for setup and validation, is it best for integration testing setup and validation to use the ORM implementation of the data access interface, to use the ORM directly, to use those INSERT and SELECT statements, or to do something else, edit: and why?

The ORM in this case is NHibernate, the ORM implementation of the data access interface is a simple pass-through to NHibernate's LINQ provider that also provides simple pagination and sorting mechanisms.  I'm curious to know what you think, either generally or with this specific scenario.

edit:  I'm not looking to know what DAO I should connect to the BL objects.  That clearly should be the same DAO that will be used in production.  The question is about the mechanism used to put data into the database to set up the test before the business logic function is tested.  Presumably, the same mechanism would be used to poll the database after the business logic function is tested.  Here's some very high-level pseudo-code to demonstrate what I mean:

```<code>MyIntegrationTest()
{
    Foo fooBefore = GenerateFooForTesting();
    SomehowInsertIntoDatabase(foo); // What should be used here and why?

    // Plumb things together; actually done using IoC, not hard-coded.
    DaoFactory realDaoFactory = GetRealDaoFactory();
    BizFactory realBizFactory = GetRealBizFactory();
    realBizFactory.DaoFactory = realDaoFactory;

    BusinessLogicObject biz = realBizFactory.BuildBusinessLogicObject();
    biz.DoBusinessWithFooById(fooBefore.Id);

    Foo fooAfter = SomehowGetFooFromDatabase(fooBefore.Id); // Same question.

    Assert.AreEqual(5, fooAfter.SomethingThatShouldBeFiveAfterBusinessIsDone);
}
</code>```

答: If you're doing an integration test, then you're testing the interaction among different objects in different layers.  Therefore, I'd use a setup as close as possible to the final system.  You can often flush out edge cases this way (e.g., the ORM may throw an exception you hadn't anticipated when you present it with invalid data).</p>


答: Your DAL should return a Dataset. That Dataset returned should be the buisness object, there shouldn't be anything you need to do to it other than check that that it has the expected data.  If you need to do more with it then you are either trying to do too much in a single stored procedure or not returning the data properly in the stored procedure.</p>

Title: Business Objects within a Data Access Layer

Body:
So I've been creating a data access layer via TDD and have approached somewhat of a concern. I'd rather not start down the wrong path, so I figured I'd ask you guys to see if my thoughts were in line with a clean architecture.

The methods within my Data Access Layer (DAL for short), are pretty simple. They are in line with the stored procedures in the database (no other way to call into it to keep things clean), and they contain those same parameters that the procedures do. They then just connect to the database, and return the query result. Here's one example:

```<code>public int DeleteRecord(int recordId)
{
    recordId.RequireThat("recordId").NotZeroOrLess();

    List<SqlParameter> parameters = new List<SqlParameter>();
    parameters.Add(new SqlParameter { ParameterName = "@RecordId", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Input, Value = recordId});

    return this.ExecuteNonQuery("DeleteRecord", parameters.ToArray());
}
</code>```

This works perfectly for this type of method because I am not doing anything meaningful with the result set. I just want to make sure the command worked, so I will return the result of the non-query, which is just the rows affected, and I can verify the logic using that number.

However, say in another DAL method, I want to load a record. My load procedure is going to be executing selects against a bunch of tables and returning a DataSet, but I am battling with whether my DAL should create the Business Objects within the method using the DataSet, or if my Business Objects themselves should just have a Load() method that gets the DataSet from the DAL, and then basically fills itself in.

Doing it through the DAL would result in less logic in the Business Objects (even though this is just select logic, it's still logic), but would crowd the DAL a little bit and make it feel like it really is doing something that it shouldn't be doing.

What do you guys think?


答:
Your DAL should return your data objects

Ideally your DAL should be a "black box" object, that your application code can use to ask for a data object or manipulate existing data objects. Sometimes there is another layer put between the DAL and the application code called the Repository, which further separates the two layers, although this is not always needed.

In addition, you usually do not want your business objects being able to create themselves. This can cause security holes where someone can use your library, and create a new instance of your object by calling .Load(someId) on it, and it merges together two layers that should be completely separate.

I also don't recommend providing a.Load(DataSet ds) method because if the data set definition changes, you'll have to hunt down the data objects which use that data set and change them. It's easier to keep all your data access code in one place, so if you change the data access query, you should only have to change your DAL layer.


答: I'd recommend your business objects have a constructor to populate themselves from a result set.  This removes the coupling between your DAL and the business layer.  If you want to completely isolate the two, create a simple map of column name => value pairs from your result set and pass that to the constructor.</p>


问:
What information should a good (method- / class-) comment contain?
This is something that has bothering me for a while now. I guess there are a couple of obvious important things that should go into a comment, such as:

The author(s)

A description of the parameters (and their types, if we are in a dynamic language)

A short description of what the method does, e.g. "Trims leading and trailing white-spaces for unlimited length strings."

If it throws exceptions.

Semantics of the return value.

But one could image all kinds of information that could be added to such a comment, for instance:

Usage examples

Explanation of how the method is used in the project scope

TODOs / Nice to haves for this method which are not yet implemented

And probably many more

Now my question is, how do you write a really good method or class comment (that is, what information do you put in it, and how do you make sure it is kept up-to-date), with just the right amount of information so that any developer who has to work with your code is up to the task, but considering the fact that as you add more and more information to your comment, the probability for it to become outdated rises (e.g. if I add pointers to where the method is / will be used in the project, it could be replaced in that location or it might very well never be used, even though it was intended to).

答:
The best comment is the one you don't write.

Comments get out of date quickly.

I used to write pages of comments but now I use the following principles:

Fully name classes, method and variables with real words and not abbreviations or letters.

Use a source control system (my favorite is git) to store the user name, date of change, etc.

If you do comment, don't state the obvious in a comment. /* a new comment */

If the code isn't clear erough as is, consider writing more verbose tests to express the functionality rather than adding comments.


答:
It should be regarded as a rule of thumb.

Things like "No more than 80(100,120) columns of text", "one exit point per method", "no more than 2 levels of nesting", are what I would call thresholds for indicators of code smell. If you violate them on occasion, that does not necessarily mean the code is bad. If you find yourself violating them consistently then something smells in the code and you may wish to take a pause and rethink your approach.

To me, the most important criteria are, "Is this code understandable?", "Is it repetitive?", "Is it broken up in logical places?", "Is it loosely coupled?" There are a few more, but I think the basic idea can be summed up by remembering Donald Knuth's advice: "Programs are meant to be read by humans and only incidentally for computers to execute."


答:
The one thing I would 'RECOMMEND' doing is to implement automated testing. For example; if you are testing things in Windows Forms or C# or WPF use White.Core for testing. This will allow you to test new implementations, builds, features as quickly as possible.

I work as an Automation Engineer and I use White.Core in C++/C# while testing GUIs verifying dev fixes before an iteration is over.

Title: How do you integrate Testing into a Scrum process?

Body:
This is really perplexing me. We have a 'definition of done' and it includes dev 'done', unit tests 'done', dev test 'done'. However we also have a user acceptance test that needs to be 'done' but the business wants to know when users stories are complete so that they can see stuff (the uat really isnt a priority until release). But because this is outside of the initial done (where we pass our user stories) how can we say its done? And where does this fit into estimating?

Where can I find information on integrating testing with a scrum process? I think I need to read up this...


答:
Everything is a trade-off.  The problem with the proposed approach - refactoring into several methods and classes so that each method is short - is that although for different reasons, it leads to unreadable code when taken to its extreme.

Imagine a method foo() that does 7 things.  You might argue that 7 things is too much.  Maybe in many cases you're right.  On the other hand, these 7 things might be closely related; the logic may flow smoothly and read like prose; you may have no trouble understanding it when you actually need to.  What might end up much worse is to have those 7 things distributed across a large source tree, so that if you look at foo() you have no idea what it does without looking in 7
different places.

Many people get rules like this in  their head, and the result is what I think of as OO spaghetti.  Everything is neat, boxed in its own little method or class, with atomic little micro-transactions occurring in each place.  But it's impossible to come fresh to such a code base and know what it's doing.  You become lost.


答:
Firstly: it's a guideline, not a rule. It's called a guideline, so please treat it as such. This implies that your own judgement is also required (as always)

That apart, I can think of plenty examples of good code that doesn't adhere to this constraint. Even though it's just a guideline, it's a poor one.


问:
migration and interoperability
A large system has already been done in visual fox pro. They want to add more requirements to a module and make some changes to the system.At the same time they are thinking about migration to .net. Some parts like report generation has been done in .net using visual fox pro database and loaded in vfp.

Is it a good idea to start migrating database as well? I mean is it good to create database (and tables) for the module for new requirements and changes?

I think this will cause problem and difficulty to maintain the software.

How is the process of data migration initiated? Should it be done gradually (partly in visual fox pro and partly in sql) or should it be done all at a time?

答:
It Depends.

If your VFP systems is written in such a way that it’s easy to swap out Backends than absolutely YES. But that fact that you are asking this question leads me to think that it’s not.

Here are some of my though on your situation:

If you were to change the entire back end, most likely you are going to have to modify so much of your existing VFP code base that that you may as well rewrite the whole App in .Net.

All new .Net Code Should be written in such a way that it’s easy to change the backend from VFP to SQL Server (Or whatever your favorite Db is)

Check your current File Sizes! VFP has a 2GB limit on ALL file sizes. (DBFs, CDX, FTP ext)

Milk your VFP systems for as long as you can, particularly if it works well. But keep in mind that the it is a retired language, there will NEVER be a VFP 10 and it will NEVER be 64bit

VFP connects to SQL server Nicely, It may not be a bad idea to create new tables in SQL server, or archive data to it. Look into Remote Views and SQL Pass though

Querying data between 2 tables One on SQL Server and One in VFP is very slow, and most likely a bad idea. (Not the contradiction between this and the bullet above :-)

There is no universal answer to your question, you know your system and it’s your call.

Title: migration and interoperability


答:
It's approximate

These kinds of rules shouldn't be taken too literally. They could have said "methods should be short". However, some people would have interpreted that as "less than 1 page" and others as "2 lines at most."

I would assume that they said "7 statements" to give you a rough idea (though I think they should have said "about 7"). If you need 9 once in a while, don't sweat it. But if you're hitting 20, you'll know you're not in the right ballpark for this rule.


问:
Is the "Objects First" approach a good idea?
Do you think programming novices should learn objects from day 1, as seen in the book "Objects First With Java: A Practical Introduction Using BlueJ" by David Barnes? Or do you think this is a bad idea?

For those unfamiliar with the book, here is a list of the topics discussed in the chapters:

Chapter 1 deals with the most fundamental concepts of object-orientation: objects, classes and methods. It gives a solid, hands-on introduction to these concepts without going into the details of Java syntax. It also gives a first look at some source code. We do this by using an example of graphical shapes which can be interactively drawn, and a second example of a simple laboratory class enrolment system.

Chapter 2 opens up class definitions and investigates how Java source code is written to create behavior of objects. We discuss how to define fields and implement methods. Here, we also introduce the first types of statements. The main example is an implementation of a ticket machine. We also look back to the laboratory class example from chapter 1 to investigate that a bit further.

Chapter 3 then enlarges the picture to discuss interaction of multiple objects. We see how objects can collaborate by invoking each other's methods to perform a common task. We also discuss how one object can create other objects. A digital alarm clock display is discussed that uses two number display objects to show hours and minutes. As a second major example, we examine a simulation of an email system in which messages can be sent between mail clients.

In Chapter 4, we continue by building more extensive structures of objects. Most importantly, we start using collections of objects. We implement an electronic notebook and an auction system to introduce collections. At the same time, we discuss iterations over collection and have a first look at loops. The first collection being used is an ArrayList. In the second half of the chapter we introduce arrays as a special form of a collection, and the for loop as another form of a loop. We discuss an implementation of a web log analyzer as an example for array use.

Chapter 5 deals with libraries and interfaces. We introduce the Java standard library and discuss some important library classes. More importantly, we explain how to read and understand the library documentation. The importance of writing documentation in software development projects is discussed, and we end by practicing how to write suitable documentation for our own classes. Random, Set and Map are examples of classes that we encounter in this chapter. We implement an Eliza-like dialogue system and a graphical simulation of a bouncing ball to apply these classes.

Chapter 6, titled Well-behaved objects, deals with a whole group of issues connected to producing correct, understandable, and maintainable classes. It covers issues ranging from writing clear, understandable code - including style and commenting - to testing and debugging. Test strategies are introduced and a number of debugging methods are discussed in detail. We use an example of a diary for appointment scheduling and an implementation of an electronic calculator to discuss these topics.

In Chapter 7, we discuss more formally the issues of dividing a problem domain into classes for implementation. We introduce issues of designing classes well, including concepts such as responsibility-driven design, coupling, cohesion, and refactoring. An interactive, text-based, adventure game (World of Zuul) is used for this discussion. We go through several iterations of improving the internal class structure of the game and extending its functionality, and end with a long list of proposals for extensions that may be done as student projects.

Chapters 8 and 9 introduce inheritance and polymorphism with many of the related detailed issues. We discuss a simple database of CDs and videos to illustrate the concepts. Issues of code inheritance, subtyping, polymorphic method calls and overriding are discussed in detail.

In Chapter 10 we implement a predator/prey simulation. This serves to discuss additional abstraction mechanisms based on inheritance, namely interfaces and abstract classes.

Chapter 11 introduces two new examples: an image viewer and a sound player. Both examples serve to discuss how to build graphical user interfaces (GUIs).

Chapter 12 then picks up the difficult issue of how to deal with errors. Several possible problems and solutions are discussed, and Java's exception handling mechanism is discussed in detail. We extend and improve an address book application to illustrate the concepts.

Chapter 13 steps back to discuss in more detail the next level of abstraction: how to structure a vaguely described problem into classes and methods. In previous chapters we have assumed that large parts of the application structure already exist, and we have made improvements. Now it is time to discuss how we can get started from a clean slate. This involves detailed discussion of what the classes should be that implement our application, how they interact, and how responsibilities should be distributed. We use class-responsibilities-collaborators (CRC) cards to approach this problem, while designing a cinema booking system.

In Chapter 14, we try to bring everything together and integrate many topics from the previous chapters of the book. It is a complete case study, starting with the application design, through design of the class interfaces, down to discussing many important functional and non-functional characteristics and implementation details. Topics discussed in earlier chapters (such as reliability, data structures, class design, testing, extendibility, etc.) are applied again in a new context.

答:
I was involved in a class taught with Objects First and BlueJ; while I came into the class with a stronger-than-expected programming background, my classmates who did not have any prior programming knowledge continually found themselves confused by the order in which things were taught: things like teaching the specifics of using ArrayList without explaining what the term "array" means or what the term "list" means, or not explaining what "public" means until chapter 5 (after debugging!), or teaching "for-each" almost a week before "for" (based on the rate we went through the book).

They were also totally lost as to how to do the basics when they moved to Eclipse, having no idea how to get started with a project or create their objects without the specialized BlueJ interface. After about the tenth time the person I was tutoring told me "I hate how BlueJ does this", I set her up with Eclipse (which was never used or taught in our course) and had to walk her through the basics.

In essence, it's a nice idea but horribly executed within that text.


答: I agree with the statement above me.  This is just guideline and in a perfect world everything would be objects, reused in every program, and the world would be a beautiful place.  It is not always true and sometimes that would lead to a lot of overhead or wasted resources.  You need to put that in mind also.</p>


答:
The disconnect between different states of done usually is a fabrication of project management desperately wanting to believe that the developers can completely hand off code to non-project resources for UAT and move on.

This is not Scrum.  This is not Agile.  This is an Agile Anti-Pattern.

There is only one state of "done" for a given user story and that is Accepted.  A sprint is NOT over until every assigned user story in the sprint has been pushed out of scope for that sprint, or accepted.

Now a developer can be Complete with a user story meaning that it is ready for UAT, but the developer is really not off the hook until the user story has been accepted as a number of issues could be found during UAT that the developer must address before the end of the sprint.

All phases of design, documentation, implementation, and all types of testing should be accounted for in estimating a user story.  QA or the entity that is to perform the UAT should be a project resource during sprint planning.


答:
it's not a bad guideline.  I've never regretted splitting up methods and classes (I've never found I had too many) as long as they are grouped and interrelated well enough.

The trick is to NOT split it vertically (Just pinch a method off at one point and start a new one).  The trick, like with unit testing, is to keep such a rule in mind from the start so that you actually design better, passing off 3 or 4 statements mid-method to another method because having a method call describes what you are doing better than those 3 or 4 statements in the middle of your code.

This kind of split, even if it's arbitrary and only used once, may lead to better refactorings later due to a new clarity of code, this is true of smaller classes as well.

Think of it like you would unit testing.  If you try to add unit testing after the fact it's difficult and sometimes seems impossible but if you design it in from the beginning it actually makes all your code better.

Summary? If comparing the design smell of "Use less than 7 statements" to the code smell of "I used more than 7 statements", I'd rather eliminate the code smell.


问:
Is it better to use assert or IllegalArgumentException for required method parameters?
In Java, which is more highly recommended, and why? Both types will throw exceptions, so in that regard handling them is the same. assert is slightly shorter, but I'm not sure how much that matters.

```<code>public void doStuff(Object obj) {
    assert obj != null;
    ...
}
</code>```

vs

```<code>public void doStuff(Object obj) {
    if (obj == null) {
        throw new IllegalArgumentException("object was null");
    }
    ...
}
</code>```

答: IMO the second one is slightly better because it brings more information and could be further extended (e.g. by extending exception class) to be even more informative, also it doesn't use negative comparison which is easier to understand.</p>


问:
Is it reasonable to run processes with CI tools?
At my company, we have a quagmire of disparate cron jobs (on multiple systems) and manually kicked off processes which keep our business functioning that is a result of years of expedient development and subsequent neglect.

Someday, we will need to come up with a more centralized solution for obvious reasons.

One thought that we have been kicking around is to use our Continuous Integration software (Jenkins) to run these processes, which seems logical.

My question is: Are other companies doing this? Is this a generally accepted practice? Doesn't this conflict with the definition of a CI tool implicit in its name? Are there any other options?

Note:
https://wiki.jenkins-ci.org/display/JENKINS/Meet+Jenkins

Jenkins claims that it focuses on "Monitoring executions of externally-run jobs, such as cron jobs and procmail jobs". I'm not sure if this is exactly what I am talking about.

答:
It sounds like cron is already an appropriate tool for your needs. I recommend you start by documenting your system better. Audit the various systems and put together a comprehensive list of which processes run on which machines.

Then consider designating a dedicated machine to run all these cron processes. Make sure you document which machine this is, and assign appropriate admin privileges for controlling it. Put all the the cronjobs on that machine, and then you've got a central point of control for your various automated processes.


答:
BEWARE!

Assertions are removed at runtime unless you explicitly specify to "enable assertions" when compiling your code. Java Assertions are not to be used on production code and should be restricted to private methods (see Exception vs Assertion), since private methods are expected to be known and used only by the developers. Also assert will throw AssertionError which extends Error not Exception, and which normally indicates you have a very abnormal error (like "OutOfMemoryError" which is hard to recover from, isn't it?) you are not expected to be able to treat.

Remove the "enable assertions" flag, and check with a debugger and you'll see that you will not step on the IllegalArgumentException throw call... since this code has not been compiled (again, when "ea" is removed)

It is better to use the second construction for public/protected methods, and if you want something that is done in one line of code, there is at least one way that I know of. I personally use the Spring Framework's Assert class that has a few methods for checking arguments and that throw "IllegalArgumentException" on failure. Basically, what you do is:

```<code>Assert.notNull(obj, "object was null");
</code>```

... Which will in fact execute exactly the same code you wrote in your second example. There are a few other useful methods such as hasText, hasLength in there.

I don't like writing more code than necessary, so I'm happy when I reduce the number of written lines by 2 (2 lines > 1 line) :-)

Title: Is it better to use assert or IllegalArgumentException for required method parameters?

Body:
In Java, which is more highly recommended, and why? Both types will throw exceptions, so in that regard handling them is the same. assert is slightly shorter, but I'm not sure how much that matters.

```<code>public void doStuff(Object obj) {
    assert obj != null;
    ...
}
</code>```

vs

```<code>public void doStuff(Object obj) {
    if (obj == null) {
        throw new IllegalArgumentException("object was null");
    }
    ...
}
</code>```

Body:
BEWARE!

Assertions are removed at runtime unless you explicitly specify to "enable assertions" when compiling your code. Java Assertions are not to be used on production code and should be restricted to private methods (see Exception vs Assertion), since private methods are expected to be known and used only by the developers. Also assert will throw AssertionError which extends Error not Exception, and which normally indicates you have a very abnormal error (like "OutOfMemoryError" which is hard to recover from, isn't it?) you are not expected to be able to treat.

Remove the "enable assertions" flag, and check with a debugger and you'll see that you will not step on the IllegalArgumentException throw call... since this code has not been compiled (again, when "ea" is removed)

It is better to use the second construction for public/protected methods, and if you want something that is done in one line of code, there is at least one way that I know of. I personally use the Spring Framework's Assert class that has a few methods for checking arguments and that throw "IllegalArgumentException" on failure. Basically, what you do is:

Assert.notNull(obj, "object was null");

... Which will in fact execute exactly the same code you wrote in your second example. There are a few other useful methods such as hasText, hasLength in there.

I don't like writing more code than necessary, so I'm happy when I reduce the number of written lines by 2 (2 lines > 1 line) :-)


问:
Generating code documentation
I want to generate code documentation in a simple format.  The key items are Method Signature, members, constructors, methods.  I am taking various applications in .NET and creating documentation for them.  I will be adding notes to each item.  The end result should look similar to MSDN or Java API documentation.

So, I want to take my source code and have some kind of template generated that I can append notes to.  I want to pick and choose certain classes and not others across various applications.

I'm not talking about intellisense documentation.  This documentation will be used for reference outside of visual studio.  AFAIK, that's all the XML comments are good for in .NET.

I'm documenting various interfaces and entry points for writing extensions for a 3rd party application.  We do not own their code, so I can't just go in and append XML comments to their interfaces, classes etc.  Instead, I need to implement the interface and comment it up.  Then document it on the web.  Documentating each implementation just to explain their architecture is redundant.  They do not document their stuff...that's the core issue here.

Is there any tool that can assist with this process?  What do you suggest?

答:
Doxygen is pretty great at translating XML to a human-readable format, such as MSDN-style HTML or HTML Help. (chm)  It will work with both XML generated by Visual Studio, as well as XML you create on your own, or acquire from other sources.

Another option is Sandcastle and SCHFP, though that has seen less maintenance.

In both of these cases, you can extend the XML markup for more than just VS Intellisense, including commentary that is only to be used for external documentation, etc.

Title: Generating code documentation


问:
What does mathematics have to do with programming?
I just started a diploma in software development. Right now we're starting out with basic Java and such (so right from the bottom you might say) - which is fine, I have no programming experience apart from knowing how to do "Hello World" in Java.

I keep hearing that mathematics is pertinent to coding, but how is it so? What general examples would show how mathematics and programming go together, or are reliant on one another?

I apologize of my question is vague, I'm barely starting to get a rough idea of the kind of world I'm stepping into as a code monkey student...

答:
I've seen a lot of questions on thes types of forums through the years where the real problem lay in the poster's poor mathematical understanding. For instance, anyone who has a good foundation in algebra understands that you can't divide by zero. But I've seen many a question where the poster didn't understnd that and subsequently didn't understand the error message that said basically "you can't divide by zero." I've seen a lot of questions where it was clear the poster didn't understand basic logic. I've seen way too many questions where the concepts of boolean algebra where clearly not understood.

Just because you aren't writing mathmatical proofs or directly solving equations like in the math textbook doesn't mean you don't need to understand the concepts behind them. Incidentally, in many years of work experience, I have never run into a bad programmer who had a solid understanding of math.

In some fields you use a lot of mathematics directly, such as game programming, statistical programming, financial programming, some embedded systems. In some of these instances you are given the equations you need in the requirements and sometimes you are not. However even when you are given the equation, translating those equations properly into programming code requires that you understand the equation to begin with.

While you can get by with little more than basic algebra in your basic CRUD application, most of the more interesting problems and more advanced work involves mathematical understanding. So why would you want to limit yourself from the start by not learning mathematics in depth?


答:
You need to use an exception. Using an assertion would be a misuse of the feature.

Unchecked exceptions are designed to detect programming errors of the users of your library, while assertions are designed to detect errors in your own logic. These are separate issues that should not be mixed.

For example, an assertion

```<code>assert myConnection.isConnected();
</code>```

means "I know that each code path leading to this assertion ensures that myConnection is connected; if the code above failed to get a valid connection, it should have thrown an exception or return before reaching this point."

On the other hand, a check

```<code>if (!myConnection.isConnected()) {
    throw new IllegalArgumentException("connection is not established");
}
</code>```

means that "Calling my library without establishing a connection is a programming error".

Body:
You need to use an exception. Using an assertion would be a misuse of the feature.

Unchecked exceptions are designed to detect programming errors of the users of your library, while assertions are designed to detect errors in your own logic. These are separate issues that should not be mixed.

For example, an assertion

assert myConnection.isConnected();

means "I know that each code path leading to this assertion ensures that myConnection is connected; if the code above failed to get a valid connection, it should have thrown an exception or return before reaching this point."

On the other hand, a check

if (!myConnection.isConnected()) {
    throw new IllegalArgumentException("connection is not established");
}

means that "Calling my library without establishing a connection is a programming error".


问:
Is it possible to combine programming languages?
I've been programming for a while, I've written some rudimentary programs, and I want to keep learning. I've reached that point where you just don't know what to learn next, and I'd like to ask a question for my own curiosity.

The question, in a nutshell, is if you can combine multiple programming languages into 1 result? For example, can this code be possible?

```<code><html>
cout << "Hello world!";
</html>
</code>```

or

```<code>import java.util.Scanner;
cout << "Insert a number from 1 to 10";
Scanner n = new Scanner(System.in);
System.out.println("The value you entered was" +n.newLine());
</code>```

This feels like a silly question but I can't possible know if it's possible or not, so that's why I'm asking it. In this question I notice he is using Python code in html code, if my above example is not possible, what did he do?

答:
Yes, it is possible to mix programming languages so long as your interpreter/compiler can understand it.  For instance mixing javascript, PHP, python in HTML or C++ in C#.

Mixing languages can make it more difficult to read and modify code, however, so it must be done cautiously.  One way around this is to create separate files for code in the language you need to call and to import it rather than embed it.


问:
Why is Zend Framework so complicated?
I am web developer and have experience of developing several web applications in PHP. I have an idea of developing a product for myself and decided to use a MVC based framework because I really like the idea of MVC and how one can easily manage and modify the application without any difficulty.

I chose Zend Framework and it seems more difficult than learning a new programming language. There are so many things going at one time even to run a small application.

Similarly the idea of routing is very complex as it is new for a core programmer. I know that the guys here read thousand of such questions like one I am asking but I am not looking to learn Zend Framework overnight. I am willing to give as much time as it needs but until now it's making no sense to me. There are thousand of classes in the Zend library, but how would a noob know where to use a specfic class and how to use it? I am still finding it very difficult to understand the bootstrap of Zend Framework and its mapping. I read the manual, follow it and things start working but I really don't exactly how they are actually happening.

I also still have no clue how models, views and controllers work together and how to plan an application in Zend Framework. When it comes to core php I exactly have the idea in my mind what to do and than easily translate them in code but in Zend Framework I don't know how to translate my idea.

答: Zend Framework requires some solid grounding in OOP and Design Patterns. From my experience, I only find experienced Java-JEE-Struts-Spring Programmers that easily become familiar with Zend Framework. Average PHP Developer finds it hard to digest the concepts and Architecture behind Zend Framework. But see hey ! Zend Framework comes from company 'Zend' that creates PHP in first-place. So it needs some thought maybe if not respect ! </p>

Title: Why is Zend Framework so complicated?


答:
Two examples that immediately come to mind are:

functions - The idea of applying a transformation to input variables to produce an output variable is strongly rooted in mathematics. The notion of passing a function around as a parameter to another function even more so. In general, the notion of abstract thinking associated with programing parallels mathematics quite closely.

bitMasks - This common programming approach to solving problems requires at least a basic understanding of boolean algebra to even grasp the concept.

Title: What does mathematics have to do with programming?

Body:
I just started a diploma in software development. Right now we're starting out with basic Java and such (so right from the bottom you might say) - which is fine, I have no programming experience apart from knowing how to do "Hello World" in Java.

I keep hearing that mathematics is pertinent to coding, but how is it so? What general examples would show how mathematics and programming go together, or are reliant on one another?

I apologize of my question is vague, I'm barely starting to get a rough idea of the kind of world I'm stepping into as a code monkey student...


答:
You can "mix" languages in HTML. It's actually important to how a lot of websites work that you can embed javascript into html. But of course, HTML is markup, not a programming language.

I think to do what you propose would entail writing a new language anyway. Either you would have to create an interpreter/compiler that spoke all of those languages and could frame them consistently, or you would need some way of evaluating line by line explicitly in what would be a meta-language. Those two options are basically the same except for what the programmer has to do to make the languages work together.

Title: Is it possible to combine programming languages?

Body:
I've been programming for a while, I've written some rudimentary programs, and I want to keep learning. I've reached that point where you just don't know what to learn next, and I'd like to ask a question for my own curiosity.

The question, in a nutshell, is if you can combine multiple programming languages into 1 result? For example, can this code be possible?

```<code><html>
cout << "Hello world!";
</html>
</code>```

or

```<code>import java.util.Scanner;
cout << "Insert a number from 1 to 10";
Scanner n = new Scanner(System.in);
System.out.println("The value you entered was" +n.newLine());
</code>```

This feels like a silly question but I can't possible know if it's possible or not, so that's why I'm asking it. In this question I notice he is using Python code in html code, if my above example is not possible, what did he do?


答:
Yes, it is possible indeed. Not the way you've imagined that, of course. There are some languages out there built specifically for this purpose.

In practice, it might be very useful to mix a number of domain-specific languages into a single host language. There's rarely a need in mixing two or more equally "general purpose" languages together in single source code file, although you'll often find projects written in both, say, VB.NET and C#, with different language components compiled separately.

As for HTML, it's just a markup language. You may often find a server-side code (e.g., in VB.NET), HTML markup and client-side Javascript code mixed into a single source file, although it is considered a bad practice by many.


答:
You first example is sort of possible. Usually such things happen in PHP (and other related web-programming languages) like this:

```<code><HTML>
<?PHP
call_some_php_function(1,2,"a","b"); /* This is may return nothing, a text string, or actual HTML markup code */
?>
</HTML>
</code>```

Some important points to note about this example:

HTML is NOT a progamming language, it is a markup language.

The PHP and HTML and not executed/interpreted in the same place: PHP code is executed by a PHP interpreter running on the server and the result is "injected" into the surrounding HTML. Then that whole blob is sent to the client/browser which renders the complete HTML.

Your second example looks like some sort of mash-up of C++ and Java. It's possible to have compiled modules written in different languages talk to each other, but to combine Java and C++ in the same source file would be extremely confusing and difficult: how would the compiler know which statements are Java and which are C++?

I suppose in theory you could write a special compiler/pre-processor with "language" indicators such as:

```<code>Java
{
    import java.util.Scanner;
}
C++
{
   cout << "Insert a number from 1 to 10";
}
Java
{
    Scanner n = new Scanner(System.in); //Actually, this line *could* be a C++ line - it's hard for me to tell just by looking at it.
    System.out.println("The value you entered was" +n.newLine());
}
</code>```

But I'm honestly not sure you'd gain anything useful by doing this.

Also, how would this hybrid language environment handle language features which are incompatible between the two?

Body:
You first example is sort of possible. Usually such things happen in PHP (and other related web-programming languages) like this:

<HTML>
<?PHP
call_some_php_function(1,2,"a","b"); /* This is may return nothing, a text string, or actual HTML markup code */
?>
</HTML>

Some important points to note about this example:

HTML is NOT a progamming language, it is a markup language.

The PHP and HTML and not executed/interpreted in the same place: PHP code is executed by a PHP interpreter running on the server and the result is "injected" into the surrounding HTML. Then that whole blob is sent to the client/browser which renders the complete HTML.

Your second example looks like some sort of mash-up of C++ and Java. It's possible to have compiled modules written in different languages talk to each other, but to combine Java and C++ in the same source file would be extremely confusing and difficult: how would the compiler know which statements are Java and which are C++?

I suppose in theory you could write a special compiler/pre-processor with "language" indicators such as:

Java
{
    import java.util.Scanner;
}
C++
{
   cout << "Insert a number from 1 to 10";
}
Java
{
    Scanner n = new Scanner(System.in); //Actually, this line *could* be a C++ line - it's hard for me to tell just by looking at it.
    System.out.println("The value you entered was" +n.newLine());
}

But I'm honestly not sure you'd gain anything useful by doing this.

Also, how would this hybrid language environment handle language features which are incompatible between the two?


答:
Several programming languages can be used to form 1 exe. One way is to use DLLs. Of course there are various concerns about this. For example, parameter compatibility, COM compatibility and such. In fact, if you think of how you call a database system to do you work, you might find that the DBMS is not always written in a language you know. You probably don't even care as long as the interface is known.

This concept is taken further when your solution utilizes Web Services, which is even a cleaner way combine multiple software components.

In the .NET world, all of the above applies, more over, on the interface level XAML and HTML interfaces can live together in Silverlight.

In the UNIX world, at one time, we used KShell scripts to launch C++ and COBOL programs so that the solution could work.


问:
Rails - to use STI or not...that is the question
Six months ago, I asked a question about modeling data for my app, and received some advice pointing me towards STI (see Rails data model - best practices question for the details).

I played around with it, got it working somewhat, and then got distracted and put the project on hiatus.

I just started developing it again from scratch, with the benefit of 6 more months of programming/ROR experience, and I have once again hit this wall when it comes to modeling ingredients for my beer recipes.

To give a quick summary, assume I have three ingredient types (malt, hops, and yeast) - each one shares a few attributes (name, price, vendor) but each also has attributes specific to that ingredient type. They are all related (they are all ingredients) but they do have different "behavior" (for example, grains are mashed and there would be logic to deal with that which wouldn't apply to hops/yeast, etc...)

The ingredients are just different enough that I am contemplating just having three separate tables in the db...but what about controllers? Could I use a single Ingredients controller to manage the separate models?

I've read about alternatives to STI (class table inheritance, and multi table inheritance) but all the solutions seem kludgy. Are there any alternatives that give me the convenience of STI (such as getting all ingredients, regardless of type, with a single table query) without the drawbacks (null fields, unwieldy tables when you keep adding subclasses and fields, etc)

Sorry, I know this question is a bit fuzzy, but I feel like I can't find a clean solution and I'm now trying to figure out which method out there is the lesser evil. I'm sure others have dealt with this, and I'd love to hear the pros/cons of different solutions. Thanks!

答:
While permanently null fields and large unwieldy tables are conceptually ugly, they generally don't actually cause any real inefficiency. The extra space used by null fields is not an important consideration for most systems, and the query speed will not be slower if you set up your indexes well.

And the benefits of STI are often worthwhile (database efficiency by minimizing joins, and shared code simplicity and DRYness). So if you are going to use a traditional SQL system, just learn to ignore the conceptual ugliness and use STI. Your use case is what STI was designed for.

That said, if you are not too deep in your development cycle for this project to be attached to your database system (and it sounds like you're not), and you are willing to invest some time to research/learning, you really might want to consider an alternative to SQL (there are many good ones out there). Currently the most popular alternative (and my personal favorite) is MongoDB.

MongoDB is document-based rather than schema-based. This means it's not as rigid about what can be stored in it. Because MongoDB has no enforced structured schema, in your project you could just have a single collection of ingredients ("collections" in MongoDB are akin to "tables" in SQL databases). Each ingredient in this collection could have shared fields as defined in an Ingredient superclass (these fields would not defined in the db itself). And the subclasses Malt, Hops, and Yeast could have their own individualized fields (again, as defined directly in these model subclasses, not in the db itself). This is exactly what you are looking for -- it gives you  all the convenience of STI without its conceptual ugliness.

Additional bonus: You might find that using a NoSQL database system like this will help simplify other areas of your app as well. In many (most?) common web business domains, NoSQL is a better choice than SQL, because web domains tend to be particularly document-intensive (so documents are a natural choice for storage mechanism).

Summary: If you are attached to using a SQL database because of administration or some part of your app that relies on it, or if don't have the time to invest in learning something new, just go with STI. If you are not attached to using a SQL database and you have the time to learn something new, I'd highly recommend switching to MongoDB or another document-based NoSQL database.


答: Okay, let's try this again :/  If your application normally will only work with data that has been inserted/retrieved using your ORM, then I'd test with that.  If the application is going to have to work with data inserted by other means (legacy or converted data) then you should plan to insert some using raw SQL.  The reason to use the ORM is to ensure that any changes you make will be properly tested "round trip": that is, if you add a column to a table you can make sure it gets properly populated when a record and created and properly retrieved when used.  For legacy data, you need to ensure that your code works properly with data that hasn't been subjected to the checks and validation of your ORM layer.  Be sure to use some bad data as well as good data, to ensure that you identify and handle invalid records properly.</p>

Title: In integration testing, do you use the data access objects for setup and validation or a different data access method?

Body:
When writing integration tests for business logic objects and data access objects, what makes the most sense to use for setup and validation?  In my case, I'm using an ORM in the implementation of my data access interface that will be used in production, and I plumb that ORM implementation together with the business logic objects for integration testing.  Given that the ORM implementation is tested separately using INSERT and SELECT statements for setup and validation, is it best for integration testing setup and validation to use the ORM implementation of the data access interface, to use the ORM directly, to use those INSERT and SELECT statements, or to do something else, edit: and why?

The ORM in this case is NHibernate, the ORM implementation of the data access interface is a simple pass-through to NHibernate's LINQ provider that also provides simple pagination and sorting mechanisms.  I'm curious to know what you think, either generally or with this specific scenario.

edit:  I'm not looking to know what DAO I should connect to the BL objects.  That clearly should be the same DAO that will be used in production.  The question is about the mechanism used to put data into the database to set up the test before the business logic function is tested.  Presumably, the same mechanism would be used to poll the database after the business logic function is tested.  Here's some very high-level pseudo-code to demonstrate what I mean:

```<code>MyIntegrationTest()
{
    Foo fooBefore = GenerateFooForTesting();
    SomehowInsertIntoDatabase(foo); // What should be used here and why?

    // Plumb things together; actually done using IoC, not hard-coded.
    DaoFactory realDaoFactory = GetRealDaoFactory();
    BizFactory realBizFactory = GetRealBizFactory();
    realBizFactory.DaoFactory = realDaoFactory;

    BusinessLogicObject biz = realBizFactory.BuildBusinessLogicObject();
    biz.DoBusinessWithFooById(fooBefore.Id);

    Foo fooAfter = SomehowGetFooFromDatabase(fooBefore.Id); // Same question.

    Assert.AreEqual(5, fooAfter.SomethingThatShouldBeFiveAfterBusinessIsDone);
}
</code>```


答:
The theoretical foundation of Computer Science (which is more than just programming) is mathematical in nature.  Everything from the very definition of computability to the analysis and expression of algorithms to the specifications of programming languages are all based in a wide variety of mathematics.  See this Wikipedia page for a flavor of the kind of math involved.

Most of which is not really necessary to know if all you want to do is sling code.  As far as applied math goes, unless you go into a field that requires serious number-crunching skills (detailed physical simulations, signal analysis, financial analysis and prediction, etc.) you're probably not going to use anything more involved than basic algebra on a day-to-day basis.


答:
It is possible to do some combination of languages using Perl Inline which allows to write a Perl script and insert sections of code written in a different language:

Inline has support for C, C++, Java, Python, Ruby, Tcl, Assembler, Basic, Guile, Befunge, Octave, Awk, BC, TT (Template Toolkit), WebChat and even PERL


问:
What's the difference between computer science and programming?
I'm new at computer science and programming, and I was wondering, is there a difference between computer science and programming? and do you get to choose to study only one of them at the university, or both of them?</p>

答:
A caveat:  'Computer Science' has become a muddied field in modern times because (at least in the United States) universities do not have degrees in "programming".  This means that people interested in programming must sign up for Computer Science degrees, and as a reaction to that the Computer Science programs emphasize programming more and more.

That said, Computer Science itself is a strongly mathematical science -- Computational Mathematics might have been a better term.  It involves the study of graph theory, algorithmic complexity, formal logic, automata, and in general any logical structure which can describe a transformation or response to input -- algorithms.  A Computer Scientist in the classic sense could reason about rules that govern any computing system (including modern computers) without necessarily knowing the details of implementation on current architecture.  A strong background in Computer Science gives you the ability to develop (or recall) efficient, scalable algorithms, anticipate logical reductions, and reason soundly about what is tractable.

Programming, by contrast, is what a person does when they use a programming language to transform an algorithm into something the machine can do.  (That should make obvious the intimate connection to Computer Science, and where much of the confusion comes from.)  A programmer (relative to an environment and language) should be able to take virtually any set of algorithms and transform them into a form both human- and machine-readable by writing code.  A strong background in programming (as most CS degrees will provide) enables you to write better code -- where 'better' code is more easily understood by others and more successful in expressing the algorithm you are implementing.

There is a large amount of crosstalk, of course, and a high level of experience in one will correspond strongly with developing experience in the other -- as noted, a CS major is almost always a competent programmer, and a seasoned programmer has picked up many principles of CS.  Think Physics and Engineering.

A good way of remembering the difference is this:  if it requires a computer to see if it works it's programming -- if you can do it with pencil and paper, it's Computer Science.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答: "That's not the way I would have done it"</p>

LastEditorDisplayName: Roger Pate


答:
I think more than anything else, it's the similarity of the thought process used that makes the two seem so similar.

For example, both are extremely logical. If you follow the same set of steps or same formula, you'll always come up with the same result. For example, 1+1 will always be equal to 2, and set a = 1 means a will always be 1 (until you set it to something else)

Another example is the need to think spatially. In mathematics, I found I often had to hold numbers in my head and visualize what I was doing. As a very simple example, I would break down math problems so that something like 13x13 becomes 13x10 + 13x3, which is much easier for my brain to work with, and I need to keep track that 13x10=130 + 13x3=39, so 130+39 = 169. This same ability to visualize something not visible, or break down a problem into smaller problems is often applied to programming.

So I feel that although you do not need to have a mathematical background to program, where math is defined as performing calculations with numbers, you do need to have similar thought process and understanding as what you would use when solving math problems.


问:
What Use Cases are Appropriate for JScript.NET?
In this Stack Overflow question:

https://stackoverflow.com/questions/9471332

I learned that Jscript is not dead after all. Yay!

But what is JScript.NET good for?

According to this article, you can use it to provide C# with an Eval function.  That's neat, but it seems like kind of an edge case.

If you were after first-class scripting capability, doesn't PowerShell fit the bill?

答:
From JSCript's Wikipedia:

JScript .NET can be used for ASP.NET pages and for complete .NET applications, but the lack of support for this language in Microsoft Visual Studio place it more as an upgrade path for classic ASP using classic JScript than as a new first-class language.

JScript.NET would allow one to write a server side website in something that resembles Javascript. It can allow what the *nix community has with Node.js (server side javascript) on Windows servers (yes I know that there is a Windows port of Node).

If you were after first-class scripting capability, doesn't PowerShell fit the bill?

The thing is, JScript.Net creates an executable file. So you could write a full-fledged program in it and deploy it rather than just a script with PowerShell. Granted, I don't know of anybody who would want to do that, but apparently Microsoft believes there is at least a handful that do.


问:
Scrum: Handling lack of motivation
According to this, "Scrum highly relies on a highly motivated, closely collaborating, cross-functional and self-organized teams."  So how do you handle co-workers who may not be as motivated to take ownership of the code?  How do you get someone interested in taking ownership?</p>

答:
By giving them individual ownership over the code.

Many shops work on a "team ownership" model. This is great for cross-collaboration and reducing risk, but not so great for motivating individuals to be personally responsible. Team ownership can result in average code, because there's no individual ownership incentive.

Solution: Assign individuals to each section of the code to be stewards of that part of the code, but allow full team access to the entire code base.

See also: https://softwareengineering.stackexchange.com/a/33464/1204

Title: Scrum: Handling lack of motivation


问:
As a software engineer, who should I be following on Twitter?
Who in the software engineering and software development fields uses Twitter to tweet about relevant happenings in the field?</p>

答: Twitter Top 100 for Software Developers </p>

Body: Twitter Top 100 for Software Developers


问:
Not-for-profit universities that offer computer science undergraduate degree online?
There are many masters degree programs in computer science online offered by reputable organizations. However, I've found very few bachelors only degree programs offered by non for-profit institutions.

I am looking for a degree in computer science and also any programs for entrepreneurship/management or algorithmic trading.

I've found only 2 programs so far that fit:

http://www.regis.edu/regis.asp?sctn=cpcis&p1=ap&p2=cs&p3=ol

http://depaul.edu

Requirements:

100% online undergraduate non-profit

Options: Bachelor of Science Bachelor of Arts

Bonuses: accelerated recognized ABET cost effective

Update:
I've answered my question with a list. If anyone knows an online program that combines skills in entrepreneurship (getting capital, starting a business) or algorithmic trading with a computer program that would be ideal.. maybe too much to ask though

答:
I ran across TUI International Online University which I thought looked promising. It's based in California and accredited.

The University of California will test a fully-online program, but as the article says, "it's unclear when students could enroll."

Other possibly useful resources for you:

Online Degree Reviews

Along with seeing what students think of their schools, you can also search for schools and programs

California Virtual Campus Catalog

Lets you search for online programs by degree and subject.


答:
I use NaturalDocs.  The advantage (and I presume the name) stems from the fact that it infers formatting mostly from spacing, and not from tags.  You don't have to decorate your comments with a lot of <method> and things like that, making the comments much more readable "in the wild".

A NaturalDocs comment would look something like:

```<code>/* Function:  my_method
 *
 * Accepts a Turing machine and an infinite data tape, and determines
 * whether it will halt.
 *
 * Parameters:
 *   turing_id - The ID of a valid Turing machine.
 *   tape_ptr  - A pointer to the start of the inifite-length tape.
 *
 * Returns:
 *   If the machine halts, returns 0.  If the machine doesn't halt,
 *   return value is undefined.
 */
extern int my_method(turing_id_t turing_id, void *tape_ptr);
</code>```

NaturalDocs would take that and generate an HTML file with an appropriate signature, description of the method, table-formatted list of parameters, and any additional sections (Returns here).  It will also generate a table of contents defaulting to organizing by file.  You can also group things by types other than Function (such as Types, Macros, and so forth).

I may sound overenthusiastic, but when we changed to NaturalDocs it knocked a huge amount of boilerplate out of our headers and made them look much more ... (cough) ... natural.

Title: Generating code documentation

Body:
I want to generate code documentation in a simple format.  The key items are Method Signature, members, constructors, methods.  I am taking various applications in .NET and creating documentation for them.  I will be adding notes to each item.  The end result should look similar to MSDN or Java API documentation.

So, I want to take my source code and have some kind of template generated that I can append notes to.  I want to pick and choose certain classes and not others across various applications.

I'm not talking about intellisense documentation.  This documentation will be used for reference outside of visual studio.  AFAIK, that's all the XML comments are good for in .NET.

I'm documenting various interfaces and entry points for writing extensions for a 3rd party application.  We do not own their code, so I can't just go in and append XML comments to their interfaces, classes etc.  Instead, I need to implement the interface and comment it up.  Then document it on the web.  Documentating each implementation just to explain their architecture is redundant.  They do not document their stuff...that's the core issue here.

Is there any tool that can assist with this process?  What do you suggest?

Body:
I use NaturalDocs.  The advantage (and I presume the name) stems from the fact that it infers formatting mostly from spacing, and not from tags.  You don't have to decorate your comments with a lot of <method> and things like that, making the comments much more readable "in the wild".

A NaturalDocs comment would look something like:

/* Function:  my_method
 *
 * Accepts a Turing machine and an infinite data tape, and determines
 * whether it will halt.
 *
 * Parameters:
 *   turing_id - The ID of a valid Turing machine.
 *   tape_ptr  - A pointer to the start of the inifite-length tape.
 *
 * Returns:
 *   If the machine halts, returns 0.  If the machine doesn't halt,
 *   return value is undefined.
 */
extern int my_method(turing_id_t turing_id, void *tape_ptr);

NaturalDocs would take that and generate an HTML file with an appropriate signature, description of the method, table-formatted list of parameters, and any additional sections (Returns here).  It will also generate a table of contents defaulting to organizing by file.  You can also group things by types other than Function (such as Types, Macros, and so forth).

I may sound overenthusiastic, but when we changed to NaturalDocs it knocked a huge amount of boilerplate out of our headers and made them look much more ... (cough) ... natural.


问:
Why are Python strings allocated on the stack?
According to this Python code visualizer, Python strings are allocated on the stack and not on the heap.

Why is this? I thought they would be similar to Java where Strings are allocated on the heap.

答:
That visualizer is not showing the string data on the stack. It is showing the local references to the heap data as part of the call stack. This is very similar to Java where String references are local variables that point to actual String objects on the heap.

The visualizer is free to make any kind of representation simplification it cares to. It does not imply that "Python strings are allocated on the stack" in any given implementation of Python.


答:
This is often called polyglot code - there are some fun/insane examples if you follow the link or in various other places on the web. Most of these are just for fun / to prove it is possible.

More seriously, there are various real life examples where two or more different languages can be usefully combined:

Web templating - languages such as PHP or JSP files mix code into HTML. Opinions differ widely on whether this is a good idea or not.

Macro languages - often a macro language is mixed into the source file such as C/C++ preprocessor macros. There are also interesting cases like Lisp where the macro language is itself Lisp (the only difference is whether the code is run at compile time or runtime)

DSLs - often a domain specific language is defined to help solve a particular problem effectively, which is embedded into the source code of another language. Here's an example of a beautiful DSL for SQL which can be embedded in Clojure code.

Scripting - some dynamic languages are particularly useful for short scripts and are designed to be embedded within software written in another language. Groovy scripts for example are very easy to embed within a Java application.

Polyglot projects - sometimes it makes sense to use multiple languages just to exploit the different capabilities of each. For example, the JVM supports multiple languages that can interoperate fairly transparently, so you might mix Java (for speed and statically typed OOP) with Clojure (for interactive development, concurrency and functional programming). Such projects still typically separate the different languages into separate source files/folders, but they are compiled at the same time to produce a single application.


答:
This is built into .Net by using the following syntax

```<code>/// <summary>
///  This class performs an important function.
/// </summary>
public class MyClass{}
</code>```

and then use a codeplex project called SandCastle

Sandcastle produces accurate, MSDN style, comprehensive documentation by reflecting    over the source assemblies and optionally integrating XML Documentation Comments.

XML Comments on MSDN: http://msdn.microsoft.com/en-us/library/b2s063f7.aspx

SandCastle: http://sandcastle.codeplex.com/

Title: Generating code documentation

Body:
This is built into .Net by using the following syntax

/// <summary>
///  This class performs an important function.
/// </summary>
public class MyClass{}

and then use a codeplex project called SandCastle

Sandcastle produces accurate, MSDN style, comprehensive documentation by reflecting    over the source assemblies and optionally integrating XML Documentation Comments.

XML Comments on MSDN: http://msdn.microsoft.com/en-us/library/b2s063f7.aspx

SandCastle: http://sandcastle.codeplex.com/


问:
How is the "Infinite Monkey Theorem" different to use than Genetic Programming to solve problems?
This might be a little open ended, but I heard an explanation of this talk on how GP could be used to fix bugs, and I wonder: How does this differ from the infinite monkey theorem?</p>

答:
GP relies on "evolution", whereas the Infinite Monkey Theorem is just random chance.
In GP, you have one or more fitness indicators which are used to evaluate a generation of possible solutions to "breed" to create a new generation. Each one, more than likely, getting a better and better solution.
IMT has more to do with enough candidates that eventually every combination will occur.</p>


问:
What features in Eclipse is not available in Visual Studio?
I have done much development in Java using Eclipse, and now I have started to use Visual Studio for .NET development. So far I find the IDEs to be able to do the same things, but just different.

What features in Eclipse isn't available in Visual Studio?

答:
You don't have anything like Maven available to you in visual Studio.

Maven is a complicated beast to master, but once you've got it working it is incredibly powerful - it basically takes away all the pain of build scripts and dependency management.


问:
What is a reasonable number of threads for a Java program?
In Java (or probably most other languages targeting the JVM) what is a reasonable number of threads to use? Presumably, this will be expressed as a ratio to the number of cores/processors available, is that correct?

At least initially, it seems like twice as many threads as cores might make sense, but 20+ times as many seems unreasonable. Is the ratio likely to be affected by the type and/or architecture of the software? Are there types of software and/or situations in which a much larger number of threads really makes sense?

[And yes, I know that's phrased as a number of separate questions, but I think they're closely enough related for a single answer to cover all of them, since they're all really about how many threads make sense under what circumstances.]

答:
Lots of comments, but no answer, yet. Here's a quick stab...

I would say that it depends on what your threads are doing. You can have hundreds of threads, but if the vast majority of them are just waiting, they won't incur much overhead. On the other hand, if you are doing computation, I would limit the number of threads to the number of cores. You won't get any extra pure computation speed from scheduling more. In addition, in these cases, you may want to look into task parallelism as an alternative.

If your code is a mix of waiting and processing, the answer is less clear. Aside from various strategies you can take to speed things up, your best bet in this case is to do profiling to find an optimal number.


答:
The infinite monkey theorem relies on the vastness of an infinite number of anything. An infinite number of monkeys bashing at keyboards randomly will instantaneously generate not only Shakespeare but every work ever written and every work ever to be written an infinite number of times. Including what the monkeys just typed. (How does a set contain itself you ask? It's infinite).

Genetic programming takes a large number of workers (far less than infinite) and selects the best candidates based on the fitness of their output. These workers are then mutated and allowed to run again the survivors of the next generation selected based on fitness.

Interestingly enough there is an IMT simulator that uses genetic programming to get better and better breeds of monkeys each generation. After running for 10k generations it could output the first 18 lines of Hamlet from what I remembered.

Title: How is the "Infinite Monkey Theorem" different to use than Genetic Programming to solve problems?

Body: This might be a little open ended, but I heard an explanation of this talk on how GP could be used to fix bugs, and I wonder: How does this differ from the infinite monkey theorem?</p>


答:
There are a lot of reasons for a lack of motivation, but probably the most common is not feeling like you have a say.  When our team started doing scrum I noticed that the least motivated people about scrum turned around after they saw their suggestions from the retrospectives get implemented.

A bunch of minor issues can add up to be demotivating.  For example, one thing that came up last week was a team member who didn't like 4:00 meetings.  That's easily fixed.

In other words, the best way to find out what is demotivating your team is to ask them.

Title: Scrum: Handling lack of motivation

Body: According to this, "Scrum highly relies on a highly motivated, closely collaborating, cross-functional and self-organized teams."  So how do you handle co-workers who may not be as motivated to take ownership of the code?  How do you get someone interested in taking ownership?</p>


问:
Servicing background tasks on a large site
We're dealing with an interesting problem on StackOverflow.

We've got a whole bunch of little "needs to be done soon-ish" tasks.  An example is updating "Related Questions" lists.  What we've done in the past is to piggy-back those tasks onto some users' page loads.

This was never ideal, but it wasn't really noticeable.  Now that SO has passed the 1,000,000 question mark, those unlucky users are starting to feel it.

The natural solution is to actually push these tasks into the background.  There are two broad ways of doing this I'm considering.

1. In IIS as a custom Thread-Pool/Work-Queue

Basically, we spin up a few (non-ThreadPool, so as to not interfere with IIS) threads and have them services some collections we're shoving Funcs into.

The big pro here is simplicity.  We don't have to worry about marshaling anything, nor do we have to make sure some external service is up and responding.

We also get access to all of our common code.

The con is, well, that we shouldn't use background threads.  The objections I know of are all centered around starving IIS (if you use ThreadPool) and the threads dieing randomly (due to AppPool recycling).

We've got existing infrastructure to make the random thread death a non-issue (its possible to detect a task has been abandoned, basically), and limiting the number of threads (and using non-ThreadPool threads) isn't difficult either.

Am I missing any other objections to in IIS process thread-pooling/work-queues?

Moved to StackOverflow, as it wasn't really addressed here.

2. As a Service

Either some third-party solution, or a custom one.

Basically, we'd marshal a task across the process boundary to some service and just forget about it.  Presumably we're linking some code in, or restricted to raw SQL + a connection string.

The pro is that its the "right way" to do this.

The cons are that we're either very restricted in what we can do, or we're going to have to work out some system for keeping this service in sync with our code base.  We'll also need to hook all of our monitoring and error logging up somehow, which we get for free with the "In IIS" option.

Are there any other benefits or problems with the service approach?

In a nutshell, are there unforseen and insurmountable problems that make approach #1 unworkable and if so are there any good third-party services we should look into for approach #2?

答:
I'd do it the right way and have a Windows Service running that monitors a "queue".  I say "queue" because programming w/ MSMQ is akin to sticking hot pokers in your eyeballs.

I've fallen in love with the simplicity of Delayed::Job in Rails, and something similar could easily be done in .NET.

Basically you add any sort of SomethingOperation (something that has an Perform() method).  Then just serialize the relevant parameters, give it a priority, some sort of default retry behavior and stuff it into a database.

Your service would just monitor this and work the jobs in the queue.


问:
Github Organization Repositories, Issues, Multiple Developers, and Forking - Best Workflow Practices
A weird title, yes, but I've got a bit of ground to cover I think.

We have an organization account on github with private repositories.  We want to use github's native issues/pull-requests features (pull requests are basically exactly what we want as far as code reviews and feature discussions).  We found the tool hub by defunkt which has a cool little feature of being able to convert an existing issue to a pull request, and automatically associate your current branch with it.

I'm wondering if it is best practice to have each developer in the organization fork the organization's repository to do their feature work/bug fixes/etc.  This seems like a pretty solid work flow (as, it's basically what every open source project on github does) but we want to be sure that we can track issues and pull requests from ONE source, the organization's repository.

So I have a few questions:

Is a fork-per-developer approach appropriate in this case?  It seems like it could be a little overkill.  I'm not sure that we need a fork for every developer, unless we introduce developers who don't have direct push access and need all their code reviewed.  In which case, we would want to institute a policy like that, for those developers only.  So, which is better?  All developers in a single repository, or a fork for everyone?

Does anyone have experience with the hub tool, specifically the pull-request feature?  If we do a fork-per-developer (or even for less-privileged devs) will the pull-request feature of hub operate on the pull requests from the upstream master repository (the organization's repository?) or does it have different behavior?

EDIT

I did some testing with issues, forks, and pull requests and found that.  If you create an issue on your organization's repository, then fork the repository from your organization to your own github account, do some changes, merge to your fork's master branch.  When you try to run hub -i <issue #> you get an error, User is not authorized to modify the issue.  So, apparently that work flow won't work.

答:
I would not do all the forking and branching for everything.
That is a good model for open source gems on github, but your model is within a organization that would normally have a higher level of trust about changes.

A major point of source control is that you can see, backout, reverse, etc. changes. Doing a high number of forks and branches in your situation is overkill IMHO.

I would reserve branches for things like: version upgrades, changing one of the technology pieces, working on a submodule for 3 months that has little in common with the main base.

I might not fork at all within an organization.  That mode seems more suited to open-source projects which are different in nature to in-house ones.

I would switch your focus to testing and code reviews.  Are folks writing tests? Are they good? Are code reviews done?


答: Examples of combining languages: Jython (python in Java), Cog (python used as an embedded code generator in pretty much anything). I've often used Perl code to generate C++, if you count code generation. </p>