问:
If an object should be flagged, should it be built with the flag attribute?
Let us assume I have a basic object with a handful of self-relevant points of data.

```<code>class A(object):
    def __init__(self, x, y, width, length):
        self.x = x
        self.y = x
        self.width = x
        self.length = x
</code>```

And so we go on to instantiate several A objects and shove them into a list, as programmers are wont to do.

Now let us assume that these objects need to be checked for a particular state every so often, but we needn't check them on every pass, because their state doesn't change particularly quickly. So a checking method is written somewhere:

```<code>def check_for_ticks(object_queue):
    for obj in object_queue:
        if obj.checked == 0 and has_ticks(obj):
            do_stuff(obj)
        obj.checked -= 1
</code>```

Ah, but wait - it wasn't designed with obj.checked attribute! Well no big deal, Python is kind and lets you add attributes whenever, so we change the method a bit.

```<code>def check_for_ticks(object_queue):
    for obj in object_queue:
        try:
            obj.checked =- 1
        except AttributeError:
            obj.checked = 0
        if obj.checked == 0 and has_ticks(obj):
            do_stuff(obj)
</code>```

This works, but it gives me pause. My thoughts are mixed, because while it's a functional attribute to give an object and it solves a problem, the attribute isn't really used by the object. A will probably never modify its own self.checked attribute, and it isn't really an attribute that it 'needs to know about' - it's just incredibly convenient to give it that attribute in passing.

But -- what if there are multiple methods that might want to flag an object? Surely one does not create the class with every attribute that some other method might maybe want to flag it for?

Should I be giving objects new attributes in this way? If I should not, what is the better alternative to just giving them new attributes?

答:
One method is to create a companion class that has the checked attribute in it with the primary object using the Delegate pattern. However, that means that your lists need to be lists of companion objects and not the primary objects.

In practice, adding a flag or state attribute isn't necessarily a big deal. However, it tends not to scale well.

The method you are using is possible in Python and a couple of other interpreted languages. It makes me feel icky inside, so I understand your discomfort.


问:
Algorithm for detection of overlapping between vectors
I am currently developing a math-physics program and I need to calculate if two vectors overlap one another, the one is vertical and the other is horizontral. Is there any fast algorithm to do this because what I came up so far, has a lot of repeats. Eg lets say we have vector V1((0,1),(2,1)) and a V2((1,0),(1,2)) where the first parenthesis is the coordinates starting and the second coordinates that the vector reaches. I want as a result to take that they overlap at (1,1)

So far the only idea I came up is to ''expand'' each vector to a list of points and then compare the lists e.g for V1 its list would be (0,1) (1,1) (2,1)

答:
Terminology nitpick: those aren't vectors: vectors have a direction and size, but there is no “starting point” in a vector space. instead, you're defining a line segment via the starting and ending point of this line segment.

Given these two points A and B on the line, we can calculate the direction D = B - A of the line. The line segment we are interested in consist of all points P that fulfill the following equation:

```<code>P = A + k·D,
</code>```

where k is some scalar value in [0, 1]. When you have transformed all your inputs into this form, it's fairly straightforward to find solutions where the lines overlap:

```<code>           P1 = P2
=> A1 + k1·D1 = A2 + k2·D2
=>         0 = (A2 - A1) + (-k1·D1 ) + k2·D2
</code>```

This is essentially a system of linear equations, which can be solved if we have two or more dimensions. (We have to solve for the two variables k1 and k2). There are three possible outcomes:

no solutions exist (remember also the 0 <= k <= 1 constraint), i.e. the line segments do not overlap.

exactly one solution exists, i.e. the lines touch in one point (e.g. by intersecting each other)

there is an infinite number of solutions. This means that the lines are parallel and lie in each other for more than one point.

ContentLicense: CC BY-SA 3.0

Body:
Terminology nitpick: those aren't vectors: vectors have a direction and size, but there is no “starting point” in a vector space. instead, you're defining a line segment via the starting and ending point of this line segment.

Given these two points A and B on the line, we can calculate the direction D = B - A of the line. The line segment we are interested in consist of all points P that fulfill the following equation:

P = A + k·D,

where k is some scalar value in [0, 1]. When you have transformed all your inputs into this form, it's fairly straightforward to find solutions where the lines overlap:

           P1 = P2
=> A1 + k1·D1 = A2 + k2·D2
=>         0 = (A2 - A1) + (-k1·D1 ) + k2·D2

This is essentially a system of linear equations, which can be solved if we have two or more dimensions. (We have to solve for the two variables k1 and k2). There are three possible outcomes:

no solutions exist (remember also the 0 <= k <= 1 constraint), i.e. the line segments do not overlap.

exactly one solution exists, i.e. the lines touch in one point (e.g. by intersecting each other)

there is an infinite number of solutions. This means that the lines are parallel and lie in each other for more than one point.


问:
Scrum: Baseline story for point estimation
To estimate PBIs you need to choose an average story and assign it a number of points (for example 5). Then you compare all other stories to that story and assign points accordingly. My question is, are you really supposed to compare every single story to that original story from the beginning of the project? If not, then how do you make sure your scale remains more or less consistent throughout the project?

Thanks.

答:
Story points are subjective; always.  What a '5' means to you may mean something else to another team member.  As your team grows and gains more experience after each sprint, you get an understanding of how the rest of your team members view a '5'.  Every sprint, you'll get a better understanding, and therefore a better estimate.

There is no need to make sure your scale remains consistent, it will happen naturally.

You could compare it to average tasks from the last sprint.  You don't need to utilize that "base-line" story every single time, especially as your team evolves.


答:
Having a "checked" member of your object directly couples your object and algortihm.  Sometimes this is acceptable, because there is a natural coupling between them.  In the case of a garbage collection algorithm, most have a few flags on each object because there are a fixed set of operations that will occur on the object.

If you are looking for a way to do the same thing without coupling, consider using a set object.  Python's sets are fast (they use hashes), so generally it is safe to do it

```<code>checked = set()
...
if obj not in checked:
    checked += obj
</code>```

In python, this is actually just as fast as having an attribute on the object.  In a strongly typed language like C++, it is likely that the attribute would be faster, but I have found few cases in real life application where that speed difference mattered enough.

Title: If an object should be flagged, should it be built with the flag attribute?

Body:
Let us assume I have a basic object with a handful of self-relevant points of data.

```<code>class A(object):
    def __init__(self, x, y, width, length):
        self.x = x
        self.y = x
        self.width = x
        self.length = x
</code>```

And so we go on to instantiate several A objects and shove them into a list, as programmers are wont to do.

Now let us assume that these objects need to be checked for a particular state every so often, but we needn't check them on every pass, because their state doesn't change particularly quickly. So a checking method is written somewhere:

```<code>def check_for_ticks(object_queue):
    for obj in object_queue:
        if obj.checked == 0 and has_ticks(obj):
            do_stuff(obj)
        obj.checked -= 1
</code>```

Ah, but wait - it wasn't designed with obj.checked attribute! Well no big deal, Python is kind and lets you add attributes whenever, so we change the method a bit.

```<code>def check_for_ticks(object_queue):
    for obj in object_queue:
        try:
            obj.checked =- 1
        except AttributeError:
            obj.checked = 0
        if obj.checked == 0 and has_ticks(obj):
            do_stuff(obj)
</code>```

This works, but it gives me pause. My thoughts are mixed, because while it's a functional attribute to give an object and it solves a problem, the attribute isn't really used by the object. A will probably never modify its own self.checked attribute, and it isn't really an attribute that it 'needs to know about' - it's just incredibly convenient to give it that attribute in passing.

But -- what if there are multiple methods that might want to flag an object? Surely one does not create the class with every attribute that some other method might maybe want to flag it for?

Should I be giving objects new attributes in this way? If I should not, what is the better alternative to just giving them new attributes?

Body:
Having a "checked" member of your object directly couples your object and algortihm.  Sometimes this is acceptable, because there is a natural coupling between them.  In the case of a garbage collection algorithm, most have a few flags on each object because there are a fixed set of operations that will occur on the object.

If you are looking for a way to do the same thing without coupling, consider using a set object.  Python's sets are fast (they use hashes), so generally it is safe to do it

checked = set()
...
if obj not in checked:
    checked += obj

In python, this is actually just as fast as having an attribute on the object.  In a strongly typed language like C++, it is likely that the attribute would be faster, but I have found few cases in real life application where that speed difference mattered enough.


答:
I've seen examples where that works well, but it's mostly for PODs that are dynamically populated by other code, say as a result of a REST or database query.

Usually, when you want to reach into another object's data, that's a sign your responsibilities are in the wrong classes, or could use some rearchitecting.

My first thought in your particular case is to create a separate queue for unchecked objects, and modify whatever code enables has_ticks to also put the object into the unchecked object queue.  That would have the side benefit of not having to cycle through every single element even when most or all of them don't need checking.

Another option is tobias_k's comment about creating a dict in the object queue that maps the object to a checked value.

Another option is in the internal representation of the queue, store an [A, checked] as each list element instead of just A.

Another possible approach is the Decorator Pattern, by which you create a wrapper that adds the functionality you want.  Then you can wrap it when you put it into the queue and unwrap when you dequeue it.  The decorator has the advantage that you can move a lot of the functionality of your check_for_ticks function into your CheckedA object, or other functionality that really belongs with the element objects instead of the queue.  The wrapper class might look like:

