答:
Rails has one serious performance problem: each request is queued up behind the currently active one, as opposed to threading them as most frameworks do or allowing blocking events to free other requests as the like of Node.js and Twister do. This means you have to code to make response times fast, but that's quite easy to do in most cases.

I think this is very misguided. You can run Rails in multithreaded mode. When running in multithreaded mode, you should only use IO libraries that release the GIL ( for example, 'mysql2' gem ) else it becomes sort of pointless.

If you are using jRuby, then you can just run a single rails process in multithreaded mode and fully utilize all the available CPU power. However, if you're on MRI ( Ruby 1.8.x or 1.9.x ), you must run multiple processes in order to fully utilize the CPUs, which is the case with node.js too.

Title: Ruby on Rails downsides and caveats


问:
Is it efficient to attach a comment on every function?
I moved to this company recently, and my first reaction of the development process leaves me with doubts.

Here is where I really doubt the efficiency:  Every single function must have Javadoc style comment, and the code is tested by White-box Test automatically.
Even when I write simple & short function, the function must have a Javadoc style comment.

For example:

```<code>void request_ait(void)
{
      hoa_request_ait();
}
</code>```

If I write code without a Javadoc style comment, even for this simple function, the QA tool register it as a defect.  So I write a simple comment template.

For example:

```<code>/**
  * @author peter
  * @version 1.0
  * @since   2011-08-28
  */
    void request_ait(void)
    {
          hoa_request_ait();
    }
</code>```

I know that comments on API functions or important functions are really useful. But forcing every function to have a Javadoc style comment is inefficient...

I want to listen your opinion.

Am I wrong?

答:
You might have to stick to the company policy or culture, too bad. But if you ask for opinions ...

Last time, I arrived into a huge project that had that policy. I had to comply, of course. But when I was given responsibility of a new project, I didn't choose the same policy. Every character your write may take some time, but more importantly every character will be read many times in the development activity (by many developers). Each line or character that is not useful is a pollution!

In most projects with a lot of documentation, maintaining it up to date costs a lot of effort (that means money also). Usually comes a time where it is not maintained (due to deadlines, lack of discipline from some people, forget, copy between branches...)(in a perfect world where it wouldn't happen, you might still be paying too much money for it, so it might not be optimal). Then other developers trusting the documentation will try to save time by not checking in the code, have errors and finally, after loosing a good deal of time, find that the documentation was wrong about the code. So after some time nobody trusts the documentation, so every has to go and check directly into the code. So mandatory documentation is useless, and even a liability (in case someone trusts an old documentation and have errors from this).

For these reasons, the documentation should be limited to a strict minimum.
As far as one can write an understandable code without documentation, fine.
When something requires a comment, then writing such an exceptional documentation item is a warning to all readers of that code, and taken seriously (read, and maintained). This is really useful documentation.

There is a saying that instead of documentating, you should make your code understandable. I agree, and I practice... I delete a lot of documentation in my projects :-)

Still, is there some conditions where you should document?
These are my policy:

Document more the big items (java project, then package, then class, then method, then parameter/return/throw), because as the granularity gets bigger :

it covers a bigger portion of your code

it changes less often

it is more complex

Document the omissions : when a code is not necessary, there is no code to make this understandable, so the meaning need to be carried by a comment.

Document the hacks : if you write a hack, it can't be as understandable as the code you would like to write. But why would you write a hack?

for performance reasons (after you have proved the performance problem)

when using a less than optimal foreign code (you can't modify it)

Introduction to the functionality : with a few sentences, if you can make your code more understandable to newcomers in that functional area, that's nice.
Of course, that probably wouldn't happen on methods, only on higher granularity. And it could be replaced by an external introductory document... But if your developers hate Word as much as mine, javadoc might be a good place for this.

Introduction to a technique : if you are writing sample code, or a code that will be an inspiration for beginners, explaining (possibly with links) the advanced language features or patterns might make them gain some time. This documentation must not be cut and pasted to other places (that would be pollution), it must remain unique.

OwnerDisplayName: sunglim

ContentLicense: CC BY-SA 3.0


问:
Are RSpec and Cucumber really worth it?
I know most RoR programmers are testing addicts and I understand the advantages of a large testing suite but when I start testing, I never get such a large suite and I always wonder "Am I testing the right way? Are there really efficient?". I'm often dealing with integration tests testing only the way the application behave.

First, is testing really worth it? I mean, is the time spent on writing tests really worth it?

Then, I use RSpec, I've recently discovered Cucumber, used it for a while but I don't know if writing all these steps is really worth the trouble? I know I can reuse steps but I never know if these steps are too complete or not: For instance, I've been using a Given I am logged in as (.+) but I don't know if I must say in its definition Given there's a user called $1 because it can duplicate the user if ever created but that's not worthwhile always having a step before Given I am logged in as (.+). It's quite a lot of code that will maybe rarely be useful. I guess there are not new bugs on the parts tested every day...
So is Cucumber really worthwhile compared to RSpec?

答:
Testing, in my opinion, is an art.  Doing TDD (using RSpec or any other framework) initially feels like you're "wasting your time."  This is understandable because you are not writing any production code.

However, you start seeing the benefit of TDD when you need to enhance your codebase while ensuring that everything else still works.  TDD helps you catch regression errors as early as possible.  Doing this has saved me days of work because I had focused tests which pointed out my errors.

Furthermore, having tests can be beneficial for code reviews because your reviewer can see what scenarios you are testing and how your code is meant to be used.

Once you get into the swing of TDD, doing anything else feels wrong.

Title: Are RSpec and Cucumber really worth it?


问:
Multitasking how to keep track of what you're doing
I'm in a long debugging task, I need to figure out where to hook up some extra functionality I need.

It's cumbersome work, and I've been debugging 2 whole days, and I'm on my third, but I work in multiple projects, and I'm returning to this after almost a week, and it's been hard to get back to the point I left at, and remember what was all this about, and what conclusions had I already arrived at.

How do you keep track of what you were doing/thinking in this kind of scenario where comments aren't actually the "right thing" to do? I do some comments in my testing code, plus some informative git/hg commit messages but that's kind of dirty.. written paper might be the answer...

答:
I'm not sure for you, but for me Automatic Tests (Unit tests if possible) are a good way of discovering how the code works, and knowing that it doesn't work as expected.

Automatic Tests replaces debugging, changing a memory-backed developer-checked knowledge and verification, to a file-backed explicitely-checked one.

When coming back to your work later on, you will be at the same point after a few seconds executing your tests, instead of trying to retrieve your context from old memories and replaying a long debug sequence (these last two activities may require written communication anyway as memory might not suffice ; then Automatic Tests would have no overhead).

I know, some projects are not easily testable automatically. We use TDD to solve that problem, gaining also many other advantages ....

If you already write some automatic tests, the same tests you write automatically track what you are thinking and verifying, so you probably need nothing else. When you finally found your bug, you can keep your test sequence ... or refactor it ;-)

Edit after comment :

Testing how a library works ! I call that learning tests.
Good that you do them :

they let you know exactly how the library is working.

they document that knowledge, for you later or for your team members

they may document the uses of that library, how it is used in your project
(in my Aeronautics experiences, the company policy mandated that each external code is controlled, knowing precisely what features are used, and documenting what would be the effect on our software if the library would stop working !)

they serve as a non-regression test when you upgrade your library


问:
How to get better at testing your own code
I am a relatively new software developer, and one of the things I think I should improve is my ability to test my own code. Whenever I develop a new functionality, I find it really difficult to follow all the possible paths so I can find bugs. I tend to follow the path where everything works. I know this is a well known issue that programmers have, but we don't have testers at my current employer and my colleagues seem to be pretty good at this.

At my organization, we do neither test-driven development nor unit testing. It would help me a lot but it's not likely that this will change.

What do you guys think I could do in order to overcome this? What approach do you use when testing your own code?

答:
In addition to all the other comments, since you say your colleagues are good at writing non-happy-path tests, why not ask them to pair with you on writing some tests.

The best way to learn is be seeing how it's done and pulling in what you learn from that.


问:
Are there pre-made commercial software licenses to choose from?
I currently have an open source project that is licensed under GPLv3.  I'd like to dual license it, so I can offer it for commercial use.  Are there any resources for choosing or creating a commercial software license?</p>

答:
I think Binpress' license generator is excellent:

Adjust the options below to fit your business needs.

Once you hit "Generate License" at the bottom, you will be given a unique address to your generated license.

If you leave an Email address and name, you can edit your license at any time (optional).

ContentLicense: CC BY-SA 4.0


问:
Java Vs .NET Vs Oracle(DBMS), Which technology is for Long Term Career?
I want to know about Which language is best for long term career and How?

Which language should I choose among Java and .NET Platform or Should I choose Oracle like DBMS Language (SQL/PLSQL)? I am confused?

Detailed answer would be appreciated.

答: Any technology that achieves a certain critical mass are guaranteed to be around for a while. All three of these are well in this category and even if for some reason they were canned tomorrow you would still find work for the next 10 years, time enough to retrain.</p>

ContentLicense: CC BY-SA 2.5


问:
What do you think of opening brace comments in source code?
I have developed a habit of writing comments in my code by putting the comments on the same line as the opening brace, after the brace. I've found that this saves vertical space. It also leaves a hint why something was done, but I'm wondering if it's readable for others.

Example:

```<code>void DoSomeInterestingImageManipulation(char *pImage)
{//This will convert the image to formatABC which allows x% space savings for storage
    if(pImage && pImage[0] == 0xFF)
    {//Process the extra case where image internal format needs decompression
        ++pImage;
        //...
        //...
        //...
    }

    //Proceed normally
    *pResult = Foo(pImage);
}
</code>```

Do you consider it easier to read or harder to read?

答: Although it's just my taste, I personally like the extra space (and the clear visual structure) I get from the opening brace. That's also why I always hated the brace directly after the if/loop/function head. And I also don't like comments in the same line as code, because it again violates the clear structuring a bit.</p>


问:
What percent of your college course work is unit-tested code?
As a college student do you write unit-test for the project code you write?  Do you know how to properly use TDD?  Have you been taught to use testing frameworks (jUnit for example)?

I've just recently heard that a major company's project team was delivering software to User Acceptance Testing group that had only 7% line code coverage for unit testing.  While that shocks me, it just tells me that this company's software engineering practice are immature.  However I wonder if they could just hire a few recent graduates and raise the bar on the teams practices - assuming that these newly minted programmers were trained in the best practices.

Are you 2008 - 2010 CS graduates using best practices of unit testing your code?

答:
(I graduated in 2008)

We learned ABOUT unit testing, and had to do so for some assignments in a class called "Team Software Project". The class was about software engineering practices. Other than that one class, it wasn't mentioned, but that class was required to get a BSc in Computer Science. The Computer Science department also offered a Software Engineering concentration that was more project-based, with classes devoted to testing, HCI, project management, etc. but still with a theoretical CS core.

OwnerDisplayName: David Koontz


问:
best practice when unit testing for embedded development
I am looking for some best practice strategies for unit testing code written for embedded system. By embedded system, I mean code such as device drivers, ISR handlers etc., stuff that are pretty close to the metal.

Most of the unit tests are not possible without testing it on the hardware with the aid of a ICE. Sometimes, the embedded unit also needs to be hooked up to other stimulus such as a mechanical switches, stepper motors and light bulbs. This usually occurs in a manual fashion, automation would be great but hard and expensive to achieve.

Update

I came across a C testing framework that seems to be quite successful in testing embedded projects. It uses the ideas of mocking hardware. Check out Unity, CMock, and possibly Ceedling.

Update 06Jul2016

Came across cmocka - seems to be more actively worked on.

答:
Edit : my answer is close to mattnz's, I think...

I want to relate this problem with others, all tests that depend on something external to your code (like the system clock, a persistent filesystem or a database, contacting an external web service ...). I suggest the same policy for all of them, isolate the two levels in two layers of code.

Testing a single external operation

You might want to physically test each operation. Check that the system clock gives the correct time, check a file actually remembers what has been written, check a device receives a single operation...

These tests:

should be as simple as possible: no algorithm whatsoever, no condition or loop

might be order-dependant and machine-dependant: so you need to follow a strict order, and repeat on each hardware

are mostly stable over the course of your project, so you don't need to run them that often

so running them manually is an option ; automation is even better, if not overly complex

Note that what is being tested is not your code, it is a tool that your code needs... So testing this might be optional for you, it might have been done by a different team...

Testing the logic (code, algorithm) that hooks together the external operations

By having a layer of code to make the actual external operations, by hiding them behing an interface that you can easily mock, your logic is not dependant on the actual physical devices anymore...

You can test simply, as any regular project, you are not in an embedded difficult-to-test code anymore.


问:
What determines when a computer is considered a "client"?
In web development the terms "server" and "client" are often refered to when discussing how pages are requested on the web. It is also used exstensively when talking about PC, phone, tablets, etc. The question that came to my mind was what qualified a computer to be considered a client?

I took a look at this article from wikipedia and noticed that clients are considered service requesters whereas Servers are considered service providers. If this is true couldn't all computers that request a service in a sense be considered a client?

The stereotype I noticed is that a client computer is usually synonymous with a "consumer" computer, but according to wikipedia this is not entirely accurate. Any idea on how to draw the line in this common scenario?

答:
That is true, servers are service providers. But a server has two meanings. It can mean, a computer that runs a server (software). Or a piece of software that provides content to a client.

So yes, a server (machine) can be both a content provider (server) and content consumer (client). If I'm running my website on an ubuntu box, when I request information from it, it is the server and I am the client. More specifically, if I visit a site hosted by that box, apache is the server, and my browser is the client.

A "server" can also be a client. In the case that I wanted to update the software on that box, I tell it to look at the ubuntu servers and request updated software, apt (or aptitude) is the client, and the ubuntu repositories are the server.


答:
Clients request data from servers.  Does this help?

Also, clients and servers are processes (in this context), not computers.  If you point your browser to http://localhost and serve a webpage from your machine, your computer acts as both client and server.  The client is your web browser; the server is Apache, NginX (or IIS), which serves the page.

Title: What determines when a computer is considered a "client"?

Body:
In web development the terms "server" and "client" are often refered to when discussing how pages are requested on the web. It is also used exstensively when talking about PC, phone, tablets, etc. The question that came to my mind was what qualified a computer to be considered a client?

I took a look at this article from wikipedia and noticed that clients are considered service requesters whereas Servers are considered service providers. If this is true couldn't all computers that request a service in a sense be considered a client?

The stereotype I noticed is that a client computer is usually synonymous with a "consumer" computer, but according to wikipedia this is not entirely accurate. Any idea on how to draw the line in this common scenario?


答: A computer is almost never just a server.  The sever/client question needs to be asked in the context of a particular service.  As an example, consider loading a webpage on your home computer.  In this case, you computer is acting like a client (requesting a service) and the computer serving the page is acting like a server (providing the http service).  However, the computer serving the page may also be a database client (asking for a db service) if it is requesting data from a database server.  And you home computer may also be acting as a fileserver, providing files to other clients on your home network.</p>


答:
Whether a machine is a client or server is applicable to 1 single request for data.  If I visit a webpage, my machine is the client and the machine hosting the site is the server.  If I then use my machine to run a web service, and someone else calls it, then my machine is a server and that other machine is the client.

The distinction is valid only for the given request.


答:
The client is usually considered the device that is in the hands of the end user.  Whether this be a computer, smart phone, kiosk, tablet, etc.  This is the client.

As far as other machines requesting information between the client and server(s), I would refer to these as tier(s) of the application.  This could be 2,3, or n tier architecture.  I wouldn't refer to these as clients.

More information can be found here:

http://www.pcmag.com/encyclopedia_term/0,2542,t=clientserver&i=39801,00.asp


问:
What has been your experience with SQL CLR for complex business logic?
So I thought I had a perfect use-case for a CLR SQL Procedure. I've search the Net for perhaps a similar example where data is retrieved, records added and updated. I have not looked at a SQL CLR procedure for awhile, but since it was released in 2005 (some 6 years ago!) I would have hoped there were plenty of examples!

I'm considering it because I have to look at some data, run it through a bunch of procedural logic, update, and then get it back to the client. My thinking here is to get as close to the DB metal as possible, and use that hardware to make it happen quickly.

Is anybody using SQL CLR? If you have, what has been your experience with it?

p.s. originally posted on stackoverflow and moved here based on a comment.

答:
You're better off using CLR than t-SQL if it is complicated logic. I would only consider this approach over using your application code as long as your consider:

You need/prefer to share this capability with multiple applications that use the database and are unable to share their internal code.

The database has plenty of resources available to make the calculations.

Sharing code is great, but not at the expense of your database performance.


答:
I setup a task with a reminder for two reasons:

I need a prompt to return to the code.

I can enter any notes or link to important documents, web pages, files, etc..

It's difficult to switch tasks if you're in constant fear of forgetting to back to that original bug. You do need to have some idea of when it is best to set the reminder. I also do this when leaving things over the weekend.

Title: Multitasking how to keep track of what you're doing

Body:
I'm in a long debugging task, I need to figure out where to hook up some extra functionality I need.

It's cumbersome work, and I've been debugging 2 whole days, and I'm on my third, but I work in multiple projects, and I'm returning to this after almost a week, and it's been hard to get back to the point I left at, and remember what was all this about, and what conclusions had I already arrived at.

How do you keep track of what you were doing/thinking in this kind of scenario where comments aren't actually the "right thing" to do? I do some comments in my testing code, plus some informative git/hg commit messages but that's kind of dirty.. written paper might be the answer...


答:
SQL CLR integration was developed mainly because, implementing logic through T-SQL was really hard. .NET Framework if filled with thousands of useful libraries, to which you have no access at SQL engine level. Thus, any logic should be implemented from scratch. For example, a simple foreach loop should be implemented with cursors, which are honestly, far less productive.