```<code>class CheckedA(A):
    def __init__(self, wrappedA):
        self.wrappedA = wrappedA
        self.checked = 0

    def check_for_ticks(self):
        if self.checked == 0 and has_ticks(self.wrappedA):
            do_stuff(self.wrappedA)
        self.checked -= 1
</code>```

Another option is just calling do_stuff directly whenever a tick is added, if your requirements allow for it.

Creating an attribute from outside the class adds coupling, and even worse, that coupling is invisible to anyone reading the source code of the class.  You have no protection against someone else doing the same thing and using the same name in an incompatible manner.  You have lots of other options before you need to resort to that kind of solution.

Body:
I've seen examples where that works well, but it's mostly for PODs that are dynamically populated by other code, say as a result of a REST or database query.

Usually, when you want to reach into another object's data, that's a sign your responsibilities are in the wrong classes, or could use some rearchitecting.

My first thought in your particular case is to create a separate queue for unchecked objects, and modify whatever code enables has_ticks to also put the object into the unchecked object queue.  That would have the side benefit of not having to cycle through every single element even when most or all of them don't need checking.

Another option is tobias_k's comment about creating a dict in the object queue that maps the object to a checked value.

Another option is in the internal representation of the queue, store an [A, checked] as each list element instead of just A.

Another possible approach is the Decorator Pattern, by which you create a wrapper that adds the functionality you want.  Then you can wrap it when you put it into the queue and unwrap when you dequeue it.  The decorator has the advantage that you can move a lot of the functionality of your check_for_ticks function into your CheckedA object, or other functionality that really belongs with the element objects instead of the queue.  The wrapper class might look like:

class CheckedA(A):
    def __init__(self, wrappedA):
        self.wrappedA = wrappedA
        self.checked = 0

    def check_for_ticks(self):
        if self.checked == 0 and has_ticks(self.wrappedA):
            do_stuff(self.wrappedA)
        self.checked -= 1

Another option is just calling do_stuff directly whenever a tick is added, if your requirements allow for it.

Creating an attribute from outside the class adds coupling, and even worse, that coupling is invisible to anyone reading the source code of the class.  You have no protection against someone else doing the same thing and using the same name in an incompatible manner.  You have lots of other options before you need to resort to that kind of solution.


问:
How to prepare for rewriting an application's glue
Assume you have a project that (in your opinion) is mostly decently well written, modularized, etc. and you want to keep much of it's functionality. However, an essential portion of this project is not well designed, and it can't easily be fixed with minor changes. The only way to fix it is to rip out a lot of the code; it's not so bad that you need (or should) start from scratch, but it's very pervasive.

Assume that the code is something like 20,000 lines of non-whitespace, non-single curly brace, non-comment Java, C++, C#, PHP or Ruby code. You estimate about 2000-3000 lines need to be thrown out or changed. In the case of something like Java or C#, one of your packages/namespaces will probably be entirely rewritten from scratch, and many of the references to those classes will change.

Here's the challenging part: the code that needed to change was the GLUE within the system. Here's a very simple picture that summarizes the problem:

This is the situation I was in that led to this question: What should I do when I've already waited too long between commits?

As you can see, it's not only the parts of the code that were doing the internal processing, but also the parts that were communicating with the other parts of the system. Both the APIs and the internal data structures were insufficient. Attempting to keep both sets of APIs working for incremental changes would have been woefully redundant.

I, of course, branched before I did anything, but every change I made produced a product that simply did not work. In many cases I created compile errors. This led to me continually putting off commits, because I thought "yes, I wired these pieces back together, but I still need to implement this other new interface, write this essential functionality, etc." This resulted in the cardinal sin of not checking anything in, a mistake I'd prefer not to repeat should I be in this situation again. This was mitigated by the fact that all my APIs were internal, except that I had to conform to the APIs of the outside world and third party modules, but my wrappers to those sections were changing.

One obvious alternate solution would be to just accept the fact that each change will result in a broken overall product, but since you're checking into a branch, it's okay. Especially since I am the only developer working on this code and using these APIs. So maybe that's the right thing to do. Or maybe the right thing to do is try to first refactor the API to the new one, without actually changing the functionality (if possible), even if some arguments are dummy or will eventually be removed, and then incremental changes are a lot more self contained. Or maybe there's a better way entirely?

答:
It's important to know whether your product has been released or not, and whether the API you intend to touch is exposed in any way to other entities (modules, projects, products, documentation, etc) which are released separately.
If the answer to any of that is "yes", then you must preserve API compatibility in the transition phase. Rather than replacing the old API, extend it. In the second step, you can obsolete the old API and give the affected entities a chance to update. If you can verify that all relevant entities have stopped using the old API, only then you can remove it from your side. (Even if you have no external dependencies, it may still help your rewrite to use this same method).

That being said, a good approach to a major rewrite is to divide the work in smaller independent steps, as much as you can.

It's easy to fall into the trap of working on multiple ends simultaneously, but that usually tangles your commits one way or another - best case, you'll have to keep track of multiple branches and progressing features, that will need to be merged at some point; worst case, all new features are developed interleaved with each other, preventing you from making clean commits belonging to a single feature, or even preventing you from making any commits at all, because you keep having half-working or non-compiling features. It will also "help" you introduce all sorts of obscure interaction bugs, giving you a lot of trouble when trying to find the exact point of introducing the bug.

This is largely an exercise in mental discipline, and there is more than one approach to it. You could start by stubbing out the new API and documenting intended purpose and API details. Once that's done, you have a stable commit point. Then, you can move to implementing individual features and unit tests (and you are able to commit multiple times along the way). Lastly, you modify the modules which call your new API, and do all the "glue" work. This order will help you have stopping points where you can commit without breaking the build.

Again, this is just one way, not the only way. Your purpose is to modularize your rewrite and minimize interactions between changes.


答:
Put simply: Don't boil the ocean.

In other words, break off little, manageable chunks instead of trying to do the entire thing at once. In one branch. Without regular checkins.

I've always liked this article at Joel on Software. It gives very good concrete examples about the kind of small changes that can be made against a code base to make it cleaner little by little.

Decide on a conceptually similar chunk of changes, and make a branch for that. An example might be moving all of your SQL code into classes. In that branch, your workflow would look like this:

Remove one SQL statement

Run your tests

Check in your code

Repeat

Once you've finished that chunk of changes, merge it into your master branch, and start a new chunk.

This is assuming you have tests. If not, you should create them before you start (including unit, regression, and integration tests). Again, not all at once. If you have a function you want to refactor that you don't have tests for, write the tests, refactor your code and run the tests until they pass. This is exactly what these tests are built for. Make sure you're making use of them.

Title: How to prepare for rewriting an application's glue

Body:
Assume you have a project that (in your opinion) is mostly decently well written, modularized, etc. and you want to keep much of it's functionality. However, an essential portion of this project is not well designed, and it can't easily be fixed with minor changes. The only way to fix it is to rip out a lot of the code; it's not so bad that you need (or should) start from scratch, but it's very pervasive.

Assume that the code is something like 20,000 lines of non-whitespace, non-single curly brace, non-comment Java, C++, C#, PHP or Ruby code. You estimate about 2000-3000 lines need to be thrown out or changed. In the case of something like Java or C#, one of your packages/namespaces will probably be entirely rewritten from scratch, and many of the references to those classes will change.

Here's the challenging part: the code that needed to change was the GLUE within the system. Here's a very simple picture that summarizes the problem:

This is the situation I was in that led to this question: What should I do when I've already waited too long between commits?

As you can see, it's not only the parts of the code that were doing the internal processing, but also the parts that were communicating with the other parts of the system. Both the APIs and the internal data structures were insufficient. Attempting to keep both sets of APIs working for incremental changes would have been woefully redundant.

I, of course, branched before I did anything, but every change I made produced a product that simply did not work. In many cases I created compile errors. This led to me continually putting off commits, because I thought "yes, I wired these pieces back together, but I still need to implement this other new interface, write this essential functionality, etc." This resulted in the cardinal sin of not checking anything in, a mistake I'd prefer not to repeat should I be in this situation again. This was mitigated by the fact that all my APIs were internal, except that I had to conform to the APIs of the outside world and third party modules, but my wrappers to those sections were changing.

One obvious alternate solution would be to just accept the fact that each change will result in a broken overall product, but since you're checking into a branch, it's okay. Especially since I am the only developer working on this code and using these APIs. So maybe that's the right thing to do. Or maybe the right thing to do is try to first refactor the API to the new one, without actually changing the functionality (if possible), even if some arguments are dummy or will eventually be removed, and then incremental changes are a lot more self contained. Or maybe there's a better way entirely?


问:
How can I refactor client side functionality to create a product line-like generic design?
Assume the following situation similar to that of Stack Overflow: I have a system with a front-end that can perform various manipulations on the data (by sending messages to REST back-end):

Posting

Editing and deleting

Adding labels and tags

Now in the first version we created it well modularized but the need as of now for 'evolving' the system similar to Stack Overflow. My question is how best to separate the commonality and how to incorporate the variability with respect to the following:

Commonality:

The above 'functionalities' and sending/receiving the data from the server

Look and feel (also a variability as explained below)

HTTP verbs associated with the above actions

Variability:

The RESTful URLs where the requests are sent

The text/style of the UI (the commonality is analogous to Stack Overflow - the functionality of upvotes, posting a question remains the same, but the words, the icons, the look and feel is still different across sites)

I think this is entirely a client-side code organization/refactoring issue. I'm heavily using jQuery, javascript and backbone for front-end development.

My question is how best should I isolate the same to be able to create multiple such aspects to the tool we are currently working on?

答:
It sounds like you have created a web application in a similar way to content management systems (CMS) are designed. In CMS systems like DotNetNuke (DNN) You have a service (often called portal or site) configuration that allows you to setup DNS, DB, Styles/skinning against each instance of the application running. The code modules (your commonality) remains the same, but each "instance" includes a setting that inject skins (CSS + images) and base URL's and DB storage locations.

Invariably you need to decide how your/customers will want to configure those features and that will dictate how you store and retrieve the settings (your variability).  I suspect you have already identified the variability parts and its just a case of refactoring the solution to allow those parts to be stored/retrieved just like any other part of your application.

OwnerDisplayName: Nupul


问:
How do you version your files (Version Numbers)
I wonder how do you decide on the version number of your apps, do you really record down all changes made (for a change log)? Then how will you decide how to increment the version number. eg. +0.0.1 for each bug fix or something, +0.1 for each new feature release? or maybe you bundle many changes into +0.1 of your version number?</p>

答:
Major.Minor.Revision

Major. Big change, new features, breaks compatibility, stuff you want to charge extra for.

Minor. New features that you can give away. Doesn't break stuff.

Revision. Bug fixes.

ContentLicense: CC BY-SA 2.5


问:
Should we be using git branches or separate repositories?
So I have talked my employer into finally jumping on version control...up until now my experience with git has been for personal projects and freelance work where everything is on one server, or small scripts...so, this is a bit above my knowledge.

We are going to have 3 web-servers… test, staging, production. We are going to use beanstalk (like github) which will store our repositories remotely and beanstalk will deploy to our servers via sftp (or ssh or whatever we decide). Inside our htdocs folder we have a drupal multi-site install, and we have a bunch of stuff outside of drupal (landing pages, etc...). We would like to have all of our htdocs (except images, file folders, etc...) inside of version control.

Should we use one repository with multiple branches? Or 3 separate repositories, each with one branch since they will be deploying to 3 separate servers?

答:
As the code is going to be the same or versions of the same code, it would be healthier to have a single repository and several branches, one for each purpose. If you are in doubt on which branching scheme to use, there are many proposals out there (i.e. git flow).

As with git is so easy to port stuff from one branch to the other and back in the same repository, having separate repositories will give you a lot of headaches.

Additionally, you can have two branches on a repository that have completely different content, like for example the Bootstrap project: their code is on master branch and the github documentation pages are on another one.

And with Amazon Beanstalk you have to specify the branch you want to push to each environment, to this won't be a problem.

Git is so flexible you'll love it.


答:
I have been involved in more than one targeted rewrite.  Before you begin writing any more code you need to do some analysis:

What is different from the well designed pieces and the poorly designed pieces?

Can the poorly designed code be reworked to match the same design structure as the good code?

Identify all the touch points to the poorly designed code.  I.e. what methods are called, how are they called (i.e. object instances or singletons, etc.)

How many of those touch points can you eliminate safely?

Identify any interfaces you can use to isolate the exposure of the bad code from the good code.

From all that raw data think real hard about what your end result should look like.  You need to know when you are done, or when the rewrite is good enough to give you a quality product without the need to scrap every single line of code.

Break down the work into tasks you can work off one at a time.

Estimate how long each task will take.  If you can't really give a good estimate then the task probably needs to be broken down more.  Include time for automated and/or unit testing.

Add up all the time you think each task you will take and triple it.  Seriously.  There will be hidden consequences of your redesign you have no way of anticipating at this point.

Limit your activities to only the targeted rewrite.  You don't have time for new features, nor do you have time to work on other parts of the code.

Execute your tasks one at a time.  Make sure each task is complete and tested before moving on.

I can say after my experiences with targeted rewrites that many times the resulting product was better and easier to maintain, but the schedule was the biggest problem.  If you have limited time to get this work done, a rewrite will make your project a lot later than you initially think.


问:
What should I do when I've already waited too long between commits?
I was naughty... Too much "cowboy coding," not enough committing. Now, here I am with an enormous commit. Yes, I should have been committing all along, but it's too late now.

What is better?

Do one very large commit listing all the things I changed

Try to break it into smaller commits that likely won't compile, as files have multiple fixes, changes, additional method names, etc.

Try to do partial reversions of files just for appropriate commits, then put the new changes back.

Note: as of right now I am the only programmer working on this project; the only person who will look at any of these commit comments is me, at least until we hire more programmers.

By the way: I am using SVN and Subclipse. I did create a new branch before doing any of these changes.

More information: I asked a separate question related to how I got into this situation in the first place: How to prepare for rewriting an application's glue

答:
You're the only programmer; just do a single massive checkin detailing the important bits of what you did.

Are you likely to roll back "parts" of what you did? If not, then absolutely proceed with option 1.

There are a couple of reasons to check code into a version control system. And ALL of them, when you're the only developer, revolve around safety - namely, if you screw up, the machine dies or whatever, you can always get back to that last checkpoint.

A programmer coming into the project later is unlikely to want to roll back to a version that doesn't compile. So, IMHO, option 2 is lunacy.

Option 3 sounds like such a time sink, that if I was your boss and saw you wasting hours doing this, I'd have a little talk with you about what your time is worth.

To iterate: by checking in your code you are covering/saving your butt in case of failure on your machine. Everything else, on a one-man team, is window dressing.


问:
Large number of projects for a single application
I'm working on 300K line C/C++ Windows application that is spread across 23 different Eclipse projects (approximately one third for Qt interface, one third for DLLs and one third for static libraries).

I have complained to the project manager that it's cumbersome to work with so many different projects for one single piece of software. For example, if I change one thing at a static library, I will probably have to recompile at least 5 other projects.

Am I right to complain or is this how most similar projects are managed? Is there any reference on how it should be done?

答: Instead of focusing on the number of modules, it's more important to look at whether or not the responsibility of each of these projects/modules are well defined. Talking to previous designers/developers will certainly help.</p>


问:
How to really understand programming?
I have started to learn to program. I am interested in it and dont mind how long it takes to learn. But I am using books to start out and I find that there are some things I get and some things I have no idea.

I can understand the code when I see an example but I feel completely lost if I were to go out and do something on my own. I have barely any experience: maybe 20 or so hours, which I understand is absolutely nothing.

When does everything come together?

What are some best ways to learn that anyone else has found?

Are there any good projects people have done that have been a great learning experience?

答:
How do you learn to swim? By swimming.
How do you learn to program? By programming.

You can't learning to swim by just reading books, nor can you learn to program by just reading books (not to say reading is not important, it is important, in addition to practicing).

So start writing simple programs as much as you can, there are a lot of exercises on the internet.

Title: How to really understand programming?


问:
Coding standards for c#
I wanted to know if there are some default standards for writing c# code. By default I mean may be something officially from Microsoft, or any other organization.

I am looking for something where I can find answers to questions like following:

should I do this:

```<code>public void DoSomeThing(int id)
{
    //method body
}
</code>```

or:

```<code>public void DoSomeThing(int id) {
    //method body
}
</code>```

should I do this:

```<code>Car car = new Car();
</code>```

or:

```<code>Car car =
    new Car();
</code>```

should I declare my variable in camel or pascal case, should I declare input parameters in method signature camel or pascal, should the global variable be prefixed with underscore or internal variable be prefixed with underscore ...

all these kind of questions ... any suggestions?

The actual issue is, I work on two projects for two different companies. and both have exactly opposite standards. I want to convince either of those and my self that such and such is the right way, because of such and such reason.

I know there is no one right way, but still any defaults documented from any leader organization would help. Thanks.

答:
The IDesign coding standard is widely respected.  It sounds like your question is geared toward style, but in my opinion, a good coding standard should also include a "coding convention".  That is, things you should or should not do to avoid language specific pitfalls.

Check out the IDesign standard; it has both of the above (style & convention).  You can learn a ton just by reading through the thing.

Also, this question is a possible duplicate of this post.

Title: Coding standards for c#


问:
Is refactoring for the purpose of unit testing a code smell?
Let me preface this question by saying that I get the need for unit testing. I painfully get it. You have to do it to ensure that future modifications don't adversely affect the application in ways you did not expect. It's also good practice to utilize a test driven methodology to ensure your current modifications work as expected while providing a solid testing base for adding edge cases (bugs) later. I also understand that testing is a requirement for any company that will, or plans to be, subject to an IT audit. And finally, I get that if your code is testable, it is probably written using solid design principles.

The quandary that I have is that coding to an interface for the purpose of supporting unit testing alone, seems like a contrived complexity.

Take the case where you have a database application that does not have the requirement to be database agnostic. You've already coded a DAL that communicates with that database and BL that uses that DAL for persistence. Integration tests are in place with the current architecture that utilize a development database for test data.

To support 100% code coverage on unit tests you would now need to introduce interfaces for both the DAL and the BL, have concrete implementations of those interfaces, and use dependency or constructor injection to utilize those interfaces based on the context of the runtime.