I have experience of working with SQL CRL integration. I did it for date-time conversion at database engine level. Date-time conversion at the level of database engine is really really hard, while .NET, has System.Globalization which facilitates the work.

The main point of this method, is to follow the step exactly as described (like extension methods in which, methods should be static functions inside static classes inside first-level namespace). If you fail to do something exactly as you're told, things simply fail.

Title: What has been your experience with SQL CLR for complex business logic?

Body:
So I thought I had a perfect use-case for a CLR SQL Procedure. I've search the Net for perhaps a similar example where data is retrieved, records added and updated. I have not looked at a SQL CLR procedure for awhile, but since it was released in 2005 (some 6 years ago!) I would have hoped there were plenty of examples!

I'm considering it because I have to look at some data, run it through a bunch of procedural logic, update, and then get it back to the client. My thinking here is to get as close to the DB metal as possible, and use that hardware to make it happen quickly.

Is anybody using SQL CLR? If you have, what has been your experience with it?

p.s. originally posted on stackoverflow and moved here based on a comment.


答:
Black box testing! You should be creating your classes/methods with testing in mind. Your tests should be based on the specification of the software and should be clearly defined on your Sequence diagram (via use cases).

Now since you may not want to do test driven development...

Put input validation on all incoming data; don't trust anyone. The .net framework has throws a lot of exceptions based on invalid arguments, null references and invalid states. You should already be thinking of using input validation on the UI layer so it's the same trick in the middle-ware.

But you should really be doing some sort of automated testing; that stuff saves lives.

Title: How to get better at testing your own code

Body:
I am a relatively new software developer, and one of the things I think I should improve is my ability to test my own code. Whenever I develop a new functionality, I find it really difficult to follow all the possible paths so I can find bugs. I tend to follow the path where everything works. I know this is a well known issue that programmers have, but we don't have testers at my current employer and my colleagues seem to be pretty good at this.

At my organization, we do neither test-driven development nor unit testing. It would help me a lot but it's not likely that this will change.

What do you guys think I could do in order to overcome this? What approach do you use when testing your own code?


答:
for working on multiple, complex projects, regardless of whether they involve developing software, there's no substitute for writing things down.

I've used bug tracking software, spreadsheets, personal wikis, a self-developed database, and probably a dozen other methods I've forgotten over the years. Writing things down helps you recall not only what you did, but why you did it.

When it comes specifically to debugging, there's no reason you can check code-in-progress into your own personal version control system. You can clean it up before committing to the central source repository.


问:
VB.Net vs C# debate
I've been in workplaces where, at the start of a project, the "Should we use VB.Net or C#" question has been raised.

Granted, it's probably less common to have to make that decision now than it was in the early days of .Net, particularly given the trend towards language convergence, but it can still be a heated debate.

So, between VB.Net and C#, Which language do you prefer and why?

答:
I like to say that the only reason BASIC is still popular is that it was Microsoft's first product, and they've be shoving it down our throats for the past 35 years.  It should have died a long time ago.

With that said, I've worked on two sizable .NET projects and both were done with VB.Net - though there was a bit of C# because either the translation was a bitch, or the construct didn't exist in VB.Net.  The only advantage I see with VB.Net is that the Visual Studio editor is much more friendly to it (in my experience anyway) than it is with C# - Intellisense seems better, and so does autoformatting (note that since I have not used C# as much, I may just be missing something in the configuration of the IDE...)

A major disadvantage in VB.Net is that they brought in a lot of VB6-era crap way back in .NET 1.x to ease the conversion of VB6 code.  That stuff is still in there, and VB6 coders are coding new code using those... "extensions" rather than using the more neutral .NET classes/methods/whatever.  I don't know how many times I asked my boss why he still used that crap.  "But... It works..."  Right.  Hey, I like to bitch.

While looking for help on the web, I found the vast majority of solutions were in C# - check out the MSDN forums, various blogs, etc... Books have a tendency to focus on C#, and if there is a VB version, it usually comes in months later (e.g. Pro LINQ.... from Apress.)

Many languages share the C ancestry, which makes switching between C, C++, C#, Java, PHP and a few others much easier.  PHP is a bit of a stretch here, but it does have a lot of C-like constructs.  VB?  Well, it's pretty much its own little thing and that's that.

A project leader in my organization recently told me that more and more new projects are being developed using C# instead of VB - FINALLY.  When .NET was introduced in our organization, they more-or-less-officially went with VB.Net because of all the VB6 coding that was already going on.  The powers that be later admitted to me that that wasn't their best move.

As somebody else above pointed out, I wouldn't say no to a VB.Net project, but I'm still hoping that it will be slowly eradicated from newer development at my place of work.

Title: VB.Net vs C# debate


问:
What has been learned about making variance part of the type?
In Java, the variance of parameterized types is indicated depending on how it's used:

```<code><A extends B,B> void store(ArrayList<B> list, A elem) {
    list.add(elem);
}
</code>```

Whereas in Scala it is indicated in the class declaration with a + or -.

What I want to know is, now that Scala has been around awhile, what has been people's experience with making variance a property of the type? Is it generally flexible enough for what you want to do? Are there aspects you would have done differently, knowing what you know now?

答:
I know this is not really answers to your question, but they may trigger some other replies... :-)

I would like to suggest a different code.
I have difficulties with a few points:

type parameters are in reverse order (A is first, but depends on B)

ArrayList is a strong type, List would make the code more general (reusable new, robust to future changes)

I also like to have multiples objets (such as List) end with an 's'... :-)

```<code><A> void store(List<A> items, A item) {
  items.add(item);
}
</code>```

In Java, we also sometimes have the variable type, either as a parameter to a method or in a class. This is the part I can comment on.

As a method parameter, it has been useful for me in several situations:

when the method needs to look into a map, to find an instance that depends on the actual class needed.

```<code>Registry.java
  public <E> E find(Class<E> clazz){
    return (E) map.get(clazz);
    // The cast is fine, because it is how we store in the map.
  }
</code>```

To create an instance if needed.

```<code>public <E extends Item> List<Item> singletonList(Class<E> itemClass){
    List<Item> items = ...;
    if (items.isEmpty()) {
      items.add(createDefaultInstanceFor(itemClass);
    }
    return items;
  }
</code>```

As a class parameter, I use often :

in Builders with inheritance (to make the last line work).

```<code>ABuilder.java
class ABuilder<E extends ABuilder> {
  private int size;

  public E withSize(int someSize) {
      size = someSize;
      return (E) this;
  }

BBuilder.java
class BBuilder extends ABuilder<BBuilder> {
   // here, no redefinition of method withSize

   public void onlyOnB(){
   }
}

Caller.java
  {
     BBuilder b = ...;
     b.withSize(2).onlyOnB();
     // The call still returns the subclass BBuilder,
     // even though it is defined in the superclass ABuilder only.
  }
</code>```

Body:
I know this is not really answers to your question, but they may trigger some other replies... :-)

I would like to suggest a different code.
I have difficulties with a few points:

type parameters are in reverse order (A is first, but depends on B)

ArrayList is a strong type, List would make the code more general (reusable new, robust to future changes)

I also like to have multiples objets (such as List) end with an 's'... :-)

<A> void store(List<A> items, A item) {
  items.add(item);
}

In Java, we also sometimes have the variable type, either as a parameter to a method or in a class. This is the part I can comment on.

As a method parameter, it has been useful for me in several situations:

when the method needs to look into a map, to find an instance that depends on the actual class needed.

Registry.java
  public <E> E find(Class<E> clazz){
    return (E) map.get(clazz);
    // The cast is fine, because it is how we store in the map.
  }

To create an instance if needed.