Does that not introduce a contrived complexity? A side question I guess is where is the line drawn between unit and integration testing in these cases? It's certainly feasible that the data model can change and you'd want integration testing in addition to unit testing because it's clear that unit testing will succeed where integration testing can fail in that case.

答:
Yes, there is a catch-22 involved in some unit testing: to be able to test the code you have to sometimes change it. This is sometimes unavoidable.

As a rule of thumb, once you've crossed over into Data Access, it's not really a unit test any more. Think of a unit test as something that purely exercises your logic and internal data transformations, without doing any IO.

Which brings us back to the need for faking data access with interfaces and fake implementations.


答:
You should have unit tests for both your DAL and BL code.  The both portions of your code should work independently of each other and not depend on implementation details of the other.  Writing Unit Tests not only tests your code, but also is a tool to ensure that there is that separation of concerns.

It may seems like a large amount of work and overhead, but imagine 6 months down the road you database just isn't scaling like you hoped.  You decide to switch to a key value document store like reddis.  As long as your Reddis implementation fully implements the DAL interface and it passes all your unit tests you wrote for it, you can be extremely confident that switching out those classes should be without a hitch (ignoring data migration issues of course).

While it seems hard now, once you get the hang of writing code for unit tests, you will find it less of a chore and more of a tool for writing better code.  You will find your integration tests tend to be brittle and you will write them less and less.

I would argue that needing to refactor your code to support unit tests is a code smell, which is why we write them.

Title: Is refactoring for the purpose of unit testing a code smell?

Body:
Let me preface this question by saying that I get the need for unit testing. I painfully get it. You have to do it to ensure that future modifications don't adversely affect the application in ways you did not expect. It's also good practice to utilize a test driven methodology to ensure your current modifications work as expected while providing a solid testing base for adding edge cases (bugs) later. I also understand that testing is a requirement for any company that will, or plans to be, subject to an IT audit. And finally, I get that if your code is testable, it is probably written using solid design principles.

The quandary that I have is that coding to an interface for the purpose of supporting unit testing alone, seems like a contrived complexity.

Take the case where you have a database application that does not have the requirement to be database agnostic. You've already coded a DAL that communicates with that database and BL that uses that DAL for persistence. Integration tests are in place with the current architecture that utilize a development database for test data.

To support 100% code coverage on unit tests you would now need to introduce interfaces for both the DAL and the BL, have concrete implementations of those interfaces, and use dependency or constructor injection to utilize those interfaces based on the context of the runtime.

Does that not introduce a contrived complexity? A side question I guess is where is the line drawn between unit and integration testing in these cases? It's certainly feasible that the data model can change and you'd want integration testing in addition to unit testing because it's clear that unit testing will succeed where integration testing can fail in that case.


问:
Applying the Art Gallery problem to optimal sensor placement
I am trying to design an algorithm for optimal sensor placement in a given area.

After doing some research I found the Art Gallery Problem. However, this problem assumes that the guards can see all the way to the perimeter from their positions, which is not the case with sensors (sensors have a range). Is it possible to solve the optimal sensor placement problem by mapping it to an art gallery problem, and trying some recursive solution?

I would be grateful if someone could throw some light on this question or guide me to appropriate resource.

答:
As you correctly say yourself, the art gallery problem is not a good it because it doesn't have the notion of limited distance. It sounds like what you're trying to do can be mapped to the set cover problem. You can discretize the room into a set of places. For each place where you could put down a sensor, you can map it to the set of places that the sensor can sense. The question is then: what is the minimal number of such sets necessary to cover the whole room?

Given this mapping, you can use one of the many algorithms for set cover, for example the greedy algorithm (pick the set that covers the largest number of not-yet-covered places, iterate until everything is covered).


问:
Programs that claim they are not "multi-core" friendly
You see this phrase or similar kicked around from time to time, generally referring to a program that claims they were not designed to take full advantage of multi-core processors. This is common especially with video game programming. (of course a lot of programs have no concurrency and do not need it, such as basic scripts, etc).

How can this be? A lot of programs (especially games) inherently use concurrency, and since the OS is in charge of task scheduling on the CPU, then are these programs not inherently taking advantage of the multiple cores available? What would it mean in this context to "take advantage of multiple cores"? Are these developers actually forbidding OS task scheduling and forcing affinity or their own scheduling? (Sounds like a major stability issue).

I'm a Java programmer, so maybe I have not had to deal with this due to abstractions or whatnot.

答:
This is not a full answer. It is a cautionary tale.

One day I thought I would show the students in my concurrent programming course a parallel quicksort.  Quicksort ought to parallelize well, I thought. I used two threads.  Ran it on my single core computer. The results were:

14 seconds for a single-threaded version.

15 seconds for the 2-threaded version.

This was about what I expected.

Then I tried it on a newer, dual-core machine.

11 seconds for the single-threaded version.

20 seconds for the 2-threaded version.

The two threads shared a queue of remaining tasks.   It seems the fields of the queue object were being shuffled back and forth between one core's cache and the other's.


答:
100% code coverage is an impractical goal - let's face facts here, to get that coverage, quite a few tests are going to be the sort to cover the code but not test it. Worse, you're spending a lot of time to make tests that are unlikely to cause error, or have minimal impact if errors occur.

All database applications require database agnostic behavior - oh if I had a dollar for every time some said "oh, that isn't going to change". Sure, your database might not change, but what about licensing that code to 3rd parties? What about putting it on a mobile platform? What about putting it behind a web service? What about all the weird and interesting things we'll do in 5-10 years that you can't envision?

(IMO) Don't change your design for testability alone - and now to the meat of your question and the more contentious point I will make: You are absolutely right that testable code is probably well designed code. If you are going to refactor your code, don't do it to make the code more testable, make it to be better designed. Unit tests serve as a great proxy for alternative needs. If it's hard to test, it will likely be hard to reuse. But sometimes you make a trade off that things will be hard to use in exchange for performance, or a nice interface, or to simplify code... Don't make your production code worse in favor of your test code. The tests are there to serve you after all.

But do be cautious - the common case is that hard to test code means hard to reuse code, and well done refactoring will help your test code and your production code.


问:
Realistic time to learn new framework/API
I have my ideas, but I always feel that I'm overly pessimistic. So I'd like to hear more opinions.

How much time do you need to start coding using a new framework so that your code is production ready and not become a support nightmare later on for:

Say large scale frameworks:

```<code>ATL/MFC/STL/WTL/.NET/COM/BOOST
</code>```

And small scale frameworks/APIs:

```<code>MSXML/Silverlight/ADO/LIBXML/WIN32/OpenGL/DirectX/CUDA
</code>```

What are your estimates for both types, [from;to] for both senior/junior developers.

Any ideas on what can decrease the learning time say: Book>API doc, or Tutorials>Book

答:
Time and effort in learning a new skill set depends upon two things.

Transferable skills: We tend to overestimate these.

For example, I know jQuery but would like to learn YUI. In that scenario my knowledge of DOM, Javascript, CSS, Firebug, and HTML is all transferable knowledge. However, the structure, documentation format and usage of YUI will be completely unfamiliar to me. And this brings me to my second point.

The effort curve: I have come to understand it as somewhat like a normal distribution curve. Getting-to-know phase is not that steep, then doing something useful gets harder and harder and stays that way for a long time, we tend to underestimate this part.

For example, I can write a HelloWorld-type programs in ten new programing languages that I have never used before and will still have free time left in the day. This first phase is very misleading because of its high rate of learning, so beware. My recent experience of switching from ASP.NET MVC to Ruby on Rails made me think real hard about all this stuff. It took me almost a year to be productive in Ruby on Rails and that too after putting in lots of effort.

The frameworks you've mentioned are quite large. For example, in case of Silverlight you'll have to understand the ideology of code-behind, multithreading (which is a must in Silverlight), and WCF.

If you are a student, focus on your coursework first. Choose technologies advised by your professors. Time and energy is a limited resource. Too many students make the mistake of not concentrating on the boring core Computer Science courses and keep playing with hot technologies just for the sake of it. This interest lasts only for the first phase and once things starts to get difficult, they jump to another hot technology and it goes on.


答:
Some good answers here, but I would like to add something to answer this part of your question:

To support 100% code coverage on unit tests you would now need to
  introduce interfaces for both the DAL and the BL, have concrete
  implementations of those interfaces, and use dependency or constructor
  injection to utilize those interfaces based on the context of the
  runtime.

This depends on the way you have designed your DAL and your BL. A well designed DAL should allow objects could be created completely without a database, in-memory. And your BL should should not rely on getting its DAL objects from a database - the BL should use some approach like the repository pattern to retrieve any DAL objects. This will allow easy automatic testing for the DAL and the BL without adding interfaces for each and every DAL object - you will only need interfaces for your repositories (and repository mocks for your tests).

You could argue that this way you don't produce real unit tests this way for your BL, because you cannot test them in isolation from your DAL objects, but as long as your DAL objects are not much more than data containers, this is IMHO perfectly acceptable and a pragmatic compromise.

Does that not introduce a contrived complexity?

Your system will contain more pieces, so beeing more complex, but each piece is becoming less complicated - which will increase the overall evolvability of your system.


问:
Approach to coding algorithms to minimize rework
I find myself reworking my code quite a bit, especially when learning to write algorithms that involve keeping track of multiple attributes and labels.

I feel that having the pseudo-code written up, having a small numerical example worked out, and a few test cases is usually a good approach. Yet, I find myself making mistakes and reworking code constantly.

Is there a better approach or a structured methodology that I should follow? Greatly appreciate the advice.

答:
Yet, I find myself making mistakes and reworking code constantly. Is there a better approach or a structured methodology that I should follow?

Some decades ago some people believed that there would be a better methodology and called it "waterfall model". But nowadays its widely accepted that when trying to develop a non-trivial program, you will almost never "get it right" on the first shot - even if you are very experienced. There will be bugs, requirements and edge cases you overlooked at the first sight, performance considerations, necessary design improvements only getting visible when your program reaches a certain size, and some things more.

IMHO the key point for professionalism is learning to manage the changes. This starts with simple things like a priority list of open requirements, making some design considerations before coding (like the ones have described in your comment), the use of version control (to keep track of any changes), and it goes further with release planning, automatic tests (to make sure future changes don't break existing behaviour) and application of the SOLID principles.


问:
What programming language generates fewest hard-to-find bugs?
What language, in your opinion, allows the average programmer to output features with the least amount of hard-to-find bugs? This is of course, a very broad question, and I'm interested in very broad and general answers and wisdoms.

Personally I find that I spend very little time looking for strange bugs in Java and C# programs, while C++ code has its distinct set of recurring bugs, and Python/similar has its own set of common and silly bugs that would be detected by the compiler in other languages.

Also I find it hard to consider functional languages in this regard, because I've never seen a big and complex program written in entirely functional code. Your input please.

Edit: Completely arbitrary clarification of hard-to-find bug: Takes more than 15 minutes to reproduce, or more than 1 hour to find cause of and fix.

Forgive me if this is a duplicate, but I didn't find anything on this specific topic.

答:
One thing to take into account is the turn around time.

For the last five years or so, I've mainly developed web applications in java (JSF, Seam, etc.). Recently I got a new job, and we're using Perl (with Catalyst and Moose).

I'm way more productive in Perl, than I was in Java.

Not needing to compile and (hot)deploy, is one reason. I also find that writing use cases is easier, as it can be done in a more iterative way. And the frameworks in Java seem to be unnecessary complex, at least for the projects I've been involved in.

I guess the number of bugs in my Perl code is more or less the same as the number of bugs in my Java code, it might even be higher. But, I find et easier and faster to find and fix these bugs.


问:
Is a genetic algorithm a correct approach to this problem?
I am trying to calculate a set of items that produce the highest damage output in a video game. There are about 50 different items, of which you can choose 6. There are all sorts of conditions that each item creates. I am writing a small app in javascript that calculates your damage based on the items. Could I utilize a genetic algorithm to find out which item combinations are the strongest? Or is brute force acceptable for this size of a problem? Or is there another way?</p>

答: I think the question needs some more explaining.  If all that matters is choosing 6 items out of 50 that cause max damage, then  if you sort the items in descending order of damage capability and pick the top 6 - that will do.  However, I suspect that there is additional complexity associated with choosing these 6 items, i.e. maybe some cost associated with each item being chosen.  In that case, it looks like a knapsack problem and can be crunched quickly using dynamic programming, for the problem size you have described.  The knapsack problem is as follows: what is the optimal set of items (out of your 50 total) to carry in a knapsack to maximize benefit (in you case, damage) and stay under a certain cost (maybe total points available to choose items). In your case - if this number exceeds 6, then you can drop the least damage causing items until you get to exactly 6 items. Note, this will be an optimal solution.</p>


答:
There's a few things you can do to minimize rework still.

If you start with clean code, you won't need to clean it up.

If you write loosely coupled code, it won't need to impact as much code if you just need to touch up on a few things. Same applies to monster classes and and methods. Having it all one one place is sometimes handy, but not necessarily easy to edit.

You'll make less initial mistakes as you get more experience, and find better test cases from the start as well. For the rest, it's pretty much your normal developer's everyday life.

Title: Approach to coding algorithms to minimize rework

Body:
I find myself reworking my code quite a bit, especially when learning to write algorithms that involve keeping track of multiple attributes and labels.

I feel that having the pseudo-code written up, having a small numerical example worked out, and a few test cases is usually a good approach. Yet, I find myself making mistakes and reworking code constantly.

Is there a better approach or a structured methodology that I should follow? Greatly appreciate the advice.


问:
Is it a good practice to wrap collection in Java?
I came across a snippet like this, and find it's over engineering. Is it a good practice?

```<code>public class SchoolList extends ArrayList<School> {
}

public class School extends ArrayList<StudentList> {
}

public class StudentList extends ArrayList<Student> {
}

public class Student {
}
</code>```

Actually I prefer a straightforward option:

```<code>List<List<List<Student>>> schoolList;
</code>```

答:
It might be good practice, but only if there is something the new type can do that the Generic type couldn't.

Without context, it looks very much as if someone learned a construction that was necessary before generic types were invented and now keeps using it although it's no longer needed. After all, type-safe collection access is pretty much why Generics were invented in the first place!

But there might be corner cases and special uses where the extends actually makes sense. For instance, it can be tricky to pass a generically-typed variable to a method that expects vararg parameters. If that problem actually occurs, then having a self-defined type for common objects in your domain model might yield a benefit in readability that outweighs the extra definitions.


问:
What exactly is procedural programming? How exactly is it different from OOP? Is it the same as functional programming?
I am programming in Java in a very object-oriented (OO) style. OOP comes very intuitively to me, but I have very little knowledge about other kinds of programming.

What exactly is procedural programming? How exactly is it different from OOP? Is it the same thing as functional programming?

I used to think that all programming that isn't OO is procedural. But I'm starting to think this isn't true.

答:
OOP is nothing than a bit refined form of procedural programming, which again belongs to the greater family of imperative programming. Proof of that claim is that many C#/Java programmers tend to "do something" and prefer methods like:

```<code>void doThisAndThat(....) { ... do something ... }
</code>```

So, a program that consist of a bunch of void-methods (formerly known as procedures (sic!)) and code like:

```<code>doThis();
if (state is that) doSomethingElse();
doThat();
</code>```

is perfect procedural programming.

Body:
OOP is nothing than a bit refined form of procedural programming, which again belongs to the greater family of imperative programming. Proof of that claim is that many C#/Java programmers tend to "do something" and prefer methods like:

void doThisAndThat(....) { ... do something ... }

So, a program that consist of a bunch of void-methods (formerly known as procedures (sic!)) and code like:

doThis();
if (state is that) doSomethingElse();
doThat();

is perfect procedural programming.


答:
It depends. If you want to attribute domain behaviour to such collections, or if not all methods of an ordinary List would make sense on that collection, then I would see it as a good practice.

If anything, it communicates intent really well, but if that's the only reason to do it, then you could argue it's over engineered.

Title: Is it a good practice to wrap collection in Java?

Body:
I came across a snippet like this, and find it's over engineering. Is it a good practice?

```<code>public class SchoolList extends ArrayList<School> {
}

public class School extends ArrayList<StudentList> {
}

public class StudentList extends ArrayList<Student> {
}

public class Student {
}
</code>```

Actually I prefer a straightforward option:

```<code>List<List<List<Student>>> schoolList;
</code>```


问:
Is it substandard if I have multiple tables in my database yet there's no relationship at all?
I have multiple tables in my database. Some tables have relationship to others and some don't have. My friend told me that it is not advisable to have a table that is not related to others. Is it substandard if I have multiple tables in my database yet there's no relationship at all? Are there guidelines concerning to database table relationships?

And also, what are the guidelines in cascading tables?
thanks.

答:
No it isn't. I could name you many kinds of tables that are useful without being references by other tables. Just from memory:

system parameters that control installation-specific settings on the software

traits that record important update milestones which have already happened

event traces logged to comply with legal requirements, but not used within the application (the law only requires that it be technically possible to reconstruct certain events, not that you code a module for doing that within your software)

key words or tags entered by users - not the ones actually attached to user content items (those would be references by the items), but a list of all occurring tags, used for suggested auto-completions when users tag new items

data that are regularly imported from external services, e.g. daily exchange rates: your application uses them, but obviously has no way if influencing them or even relating them to anything (that is the job of economy advisors, not of business software engineers)

Of course, the typical domain model will have many tables that reference each other, since models are all about structure, which is usually expressed as relationships between different entity types. But that doesn't mean you should artificially seek for relationships where there are none just to satisfy such a simplistic heuristic.


答:
Usually, you just use the existing JDK API. Why? Let me give you some feedback on your code:

```<code>public class School extends ArrayList<StudentList> {
}
</code>```

or, in other words: a schools IS-A list of list of students(list of groups/classes?). What really is a school?

A school is an institution. You can find students inside(HAS-A), rooms, proffesors and more. It is obvious that if you want to redesign the above piece of code, you will end up writing:

```<code>public class School {
  private List<Student> students; // or list of list? your choice
}
</code>```

Also, if you look at the public methods, you will have an addAll method, with Collection<StudentList> as argument. A School IS-A list of StudentList (your implementation), so you can do this:

```<code>School s1 = ...;
School s2 = ...;
s1.addAll(s2);
</code>```

Do you find the above code logical? I simply cannot imagine a School adding another School :) An addStudents method seems more appropriate, like this:

```<code>s1.addStudents(s2.getStudents());
</code>```

This line speaks for itself: students will go to another school next year :)