public <E extends Item> List<Item> singletonList(Class<E> itemClass){
    List<Item> items = ...;
    if (items.isEmpty()) {
      items.add(createDefaultInstanceFor(itemClass);
    }
    return items;
  }

As a class parameter, I use often :

in Builders with inheritance (to make the last line work).

ABuilder.java
class ABuilder<E extends ABuilder> {
  private int size;

  public E withSize(int someSize) {
      size = someSize;
      return (E) this;
  }

BBuilder.java
class BBuilder extends ABuilder<BBuilder> {
   // here, no redefinition of method withSize

   public void onlyOnB(){
   }
}

Caller.java
  {
     BBuilder b = ...;
     b.withSize(2).onlyOnB();
     // The call still returns the subclass BBuilder,
     // even though it is defined in the superclass ABuilder only.
  }


答:
The biggest problem in your code snippet is  comments. It looks ugly and unreadable in any case. place comments to separated line.

```<code>void DoSomeInterestingImageManipulation(char *pImage)
{
    //This will convert the image to formatABC which allows x% space savings for storage
    if(pImage && pImage[0] == 0xFF)
    {
        //Process the extra case where image internal format needs decompression
        ++pImage;
        //...
        //...
        //...
    }

    //Proceed normally
    *pResult = Foo(pImage);
}
</code>```

is much better. I used this "style" in past but now I use better one)

```<code>void DoSomeInterestingImageManipulation(char *pImage) {
    //This will convert the image to formatABC which allows x% space savings for storage
    if(pImage && pImage[0] == 0xFF) {
        //Process the extra case where image internal format needs decompression
        ++pImage;
        //...
        //...
        //...
    }

    //Proceed normally
    *pResult = Foo(pImage);
}
</code>```

Title: What do you think of opening brace comments in source code?

Body:
I have developed a habit of writing comments in my code by putting the comments on the same line as the opening brace, after the brace. I've found that this saves vertical space. It also leaves a hint why something was done, but I'm wondering if it's readable for others.

Example:

```<code>void DoSomeInterestingImageManipulation(char *pImage)
{//This will convert the image to formatABC which allows x% space savings for storage
    if(pImage && pImage[0] == 0xFF)
    {//Process the extra case where image internal format needs decompression
        ++pImage;
        //...
        //...
        //...
    }

    //Proceed normally
    *pResult = Foo(pImage);
}
</code>```

Do you consider it easier to read or harder to read?

Body:
The biggest problem in your code snippet is  comments. It looks ugly and unreadable in any case. place comments to separated line.

void DoSomeInterestingImageManipulation(char *pImage)
{
    //This will convert the image to formatABC which allows x% space savings for storage
    if(pImage && pImage[0] == 0xFF)
    {
        //Process the extra case where image internal format needs decompression
        ++pImage;
        //...
        //...
        //...
    }

    //Proceed normally
    *pResult = Foo(pImage);
}

is much better. I used this "style" in past but now I use better one)

void DoSomeInterestingImageManipulation(char *pImage) {
    //This will convert the image to formatABC which allows x% space savings for storage
    if(pImage && pImage[0] == 0xFF) {
        //Process the extra case where image internal format needs decompression
        ++pImage;
        //...
        //...
        //...
    }

    //Proceed normally
    *pResult = Foo(pImage);
}


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
Website strategy and planning is case specific. That is, a website can have no need at all to support IE browser, let alone thinking about minor issues like supporting border-radius of CSS3. But other websites may need even to be backward compatible up to IE6.

How can we understand what we have to plan for a website? Partly from our experience. Websites which target programmers and developers can get sure that their users use pretty new and updated browsers with almost all features turned on. However, news websites should think that someone from an unknown point of the earth can connect to their website to see what is passing insider his/her country.

But besides our experience and intuition, we also need to install some kind of analytics service on our website, so that our future decisions would be more robust, based on statistical data. For example Google Analytics is a very good tool. From there, you can see whether you really need to support older browsers or not.

However, if we want to follow Web Accessibility Guidelines from W3C, then we should definitely support lots of things, without considering site-specific circumstances.

In your special case, I say that no. We can safely forget about no-script in small and mid-level websites. But for bigger projects, it's not a bad idea to include a little more markup in your pages.


问:
Language Choice for Algorithm Competitions
Hi everyone
I have just started taking part in online coding competitions.I would like to know which language would be better as regards efficiency and ease of debugging. I tend to avoid c++ and generally go with java.
1. Would some other language be suitable? How about c sharp or python or some other (No issues with learning a new one.)
2. Is proficiency in C++ necessary to do efficient programming?
3. And out of java & c# which is better for algorithm competitions?

答: I would use Common Lisp, because it is very pragmatic and expressive.</p>

OwnerDisplayName: filokalk


问:
Is it better to have separate Create and Edit actions or combine Create and Edit into one?
We are using ASP.NET MVC 2 with a Controller/View Presentation Layer and Model consisting of A Business Logic Layer, Data Access Layer [Stored Procedures and classes/methods to talk to the stored procedures].

In the business layer and above for most purposes Edit seems to be capable of representing both the creation of an object and the editing of an object. This coincides well with our Repository Design Pattern that defines a "Save" method. We can simply check in the stored procedure if the ID is 0 and then create a new object if it is 0 otherwise we can just update the existing object, since the category id should match one.

The primary point of discussion is if it makes the most sense to split Edit that includes Creation into it's separate parts of Create and Edit beyond the DAL layer.

An obvious example can be shown as routes:

Create - http://someurl/somearea/edit/0

Edit - http://someurl/somearea/edit/254

vs.

Create - http://someurl/somearea/create

Edit - http://someurl/somearea/edit/254

Are there any established standards or best practices in regard to this?

I know this is a small detail, but I think it's logistically an important one.

答:
I would definitely say that there's worth in separating Create/Edit, if not for obeying the single responsibility principle.

One could claim that there's better SEO in having the correct action in the url as well.

Not separating the two would also make the code harder to unit test.

A new programmer reading the code would probably not find the code very intuitive having to create objects in an "edit" method, it just doesn't make sense semantically. I can however sympathize with the Save() method in the DAL.

Thinking about it, I can't really see the benefits of putting it all in a Edit method.


答:
Let's take a grammatical approach towards this:

Bob asked for a book from John. John gave the requested book to Bob.

or

__ requested __ from __ , and __ responded.

Now, if you try to fill in the blanks, the requester (first blank) is the client. The requested thing (second blank) is called the resource, and the requestee (third and fourth blanks) is called server. Now, consider these sentences:

Your cell phone requested an image from Google, and Google responded.

Your cell phone is a client, an image is the resource, and Google is the server.


答:
The existing answers are excellent, but I'd like to make an analogy in non-computer terms.

Someone working as a server (waiter/waitress) in a restaurant is acting as a server.  When that person gets off work they can come back to that restaurant (or a a different one) and be a client (customer).

The same way that the same person can be both server and client, so also can a computer.

A computer can primarily be a server, that is it performs the function of serving more than that of consuming, and can be called a server machine.  Often times they can be built with that role in mind (higher security and resistance to failure, being a size and shape that fits easily on a server rack etc) but there's nothing intrinsic about a specific computer that makes it unfit to be a either server or client or both.  (Exception being when one is lacking proper software and the ability to install such software)


问:
Is Razor or XSLT better for my project?
I'm in the early stages in the design of a system that will essentially be split into two parts. One part is a service and the other is an interface with the service providing data through something like OData or XML. The application will be based on the MVC architectural pattern. For the views, we are considering using either XSLT or Razor under ASP.NET.

XSLT or Razor would help to provide a separation of concerns where the original XML or response represents your model, the XSLT or 'Razor view' represents your view. I'll leave the controller out for this example. The initial design proposal recommends XSLT, however I suggested the use of Razor instead as a more friendly view engine.