You should extend/implement the current classes/interfaces only when you feel it doesn't suit for you. Imagine a circular list, the iterator should move to the first element at the end of the list. I don't know any circular list implementations in the JDK API, so I am forced to implement my own, I have no other choice. You do.

Body:
Usually, you just use the existing JDK API. Why? Let me give you some feedback on your code:

public class School extends ArrayList<StudentList> {
}

or, in other words: a schools IS-A list of list of students(list of groups/classes?). What really is a school?

A school is an institution. You can find students inside(HAS-A), rooms, proffesors and more. It is obvious that if you want to redesign the above piece of code, you will end up writing:

public class School {
  private List<Student> students; // or list of list? your choice
}

Also, if you look at the public methods, you will have an addAll method, with Collection<StudentList> as argument. A School IS-A list of StudentList (your implementation), so you can do this:

School s1 = ...;
School s2 = ...;
s1.addAll(s2);

Do you find the above code logical? I simply cannot imagine a School adding another School :) An addStudents method seems more appropriate, like this:

s1.addStudents(s2.getStudents());

This line speaks for itself: students will go to another school next year :)

You should extend/implement the current classes/interfaces only when you feel it doesn't suit for you. Imagine a circular list, the iterator should move to the first element at the end of the list. I don't know any circular list implementations in the JDK API, so I am forced to implement my own, I have no other choice. You do.

ContentLicense: CC BY-SA 4.0


答:
Extending generic containers usually doesn't make sense for anything which represents a business object.

```<code>public class School extends ArrayList<Student>
</code>```

In this example, a school is an ArrayList of Students. But is that everything a school is? What do you do when business requirements meant the school gets more attributes, like an ArrayList<Teacher> or an ArrayList<ClassRoom>?

It's much better when classes don't extend the container which represents their data. Instead of that, classes should be composites containing the container(s) which contain their data:

```<code>public class School {
     private List students;
     private List teachers;
     private List rooms;

     // methods for accessing and manipulating the above lists
}
</code>```

But are there cases where extending collections makes sense? Yes, it does, when you want a more advanced container. There was one time where I needed a map which was able to tell which changes were made to it. So I created a public class LoggingHashMap extends HashMap<Object, Object> which was overriding all mutator methods to also create an entry in a private journal and also had a method for getting and resetting that journal.

Body:
Extending generic containers usually doesn't make sense for anything which represents a business object.

public class School extends ArrayList<Student>

In this example, a school is an ArrayList of Students. But is that everything a school is? What do you do when business requirements meant the school gets more attributes, like an ArrayList<Teacher> or an ArrayList<ClassRoom>?

It's much better when classes don't extend the container which represents their data. Instead of that, classes should be composites containing the container(s) which contain their data:

public class School {
     private List students;
     private List teachers;
     private List rooms;

     // methods for accessing and manipulating the above lists
}

But are there cases where extending collections makes sense? Yes, it does, when you want a more advanced container. There was one time where I needed a map which was able to tell which changes were made to it. So I created a public class LoggingHashMap extends HashMap<Object, Object> which was overriding all mutator methods to also create an entry in a private journal and also had a method for getting and resetting that journal.


答:
It is a good practice to replace something like List<List<Map<String, Integer>>> with a domain specific class. But in almost all the cases the best way to do is by aggregation not inheritance. This has some advantages:

no tight coupling with the superclass

you can choose what methods to expose; you may not want to use all the methods from ArrayList

you do not violate encapsulation

In general it is bad to extend collections; if you want to have List functionality then you should still use aggregation for functionality and implement the List interface. For more details about this see Item 16 in Effective Java 2nd edition by Joshua Bloch.

In your case, instead of

```<code>public class School extends ArrayList<Student> {
}
</code>```

use

```<code>public class School {
    private List<Student> list;
}
</code>```

or if you need List functionality:

```<code>public class SchoolList implements List<Student> {
     private List<Student> list;
}
</code>```

Body:
It is a good practice to replace something like List<List<Map<String, Integer>>> with a domain specific class. But in almost all the cases the best way to do is by aggregation not inheritance. This has some advantages:

no tight coupling with the superclass

you can choose what methods to expose; you may not want to use all the methods from ArrayList

you do not violate encapsulation

In general it is bad to extend collections; if you want to have List functionality then you should still use aggregation for functionality and implement the List interface. For more details about this see Item 16 in Effective Java 2nd edition by Joshua Bloch.

In your case, instead of

public class School extends ArrayList<Student> {
}

use

public class School {
    private List<Student> list;
}

or if you need List functionality:

public class SchoolList implements List<Student> {
     private List<Student> list;
}


问:
How to write camel case for words like "phonenumber", "motorcycle", "wavelength", etc
I am having a problem in understanding how to apply camelCase syntax to some of my variable names.

For example, how should I correctly write a word like "phonenumber" in camel case?  Is it phoneNumber or phonenumber?  Similarly with "username", is it username or userName?

I think it doesn't look right with camel case like motorCycle, passWord, sunDay, setUp or waveLength since these are just one word each. I think that could be why it's called hashMap but also hashtable in camel case without the capital in the last case because hashtable is one word while hash map is two words.

But if the motorcycle has a color then would it be motorcycleColor since a word is concatenated?  Is that correct or should it be phoneNUmber, waveLength, sunBlock and even sunDay for the Sunday of the week?

Why for instance is the method called getISOCountries while it says HttpHeaders e.g. it's not clear what becomes lowercase if we have a method like String camelCaseString = dog.toCamelCase() or interface CamelCase.

Related: https://english.stackexchange.com/questions/889/when-should-compound-words-be-written-as-one-word-with-hyphens-or-with-spaces

答:
Insure consistency within the code file.

Promote consistency within the code project.

Prefer consistency within the code library.

The compounding of words to represent concepts changes as we become more familiar with a given agglutination.

For example...

'telephone set' became shortened to just 'telephone'

'telephone' became shortened to just 'phone'

'phone number' was sometimes contracted into 'phone-number'

'phone-number' soon became 'phonenumber'

'phonenumber' is often further shortened to just 'phone'

'cellphone', or just 'cell' are in common usage today

'homephone', and 'workphone' may soon become common as well

Note that the StackExchange spell-checker can't make up its its mind. 'Phonenumber' at the end of the sentence above was fine but it flags the one at the beginning of the sentence (capitalized or not).

As much as most everyone desires there to be "one right way" to do things, when it comes to language, that can never be. By the time you finish your project, usage will probably have changed. Certainly your understanding will have changed and the functionality of the method/et.al. will probably have changed too. (In which case, you should probably change the name appropriately.)


问:
Trouble understanding the COCOMO model
In the basic COCOMO Model which is used to estimate the development time of software

Effort : a * KLOC^b  = X person months

Development time : c * Effort^d =  Y months

where a , b , c , d are constants derived from the table below depending on the type of your software project

Question 1

Assuming X = 10 , Effort will be equal to 10 person months.

Does 10 person months mean that the effort required to complete this project will be 1 month if we have 10 people working on it

OR

Does 10 person month mean that the effort required to complete the project will be 10 months if we have 10 people working on it.

Question 2

Do the constants have any SI units like the SI unit of Effort is person months

I am confused by the terminology

答:
Ten person months means that one person can do the job in ten months, but also that ten people can do the job in one month. This is pure fiction. The following canonical example is politically incorrect, but is illustrative. It takes a woman nine months to have a baby. Nine women will not reduce this nine month interval one iota. Read The Mythical Man Month. You need to read this alongside of Boehm.

Cost estimation, done right, accounts for constraints such as that nine month interval between conception and birth. Done even better, you need to account for the random events that inevitably raise their ugly heads in a large software project. The state of the practice (not state of the art) in software project management is to account for known constraints and for the random nonsense that inevitably slows things down. Another name for this: Monte Carlo software cost estimation.

Addendum

Think of person months as the software equivalent of the kilowatt-hours that your electric company uses as the basis for your electric bill.

Suppose you land a contract to build ten widgets. Suppose this task is fully automated. Throw a switch on a one kilowatt appliance and one hour later, voila, you have a widget. The total effort for this job is ten kilowatt-hours (ten widgets times one kilowatt-hour per widget). You can get the job done in ten hours if you use one appliance, five hours if you use two appliances. Can you get the job done in one hour with ten appliances? Theoretically, yes. In practice, no. First you have to procure those extra appliances, and then you'll blow fuses when you turn all ten on at the same time. To make matter when you go to the local hardware store will be out of the size you need. You'll end up spending hours searching for that size fuse. You would have been better off using the two appliances you already have on hand.

Title: Trouble understanding the COCOMO model


答:
My rule is: No checkin without a serious code review. If I'm on my own, I'll have to review the code myself, but it will be reviewed. You seem to have an amount of code changes that someone else couldn't review, therefore you can't review it yourself (reviewing your own code is harder and requires more discipline, because you automatically make the wrong assumption that your own code is correct).

Everyone's totally unbreakable rule is: Never check in code that doesn't even build, and seriously avoid checking in code that doesn't work.

Solution: Copy your changed code, go back to the original point. Merge one change at a time into the original code, review it, test it, check it in. With the programming method you described, you are bound to find some serious bugs that way.

It's also a good way to train yourself good programming habits.

Title: What should I do when I've already waited too long between commits?

Body:
I was naughty... Too much "cowboy coding," not enough committing. Now, here I am with an enormous commit. Yes, I should have been committing all along, but it's too late now.

What is better?

Do one very large commit listing all the things I changed

Try to break it into smaller commits that likely won't compile, as files have multiple fixes, changes, additional method names, etc.

Try to do partial reversions of files just for appropriate commits, then put the new changes back.

Note: as of right now I am the only programmer working on this project; the only person who will look at any of these commit comments is me, at least until we hire more programmers.

By the way: I am using SVN and Subclipse. I did create a new branch before doing any of these changes.

More information: I asked a separate question related to how I got into this situation in the first place: How to prepare for rewriting an application's glue


问:
When changing a class/method and you already have passing unit tests, should you change then test or write a test then change?
Say I have a class with a single constructor that accepts 2 parameters and initialises itself using those parameters. I have written tests for this and they are all passing.

I later realise I need to make an addition to the constructor to accept three parameters. Should I

a) Add in the new parameter, watch my tests break and try and fix it

b) Rewrite existing tests to test for the new expected behavior, watch them initially fail and then add to the class (this to me seems a more TDD way)

From a TDD point of view, I think that option 'b' makes more sense. However, option 'a' (to me) seems like a more natural approach.

Is there any standard way that most people do this?

答:
Obviously, TDD says you should do (b).

Changes in method signatures pose the complication that in many languages the tests won't actually fail - they won't even compile! It is a matter of opinion whether this constitutes a 'failing' test for which, according to the strictest kind of TDD, you are allowed to write new code.

But the point of TDD is really to check that your API makes sense before programming it. If you have to change a lot of tests to add a parameter, you may notice that this is cumbersome, that it would be better to create a compound object for some of these parameters, or that you do need to be able to create objects without the new parameter after all! This is the real value of TDD (as opposed to merely guaranteeing test coverage), and that's why I would say go ahead and revise your tests first.


问:
What should I do when I've already waited too long between commits?
I was naughty... Too much "cowboy coding," not enough committing. Now, here I am with an enormous commit. Yes, I should have been committing all along, but it's too late now.

What is better?

Do one very large commit listing all the things I changed

Try to break it into smaller commits that likely won't compile, as files have multiple fixes, changes, additional method names, etc.

Try to do partial reversions of files just for appropriate commits, then put the new changes back.

Note: as of right now I am the only programmer working on this project; the only person who will look at any of these commit comments is me, at least until we hire more programmers.

By the way: I am using SVN and Subclipse. I did create a new branch before doing any of these changes.

More information: I asked a separate question related to how I got into this situation in the first place: How to prepare for rewriting an application's glue

答:
I think you are worrying far too much. If you're the only programmer and you don't have a spec sheet to work against then it's entirely up to you what you do. I assume nobody is going to punish you for making a large commit so the only issues you're going to run into are technological, such as not being able to roll back individual file changes within the commit. Since you're solely in control of the repo at this moment that shouldn't be a huge concern either though.

There's a line to be drawn between pragmatism and dogmatism. What you did would not be a good idea in a team and probably shouldn't be repeated going forward, but in your situation I would just submit the large commit.


问:
Software architecture which allows for growth, real life situation
I know of Interfaces, Abstract classes that serve as Base class, I've been reading up on loose coupling, ... But I can't come up with a decent solution when a property of a class changes, and the new type needs to be implemented in other classes using this updated class.

Example

Below is a simplified representation of a real life situation. Invoice contains a Contact object which has an Address property.

```
Abstract Class Contact{
    string Name{get;set;}
    string Address{get;set;}
}
```

```
Class Customer:Contact{
    string CustomerNumber{get;set;}
}
```

```
Class Invoice{
    string DocumentNumber{get;set;}
    Customer Customer{get;set;}
}
```

Next, we decide to upgrade the Contact class to contain multiple Addresses. Of which the Invoice will need one.

```
Class Address{
    string Street{get;set;}
}
```

```
Abstract class Contact{
    string Name{get;set;}
    List<Address> Addresses{get;set;}
}
```

Logically, the Invoice class needs to be changed to something like

```
Class Invoice{
    string DocumentNumber{get;set;}
    Customer Customer{get;set;}
    Address InvoiceAddress{get;set;}
}
```

Problem

You immediately see that everywhere I used the string property Address before, I will now have to change it to an occurence of the type Address

As stated before, this is just a simplified example. The real life problem would be much, much bigger as contacts will be used throughout the entire software.

Conclusion

I want to develop the software with a principle that will keep my software light for new versions of certain modules. So that if I decide to create a new Contact module, the impact to the other modules is close to non-existing. So, the added functionality can be implemented gradually.

I want to know how I can tackle such versioning problems. This project is currently still in the architectural design stage, and I want this sorted out before we continue.

答:
I want to develop the software with a principle that will keep my
  software light for new versions of certain modules. So that if I
  decide to create a new Contact module, the impact to the other modules
  is close to non-existing. So, the added functionality can be
  implemented gradually.

Design your class so that consumers are isolated from the changes, so:

```<code>class Contact {
  string Address {get; set;}
}
</code>```

would become

```<code>class Contact {
  List<Address> Addresses {get; set;}
  Address getAddress() { return Addresses[0].StreetAddressLine; }
}
</code>```

As stated before, this is just a simplified example. The real life
  problem would be much, much bigger as contacts will be used throughout
  the entire software.

Once you see a logical entity more than once across classes, consider extracting it into a class.  The change could have happened once you noticed that address was in both Contact and Invoice, and this would have been fixed before you needed to support multiple addresses.

Extract Class design pattern

I am very curious of the suggestions of other programmers / software
  architects, and how you tackled versioning problems like these in your
  projects. This project is currently still in the architectural design
  stage, and I want this sorted out before we continue.

If you wrote code, and then refactored it, you have moved past the design stage and into implementation.  Consider improvement in the following areas:

1) Designing small components that can be quickly implemented

2) Isolating other components from changes to this component

Do not design for theoretical changes, instead have a development cycle that is short enough to react to change.  If the design and implementation are fairly short, the process of making both the original code and the changed code would have been shorter than combining the two.

Body:
I want to develop the software with a principle that will keep my
  software light for new versions of certain modules. So that if I
  decide to create a new Contact module, the impact to the other modules
  is close to non-existing. So, the added functionality can be
  implemented gradually.

Design your class so that consumers are isolated from the changes, so:

class Contact {
  string Address {get; set;}
}

would become

class Contact {
  List<Address> Addresses {get; set;}
  Address getAddress() { return Addresses[0].StreetAddressLine; }
}

As stated before, this is just a simplified example. The real life
  problem would be much, much bigger as contacts will be used throughout
  the entire software.

Once you see a logical entity more than once across classes, consider extracting it into a class.  The change could have happened once you noticed that address was in both Contact and Invoice, and this would have been fixed before you needed to support multiple addresses.

Extract Class design pattern

I am very curious of the suggestions of other programmers / software
  architects, and how you tackled versioning problems like these in your
  projects. This project is currently still in the architectural design
  stage, and I want this sorted out before we continue.

If you wrote code, and then refactored it, you have moved past the design stage and into implementation.  Consider improvement in the following areas:

1) Designing small components that can be quickly implemented

2) Isolating other components from changes to this component

Do not design for theoretical changes, instead have a development cycle that is short enough to react to change.  If the design and implementation are fairly short, the process of making both the original code and the changed code would have been shorter than combining the two.


问:
Why should I use node.js as http server?
I know what node.js is & what it does.

What I really want to know is how does it work as an http server?

A server like apache gets a request, fork a process, allocate memory to process, handle the request & release the process after it is completed. If we get thousands of http requests at a time, then apache waits for the the process queue to release process.

How does node.js with a single threaded environment handles so many http requests. All the incoming requests are given their own event loop. All these event loops share same memory.

How does using node.js to handle millions of http requests more scalable than using apache?

答:
key point would be not forking a new process for each request,

node.js assumes your process is heavily IO bound (reasonable for a webserver with separate DB)

this means that each time you are waiting on the database to return the next result another request is being handled


答:
When a property of a class changes, you have to modify all callers who use that property. Its not possible to magically have an interface change that doesn't require changes to callers who use that interface.

However, you can isolate internal properties from  external interfaces - generally this is as simple as not using getters and setters. They are a true anti=pattern and should be avoided at all times. See, all you are doing by implementing a getter is exposing an internal variable using a method.There's little decoupling or hiding going on. Change the internal variable type.. and you have to change the getter too, which means you have to change all your clients. You might as well make all your members public and cut out the middleman. See this post for more detail.
If you provide true methods that get data from your class, then you can hide the internal variables. If invoice number changes from a string to an int, you can keep the old method that exposed the InvoiceNumber and cast it. Obviously this will not work in every case, but it can help hide the implementation from your callers.

The other thing you can do is implement multiple interfaces on your class, so that old callers can still call the old interface while new ones can access Interface2 or InterfaceEx or whatever.

Title: Software architecture which allows for growth, real life situation

Body:
I know of Interfaces, Abstract classes that serve as Base class, I've been reading up on loose coupling, ... But I can't come up with a decent solution when a property of a class changes, and the new type needs to be implemented in other classes using this updated class.

Example

Below is a simplified representation of a real life situation. Invoice contains a Contact object which has an Address property.

```
Abstract Class Contact{
    string Name{get;set;}
    string Address{get;set;}
}
```