These are the reasons I suggested for Razor (C#):

Easier to work with and build more complicated pages.

Can easily produce non-*ML output, eg csv, txt, fdf

Less verbose templates

The view model is strongly typed, where XSLT would need to rely on
convention, eg boolean or date values

Markup is more approachable, eg nbsp, newline normalization, attibute
value normalization, whitespace rules

Built in HTML helper can generate JS validation code based on DTO attributes

Built in HTML helper can generate links to actions

And the arguments for XSLT over razor were:

XSLT is a standard and will still exist many years into the future.

It is hard to accidentally move logic into the view

Easer for non programmers (which I don't agree with).

It's been successful in some of our past projects.

Data values are HTML-encoded by default

Always well formed

So I'm looking for aguments on either side, recommendations or any experience making a similar choice?

答: I HAVE successfully used XSLT as a web presentation tier...  in 1999.  In the last 12 years, much better options have come along.  Do yourself a big favor, and use Razor.  It's a pleasure.

Title: Is Razor or XSLT better for my project?


答:
My recommendation is Razor and the main reason is that it's much more easier to work with (than XSLT, and opposite to your enumerated argument in favor of XSLT, though, you're on my side). I have experience of working with both and Razor becomes exceptionally powerful in conditional statements, declarative helpers (functions in principal), branching, looping, etc.

After all, let's not forget Razor is a programming language (yeah, a template engine, or view engine, but implemented via a programming language like C# or VB.NET), while XSLT is more have a markup structure.

I think your scenario is like trying to select C# or T-SQL to write a complex business application. While T-SQL is pretty powerful in set operations, it simply breaks when you try to implement logic (if-else, switch, for, etc.) in it.

Title: Is Razor or XSLT better for my project?

Body:
I'm in the early stages in the design of a system that will essentially be split into two parts. One part is a service and the other is an interface with the service providing data through something like OData or XML. The application will be based on the MVC architectural pattern. For the views, we are considering using either XSLT or Razor under ASP.NET.

XSLT or Razor would help to provide a separation of concerns where the original XML or response represents your model, the XSLT or 'Razor view' represents your view. I'll leave the controller out for this example. The initial design proposal recommends XSLT, however I suggested the use of Razor instead as a more friendly view engine.

These are the reasons I suggested for Razor (C#):

Easier to work with and build more complicated pages.

Can easily produce non-*ML output, eg csv, txt, fdf

Less verbose templates

The view model is strongly typed, where XSLT would need to rely on
convention, eg boolean or date values

Markup is more approachable, eg nbsp, newline normalization, attibute
value normalization, whitespace rules

Built in HTML helper can generate JS validation code based on DTO attributes

Built in HTML helper can generate links to actions

And the arguments for XSLT over razor were:

XSLT is a standard and will still exist many years into the future.

It is hard to accidentally move logic into the view

Easer for non programmers (which I don't agree with).

It's been successful in some of our past projects.

Data values are HTML-encoded by default

Always well formed

So I'm looking for aguments on either side, recommendations or any experience making a similar choice?


答:
Generally when the coverage is so low it has nothing to do with the skill level of the developers or how recently they graduated.

Usually two things have caused this, old code that was written before TDD was common (when much of your code base was written ten years ago, it would be extremely unlikely that you would have test coverage) and tight (often impossible) deadlines. Testing is one of the first casualties of the impossible deadline.

So adding new people more familar with testing is unlikely to change either fo those two conditions and test converage will likely only slowly improve.

That said, I personally have only rarely seen a recent graduate who cared much about testing. That is because the projects they work on in school are both small and not in need of maintenance over time. So the critical reasons for test converage are not there and most studnets don't do TDD routinely. Recent grads often also have to be taught about using source control. There is a huge difference between working on enterprise software and class assignments and thus these things are not really on their radar until they get dropped into a large and continuing project.

Title: What percent of your college course work is unit-tested code?

Body:
As a college student do you write unit-test for the project code you write?  Do you know how to properly use TDD?  Have you been taught to use testing frameworks (jUnit for example)?

I've just recently heard that a major company's project team was delivering software to User Acceptance Testing group that had only 7% line code coverage for unit testing.  While that shocks me, it just tells me that this company's software engineering practice are immature.  However I wonder if they could just hire a few recent graduates and raise the bar on the teams practices - assuming that these newly minted programmers were trained in the best practices.

Are you 2008 - 2010 CS graduates using best practices of unit testing your code?


问:
Naming conventions and organization of packages
I've been programming in Java, C#, Python and AS3 most of the time and in all of these languages there are packages (or something like that). The problem I found is with the naming convention, or even with the organization of the packages. I need someone to tell me WHY is this:

com.company.app.type.Object or org.authorname.project.type.Object

better than this:

app.feature.Object or app.module.Object

Another example:

Why this:

```<code>com
 +--company
     +--app
         +--events
         |   |--FeatureOneEventA
         |   |--FeatureOneEventB
         |   |--FeatureOneEventC
         |   |--FeatureTwoEventA
         |   |--FeatureTwoEventB
         |
         +--models
         |   |--FeatureOne
         |   |--FeatureTwo
         |
         +--services
             |--FeatureOneServiceA
             |--FeatureTwoServiceA
             |--FeatureTwoServiceB
</code>```

Is "better" than this:

```<code> company
  +--app
      +--feature
          +--one
          |   |--Model
          |   |
          |   +--events
          |   |   |--EventA
          |   |   |--EventB
          |   |   |--EventC
          |   |
          |   +--services
          |       |--ServiceA
          |
          +--two
              |--Model
              |
              +--events
              |   |--EventA
              |   |--EventB
              |
              +--services
                  |--ServiceA
                  |--ServiceB
</code>```

In the first one you have all organized by "types of objects", but the "features" are all mixed, but in the second one, the organization is by "feature" and each one has their own objects; so, you can see one feature well separated from another.

So, can anyone tell me why a lot of companies and programmers prefer the first?

答:
Agree with the others on the package prefix being the company domain.

On the second point, I usually choose package names like you suggest, by feature before by file type (as you wrote, the other policy is often chosen).

Note that technical code (like StringHelper or MenuInterceptor) is not directly a feature, so it doesn't follow the same conventions.

I prefer it because :

when working on a feature, you find easily the corresponding code

you can make use of the package visibility (intermediate between a private inner class and a really public class).

you can launch automatic tests to fully verify a feature (it is what matters to your client ; and it is also what could break when you modify old code)

if a project typically have small features with few classes, or many optional classes that are not always needed, subdirectories might not be needed, all classes can be contained in the same package (and let the suffix indicated what role that class plays in the feature).

By the way, I think that several features don't usually share a lot of code. If a code is reusable, it is either:

in a different layer (like technical code), so completely elsewhere (maybe not in the same Java project)

in a superclass (common code may use packages as features do)


问:
What are advantages and disadvantages of browser rapid release cycles for web developers?
Chrome and Firefox have now rapid release cycles. Also Opera is starting to get speed and Internet Explorer should take the high road soon. I am a web developer. What does that mean for me? What consequences does it have for me? Will it be an advantage for my work or another burden?</p>

答:
With HTML5 being supported more fully, I would say advantageous. You will need to worry far less about feature detection (although it is still a good practice).

However, if the companies fail to perform, more errors will surely be annoying/cause more feature detection.

My 2 cents.

OwnerDisplayName: tomaszs


答:
It's best to think of servers and clients in terms of processes, rather than hardware.  It's extremely rare for hardware to be strictly one or the other, and thinking in those terms leads to confusion.

Consider the X windowing system - the X server is on the end user's machine (including dumb, diskless X terminals), whereas the client may be running on the central server or mainframe.

Almost any piece of hardware can act as a server or a client, or even serve both roles simultaneously.


答:
From what I've seen, the first is common in Java and its kin (ActionScript, for example).  I don't quite know the reason why but I assume it's something to do with avoiding any possible naming clashes.

C# and .NET in general, as well as I believe Python, prefer the second style.  In fact, .NET guidelines expressly discourage the Java style and recommend: CompanyName.ApplicationName.ModuleName.LogicalGroup for example Cyberdyne.Skynet.SelfDefense.CyborgActivation

Title: Naming conventions and organization of packages

Body:
I've been programming in Java, C#, Python and AS3 most of the time and in all of these languages there are packages (or something like that). The problem I found is with the naming convention, or even with the organization of the packages. I need someone to tell me WHY is this:

com.company.app.type.Object or org.authorname.project.type.Object

better than this:

app.feature.Object or app.module.Object

Another example:

Why this:

```<code>com
 +--company
     +--app
         +--events
         |   |--FeatureOneEventA
         |   |--FeatureOneEventB
         |   |--FeatureOneEventC
         |   |--FeatureTwoEventA
         |   |--FeatureTwoEventB
         |
         +--models
         |   |--FeatureOne
         |   |--FeatureTwo
         |
         +--services
             |--FeatureOneServiceA
             |--FeatureTwoServiceA
             |--FeatureTwoServiceB
</code>```

Is "better" than this:

```<code> company
  +--app
      +--feature
          +--one
          |   |--Model
          |   |
          |   +--events
          |   |   |--EventA
          |   |   |--EventB
          |   |   |--EventC
          |   |
          |   +--services
          |       |--ServiceA
          |
          +--two
              |--Model
              |
              +--events
              |   |--EventA
              |   |--EventB
              |
              +--services
                  |--ServiceA
                  |--ServiceB
</code>```

In the first one you have all organized by "types of objects", but the "features" are all mixed, but in the second one, the organization is by "feature" and each one has their own objects; so, you can see one feature well separated from another.

So, can anyone tell me why a lot of companies and programmers prefer the first?


问:
Should I use try catch in my test methods?
I am doing unit testing.

I am trying to test one function.

I call it from my test component. But If remote function cannot handle the exception then my tester component will also get exception, I guess.

So should I worry about getting exception in my tester component?

Thanks.

EDIT:

PS:

Throwing an error is good, but only for other functions, not to end users until its a last option!

OMG I wrote a programming quote!!

答:
In general, you should just let the exception out, and the testing framework will give you a nice report with all the information you need.

But in the TDD methodology, we are expected to follow that steps:

Write a test

Watch it fail, and make the error understandable

Correct the code

Refactor the code and the test

When you let an exception out, if the error is clear, then it is fine.
But sometimes the exception is obscure, or even misguiding.
How could you let that be in your code (for you later when you will have forgotten, or for a team member that will loose big time figuring out the problem) ? So my policy is: "If it is necessary to make a failure clear, you need to catch the exception".


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

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

答:
As a general rule, the most successful man in life is the man who has the best information.

    — Benjamin Disraeli

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Roger Pate


问:
How do you decide where functionality should belong in a large-scale project?
In my current development situation, we have a lot of DLLs, executables, and static libraries. How do you decide what should go into a DLL? What should go into an executable? Why have separate functionality in different executable files? I'm hoping the answer will be concise, but this is a largely opinionated topic it would seem.

How do you decide where functionality resides in a large-scale project (more than one executable file)? I'm expecting answers to range from, "Good Design" to "Modularity" to "Whatever management puts in a requirements doc".

答:
What's going to make it easier to maintain the code in the long run?  If you have unrelated functions in the same component (i.e., dll, exe, compiled unit), and you have to change one function, is that going to break the other?  When you make a change on a component, you'll need to retest all the downstream components depending on ALL the functions in that component.  If you limit the functionality within each component, changing each one will be less risky.

Also, By focusing components on a small number of closely related functionality, you'll have a much easier time proving that that one component behaves the way it should.


问:
When writing a library, how much should the end user do?
First off, this question goes beyond my example (don't want this to be too localized or migrated to Stack Overflow) but I've come across this when thinking about something I wanted to try in C so I thought I'd use that as an example.

So my idea is to create a generic linked list in C and started it last night and it is coming along pretty well for being new in C. The issue I ran into is type casting and it leads me to this question: how much work should a library designer expect the end user to do when using the library?

If you take my example, right now, I don't perform any casts and return an Object (which is a typedef of void*). Is it reasonable to make sure that the end user keeps track of their types or should the library designer make sure that the list is type safe (I think I have a general idea on how to implement that for at least the built in data types)? Is it reasonable, when designing a library to expect a certain amount of work on the end users part to use the library or should it be dumbed down as much as possible? Are there factors that would affect this decision, such as language?

答:
When you write the "end user", I assume you mean the "developer of the calling code".

The TDD methodology makes you write the tests first, then the code.

Among others, a huge benefit is that your API is designed to be usable (because the test code is calling your code, just as a regular caller of your API). The calling code becomes simple, and very readable. That should answer any questions you have about the exact API you should offer.

Please also note that an API often allow changing language level. For example, a functional code about farm cows and pigs, can use an API for disguising them, before they can play ninja turtles ;-) Or grouping clients
can use the List data structure, and don't even consider the technical details.


问:
When developing algorithms, is skipping the pen&paper phase a bad habit?
I heard many people saying that when developing algorithms you should first use pen and paper, flowcharts and what not, so that you can focus on the algorithm itself, not worrying about the implementation of said algorithm (i.e., you deal with one problem at a time).

However, most of the time I find it easier to actually develop my algorithm on the fly. That is, I think a bit about the problem until I know the general direction to take, and then I start writing code and making changes until the algorithm emerges and works.

Is this a bad habit that I should try to change?

答:
This depends on your thinking habits and algorithm complexity.

Pen and paper offer "free form" thinking without a compiler shouting at each character you type.

Some of us who use pen and paper, take the time to adjust loop limits, try different values, etc.

So, I guess that writing the code directly encouraging test-first approach where as the pen and paper promotes think-first approach.
It is definite that if the task is trivial, you can code it on the fly (if you are experienced enough) but complex algorithms would probably need a different development approach.

Diagrams help in some cases, but this requires that you be familiar with them and have used them before.


答:
I think yours is the more common approach.  If the algorithm is especially intricate or difficult it can be tough to both figure out the algorithm and implement at once, but in general I doubt it helps most people.

But I wouldn't, say, invent rules for a grammer and implement a parser for it without writing the rules out on paper (or maybe with some special tool I don't have) first, or implement a B-Tree without pseudo-code available.

I wouldn't say you have a bad habit unless it's doing you some harm, and I think you would notice if it were.

Title: When developing algorithms, is skipping the pen&paper phase a bad habit?

Body:
I heard many people saying that when developing algorithms you should first use pen and paper, flowcharts and what not, so that you can focus on the algorithm itself, not worrying about the implementation of said algorithm (i.e., you deal with one problem at a time).

However, most of the time I find it easier to actually develop my algorithm on the fly. That is, I think a bit about the problem until I know the general direction to take, and then I start writing code and making changes until the algorithm emerges and works.

Is this a bad habit that I should try to change?


答:
One one hand, it is a good thing since new features and updated support can be pushed out in more regular cycles, rather than waiting for a big-bang type of release.

On the flip side, it means there is a greater range of support levels for different browsers - more versions of Firefox and Chrome out there. This is negated somewhat by the rapid release aspect, so browsers are more likely to be up to date.

Another possible downside, depending on how you look at it, is that the rapid releases will keep developers busy in testing the latest browser versions.

Title: What are advantages and disadvantages of browser rapid release cycles for web developers?

Body: Chrome and Firefox have now rapid release cycles. Also Opera is starting to get speed and Internet Explorer should take the high road soon. I am a web developer. What does that mean for me? What consequences does it have for me? Will it be an advantage for my work or another burden?</p>


答:
Advantages: browser updates are now following a push model ala Chrome so that you aren't waiting on users to go out and download the latest browser. Rapid release allows the browser developer to push new features out quicker instead of having to wait for a major update. There will soon be only one "version" of a browser. </p>

<p>Disadvantages: pretty much all of the above. Users behind a firewall may not be allowed to stay up to date and it will be difficult to support specific versions as version numbers ar disappearing. This means those new features may not be on your user's machine (how will you then support older "versions" when your test browser keeps updating itself?). It will also make it difficult say which versions of a browser your site will support. Testing will also be difficult as you will need to monitor all the silent updates sent to browsers and make sure your site didn't break. </p>

Body:
Advantages: browser updates are now following a push model ala Chrome so that you aren't waiting on users to go out and download the latest browser. Rapid release allows the browser developer to push new features out quicker instead of having to wait for a major update. There will soon be only one "version" of a browser.

Disadvantages: pretty much all of the above. Users behind a firewall may not be allowed to stay up to date and it will be difficult to support specific versions as version numbers ar disappearing. This means those new features may not be on your user's machine (how will you then support older "versions" when your test browser keeps updating itself?). It will also make it difficult say which versions of a browser your site will support. Testing will also be difficult as you will need to monitor all the silent updates sent to browsers and make sure your site didn't break.


答:
Plans are worthless, but planning is everything.

    — Dwight D. Eisenhower

Body:
What's your favourite quote about programming?

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


答:
you can create a design while making the stub classes, methods and tests but you can get bogged down while creating the details

for the really complex stuff (compilers and such) a pen and paper design (or at least on a design tool of sorts) will help to keep you on track and the eye on the whole picture and avoid bad design choices and even let you choose certain design patterns from the start

but ultimately it depends on how well you can keep seeing the big picture


问:
Non-transactional Database and Integration Testing
One issue I think I am going to run into with my integration testing is having multiple tests accessing the same database.  While this is not a problem now, I know we have multiple applications here that access the same database and I am just trying to think of a way to prevent this issue before it happens.

An idea I have seen a lot is using transactions.  In the start up you start a transaction and then in the teardown you rollback the transaction.  This means that multiple tests accessing the same database tables and will not effect each other which is great.  The issue I have is that in my case, 85-95% of the tables I am working with in MySQL are MyISAM which don't support transactions.

Are there any ways to get around storage engines that don't support transaction but still allowing multiple test to access the same tables without them effecting each other?  From what I hear, the ruby on rails testing framework uses transactions in this way, how do they get around this issue (or do they)?

答:
In my company, there was that debate: persistency is a huge problem for testing.

There are some hacks that will get you halfway. We decided not to loose our time with them:

using Transactions that you rollback. That fails as:

You sometimes open an isolated transaction (inside a more general one), so it has been closed before your test code can get a grip on it

You cannot test your real persistence. (What happens when a test closes one transaction, and runs a complex querying affected by that data in a different transaction ; or saving data, and loading it again later on.)

You cannot test your code fully (only the layers below transaction level ; not good enough if you consider the drawbacks of integration testing).

using a fresh clean Database for each test. That also fails as:

our test suite will soon get to a few thousand tests (we have big teams). Setting up a new Database requires minutes at best (as we have many catalogs and parameters that are part of each version). Our test suite would soon take months to finish, and we can only wait a few days.

we would need a specific database instance for each developer, or each machine, and have a policy to launch only one test at a time. We need to use Oracle 11 to check our queries are fine, that would be too costly (Oracle licences).

carefully cleaning up after each test (testing frameworks provide hooks for running code after a test). That fails as:

it is very costly to maintain a perfect match between the code that does, and the test that undoes. As soon the match is not perfect, the symptoms are not clear, a test might fail while being a few hundreds lines later ; or a test that should fail could pass erroneously.

there are always edge cases where the cleaning is not correct (machine or software crash ?). That leaves an unknown state for later executions.

when a test shows an error, the database state would be be an essential information, but it would be lost (because we clean up before the next test, to finish the test suite and show the developer a full information).

So we moved to a policy we knew was valid:

have automatic Unit Tests for our requirements:

if needed, mock database accesses (but we usually don't need JMock, I could explain our design if asked to).

tests execute with a rate over 100 per second

tests are quick to write, short and clear to read.

tests do not depend on any persistent state, so they are fully isolated from each other naturally (no complex mecanism needed)

test integrating with the database separately (that is, request by request, not integrated with the application logic).

we considered automating that task, but it seemed too costly (see previous part of my post)

so we kept these tests manual: each developer that modifies a query is expected to test it again the database (that is usually part of his end-to-end tests through the user interface).


问:
How to calculate the quality of software project
I am working on a project and my task is to evaluate quality of that project by quality metrics. I found three types of metrics namely product, process & project. On some websites I fount other types like Defect Detection Percentage, Defect Removal Efficiency, Defects Find Rate, Escaped Defects Found, Function Points, Lines of Code, Mean Age of Unresolved Defects, Mean Time to Fix, Resolved Defects metrics, etc .

So my question is which are the right types of metrics and how do I get that I should use X type of metrics for calculation(My project is in .NET). Also help with the names of freely available tool.

答:
I should think it is the client's onus to indicate your team what quality metrics he/she wants to see. If that's not the case, one should clarify back with the client if what he/she really wants is evidence (in the form of metrics) that your software shop produces work of quality.

For the later, defects per release (or a delta per release such as changed SLOCs and/or FPs or implemented requirements) would be one to consider. This alongside

customer satisfaction,

rate of defect removal per release/release delta,

average age of defect (from detection to removal), both as a average
for the last X months, for the last Y number of releases, and annual
since the beginning of time (hopefully to show defect age is not
increasing.)

source-code level metrics such as cyclomatic complexity and LCOM (to
show the quality of the code structure itself.)

There are tools such as Sonar that can make this type of metric gathering a lot easier. Once you have such QA infrastructure plumbing in place and integrated with your build-release cycles, it is just a matter of gathering the data over time.

OwnerDisplayName: Ujj


问:
What percent of your college course work is unit-tested code?
As a college student do you write unit-test for the project code you write?  Do you know how to properly use TDD?  Have you been taught to use testing frameworks (jUnit for example)?

I've just recently heard that a major company's project team was delivering software to User Acceptance Testing group that had only 7% line code coverage for unit testing.  While that shocks me, it just tells me that this company's software engineering practice are immature.  However I wonder if they could just hire a few recent graduates and raise the bar on the teams practices - assuming that these newly minted programmers were trained in the best practices.

Are you 2008 - 2010 CS graduates using best practices of unit testing your code?

答:
As a college student do you write unit-test for the project code you write?

MS thesis project; sorta. I do interactive testing with Lisp/Slime. Some stuff gets unit tests, some stuff doesn't.

Do you know how to properly use TDD?

Meh, tried it, didn't see the point. Rather test during than before.

Have you been taught to use testing frameworks (jUnit for example)?

Why should a professor waste our time teaching me an API? If I can't learn an API, I need to leave the field.


问:
What do you think of opening brace comments in source code?
I have developed a habit of writing comments in my code by putting the comments on the same line as the opening brace, after the brace. I've found that this saves vertical space. It also leaves a hint why something was done, but I'm wondering if it's readable for others.

Example:

```<code>void DoSomeInterestingImageManipulation(char *pImage)
{//This will convert the image to formatABC which allows x% space savings for storage
    if(pImage && pImage[0] == 0xFF)
    {//Process the extra case where image internal format needs decompression
        ++pImage;
        //...
        //...
        //...
    }

    //Proceed normally
    *pResult = Foo(pImage);
}
</code>```

Do you consider it easier to read or harder to read?

答:
I don't mind it so much, but I would like to see some indentation there, so the braces still easily stand out when scanning over code:</p>

```<code>void DoSomeInterestingImageManipulation(char *pImage)
{   //This will convert the image to formatABC which allows x% space savings for storage
    if(pImage && pImage[0] == 0xFF)
    {   //Process the extra case where image internal format needs decompression
        ++pImage;
        //...
        //...
        //...
    }

    //Proceed normally
    *pResult = Foo(pImage);
}
</code>```

Body:
I don't mind it so much, but I would like to see some indentation there, so the braces still easily stand out when scanning over code:

void DoSomeInterestingImageManipulation(char *pImage)
{   //This will convert the image to formatABC which allows x% space savings for storage
    if(pImage && pImage[0] == 0xFF)
    {   //Process the extra case where image internal format needs decompression
        ++pImage;
        //...
        //...
        //...
    }

    //Proceed normally
    *pResult = Foo(pImage);
}


答:
Some algorithmic development can require a lot of trial-and-error testing and tuning, as one can find that the assumptions that would go into a strictly paper design turn out not be accurate enough when given real data and performance constraints.

Maybe iteration (think-code-test-think-code-test...), rather than just an either-or choice for the optimal "habit".


答:
Education: that which reveals to the wise, and conceals from the stupid, the vast limits of their knowledge.

    — Mark Twain

Title: What's your favourite quote about programming?


问:
Over normalization in database
Currently I am working on creating a new database schema as part of a major new product.  Our previous customer address records (in a previous product)  look something like this in our current schema (not all columns shown):

```<code>AddressID, AddressLine1, AddressLine2, City, State. Zip, Country, Etc.
</code>```

I want to normalize this so that an address actually breaks down to:

1 address to many address lines

1 address to a zip/postal code

So I sent out a communication saying that zip code will now be in its own table and that each "address" corresponds to one zip/postal code.  In addition, addresses would be broken out so that we could support more than 2 address lines with a 1 to many relationship.

Some people in my group are now saying that I am over-normalizing the database.  Am I?

Note, I am not a DBA but I feel that this is more logical and more efficient than the previous schema.

Update

Thx to everyone for their input.  I'm not going to break out the address or zips to their own tables.  My original plan was to have a zip code lookup and re-use for the addresses so I would only have to have one set of zips, but I'll just drop everything on the record itself, and have a separate table for zip lookups.

答:
It's hard to say. Usually postal codes and zip codes are not normalized to a separate table (from most of the databases I've seen), but there may be cases where it makes sense. I don't know enough about your business domain to know if it does. I've seen reporting databases that had tables of zip/postal codes, and then also had other data (some codes - I don't know what they were for) associated with each zip/postal code. In that case, the addresses referenced the postal/zip codes through a combination of territory IDs and something else... it was not as simple as I had hoped!

Normalizing the address lines does seem excessive. How often are you going to reference the same Address Line 1 value (assuming I understand what you are doing)? I suppose it could happen where you have hundred of records in all sorts of tables referencing "123 Main Street" but it seems very unlikely to me (but if you do have that data then it might make sense).

Title: Over normalization in database


答:
Yes and no.  You can have a lookup table for the ZipCodes, however, I wouldn't use a key to relate the two. Use the actual ZipCode in the Address record.

And since AddressLine1, AddressLine2, etc are really quite arbitrary, rather than breaking it into it's own table, just change the field to AddressLines and have it contain line feeds where applicable.

It will make searching easier as it's in one field.  And you always display them together anyhow.  Since they are just free-text, you can't do anything meaningful with them split.  Youre two AddressLine fields currently can contain anything from box numbers, appt numbers, street addresses, care of text, etc... and you never know which one will contain what.  If you do know, they should be labeled better.

Title: Over normalization in database

Body:
Currently I am working on creating a new database schema as part of a major new product.  Our previous customer address records (in a previous product)  look something like this in our current schema (not all columns shown):

```<code>AddressID, AddressLine1, AddressLine2, City, State. Zip, Country, Etc.
</code>```

I want to normalize this so that an address actually breaks down to:

1 address to many address lines

1 address to a zip/postal code

So I sent out a communication saying that zip code will now be in its own table and that each "address" corresponds to one zip/postal code.  In addition, addresses would be broken out so that we could support more than 2 address lines with a 1 to many relationship.

Some people in my group are now saying that I am over-normalizing the database.  Am I?

Note, I am not a DBA but I feel that this is more logical and more efficient than the previous schema.

Update

Thx to everyone for their input.  I'm not going to break out the address or zips to their own tables.  My original plan was to have a zip code lookup and re-use for the addresses so I would only have to have one set of zips, but I'll just drop everything on the record itself, and have a separate table for zip lookups.


问:
Determine Better Coding Practice
As a new programmer, it has always been hard to create applications, because I am still at the learning stage.

I understand that to achieve a particular affect or function in an application, there will be numerous ways to achieve the same result.

However, should I just purely create a function to it's working state, which means that as long as it works, just as the way I want it to, then it should be fine.

Can any fellow programmers of a higher level kindly let me know the right way of doing things?

答:
There are several "known" coding standards that you can look at. For example, for embedded C development - MISRA C would be a good start. JSF AV is a nice C++ coding standard. There are probably others available for other languages.

In the end its a lot of common sense and common practices, you gain that with experience. Of course, workplaces have their own coding standards (or at least should have) to which you should adhere as well.

Title: Determine Better Coding Practice


答:
You are overnormalizing (and as a database specialist, I don't say that often).

Think of how you use this data and you will see it makes the most sense to be in one table. If each address related to multiple zip codes, a second table makes sense. Since the relationship is one-to-one there is no need at all to split out the table unless you have too wide a record which is rarely the case in an address table.

Also since your configuration is not the common way that this data is stored, you will create a maintenance issue as new devs will be confused by the structure. Really, each address should be completely contained in one record.

Title: Over normalization in database


问:
Storing hierarchical template into a database
If this title is ambiguous, feel free to change it, I don't know how to put this in a one-liner.

Example:

Let's assume you have a html template which contains some custom tags, like <text_field />. We now create a page based on a template containing more of those custom tags. When a user wants to edit the page, he sees a text field. he can input things and save it.

This looks fairly easy to set up. You either have something like a template_positions table which stores the content of those fields.

Case:

I now have a bit of a blockade keeping things as simple as possible. Assume you have the same tag given in your example, and additionally, <layout> and <repeat> tags. Here's an example how they should be used:

```<code><repeat>
  <layout name="image-left">
    <image /> <text_field />
  </layout>

  <layout name="image-right">
    <text_field /> <image />
  </layout>
</repeat>
</code>```

We now have a block which can be repeated, obviously. This means: when creting/editing a page containing such a template block, I can choose between a layout image-left and image-right which then gets inserted as content element (where content for <image /> and <text_field /> gets stored). And because this is inside a <repeat>, content elements from the given layouts can be inserted multiple times.

How do you store this? Simply said, this could be stored with the same setup I've wrote in the example above, I just need to add a parent_id or something similiar to maintain a hierarchy. but I think I am missing something. At least the relation between an inserted content element and the origin/insertion point is missing. And what happens when I update the template file?

Do I have to give every custom tag that acts as editable part of a template an identifier that matches an identifier in the template to substitue them correctly?

Or can you think of a clean solution that might be better?

答:
It looks like most people are like me, they have trouble understanding what you want. But I will try and expose myself, maybe it can unblock your post ...

I think I understand why you consider creating many ids, and linking your elements together with them.

Storing a hierarchy in a relational database is not easy:

if you use just one table, there are no standard SQL way to obtain all data (but specific database have non portable solutions for this)

you could use several tables for the various levels, but that would be rigid and not recursive

Maybe the easiest way would be to store your hierarchy as a file (on your filesystem or in your database). A file naturally can contain hierarchical information, and you can parse into a hierarchical memory structure, so no problem (unless you need to query the relations between items).

Your file format is standard xml, so you have many tools available.


答:
Yeah, probably.

Do you have a specific business case/conceptual reason for separating them?  Have you considered the impact on the application of making the queries more complex, both in terms of performance and application maintenance?  Will someone now have to debug sql queries that now feature a bunch of joins, where before it was a simple select?  (I'm not talking just simply selecting addressess, but when addressess need to be extracted along with other data).

Normalization is about storing data efficiency.  But there's other important factors in software development which often trump the need for the maximum efficiency in storage.

Title: Over normalization in database


答:
Normalization for the sake of normalization is a bad idea. How far do you take it?

As others have said, normalizing the address might make sense, but it's probably just going to make it harder to work with.

For the zip codes, I don't see much of a point. They are only 5 digits long (9 with +4) and as such can be represented by a single 32-bit integer field. My suggestion would be to continue doing that, and if the need arises to split it into a separate table, just use the zip code as the PK and slap an FK on the existing column. This gives you the benefit of normalization, without implementing something before you need it (YAGNI)

Title: Over normalization in database


答:
The table of zip codes isn't too unusual, and does make sense if you want other information to be tied to zip codes - either other columns in the zip code table or references from other tables (along the lines of salesmen have regions which are sets of zip codes).

I assume you want address lines in their own table because you want to follow first normal form.  I've never seen anyone actually do this, probably because it's so unlikely that you will need more than a very small number of columns for address lines, ever.

I find it unlikely you will get any practical value out of it.  Consider some of the other things you might do to rigorously model names and addresses:

1 Have a separate table for each name, instead of first, last, middle, since a person might have any number of names (and it's actually much more common than for address lines to have a large number of them).

1 Have address be many to many with entity, since in the real world this is actually how it works.

2 Use address standardization software to get the many to many mapping right.

3 Support international addressing for all countries.

4 Have name be many to many with address, because you might use more informal names when contacting someone at home.

5 Have name be many to many with entity, since some people might use nicknames only with certain people.

Now imagine writing a query to put a bunch of people's name and address on a report.

Are any of these ways of modelling the data wrong?  No, not in and of themselves.  But for most applications they are more work than they are worth.  Your question didn't make any sort of case your design other than that it seemed logical to you.  I would be very careful about having a good justification for the added complexity before making that change, because it's a drag joining 14 tables for a simple query, and those 14 tables can creep up on you.

Title: Over normalization in database


答:
Some good improvement ways are:

reading books

working in a team, under the authority of experienced developers

You don't give us many information to help you more precisely...

Title: Determine Better Coding Practice

Body:
As a new programmer, it has always been hard to create applications, because I am still at the learning stage.

I understand that to achieve a particular affect or function in an application, there will be numerous ways to achieve the same result.

However, should I just purely create a function to it's working state, which means that as long as it works, just as the way I want it to, then it should be fine.

Can any fellow programmers of a higher level kindly let me know the right way of doing things?


答:
There is also a middle way, that I usually use.
Not thinking too much in advance, and not getting lost into the details of my code ...

TDD (Test driven development) lets you think a bit, then make it work ; then think a little more about what you need, then make it work, having the security net that your previous Use Case keeps working at all times... The steps are:

Write a test (ie a Use Case).

Watch it fail, make the failure understandable.

Write the code.

Refactor the code and the test.


答:
I don't know enough about your application to know when this amount of data break down makes sense. If you require strong control over city-state-country-zip code combinations (voter registration, emergency vehicle response), you can have a table to manage this. You really need a strong understanding how this works, so you don't paint your users into a data corner. Cities can have multiple zip codes and some zip codes can have multiple cities or other entities. Make sure you can justify this additional complexiity. Other members of your firm disagree. You need a better arguement than normalization.

There is no need to break out address lines.

Title: Over normalization in database


答:
The mantra that I repeat to my junior devs is "Make it work, then make it pretty." Your code should follow a standard for naming and what not. I use the Framework Design Guidlines when writing C# with one exception: I always place an _ before the name of a private member. Makes finding them that much easier.

Anyway, there is a second question here. And that is how to improve the code that you've written. I'll point to Clean Code and Triple P as must reads for developers wanting to learn how to code better.

Title: Determine Better Coding Practice


答:
The rule of thumb is to ask if your changes will allow you to use just a query to retrieve data that previously involved some manipulation in the software, or at least allow for a simpler query.  The answer here is no.  In fact, your changes will make some common existing queries more complex.

You're already able to retrieve a list of addresses by zip code.  The only reason to split them out would be if you're using zip codes for another purpose than customer records, such as typing in a zip code to auto-populate the city and state.  Even then, the easiest key for the zip code table is the zip code itself.

Title: Over normalization in database


答:
Realistically, you can't appropriate other people's coding standards. This is because they have requirements you probably don't. For example, look at Google's C++ style guide. It is that way not because it produces good C++, but precisely the opposite- because it produces terrible C++ that's C-style so they can interact with their legacy C code.

The only way to realistically develop good coding standards is to either inherit them from someone who has already worked on the codebase for a long time, or to learn from your own hard experiences working on it.

You should design first, then code. Rushing into programming is a bad habit. But don't make it pretty- that's just a waste of time.

Title: Determine Better Coding Practice


答:
Just have each user or each run override the database used.  That's what we do at work.  Then you never have issues with 2 simultaneous tests interfering with each other.

We have each test run build the db up with migrations, populate the db with fixtures, and then tear them back down at then end.

If the DBMS supports transactions we use that as an optimization for the initial setup and teardown.  They are optional, although your test can run a little long without it.  As always YYMV.

No fuss, no muss.

Title: Non-transactional Database and Integration Testing

Body:
One issue I think I am going to run into with my integration testing is having multiple tests accessing the same database.  While this is not a problem now, I know we have multiple applications here that access the same database and I am just trying to think of a way to prevent this issue before it happens.

An idea I have seen a lot is using transactions.  In the start up you start a transaction and then in the teardown you rollback the transaction.  This means that multiple tests accessing the same database tables and will not effect each other which is great.  The issue I have is that in my case, 85-95% of the tables I am working with in MySQL are MyISAM which don't support transactions.

Are there any ways to get around storage engines that don't support transaction but still allowing multiple test to access the same tables without them effecting each other?  From what I hear, the ruby on rails testing framework uses transactions in this way, how do they get around this issue (or do they)?


答:
Another reason to split things is if you have to offer your application in multiple languages where the same city, state and country name can be different in each language.

I have seen the same address be different in one language than another.  (think rue and street) but I agree that for most applications the address fields can all be in one table.

Breaking an address into multiple fields makes printing labels much easier and allows for the edge conditions where the address is:  Around the bend, at the corner of x and y, down the street from here, and over there.  North American address standards are not followed across the world so a few extra address fields helps out.

Title: Over normalization in database


答:
Time is a big factor in this.  You could do one programming assignment per month with time to TDD it, or you could do one every two weeks with some other testing method.  In the workplace, the month is worth it because you will live with that code for months/years/decades, and maybe even make money from it.  In the classroom where it's written and promptly thrown away (if not immediately at last check-in, at least at the end of the semester, maybe at the end of two for some special projects class), it just doesn't make educational sense.  Your professor would rather you learn twice as many programming concepts through personal experience (a project), than learn one concept and spend weeks making the code bulletproof.

The goals are different.  With the exception of a software engineering course, required-TDD on all projects might actually be a warning sign of a less-than-optimally-effective instructor at the college-project level (you're going to learn less).

And for laughs, there's always the silly case of write a unit test for Hello World before you know how to program... because you're learning how to write your first program :)  Laugh.  Do not take hello world example seriously.