```
Class Customer:Contact{
    string CustomerNumber{get;set;}
}
```

```
Class Invoice{
    string DocumentNumber{get;set;}
    Customer Customer{get;set;}
}
```

Next, we decide to upgrade the Contact class to contain multiple Addresses. Of which the Invoice will need one.

```
Class Address{
    string Street{get;set;}
}
```

```
Abstract class Contact{
    string Name{get;set;}
    List<Address> Addresses{get;set;}
}
```

Logically, the Invoice class needs to be changed to something like

```
Class Invoice{
    string DocumentNumber{get;set;}
    Customer Customer{get;set;}
    Address InvoiceAddress{get;set;}
}
```

Problem

You immediately see that everywhere I used the string property Address before, I will now have to change it to an occurence of the type Address

As stated before, this is just a simplified example. The real life problem would be much, much bigger as contacts will be used throughout the entire software.

Conclusion

I want to develop the software with a principle that will keep my software light for new versions of certain modules. So that if I decide to create a new Contact module, the impact to the other modules is close to non-existing. So, the added functionality can be implemented gradually.

I want to know how I can tackle such versioning problems. This project is currently still in the architectural design stage, and I want this sorted out before we continue.


问:
What is the best practice for method parameter validation in a library?
I develop a game library in javascript, containing many classes. I hesitate on the behavior that I should follow concerning method parameter validation:

Should I check the validity of parameters passed to each method ?

By example, when a method take only a number between 0 and 100 in parameter, should I check that the value is correct?

I have dozens of classes, each with dozens of methods. For a simple getter, I can have more than half lines code only used for checking parameters. Add checks makes my code less maintainable, more heavy.

Seeing that it's a library, destined to be used by many other programmers, checking parameters can avoid many mistakes and bugs, and would be a appreciated.

So, how do other javascript libraries, handle this and what is the best solution?

答:
Validate anything that you might consider "suspect", i.e. anything that comes from outside your own class.  Parameters to public methods?  They come from "Outside" so validate them.  Parameters to private methods?  Technically these are already "Inside" so there's less reason to do it again.  (Of course, you might be checking for different criteria at this level, so you might still have Good Reason to do so).

And have a consistent means of handling parameter "problems".  Some people like to throw Exceptions, others return null values from their methods.  YMMV.  Pick what works for you and stick with it.


问:
Why is my page load time so closely correlated with number of database queries?
Whenever I'm doing web development, and a page takes longer than half a second to be generated, I know that somewhere my code is hitting the DB too many times. The normal way to fix this situation is to ask the DB for all the information all at once instead, by doing JOINs and the like.

My question is: Why do many database queries make a page slow? There must be considerable overhead to each query, but what is it?

EDIT: Alright, let's take an example (it's a bit silly and small, but it'll do)

people table:

```<code>| name | football_team_id |
+------+------------------+
| jim  | 1                |
| mike | 3                |
| carl | 2                |
</code>```

football_team table:

```<code>| id | color |
+----+-------+
| 1  | red   |
| 2  | blue  |
| 3  | green |
</code>```

We all know that this is slow:

```<code>SELECT name,football_team_id FROM people;
# start rendering the page, realise we need colors
SELECT color FROM football_team WHERE id=1
# oops, need mike's color
SELECT color FROM football_team WHERE id=3
# oh, and carl's
SELECT color FROM football_team WHERE id=2
</code>```

This is a bit better:

```<code>SELECT name,football_team_id FROM people;
SELECT id,color FROM football_team WHERE id IN (1,3,2)
</code>```

This is best:

```<code>SELECT name,football_team_id,color FROM people JOIN football_team ON people.football_team_id=football_team.id
</code>```

In each example we're getting the same amount of data, but the latter is easily the fastest.

You wouldn't expect the same behaviour if you were reading from a file descriptor, for example.

答: Generally it's what we call "on-the-wire overhead".  In a lot of servers, the database is located on a different machine than the server app.  (This has scalability benefits, among other things.)  That means that any database call has to go over a network connection, and all results have to be pushed back over the network. The cost of that overhead, even if the machine is only sitting a few feet away from the one hosting the server app, can add up very quickly.</p>


问:
Shared source file between two parts of project
I have the following sort of directory structure:

```<code>part1
    build
    src
part2
    build
    src
</code>```

Now I have a header file that I would like to include in both parts of these projects, it will contain constants and some macro definitions as well as some utility functions, and I want these to be synchronized between the two parts. What would be the generally acceptable way to format my directory structure?

Something like so?

```<code>part1
    build
    src
part2
    build
    src
share
    src
</code>```

and set up my make files in the build directories to also look in ../../share/src

Or is there a more "correct" way of doing this?

答:
That's how I've done it in many projects.

Dare I say "self-documenting"?

It makes it completely clear to anyone looking at this what's going on.

And that includes you.

Imagine yourself going off to work on some other, completely unrelated project for three/ four years and then coming back to this one.  All those little snippets and assumptions and "understandings" that you work with day-in, day-out, today will all be long forgotten.  it'll be like coming to this code completely cold.  It's not nice finding hidden "nasties" in code, is it?  So; try not to leave any for yourself.


答:
Why do many database queries make a page slow?
  Why does a large number of anything make a page slow?

Do something once and it takes "some amount" of time.

Do the same thing a thousand times and yes; it's going to take [roughly] a thousand times as long.  There's no magic here.  Unless you start parallelising and multi-threading your programs, everything's going to get done "one thing after another".

Yes; getting a database connection and using it does have an overhead, although things like Connection Pooling serve to diminish the impact, but the more times you go to the database, the longer things are going to take.

Also, watch out for the amount of data you're pulling back.  "select *" seems to be making something of a comeback in the "Newbie" coding communities at the moment.  Great if your table has three columns and you want all three of them.  Not so good if you only want three columns but your tables as "somehow" acquired another twelve of them; all of them massive text fields!

(Remember; you're not the only user of "your" database).

Title: Why is my page load time so closely correlated with number of database queries?

Body:
Whenever I'm doing web development, and a page takes longer than half a second to be generated, I know that somewhere my code is hitting the DB too many times. The normal way to fix this situation is to ask the DB for all the information all at once instead, by doing JOINs and the like.

My question is: Why do many database queries make a page slow? There must be considerable overhead to each query, but what is it?

EDIT: Alright, let's take an example (it's a bit silly and small, but it'll do)

people table:

```<code>| name | football_team_id |
+------+------------------+
| jim  | 1                |
| mike | 3                |
| carl | 2                |
</code>```

football_team table:

```<code>| id | color |
+----+-------+
| 1  | red   |
| 2  | blue  |
| 3  | green |
</code>```

We all know that this is slow:

```<code>SELECT name,football_team_id FROM people;
# start rendering the page, realise we need colors
SELECT color FROM football_team WHERE id=1
# oops, need mike's color
SELECT color FROM football_team WHERE id=3
# oh, and carl's
SELECT color FROM football_team WHERE id=2
</code>```

This is a bit better:

```<code>SELECT name,football_team_id FROM people;
SELECT id,color FROM football_team WHERE id IN (1,3,2)
</code>```

This is best:

```<code>SELECT name,football_team_id,color FROM people JOIN football_team ON people.football_team_id=football_team.id
</code>```

In each example we're getting the same amount of data, but the latter is easily the fastest.

You wouldn't expect the same behaviour if you were reading from a file descriptor, for example.


问:
What is the most productive way to handle development-related failures?
We've all been there:

Your project failed or got cancelled.

The code you spent days working on got rejected by your team.

The design pattern you introduced to the team created chaos.

Everyone ignores your ideas.

My question is, what is the most productive way for a programmer to handle development-related failures such as these?

答:
Stay calm - don't panic, it won't make anything better

Damage control - save what can still be saved

Learn from your mistakes - doing the wrong thing again probably won't make it work

Consider a fresh start - start your next attempt without a backpack of disappointments and guilty feelings

Look at bigger failures - compared to Ariane 5's first flight, your failure is negligible

Consult a psychotherapist if you can't handle it alone


问:
Should I consider loosely-coupling for class methods as well?
I'm a fan of Dependency Injection, however I don't know how much both public and private methods inside a class should be loosely-coupled.

Just to picture it better, when I have both projectId and userId as private properties in my class, and both of them have their own decent setter methods which will do the input validation also -- throwing an error in case of unexpected input, then isn't it better that all the class' methods relies on these properties instead of getting them via method arguments' and repeat the whole validation, etc. again?

In this case the methods will tightly-bind to the class itself -- and probably the constructor as well, but the advantage is that all the methods can easily rely on the setter methods and they will always assume also that the proper data is always available for me to process -- because the setter should have thrown an exception otherwise.

This seems quite helpful to me and I can make all the classes and libraries loosely-coupled in a way they don't depend to each other, however my question is, can a method inside a class be dependent on the class properties itself or not? Is it considered as a bad-practice?

答:
If the methods of a class cannot depend on the variables of that class then who can? If all of your methods were completely decoupled from all other methods and variables, then all classes involved would be stateless and all methods might as well be static.

Of course there are always trade-offs when it comes to design, but I think it simply comes down to the idea of cohesion -- if your private properties increase the cohesion within the class (and if they are indeed always valid and ready to be consumed at all times), then yes, by all means use them, otherwise get rid of them.

(Whether or not you actually want to be using setters is another question entirely...)