问:
When are Getters and Setters Justified?
Getters and setters are often criticized as being not proper OO. On the other hand, most OO code I've seen has extensive getters and setters.

When are getters and setters justified? Do you try to avoid using them? Are they overused in general?

If your favorite language has properties (mine does) then such things are also considered getters and setters for this question. They are the same thing from an OO methodology perspective. They just have nicer syntax.

Sources for Getter/Setter Criticism (some taken from comments to give them better visibility):

http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

http://typicalprogrammer.com/?p=23

http://c2.com/cgi/wiki?AccessorsAreEvil

http://www.darronschall.com/weblog/2005/03/no-brain-getter-and-setters.cfm

http://www.adam-bien.com/roller/abien/entry/encapsulation_violation_with_getters_and

http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html

To state the criticism simply: Getters and Setters allow you to manipulate the internal state of objects from outside of the object. This violates encapsulation. Only the object itself should care about its internal state.

And an example

Procedural version of code:

```<code>struct Fridge
{
    int cheese;
}

void go_shopping(Fridge fridge)
{
     fridge.cheese += 5;
}
</code>```

Mutator version of code:

```<code>class Fridge
{
     int cheese;

     void set_cheese(int _cheese) { cheese = _cheese; }
     int get_cheese() { return cheese; }
 }

void go_shopping(Fridge fridge)
{
     fridge.set_cheese(fridge.get_cheese() + 5);
}
</code>```

The getters and setters made the code much more complicated without affording proper encapsulation. Because the internal state is accessible to other objects we don't gain a whole lot by adding these getters and setters.

The question has been previously discussed on Stack Overflow:

https://stackoverflow.com/questions/565095/java-are-getters-and-setters-evil

https://stackoverflow.com/questions/996179

答:
If using getters and setters feels complicated, the problem might be the language, not the concept itself.

Here's the code from the second example written in Ruby:

```<code>class Fridge
  attr_accessor :cheese
end

def go_shopping fridge
  fridge.cheese += 5
end
</code>```

Notice it looks a lot like the first example in Java? When getters and setters are treated as first class citizens, they're not a chore to use, and the added flexibility can sometimes be a real boon - for example, we could decide to return a default value for cheese on a new fridge:

```<code>class Fridge
  attr_accessor :cheese

  def cheese
    @cheese || 0
  end
end
</code>```

Of course there will be many variables that shouldn't be exposed publicly at all. Needlessly exposing internal variables will make your code worse, but you can hardly blame that on getters and setters.

Title: When are Getters and Setters Justified?

Body:
If using getters and setters feels complicated, the problem might be the language, not the concept itself.

Here's the code from the second example written in Ruby:

class Fridge
  attr_accessor :cheese
end

def go_shopping fridge
  fridge.cheese += 5
end

Notice it looks a lot like the first example in Java? When getters and setters are treated as first class citizens, they're not a chore to use, and the added flexibility can sometimes be a real boon - for example, we could decide to return a default value for cheese on a new fridge:

class Fridge
  attr_accessor :cheese

  def cheese
    @cheese || 0
  end
end

Of course there will be many variables that shouldn't be exposed publicly at all. Needlessly exposing internal variables will make your code worse, but you can hardly blame that on getters and setters.


问:
Can we guarantee a program will never go wrong?
We have a system here. Recently there is a wrong calculation in one of the number in the report generated by the system. Through out our experience, we've never encounter any problem/error in this system for some years.

Because the writer of this system had already gone, we can hardly trace the programs. But we've verify the input data, the setting and they are right.

Now my question is, will a computer program suddenly go wrong without any logical reason? If I slam on the server machine, will one of the number which the computer is calculating, become another number and make the calculation wrong?

I agree my idea there is quite mad, but I just want to know, how can we know the problem is not caused by the program and the input, but some other factors?

P.S. This mad system has no log.

答: It is just barely possible that the problem is caused by failing RAM, but this is relatively (very) unlikely. Run a memory test, but be ready to look through code.</p>

ContentLicense: CC BY-SA 3.0


答:
Most (standard) computing is deterministic, I would think.

If possible, set it up to do a batch of 1000 or 10000, etc., iterations with the same input data, and verify that the results come out the same.

Make sure the current values going into the calculation would cause an over- or underflow anywhere (if it is an older system it may not have been intended to be used this long).

Y2K11 anyone?

Title: Can we guarantee a program will never go wrong?

Body:
We have a system here. Recently there is a wrong calculation in one of the number in the report generated by the system. Through out our experience, we've never encounter any problem/error in this system for some years.

Because the writer of this system had already gone, we can hardly trace the programs. But we've verify the input data, the setting and they are right.

Now my question is, will a computer program suddenly go wrong without any logical reason? If I slam on the server machine, will one of the number which the computer is calculating, become another number and make the calculation wrong?

I agree my idea there is quite mad, but I just want to know, how can we know the problem is not caused by the program and the input, but some other factors?

P.S. This mad system has no log.


问:
Developing scalable applications using Agile methods
Maybe someone can share from his experience about developing an application that is meant to scale big time where just throwing more money at better hardware isn't a realistic option using development methodologies such as SCRUM and XP.

Did you need to rewrite substantial parts of your app
because of current framework couldn't scale enough to fit current sprint's
stories? how do you avoid that?

When do you do stress (or load) testing?

In what stage did you make your SMART(TM) design concerning bleeding edge requirements?

Did you add more stages to the dev-cycle of
write-a-test, code-to-pass-test, refactor?

Did you just refactor everything in the end to meet demands?

答:
In most cases, your customer should have some idea of the scale of the application.  For instance if you're building an in-house CRUD app or the "next facebook".  That on-demand customer context is sorta the point of Agile, you don't have a team of developers running off with outdated specs hoping to hit a moving target.

In that way the customer is somewhat responsible for prioritizing the stories, so if performance is mission-critical, it doesn't fall off until the end of the project.  There's also the side effect that the whole team is aware that there is a story in the backlog that requires certain performance criteria and it will naturally provoke a conversation if finishing story X in this iteration might throw off the estimate for that performance story later.

Now, discovering a performance requirement could really go badly with any methodology.  Agile may or may not be more efficient at handling this problem.  A waterfall team could easily say it wasn't in the requirements, so it's not our problem.  An agile team would likely at least try to change course.  Both have a high possibility of failing to deliver what the customer really wanted.


答: Yes, hitting a system could bend and/or move parts enough to cause a temporary open-circuit (or possibly short-circuit, though it's probably less likely).</p>


答:
Now my question is, will a computer program suddenly go wrong without any logical reason?

If you have the same computing environment exactly, then given an input X to a program will always produce the same result R. In practice, it is seldom to have a single program executing in isolation. The simplest application today runs in an operating system and shares memory with other programs that may be 'loaded' in memory at the same time. These programs may alter the memory in a way that makes a given program malfunctions. This is a famous problem with variables of type 'pointer' for example. Usually such errors cause abnormal system behaviors and not wrong calculation results.

In your case, I assume that the problem may be (and usually is) not what I have described above. The problem may be that:

the program used the wrong datatype(s) to calculate the result, that error only manifests itself when special values are used.

the program encountered an error in calculation (due to a logical condition) but did not handle the error and still produced the result. (e.g. mixing float and integer arithmetic)

a business rule or a logical condition was not coded correctly, the data that was entered represents this condition but the wrong calculation was used. (e.g. subtract amount from account amount before checking the amount in the account first).

using formulas that apply only to certain range of numbers but the data contains different range. (e.g. calculating an interest rate based on a range of values)

Because of the above and many other reasons software people spend so much resources in an attempt to create correct software, however, software errors still occur, but the errors are 'logical' and have a reason, it is just that the reason is not obvious to some without good research. So, in general tested software is predictable and does not produce random results. Due to the complexity of some programs, and other factors, even tested programs can go wrong but when that happens, errors are for a logical reason.

If I slam on the server machine, will one of the number which the computer is calculating, become another number and make the calculation wrong?

The answer is no in general, software is not fragile in that sense.

What you can do is isolate the cases where the error is occurring, find the similarity between these sets of data causing the error and find the difference between theses sets and the other sets that produce the correct result. You may be able to identify the specific set of values causing the problem. For example you may find that every time a variable has a negative value, the result is wrong.

Updated information about memory corruption errors:
Please see Memory Corruption


问:
Does C# experience translate well to C++?
My programming classes in school were C++, but I ended up working a job doing C# for the last few years. If there was a position that required say 1 or 2 years experience in C++, would my experience in C# be worthy of consideration? How effective could I be in such a position? So do I need to start out as an entry-level C++ programmer to gain the necessary experience?</p>

答:
Yes. It may not be as relevant as C++ experience, but it is good.

Good employers are going to be interested in how you think, more than how many years of a specific language you have.

An entry-level C++ position is fine: you can learn quickly, and do a great job. A good company will give you plenty of opportunity to grow. If not you can go somewhere else, and have both C# and C++ experience.


问:
Identify Service Oriented Architecture
How can I tell if a system is built upon a service oriented architecture when reading its source code?</p>

答:
If the system makes numerous calls to services which encapsulate their own logic and are defined only by their contract (parameter types and operations), then it is likely a service oriented system.

If the system doesn't make any calls to external services, then it's not a service oriented design.

Title: Identify Service Oriented Architecture


答:
I would say no!

In theory the answer is no, we can only test for:-

some limited number of environments.

some limited number of timescales.

some limited number of test cases.

This is considerably less than the total possible number of environments, times and cases the program may encounter in its lifetime. Also we have little knowledge of the future should you program cope with 10,000% inflation, should your program cope with a super duper new 31 bit architecture?

The theory is supported by experience I personally have encountered:-

Programs breaking when moved to a different locale.
Checking for "MAY" when the month was "MAI".

Programs failing tests on a new version of the compiler,
A bug in the previous version in conjunction with a bug in the program produced the correct result.

Programs breaking on a new release of the OS.
When Solaris increased the default number of directory entries the SMALLINT returned by ftok() always returned zero for the first file in the directory.

programs breaking because it was the first time they encountered a particular combination of inputs, which were both valid and unexpected and would never have been tested for -- negative interest rates on deposits, zero weight items to be shipped, items of such low value that VAT couldn't be calculated etc. etc.


问:
What are the trademark guidelines for Java technologies?
The former page "Trademark and Logo Usage Requirements" at http://www.sun.com/policies/trademarks/ is no longer available, is there a new version which helps with the proper naming of products (beans, libraries) for Java?

I have found Third Party Usage Guidelines for Oracle Trademarks at http://www.oracle.com/us/legal/third-party-trademarks/index.html however there is no occurence of "Java" related product names.

Former guidelines said that "(productname...) for the Java platform" was a correct name, and now it seems to me that it must be renamed to "(productname...) for Oracle Java" to comply with the Third Party Usage Guidelines for Oracle Trademarks

答:
Ask a lawyer.

I'd follow the instructions Oracle give on that page:

Credit Line

  All products, packaging, manuals,
  advertisements, promotional materials
   and Web pages bearing Oracle
   trademarks should include the
  following trademark credit line.

  "Oracle and Java are registered
  trademarks of Oracle and/or its
  affiliates. Other names may be
  trademarks of their respective owners."

  The credit line may appear anywhere
  on the collateral, but typically is
  displayed on a copyright page, the back
  of a package or at the end of a
  document or web page.

Alternatively contact Oracle directly:

If you have any questions regarding
  Oracle trademarks, please contact the
  Oracle Legal Department at
  +1.650.506.5200 or trademar_us@
  oracle.com. back to top Oracle 1-800-633-0738 Have Oracle call you


问:
Are there any unions for software developers?
Why does Software Engineering not have union representation like other professional occupations, such as teaching? Are there any unions for software developers that exist and are successful?</p>

答:
The software industry lacks unions simply because neither the workers nor management see the need for collective representation. There are obvious reasons why management would rather not see software professionals collectively bargain on work issues such as compensation, working conditions, etc. But software professionals haven't felt enough discomfort in the industry as a whole to take action collectively.

But the larger issue is that software professionals also haven't looked at the collective representation model the same way professionals in other industries have. The American Bar Association could be considered a union for lawyers, as the AMA is for medical doctors, and AIA for architects. Those organizations define the level of professionalism for practices and skillsets that we should model ourselves on to improve the quality of software and working environments.

We must because it's clear the management at your company isn't likely to do it.

ContentLicense: CC BY-SA 2.5


问:
What would you choose for your project between .NET and Java at this point in time?
You are just starting a new project and you have these two technologies to choose from, Java and .NET. The project you are working doesn't involve having features that would make it easy to choose between the two technologies (e.g. .NET has this that I need and Java does not) and both of them should work just fine for you (though you only need one of course). Take into account:

Performance

Tools available (even 3rd party tools)

Cross platform compatibility

Libraries (especially 3rd party libraries)

Cost (Oracle seems to try and monetize Java)

Development process (Easiest/Fastest)

Also keep in mind that Linux is not your main platform but you would like to port your project to Linux/MacOs as well. You should definitely keep in mind the trouble that has been revolving around Oracle and the Java community and the limitations of Mono and Java as well.
It would be much appreciated if people with experience in both can give an overview and their own subjective view about which they would choose and why.

答:
Performance - Even

Both platforms perform extremely well for virtually all applications.

Not really much to set them apart, though my subjective experience is that Java has a slight edge for long running applications, whereas .Net is quicker for application startup time.

Tools available (even 3rd party tools) - Debatable

Depends on what tools you need and what you are familiar with.

.Net certainly has some great tools provided by Microsoft. On the other hand, there are equally good tools in the Java world e.g. in the Eclipse, Netbeans of IntelliJ environments.

Cross platform compatibility - Java win

.Net is fundamentally tied to Microsoft platforms (Windows, Xbox etc.). Complete implementations are not available for any non-Microsoft platforms.

Mono is nice, but it doesn't actually give you full cross-platform capability because it doesn't support all the .Net libraries (for example you can't expect all the Windows GUI stuff to work correctly, so unless you switch to a cross-platform toolkit such as GTK# you won't be able to run your app on different platforms)

Java is genuinely portable. Not just the language, but much more importantly all the Java libraries are portable. Providing you stick to pure Java libraries (e.g. Swing for GUI) then your code will run anywhere you have a Java runtime environment.

Libraries (especially 3rd party libraries) - Java win

Probably the best strength of the Java platform is the vast ecosystem of libraries, especially open source libraries. Some examples:

All of the Apache libraries and tools

All the libraries in the vast Eclipse ecosystem

All the libraries contributed / maintained by Google

JBoss and all the related enterprise tools maintained by Red Hat

Cost (Oracle seems to try and monetize Java) - Java win if you go open source, otherwise Even.

You can have a 100% open source Java stack which is free and doesn't tie you into any particular proprietary platform. This is 100% free.

Alternatively, you can buy IntelliJ IDEA, run Java on Windows and use a proprietary database, in which case it's pretty much the same cost-wise as a typical Microsoft .NET stack.

Development process (Easiest/Fastest) - Debatable

This probably depends more on the experience of your developers with each platform rather than the particular attributed of the platform.

.Net certainly has some great tools that can make you very productive for simple GUI apps on Windows. Not surprising as this is the "sweet spot" for .Net development.

On the other hand, I prefer the Java stack for server-side development. With tools like Maven and all the continuous deployment / integration capabilities you can establish a very effective development process for robust server-side apps.

Language-wise C# has some productivity advantages over Java. But on the other hand if you are developing on the Java platform nowadays the trend is not to use Java itself but instead use one of the new JVM languages such as Scala, Groovy or Clojure - if you do that then you will be far more productive than either C# or Java.

OwnerDisplayName: Basic


答:
The first computer I owned was an Altair 8080 with 256 Bytes of memory.  Input was from console switches and output was from a few blinking lights.  If you disallow cosmic rays and hardware failures, I believe I could prove that some programs I ran on it would always produce the same results.

Since then, no.


问:
How do you cope with Java coming from javascript?
I learned some javascript as my introduction into programming, and now I'm trying to move on to Java and Python and from there to c++, c#, etc.

I've been caught up with schoolwork, so I've had very little chance to learn anything yet, but I have been lurking around SO looking for easy Java questions that I might have asked myself and trying to learn from the answers.

I saw one that was kind of interesting. It was a homework assignment about finding the most efficient order of jobs to do, assuming each job took two days and had to be in sequential order. I could have easily done this in javascript, but I'm having trouble figuring out how in Java. With javascript I would just return a two dimensional array. Each element being an array containing the profit and the days to work. Ignoring whether or not that's a stupid way to return data in javascript, what is the proper way to return data like this in Java?

In other words, the javascript array I would return would look something like:

[ ['1-3-5', 50], ['2-5-8', 90], ['2-4-7', 75] ]

In Java, I would have to convert the integers to strings to start off, and then find a way to concatenate two two dimensional arrays... Needless to say, this is the wrong way to go about it.

答:
Needless to say, this is the wrong way to go about it.

Not necessarily. Whatever does the job at hand in an understandable, testable and reliable fashion is a good way to go about it. At the data structure abstraction level, one can think more-or-less language-agnosticly.

Now, languages with a strong type system like Java just nudge you a little bit to good and thought-out data structures, because dirty hacks like your 2xX string vector are not much easier to pull of.

So, what you'll have to think about in making your transition is how you think about your data and put this structure into a data structure. That is, you'd probably declare a WorkLoad class that consists of a list of WorkItem objects, each of which consists of a number of week days (or whatever is in your first array element, can't tell that from looking at your data) and a profit.


答:
Firstly, I recommend you rid yourself of the notion that Java and Javascript are in any way related. It's a common misconception with newcomers, but apart from the name, and some of the basic syntax, they're about as closely related as C++ and Python.

Now, I'm not quite understanding the requirements of the actual problem (what does the string of numbers represent?) but if you're trying to decide what data structures to use in Java, the place to look is the java.utils package.

Title: How do you cope with Java coming from javascript?

Body:
I learned some javascript as my introduction into programming, and now I'm trying to move on to Java and Python and from there to c++, c#, etc.

I've been caught up with schoolwork, so I've had very little chance to learn anything yet, but I have been lurking around SO looking for easy Java questions that I might have asked myself and trying to learn from the answers.

I saw one that was kind of interesting. It was a homework assignment about finding the most efficient order of jobs to do, assuming each job took two days and had to be in sequential order. I could have easily done this in javascript, but I'm having trouble figuring out how in Java. With javascript I would just return a two dimensional array. Each element being an array containing the profit and the days to work. Ignoring whether or not that's a stupid way to return data in javascript, what is the proper way to return data like this in Java?

In other words, the javascript array I would return would look something like:

[ ['1-3-5', 50], ['2-5-8', 90], ['2-4-7', 75] ]

In Java, I would have to convert the integers to strings to start off, and then find a way to concatenate two two dimensional arrays... Needless to say, this is the wrong way to go about it.


答:
Java is not JavaScript. You have to rid yourself of the JavaScript loose typing habits to appreciate Java's type system.

In loose languages you optimize for easy implementation of the function being called. Because the function can accept and return data in any format, it makes implementing the function without a lot of overhead easy. The downside is that whoever is calling your function has to look at the source code of your function to know what data it accepts and what data it returns. This is efficient for a single programmer (assuming you can remember your functions), and inefficient for a team (everyone has to read all the source code).

In strict languages, like Java, you optimize for easy implementation by the caller of the function. The caller knows what data format the function accepts, and what data format the function returns. The more strictly you define these data formats, the easier things become for the caller. They can rely on the function signature, without looking at the source code, to know how to use the function. This is inefficient for a single programmer, but efficient for a team (people can treat functions like black boxes).

In this specific case you would have to think carefully about how this function could define its input and output so that it becomes a black box. You wouldn't return arrays of strings. You would return lists of objects of a specific (possibly self-declared) type.


答:
Using arrays for everything is a bad idea. Even in JavaScript. But in Java even more so, because arrays are far more narrow in Java.

The elements of your return array are in fact representing results. You should communicate it accordingly:

```<code>class Result {
     public int someInt;//no idea what this actually is, but a class will allow you giving it a proper name
     public String someString;//same as with the other field. Also, I suppose String is actually wrong here, since it rather looks like a '-'-separated list of integers, which should rather be represented as an array of integers
     Result(String someString, int someInt) {
           this.someString = someString;
           this.someInt = someInt;
     }
}
</code>```

And then your return value should look something like:

```<code>ArrayList.ofList(new Result('1-3-5', 50), new Result('2-5-8', 90), new Result('2-4-7', 75))
</code>```

Body:
Using arrays for everything is a bad idea. Even in JavaScript. But in Java even more so, because arrays are far more narrow in Java.

The elements of your return array are in fact representing results. You should communicate it accordingly:

class Result {
     public int someInt;//no idea what this actually is, but a class will allow you giving it a proper name
     public String someString;//same as with the other field. Also, I suppose String is actually wrong here, since it rather looks like a '-'-separated list of integers, which should rather be represented as an array of integers
     Result(String someString, int someInt) {
           this.someString = someString;
           this.someInt = someInt;
     }
}

And then your return value should look something like:

ArrayList.ofList(new Result('1-3-5', 50), new Result('2-5-8', 90), new Result('2-4-7', 75))


答:
In theory, if you start with identical state, the result will be identical. In reality, assuring identical initial state in "server sized" equipment is pretty much impossible.

Take uninitialized variables. Look at this code:

```<code>  short i;

  if(i==-1)
  {
        //do something special
  }
  else
  {
        i=0;
        //do something else
  }
</code>```

This will produce unexpected results once in 65536 runs. And unless you assure memory will be in the same state before each run, i will be entirely random.

There are hundreds similar ways for errors to pop up following unpredictable elements of the initial state someone forgot to override, or border cases that happen rarely - race conditions in multi-threaded environment, out of bounds array access, disk IO on corrupted filesystem, and so on.

If you can prove the program is bug-free, there's only the cosmic rays that can break it. But mathematical proof of correctness of anything more complex than two nested loops is pretty much beyond scope of the biggest systems (and costs a small fortune), and for all the rest you can only hope.

Body:
In theory, if you start with identical state, the result will be identical. In reality, assuring identical initial state in "server sized" equipment is pretty much impossible.

Take uninitialized variables. Look at this code:

  short i;

  if(i==-1)
  {
        //do something special
  }
  else
  {
        i=0;
        //do something else
  }

This will produce unexpected results once in 65536 runs. And unless you assure memory will be in the same state before each run, i will be entirely random.

There are hundreds similar ways for errors to pop up following unpredictable elements of the initial state someone forgot to override, or border cases that happen rarely - race conditions in multi-threaded environment, out of bounds array access, disk IO on corrupted filesystem, and so on.

If you can prove the program is bug-free, there's only the cosmic rays that can break it. But mathematical proof of correctness of anything more complex than two nested loops is pretty much beyond scope of the biggest systems (and costs a small fortune), and for all the rest you can only hope.


问:
What's the best way to organize our unit tests
We've built up a substantial number of unit tests for our main program over the years. Several thousand. The problem is that we don't have a clear idea of what tests we have because there are so many. And that's a problem because we don't know where we're weak on tests (or where we have duplicates).

Our app is a reporting engine. So you can have a template that is used to test parsing (do we read all table properties), merging in data (did we keep the correct table properties in the merge), formatting the final page (is the table placed correctly on the page), and/or the output format (is the created DOCX file correct).

Add to this what we need to test. Take the padding around a table cell (we use Word, Excel, & PowerPoint for the report design). We have to test the padding across page break, for a table inside a cell, vertically merged cells, horizontally merged cells, a vertically & horizontally merged cell that contains a table with a vertically & horizontally merged cells in the inner table, where that table breaks across a page.

So what category does that test go in? Table padding, page breaks, nested cells, vertically merged cells, horizontall merged cells, or something else?

And how do we document these categories, name the unit tests, etc.?

Update: A number of people have suggested using coverage tools to verify that we have full coverage. Unfortunately that is of limited use in our case because the bugs tend to be due to specific combinations so it's code that has all been tested, but not in that combination.

For example, we had a customer yesterday that started a Word bookmark at the end of a forEach loop in their template (a Word document) and ended it in the beginning of the next forEach loop. This all used code that has unit tests against it, but we had not thought of the combination of a template expanding a bookmark start to be started 25 times, then ended 10 times (the two forEach loops had a different number of rows).

答:
There is no reason for a unit test to be only in one category. All major unit test toolkits support the creation of test suites, which bundle tests for a particular category. When a particular area of code has been changed, the developer should run that suite first and often to see what has broken. When a test concerns padding and breaks and nesting, by all means put it into all three suites.

That said, the point of unit tests is to run them all the time, i.e. they should be small and fast enough that it's feasible to run them all befor committing any code. In other words, it doesn't really matter what category a test is, it should be run before committing anyway. Suites are really just a crutch that you use if for some reason you can't write tests that are as fast as they should.

As for coverage, there are very good coverage tools that tell you what percentage of lines were actually exercised by running your tests - this is an obvious pointer to what kind of tests you are still missing.

As for naming, there is no particular value in expending effort on the names of unit tests. All that you want to hear from your tests is "5235 of 5235 tests passed". When a test fails, what you read is not its name, but the message, e.g. the String in the assert() that implements your success critrion. The message should be informative enough that you have an idea of what's wrong without reading the body of the test. The name is unimportant compared to that.


答:
Generally, I tend to mirror the source tree for my unit tests.  So, if I had src/lib/fubar, I would have a test/lib/fubar which would contains the unit tests for fubar.

However, what you seem to be describing are more functional tests.  In that case, I would have a multi-dimensional table that enumerated all your possible conditions.  Then, the ones that have no tests are either nonsensical or need a new test.  You can, of course, then put them in sets of test suites.

Title: What's the best way to organize our unit tests

Body:
We've built up a substantial number of unit tests for our main program over the years. Several thousand. The problem is that we don't have a clear idea of what tests we have because there are so many. And that's a problem because we don't know where we're weak on tests (or where we have duplicates).

Our app is a reporting engine. So you can have a template that is used to test parsing (do we read all table properties), merging in data (did we keep the correct table properties in the merge), formatting the final page (is the table placed correctly on the page), and/or the output format (is the created DOCX file correct).

Add to this what we need to test. Take the padding around a table cell (we use Word, Excel, & PowerPoint for the report design). We have to test the padding across page break, for a table inside a cell, vertically merged cells, horizontally merged cells, a vertically & horizontally merged cell that contains a table with a vertically & horizontally merged cells in the inner table, where that table breaks across a page.

So what category does that test go in? Table padding, page breaks, nested cells, vertically merged cells, horizontall merged cells, or something else?

And how do we document these categories, name the unit tests, etc.?

Update: A number of people have suggested using coverage tools to verify that we have full coverage. Unfortunately that is of limited use in our case because the bugs tend to be due to specific combinations so it's code that has all been tested, but not in that combination.

For example, we had a customer yesterday that started a Word bookmark at the end of a forEach loop in their template (a Word document) and ended it in the beginning of the next forEach loop. This all used code that has unit tests against it, but we had not thought of the combination of a template expanding a bookmark start to be started 25 times, then ended 10 times (the two forEach loops had a different number of rows).


答:
In our organisation, at this point in time, we'd choose Java. The reason for that is simple: our Java team is larger, more experienced, and better tooled than is our .NET team (who also are tied up enough in maintenance of existing systems that they lack the resources to take on any major new projects).

That said, if there were pressing reasons to use .NET (e.g. client requirements, some customers may have a large installed base of .NET software and want their new system to fit into that base, take over maintenance themselves, etc.) we will do so and hire contractors to do the work where we can't free our own people.

I would not force either technology on a customer against their best interests, and some customers simply benefit (because of their internal organisation) more from one than the other because of investments needed to deploy the system (again, say we have a customer who already has a number of .NET applications running and has the staff to support those, we're not going to try and force them to hire people and buy hardware and software licenses to run a Java application on the side, and of course the reverse would also be true. We'd in fact advise them not to do so if they came to us with that as a request).

Title: What would you choose for your project between .NET and Java at this point in time?

Body:
You are just starting a new project and you have these two technologies to choose from, Java and .NET. The project you are working doesn't involve having features that would make it easy to choose between the two technologies (e.g. .NET has this that I need and Java does not) and both of them should work just fine for you (though you only need one of course). Take into account:

Performance

Tools available (even 3rd party tools)

Cross platform compatibility

Libraries (especially 3rd party libraries)

Cost (Oracle seems to try and monetize Java)

Development process (Easiest/Fastest)

Also keep in mind that Linux is not your main platform but you would like to port your project to Linux/MacOs as well. You should definitely keep in mind the trouble that has been revolving around Oracle and the Java community and the limitations of Mono and Java as well.
It would be much appreciated if people with experience in both can give an overview and their own subjective view about which they would choose and why.


答:
One way of knowing whether you are weak on tests is traceability. Usually for tests, this takes the form of coverage.

The aim is to measure what parts of code are exercized by your tests, so that you can see code that is not covered by your tests. It is up to you (and the coverage tool) to define what a "part of code" is. The least is branch coverage.


问:
Which programming methodology would be a good fit for us?
Unfortunately, somebody has taught our upper management the word "Agile" and now they want us to move towards it. I have a peripheral understanding of agile (in principle) but have never used it in practice. From what I know, it will not be a good fit for our organization. Right now, things are pretty grungey. Here's how it is;

We're a very small team - two developers, one DBA, one designer. The company I work for makes a disproportionately large amount of money relative to its size, and nearly 95% of that is pure online sales.

From a development perspective, we are subjected to many desk invasions during a typical day (we're tech support as well as dev), work can regularly just fall out of the sky at a moments notice if a sales team member promises something to someone. We do undertake larger projects too, and they're a nightmare with the constant interruptions. Some of us are starting to tear our hair out! Project plans are drawn up by non technical managers in excel spreadsheets, where they try and break the task down into bite-sized sentences that they can understand and put a date beside each one. These dates are always hideously unrealistic and often missed, and our meetings (which we have around weekly) are regularly filled with awkward moments with people asking "why hasn't this been done yet".

I am pretty sure Agile isn't the one for us. Now, given that (and i have tried) this company will not change its ways, and only the dev team is willing to change, is there a development methodology that we could adopt which is a good fit for just saving us some sanity?

答:
Agile isn't a programming methodology, Agile is a project management methodology. If upper management really want you to try this new buzzword that they've found, they need to be able to understand that the Agile method starts from the top and involves the management through every step of the way. If you need to give them a hard dose of reality, maybe organise a 30 minute Powerpoint presentation about Agile to give them a bit of education. Managers love Powerpoint.

However if, as you say, the dev team are the only people willing to change, then no development methodology will be able to help you. Without an alleviation of the rest of your duties, interruptions will continue to happen and you will continue to be asked to meet deadlines that you simply cannot meet.

My advise in this scenario is to educate, not berate, management as to how it really is on the front lines.


答:
I would say you need a methodology such as Agile is essential for your team. As your company is so disorganised you need to be more organised within your own dev team. I dont think however your non technical managers should have anything to do with it.

If your going to push back on your sales people and demand realistic deadlines you need to justify that with organised plans.

Also on a seprate note if they come to you with estimates without consulting  technical then just refuse them point blank.

Title: Which programming methodology would be a good fit for us?

Body:
Unfortunately, somebody has taught our upper management the word "Agile" and now they want us to move towards it. I have a peripheral understanding of agile (in principle) but have never used it in practice. From what I know, it will not be a good fit for our organization. Right now, things are pretty grungey. Here's how it is;

We're a very small team - two developers, one DBA, one designer. The company I work for makes a disproportionately large amount of money relative to its size, and nearly 95% of that is pure online sales.

From a development perspective, we are subjected to many desk invasions during a typical day (we're tech support as well as dev), work can regularly just fall out of the sky at a moments notice if a sales team member promises something to someone. We do undertake larger projects too, and they're a nightmare with the constant interruptions. Some of us are starting to tear our hair out! Project plans are drawn up by non technical managers in excel spreadsheets, where they try and break the task down into bite-sized sentences that they can understand and put a date beside each one. These dates are always hideously unrealistic and often missed, and our meetings (which we have around weekly) are regularly filled with awkward moments with people asking "why hasn't this been done yet".

I am pretty sure Agile isn't the one for us. Now, given that (and i have tried) this company will not change its ways, and only the dev team is willing to change, is there a development methodology that we could adopt which is a good fit for just saving us some sanity?


答:
look at extremeprogramming.org - XP is a form of Agile with easily understood aspects which you can pick and choose a la cart; a very good place to start

the customer commitment to not change their minds during an interation would be a good starting place for your environment, from the sound of it ;-)


答:
Perhaps focussing on the incremental/iterative aspects is what both your team, and the fall-out-of-the-sky stakeholders need to be able to deliver regularly and consistently. Over time, the sales team and management will gain faith in that when they put in a new feature request, they can be sure your team will deliver in a suitable timeframe.

Of course, you need to invest in unit/system/regression testing, automated builds, dogfooding, etc, to get there if you're not there already.


问:
How can I advocate unit testing on private code?
I'm trying to advocate unit testing in my workgroup, but an objection I often get is that it should be used only for externally exported API (which is only a minimal and non critical part of our system), and not on internal and private code (which now has only functional testing).

While I think that unit test can and should be applied to all the code, how can I persuade my coworkers?

答:
Unit testing is all about testing units of your code. It is up to you to define what a unit is. Your coworkers define units as API elements.

Anyway, testing API should result in exercising private code as well. If you define code coverage as an indicator of unit testing progress, you will end up in testing all your code. If some part of code has not been reached, give your coworkers three choices:

define another test case for covering that part,

analyze code for justifying why it cannot be covered in the context of unit testing but should be covered in other situations,

remove dead code that has neither been covered not justified.


答:
Testing shows the presence, not the absence of bugs (Edsger W. Dijkstra)

If you're trying to prove that your program works correctly by testing, it won't work.

However, there some approaches in theoretical computer science where you develop a formal proof of the software you have written. Depending on the complexity of your system, this can be a tedious process though. If your system, however, works on a restricted set of commands, you could be successful with this approach.


问:
Is it unusual for a small company (15 developers) not to use managed source/version control?
It's not really a technical question, but there are several other questions here about source control and best practice.

The company I work for (which will remain anonymous) uses a network share to host its source code and released code.  It's the responsibility of the developer or manager to manually move source code to the correct folder depending on whether it's been released and what version it is and stuff.  We have various spreadsheets dotted around where we record file names and versions and what's changed, and some teams also put details of different versions at the top of each file.  Each team (2-3 teams) seems to do this differently within the company.  As you can imagine, it's an organised mess - organised, because the "right people" know where their stuff is, but a mess because it's all different and it relies on people remembering what to do at any one time.  One good thing is that everything is backed up on a nightly basis and kept indefinitely, so if mistakes are made, snapshots can be recovered.

I've been trying to push for some kind of managed source control for a while, but I can't seem to get enough support for it within the company.  My main arguments are:

We're currently vulnerable; at any point someone could forget to do
one of the many release actions we have to do, which could mean whole
versions are not stored correctly.  It could take hours or even days
to piece a version back together if necessary

We're developing new features along with bug fixes, and often have to delay the release
of one or the other because some work has not been completed yet.  We also have to force
customers to take versions that include new features even if they just want a bug fix,
because there's only really one version we're all working on

We're experiencing problems with Visual Studio because multiple
developers are using the same projects at the same time (not the same
files, but it's still causing problems)

There are only 15 developers, but we all do stuff differently; wouldn't
it be better to have a standard company-wide approach we all have to
follow?

My questions are:

Is it normal for a group of this size not to have source control?

I have so far been given only vague reasons for not having source control - what
reasons would you suggest could be valid for not
implementing source control, given the information above?

Are there any more reasons for source control that I could add to my
arsenal?

I'm asking mainly to get a feel for why I have had so much resistance, so please answer honestly.

I'll give the answer to the person I believe has taken the most balanced approach and has answered all three questions.

Thanks in advance

答:
Source-control is good for even a single developer team. Any source control system is basically a version control system that keeps the track of changes. Imagine of a single developer, who might have removed some code and feels that the code is now required. Can he get the old code back?

Just go for a tool that helps you. The size does not matter everywhere. The quality does matter everywhere.

OwnerDisplayName: LordScree


答:
It is absolutely not normal for a group that size to be working without source control—the size of the largest group of programmers that can work effectively without source control is less than or equal to one. It’s absolutely inexcusable to work without version control for a professional team of any size, and perhaps I’m not feeling creative, but I can’t come up with any reason why you would want to forgo it.

Version control is just another tool—a particularly powerful one, and one which delivers enormous benefits relative to its minimal cost. It gives you the power to finely manage all of your changes in an organised fashion, with all kinds of other handy things like branching, automated merging, tagging, and so on. If you need to build a version from umpteen versions ago, you can check out the code from that point in time and just build without having to jump through any other hoops.

More importantly, if you need to write a bugfix, you can merge it into an update without having to deliver the new features you’re working on—because they’re on another branch, and as far as the rest of the development needs to be concerned, they don’t exist yet.

You’re experiencing resistance because you’re challenging the culture of the company. It will take time for them to adjust, no matter what you say. The best you can do is keep pushing for it, and if the company really won’t budge, find another job that’s better suited to your level as a developer.

Title: Is it unusual for a small company (15 developers) not to use managed source/version control?

Body:
It's not really a technical question, but there are several other questions here about source control and best practice.

The company I work for (which will remain anonymous) uses a network share to host its source code and released code.  It's the responsibility of the developer or manager to manually move source code to the correct folder depending on whether it's been released and what version it is and stuff.  We have various spreadsheets dotted around where we record file names and versions and what's changed, and some teams also put details of different versions at the top of each file.  Each team (2-3 teams) seems to do this differently within the company.  As you can imagine, it's an organised mess - organised, because the "right people" know where their stuff is, but a mess because it's all different and it relies on people remembering what to do at any one time.  One good thing is that everything is backed up on a nightly basis and kept indefinitely, so if mistakes are made, snapshots can be recovered.

I've been trying to push for some kind of managed source control for a while, but I can't seem to get enough support for it within the company.  My main arguments are:

We're currently vulnerable; at any point someone could forget to do
one of the many release actions we have to do, which could mean whole
versions are not stored correctly.  It could take hours or even days
to piece a version back together if necessary

We're developing new features along with bug fixes, and often have to delay the release
of one or the other because some work has not been completed yet.  We also have to force
customers to take versions that include new features even if they just want a bug fix,
because there's only really one version we're all working on

We're experiencing problems with Visual Studio because multiple
developers are using the same projects at the same time (not the same
files, but it's still causing problems)

There are only 15 developers, but we all do stuff differently; wouldn't
it be better to have a standard company-wide approach we all have to
follow?

My questions are:

Is it normal for a group of this size not to have source control?

I have so far been given only vague reasons for not having source control - what
reasons would you suggest could be valid for not
implementing source control, given the information above?

Are there any more reasons for source control that I could add to my
arsenal?

I'm asking mainly to get a feel for why I have had so much resistance, so please answer honestly.

I'll give the answer to the person I believe has taken the most balanced approach and has answered all three questions.

Thanks in advance


答:
Not using source control is asking for problems, even for a solo developer. The simple fact that you can edit ruthlessly without risking to lose anything makes up for the learning effort within weeks or days.

That said, if you can't convince your managers to introduce source control, do yourself a favor and at least use something like git or mercurial locally - if things blow up due to lack of source control, at least you won't be the one who did it.


答:
It really does depend on the nature of the business you're applying to. If they're looking for someone who has good OO-based programming and architecture skills, C# is likely as good as the next thing.

If they take pride in their software's speed/responsiveness, then you're going to need to know your algorithms as this matters more than micro-optimisations - Hash Tables versus Linear lookup, etc. C# is still relevant here, but you'd need to demonstrate understanding of the performance characteristics - not everyone knows about ngen.exe, for example.

If they're into embedded/mobile and/or non-garbage collected environment, you really need to know about how to effectively manage memory. Smart Pointers, as @DeadMG pointed out, are key here, but so is understanding the memory allocation profile. Games programmers often pre-allocate large arrays of objects and recycle them in order to know the memory requirements up-front and reduce unknowns on a per-frame basis. This is also the technique used in the scrolling TableViews in iOS.

If there's any integration work, you're likely to need C-level expertise in terms of marshalling data between languages (like P/Invoke) but also byte-level understanding of how these data structures may get used, which is not common practice in C# in my experience.

Title: Does C# experience translate well to C++?

Body: My programming classes in school were C++, but I ended up working a job doing C# for the last few years. If there was a position that required say 1 or 2 years experience in C++, would my experience in C# be worthy of consideration? How effective could I be in such a position? So do I need to start out as an entry-level C++ programmer to gain the necessary experience?</p>


答:
I would say take advantage of your managements whims! Sounds like they are doing you a favour and giving you some leverage to improve your working methods.

Say to them OK we will go agile it requires among other things:-

a separation of development and support

a formal requirements gathering process -- under control of the IT team.
"Stories" etc. sounds all very vague -- but its actually a "formal" method dressed up to look informal.

scheduling is under control of the IT team.

If they don't accept this then tell them you cannot go agile.


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答:
In C/C++: That assignments are also expressions COMBINED WITH the very similar assignment = and comparison == operators. Not a harmful feature per se, but it's way to easy to introduce (sometimes subtle) bugs by accidentally mistyping the operator.</p>

```<code>int i = 10;

someCode();

if(i = 5)
{
    /* We don't want this block to be executed, but it is */
    moreCode();
}
</code>```

Body:
In C/C++: That assignments are also expressions COMBINED WITH the very similar assignment = and comparison == operators. Not a harmful feature per se, but it's way to easy to introduce (sometimes subtle) bugs by accidentally mistyping the operator.

int i = 10;

someCode();

if(i = 5)
{
    /* We don't want this block to be executed, but it is */
    moreCode();
}


答:
we have 3 members of development staff and use source control. On my personal projects I have one developer and I use source control. It's not just useful for team management, it's useful for being able to get into doing experimental work without fear you're doing to destroy something.

Easiest way to convince management? There's less risk to the overall product, and it'll increase developer productivity in the long run. Both are true as well, and both appeal to managers.


答:
It is by no means a normal scenario and i think you should give a tough fight for getting this setup in your company. It has far reaching benefits and has no point in realizing the same when you approach doomsday and it ain't the situation which fall under If it ain't broken don't fix it

Any reason for not implementing it could be only an excuse for bad work or a blunder waiting to happen.

Just tell them how great its to find what the app was on 1 Jan this year

how about hey this functionality was added in March i think we need to expand a bit more on this.

Wow this bug 154256 has been fixed in this commit.

i can branch out the app and send out the deployment no problem guys you can carry on working.

This can go on and on ... (remember to add comments on commits later on else that would be coming in as another question )


答:
Is it normal for a group of this size not to have source control?

In my experience, it is not the norm, but not as completely unusual as other answers here suggest. The majority of small companies does use source control, but a significant number doesn't, unfortunately.

I have so far been given only vague reasons for not having source control - what reasons would you suggest could be valid for not implementing source control, given the information above?

See this question on SO for a good discussion. The accepted answer says:

 "There are no good reasons not to use version control. Not one."

Are there any more reasons for source control that I could add to my arsenal?

The consensus among all developers and project managers I have met, and of course here on Programmers and SO is that source control is a must. It's an accepted best practice. If somebody decides to ignore it, he needs to have some very strong and convincing arguments why this is the right decision for him (i.e. a little more than 'we never needed it, so why should we need it in the future'). The arguments you have presented so far are focused on specific issues, perhaps you should try a wider approach along the lines of 'everybody does it, so why don't we as well?


问:
Project Management Software / 1 maybe 2 developers
I am looking for software that I can use to "manage" multiple projects (5 - 10). Here are the features I would like but any recommendation is welcome.

Bug/Feature tracking on a per project basis.

Some way to keep all documents, diagrams, specs, requirements, in one place with the project. Better yet a tool where all these things or most of them could be authored.

Task management during the development phase with milestones and estimates/actuals.

Git integration

I have been doing contract work and i have been doing really well for myself as far as getting projects but its becoming VERY hard to manage everything in an efficient manner. I am trying to learn about best practices when it comes to software programming methodologies and the more I read the more i realize that I am just managing these projects poorly. I am getting things done but the more I take on the less "solid" everything is. I am afraid if I don't get some good solid tools/practices in place I am going to do my customers and myself a disservice. The problem is that there are SO many options that its hard to weed through them all. I was at a point today where I had decided that I would just code my own (there is some irony here)!

Obviously everyone has their likes dislikes I would love to hear from some of you lone programmers and how you manage everything since our needs aren't exactly the same thing that a large team might need. I also want a solution that can scale to 2 maybe 3 developers if I end up hiring some people to help with my work load.

Thanks again for your usual insights!

答: Try using Microsoft Project Professional 2010. It has helped me meet crucial deadlines and select the right resources. This online Project Management Software delivers collaborative project management across groups of all sizes.</p>


答:
I cannot imagine how 15 developers can work without any source control. However, from:

(...) uses a network share to host its source code (...)

I assume you have created your own poor-man's version control like VSS (also based on shared folder). It's risky and not efficient.

Explain to your boss how bad it is, invest in some 2-days SVN or GIT training, and start using real version control system while you still have your code in reasonable shape.


答:
Is it normal for a group of this size not to have source control?

No definitely not. When I started at my current company, there was one person whom you should send your changed code to, and he would merge it. I could convince everybody within days to use SVN.

I have so far been given only vague reasons for not having source control - what reasons would you suggest could be valid for not implementing source control, given the information above?

I think the reason you only heard vague reasons is because there are no valid reasons for not using version control.

Are there any more reasons for source control that I could add to my arsenal?

Yes, there are a lot of reasons.

Branching gives you the possibility to develop new functionality without interfering with other developments.

Each commit gives you the information about what exactly has been changed, who did that change, and when that change was made.

You can easily commit bugfixes, and deploy them to the customers, and leave out the unfinished new functionality.

You can maintain different versions, if customers are afraid of going to a newer version.

You can work on the same project (even the same source files!) with ease.

You can easily revert a mistake, with preserving the changes after that committed mistake.


答:
It may not be normal, but as Treb says, it's probably not that unusual

As others have said, there are no valid reasons for not having source control in a company your size. So you need to identify and attack the invalid reasons:

a) the main one is the status quo: "if it ain't broke, don't fix it". This is difficult: you could start pointing out all the things which aren't working as well as they should (which can quickly get you labelled as a 'negative person'), or you just wait for something to blow up (which might never happen), or you could emphasise all the things that could go wrong. Unfortunately people in charge of small companies are relatively impervious to 'things which could go wrong' until they actually do go wrong...

b) ignorance/fear/uncertainty: "we don't really understand what source control is; we don't know how to use it; we don't know which tool to choose; it's going to cramp our style". This is one reason I definitely wouldn't send them here! It might be a fairly tall order for you on your own, but I think to maximise your chances you need to present a 'turn-key' solution, and not too many variants or alternatives. You need a clear idea of: how you want to fit/transform your working process to work with the given tool; how/if you plan to back-port existing code; how fast you think you can 'train' users and have them up and running; how you can manage the transition period (if there is one); how much it is likely to 'cost' (in hours, if not in dollars).

c) there may be other reasons (previous bad experiences with VSS for example, or having read 'horror stories' about allegedly over-complicated tools), but you'll have to bat those ones individually when you discover them.

There are ample reasons for source control outlined in the other answers. My advice would be to pick out the main 2 or 3 that could really make a difference to your company and polish them up and present them in a meeting to as many of your colleagues as possible. Try to provoke discussion: even if you don't immediately convince them, you will gain insight into what the sticking points may be.

(Have you read/heard about The Change Function?)


问:
Which algorithms and data structures should a developer absolutely know?
I want to be a successful enterprise Java developer. With what algorithms and data structures should I be well versed? What books would you recommend to me?

To be a successful Java developer, do I need to know all the advanced algorithms such as those given in CLRS?

Can you suggest a list of the topics that I should learn in the descending order of their priority?

Must I know:

Searching?

Sorting?

Graphs/Trees?

etc?

答:
Cormen's Introduction to Algorithms is a good book for some basic theoretical foundations.

That said, most algorithms and data structures have been coded, tested and optimized by others already, and there's no reason to re-implement them once more. To be a successful Java developer you need to know The Collections Framework inside out.


答:
Can you guarantee a program has no bugs and will never go wrong? No, unfortunately not.

Can you demonstrate that a program has a sufficiently small number of bugs that the cost of finding and fixing them far exceeds the benefit from that action? It sounds to me like you already have.

To paraphrase an old statistics maxim, all programs are wrong, but some programs are useful.


问:
How much does/should your style imply about your skill in a language?
Two things I've noticed in the past week that make me wonder:

An interview where my Perl skills were reviewed. I always use C-style for loops and use map about once in every 10,000 lines of code, so I almost always have to reference it before using it. While I can interpret others code using that, it's not my style and that is for reasons involving readability and ease of changing between languages. I at least perceived that I was dinged for that.

This answer to my question in which the answerer proceeded to refactor and bullet-proof my tiny script. I admit I was a little bit offended and kind of annoyed at that, though I can understand how that as a habit may be helpful.

I understand that in a team, my style will need to adapt what the team has decided is correct -- this is necessary in every project and everybody has their own ideas. Yet I feel like I'm judged for what is syntactically fine and readable code.

How much does the style of your smaller snippet code weigh in? Does code like that imply to others that I don't have control of the language because I didn't use all the features? Does my code imply that I'm not familiar with unit testing and proper testing because I didn't fully error-protect a tiny script?

答:
1) Like ikegami, I spend a fair bit of time on SO answering Perl questions and one of my common pieces of advice is "don't use C-style for loops in Perl; use the list iterating version instead because it's harder to mess it up".  If you write for my $i (1 .. 10), there's no way you're going to get the boundary conditions wrong, plus it's quicker to write and requires less thought than the C-style equivalent.  If I were an interviewer and saw you write for (my $i = 1; $i <= 10; $i++) instead, I would question how well you know Perl and whether you were writing Perl directly or if you were thinking in C, then translating it to Perl.

If I saw you write for (my $i = 1; $i <= 10; $i++) { $data = $some_array[$i];... } instead of for my $data (@some_array) { ... }, on the other hand, then I would conclude that you clearly don't know Perl very well and the interview would be pretty well over in my mind, assuming it was for an experienced Perl position.  (Unless $i was going to be used for something else beyond just sequentially indexing into @some_array, but even then I'd favor for (..) over for (;;).)

Style does matter, especially with a language that's as TIMTOWTDI as Perl.  There are many ways to do it, but not all are equally good (for any given value of "good", which does vary from situation to situation).  Using all the language features isn't necessary for good style, but using the right ones when they're appropriate will get you pretty far in that direction.

2) Regarding the linked answer, your code there looks fine to me overall.  The main thing I question is the & prefix on your final function call.  You don't need it (unless you're writing Perl 4, in which case you have far bigger problems!) and it's generally discouraged these days because it has side-effects which aren't immediately obvious.  Definite bonus points for using strict, three-arg open, lexical filehandles, and CPAN modules, though.

On the larger point of your second question, I frequently rewrite people's code to clean it up and show (at least some elements of; I try to match it to their apparent skill level) how I would do it.  It's not meant as a slight on the original author; it's an attempt to help and to educate beyond the immediate question at hand.  It's usually pretty fun, too.  But, perhaps most importantly, the simple fact of the matter is that Perl has an image problem.  There are a lot of people out there (*cough*Job*cough*) who think that "there is no such thing as good Perl style" and I feel that it's important to disprove that belief by showing off well-written, maintainable Perl code when the opportunity presents itself.


答:
If one considers the landscape of methodologies, both traditional and contemporary, one would realise that "Agile" is more of an "anti-methodology" than a methodology. Patterns aim to portray the "best-case" solution to a given problem within a particular context. Attempts to directly violate such a solution or pattern, are generally referred to as "anti-patterns" or worse-case practices. Likewise, while true software development methodologies attempt to prescribe best-case practices in developing solutions, "Agile" (Scrum, XP, etc.) attempt to directly violate any and all structure within the software development process, in favour of a haphazard, chaotic approach - which (of late), also seems to demand applause from (naive) onlookers.

With that said, it is appropriate to bear in mind the context in which the Agile philosophy arose. Although sophisticated iterative methodologies (e.g. Unified Process) existed at the time, the primary methodology was still the old waterfall approach, which prescribed a "best-practice" of complete requirements analysis, then complete design, then develop/code the solution, then implement the solution. Clearly, this engineering approach to software development was ill-advised - and resulted in heaps of paperwork before (and sometimes without ever) seeing an executable solution.

However, it still does not warrant the throwing out of the baby with the bath water, as was the case with the conjurers of Agile. The Agile approach almost enforces a direct negation of anything that was used prior to it - except maybe the actual coding of the solution. Clearly, this is an indication of limited insight on the part of its originators, or maybe it's simply a case of "there are none as blind, as those who do not want to see".

Nevertheless, the merit of agile is that it encourages streamlined processes and focuses on executable code - which is inevitably your ultimate deliverable.

NOW, to answer your question more directly:

Given your overview of your environment, I suggest you firstly select an Agile implementation (i.e. Scrum, XP, etc). Then customise the approach to suite your environment, delineating a clear process of how your team will be working, e.g.:

Receive request from user(s);

Prioritise user requests;

Gage impact of enhancement on the existing system (maybe during your daily/weekly stand-up meetings);

Estimate the development time of each enhancement - and communicate these back to various requesting users;

Perform actual enhancement(s) on existing system (i.e. coding).

Conduct user testing - and get commitment from the users (e.g. via email) that the requested changes has been successfully implemented.

This should provide some structure (and order), whilst also maintaining some semblance of an Agile approach.

With the above said, remember that the old English figure of speech, "As Agile as a monkey”, was not coined without reason!


答:
If I don't commit several times a day, or at least before I leave for home, I feel like .. somethings missing, somethings wrong.

I once worked in a company with just 2 developers (me + long haired admin guy), back in 1998. Even then we used svn. It's just so convenient.

Several times in my career I lost a days of work because I did something like mv instead of cp and then rm -rf. Made me cry and wander around in the city streets in despair.

I worked in 5 companies over my 13 years of being in the SE, been to some conferences, and never encountered a company not using version control.

However, my favorite interior design company, 20 employees, use a white board for project management + collaboration. They know its plain wrong, but they don't seem to find time to upgrade. Somehow it works though. Don't ask me how.


答:
No software development and project management methodology can help in an organization where sales people dictate the day to day schedule.  How are you supposed to manage a project amidst such a chaotic and distraction ridden work week?

So many upper managers see the value of Agile and want the benefits of it but they almost never are able to make the internal changes necessary to make sure the move is successful.  The only successful Agile shops I have known of had started out that way.  I can't recall a single instance in my professional experience of a sales managed or waterfall software development shop making the move because it requires a fundamental change in culture.

Is this change in culture possible?  Yes, but in your case almost certainly not.

A change in culture is usually necessitated by a competitor threatening the existence of the company or a make or break situation or some other similarly involved situation to justify a re-org.  In your situation, your company is at the complete other end of the spectrum where money right now is easy and everybody is getting fat.

Companies NEVER change from within when the money is easy.  Why should they, they are successful despite the software development failures, not because of software development successes.

My final advice is that if I were you I would look for something better.  People on here have great advice but I have seen this song and dance before and it just doesn't work in your situation.


问:
How do you manage your knowledge base?
As programmers we have a lot of inputs:

Ebooks

Code snippets

Interesting emails

Documents

Web articles

Blog posts

StackOverflow questions

Podcasts
...

Which tools do you use to store, organize, search and consult all of this stuff?

Is there a silver bullet solution to handle this huge amount of data?

答:
I've been using TiddlyWiki for a few months now. It's a editable wiki page all contained within a single html file.

The idea is that you make notes (called tiddlers) and edit content via the html/js interface. When you hit save (or the autosave kicks in) it overwrites itself to include all your updates.

It doesn't require a web host or anything complex, just save the .html file on your hard drive and open it in your favourite browser. I have set the file as my homepage and put it in my dropbox so it syncs across all my PCs.

Alternatively, GSto has pointed out that tiddlyspot.com provides free online hosting of tiddlywiki pages with public and private options.

Title: How do you manage your knowledge base?


问:
Can we guarantee a program will never go wrong?
We have a system here. Recently there is a wrong calculation in one of the number in the report generated by the system. Through out our experience, we've never encounter any problem/error in this system for some years.

Because the writer of this system had already gone, we can hardly trace the programs. But we've verify the input data, the setting and they are right.

Now my question is, will a computer program suddenly go wrong without any logical reason? If I slam on the server machine, will one of the number which the computer is calculating, become another number and make the calculation wrong?

I agree my idea there is quite mad, but I just want to know, how can we know the problem is not caused by the program and the input, but some other factors?

P.S. This mad system has no log.

答:
I'm inclined to say no, you cannot prove that a program will never go wrong or provide an incorrect result, even if you can assume perfect input.

Raku mentioned formal proof of correctness. That's one thing to consider, but unless I'm completely mistaken, that will still have to assume a perfect execution environment. So, with some amount of time and effort, you can perhaps prove that the program is correct, but that does not necessarily prove that it will always produce the correct results, even given perfect input. The execution environment matters. And I would be wary of assuming that the input is always perfect, either.

This is why, in certain high-availability situations, multiple, completely independent implementations and execution environments are used, and the results are compared to make sure that they are within an acceptable margin of error from each other. In some situations, that margin may very well be zero. Even back in the 1960s, this was deemed important enough to include separate sets of computing hardware in spacecraft. Even if an errant static discharge, cosmic ray or whatever were to affect both computers simultaneously, the odds that both would be affected in the same way (particularly if they are both still working and producing valid-looking results) are miniscule. The odds of the same bug creeping into two completely separate implementations are also extremely small. And so on.


答:
Where I work we have the same problem. I'm currently trying to slide source control in "under the radar" to get around the same issues you have. I use fossil for the projects I develop personally.

I recently got a fossil server set up on the company LAN, so now its even more convenient. I'm hoping that as I demonstrate the usefulness on some smaller projects that I'll undermine the resistance and move us away from the status quo of network folders.

The biggest reasons I've heard for not using fossil, or some other VCS are:

Many of the "programmers" are script kiddies, and won't understand how to use it

Those who could learn, think it is a nuisance to use

These people are the old guard, comfortable with the network folders, so everyone should be

No one has time to set it up right, or learn how to use it

While the features might be great, none of them are necessary

As you can see, I'm trying to get around these by demonstrating that it's simple to use, already set up, easy to learn, and the features are completely worth it.

Finally, even if you don't get them to use source control, it's all in a network tree. Fossil can version everything in the entire tree, and you can set it up to run whenever a file change occurs, or at least every hour. I've done that for some of our projects that "didn't need source control" and it ended up allowing me to roll back to a good version when something went wrong.

Do it right, and they won't even know you've done it. Then you can be the hero who restores the broken build, and demonstrates how useful your tool is.


答:
We were in a similar position with a 6 person team a few years ago. One of the developers took the step of installing SVN on a dev server where the shared folder was and just started using it.

Everyone followed suit, and wasn't long before we implemented CI (CruiseControl) and revolutionized our build and release process to include automation and quality checks.


问:
Does a project using proper TDD have a lot of code without tests?
Most (all?) TDD resources show you how the cycle goes:

Write Test

Check Test

Write Production Code

Check Test

Clean up Production Code

Check test

They also - to me - seem to imply that all code is covered by tests.

However, reading posts like Writing Great Unit Tests: Best and Worst Practices (for example, linked to here) it's said that

TDD is a robust way of designing software components (“units”) interactively so that their behaviour is specified through unit tests

To fill in some more context:

At the other end of the scale, integration tests contain no knowledge about how your codebase is broken down into units, but instead make statements about how the whole system behaves towards an external user.

This makes perfect sense to me. However, it implies that large parts of the applications code are not covered by tests. Why? Because if you have units (and you need a lot of units to get your Unit Tests right) you need code that wires the units together. This code, IMHO, will get complicated enough that it deserves to be tested on a more granular level that integration tests while it probably falls into "Dirty Hybris":

Anywhere in between, it’s unclear what assumptions you’re making and what you’re trying to prove. Refactoring might break these tests, or it might not, regardless of whether the end-user experience still works

So to sum up:

I easily see the value of Unit Tests with TDD

Some code is needed to wire the units together

This code will be complex and integration testing will/may not be enough.

TDD resources on the net seem to imply 100% code/test coverage, yet

looking at TDD with True Unit Tests will leave some code untested

Edit: wikipedia says:

Integration testing takes as its input modules that have been unit tested

but somehow I feel there's still quite a bit of wiring code missing from the picture. (except if "module" means "class or function" because that is what's unit tested in isolation)

Insights?

答:
However, it implies that large parts of the applications code are not covered by tests. Why? Because if you have units (and you need a lot of units to get your Unit Tests right) you need code that wires the units together. This code, IMHO, will get complicated enough that it deserves to be tested on a more granular level that integration tests while it probably falls into "Dirty Hybris":

Your assumption is faulty because you are neglecting a layer of testing - acceptance testing.

Your unit tests cover individual units - the classes and methods that compose them. This enables you to test methods and classes in isolation to ensure that they are behaving as expected. Above this lies your integration tests, which tests the collaboration between classes and ensures that larger modules (packages and even inter-package collaboration) work as expected. Finally, your acceptance tests are used to verify and validate your entire system, as assembled, against the user requirements.

Assuming that you have the appropriate unit and integration tests that correspond to requirements and well-defined acceptance criteria and acceptance test plans, then everything in your system is tested. Other aspects of testing - smoke tests, regression tests, and so forth, are simply an appropriate subsampling of the unit, integration, and acceptance tests.

TDD is a robust way of designing software components (“units”) interactively so that their behaviour is specified through unit tests

That particular quote is also missing something. As I was taught, TDD isn't just about unit tests, but developing all tests first. That includes not only unit tests, but the necessary acceptance and integration tests as well.


答:
It sounds like you are already using a system of version control, but not a very good one.  People already seem to recognize the need version control.  You just need to introduce them to the next level -- software version control.

If it were me, I would introduce SCM as an improved version of what they are already doing.  I would emphasize how using a good tool will automate a lot of the work that is already going on.

Instead of recording changes in a spreadsheet, the SCM system keeps
track of not only what changed, but who changed it and why.

As a bonus, you can go back to any point in the code's life and see what was actually there.

Instead of having different versions of code in different folders and needing to move/merge things between folders to port a change, you can keep everything in the same place, and (more importantly), let the tool do the merging.

As others have already said, I would expect some resistance, so I would prototype the system by using it on the stuff I am doing.

(BTW, I actually put my Resume and other documents under SVN.  Then again, I've been played the roles of Configuration and Integration Managers several times.)


问:
Managing cross-thread communication on issue/bug reports
On my current project we have two or three engineers who are tagged as Tier 2 or Tier 3 support. We often work directly with customers to gather detailed information about bug and issue reports.

Frequently we get cross-talk in the email threads and conversations about issues. While discussing Issue #1, someone pipes up "Oh by the way we found Issue #2". Or having resolved Issue #1 we get asked "Thanks for fixing that. Where are you with Issue #3".

I find this incredibly annoying and it can make it tricky to unravel threads when reviewing the history of a bug report because the threads are all mixed up.

Can anyone suggest any strategies to manage this communication?
Is there a polite way to address this and keep things single task focused?
Is there a disadvantage to a single issue focus?

答:
You need a bug tracking tool : http://www.joelonsoftware.com/articles/fog0000000029.html

This article explain pretty much everything so I let you read. But basically, it will help you to get good bug repports and follow them during the whole duration of the fix's dev.

A plus is to add unittest to avoid regression in the future. But this is off topic here.


答:
I would go for something like</p>

```<code>public class Main {
  // ...
  public static class Item {
     private List<Integer> list = new ArrayList<Integer>(); // good when you need add elements
     //or: private int[] array; // instantiate when you know number of olements
     private int something;
     // getters, maybe setters (or fill data in constructor and don't allow changing them
     // int that case, don't expose array/list, make accesor methods instead
  }

  public List<Item> yourFunction() {
       // something
  }
}
</code>```

Body:
I would go for something like

public class Main {
  // ...
  public static class Item {
     private List<Integer> list = new ArrayList<Integer>(); // good when you need add elements
     //or: private int[] array; // instantiate when you know number of olements
     private int something;
     // getters, maybe setters (or fill data in constructor and don't allow changing them
     // int that case, don't expose array/list, make accesor methods instead
  }

  public List<Item> yourFunction() {
       // something
  }
}


答: I use version control for my one-man projects and my work projects, where we have upwards of 30- 40 people working on the same code at once. Version control has its organizational advantages, but the ability to revert files and stash changes can really take the headache out of managing code... and in the end that is the best scenario for a programmer, so they can just focus on coding.</p>


问:
Bringing my genius brain back
Well... I was hired because I did not take a comp-sci or engineering course, however I was really good at coding. My job is doing the heterodox stuff when needed... You know, the guy that sometimes has to use a goto, or invent some bizarre technology.

When I started my job, I blasted though stuff I needed to do, then I got slower and slower until I almost got fired.

Now I am more or less stable, but I am noticing I am slowing down again. I plainly open my source code, look at it, and have no idea what I have to do, sometimes I do not know even what I was doing.

I think this is related to my lifestyle. My work is a two hour commute (meaning I lose 4 hours daily), and I have not completed university yet (so I need to do some university work at home), and on weekends I spend time with my significant other.

Does anyone know what to do in a situation like this? I am depressed that I cannot write code like I could when I started, or when someone would throw some oddball problem at me and I would spit out a solution instantly. Now I am having trouble typing even 10 lines of code in a day, because I spend the entire day trying to figure what to do.

In fact, I can't even  procrastinate when I want to procrastinate, I open the browser, and I have no idea of what web page to open. It is really annoying :(

I feel like my IQ dropped from its measured levels to something like 80...

答: You sound like you're tired really, you're doing a lot of stuff and that 4 hours of travelling is a killer (I do 3 a day so I can feel your pain). I'd recommend getting to sleep earlier, try take some time off work if you have any holidays available and rest and relax. </p>

Title: Bringing my genius brain back


答: Either lack of motivation or burnout issue (too much coding). Retrospect yourself. Are you happy at your job? Do you really like doing what you are doing right now? Talk to your friends and they may be able to point out what they see wrong with your attitude towards things.</p>

Title: Bringing my genius brain back

Body:
Well... I was hired because I did not take a comp-sci or engineering course, however I was really good at coding. My job is doing the heterodox stuff when needed... You know, the guy that sometimes has to use a goto, or invent some bizarre technology.

When I started my job, I blasted though stuff I needed to do, then I got slower and slower until I almost got fired.

Now I am more or less stable, but I am noticing I am slowing down again. I plainly open my source code, look at it, and have no idea what I have to do, sometimes I do not know even what I was doing.

I think this is related to my lifestyle. My work is a two hour commute (meaning I lose 4 hours daily), and I have not completed university yet (so I need to do some university work at home), and on weekends I spend time with my significant other.

Does anyone know what to do in a situation like this? I am depressed that I cannot write code like I could when I started, or when someone would throw some oddball problem at me and I would spit out a solution instantly. Now I am having trouble typing even 10 lines of code in a day, because I spend the entire day trying to figure what to do.

In fact, I can't even  procrastinate when I want to procrastinate, I open the browser, and I have no idea of what web page to open. It is really annoying :(

I feel like my IQ dropped from its measured levels to something like 80...


答:
Sounds like you're in over your head. Here are some things you need to decide:

Whether your four-hour commute is worth your time or if you should rather be working somewhere closer to home.

Whether completing your university education is more important than working full-time.

Whether the type of work you are doing is right for you. You may have simply lost interest in working at your current job, so moving on will be better for you and your current employer.

You basically need to prioritize what is most important for you and let that guide your decision-making process.

Good luck!

Title: Bringing my genius brain back


答:
My suggestion is to simply stop using email to communicate about defects.

Once a defect is reported, either by a customer/user or by an internal testing team, it should be entered into a bug tracking tool of some kind. From that point on, all discussion regarding the bug is done only through the bug tracking tool. Once entered, it's prioritized and assigned based on your internal process.

I'm not sure what tools you use, but I've used both Trac and ClearQuest for issue tracking, and both support email notifications of changes to issues, which would enable people to follow defects that they are interested in (by product, by severity, or because they are involved in finding and fixing them) as they are changed.

Title: Managing cross-thread communication on issue/bug reports

Body:
On my current project we have two or three engineers who are tagged as Tier 2 or Tier 3 support. We often work directly with customers to gather detailed information about bug and issue reports.

Frequently we get cross-talk in the email threads and conversations about issues. While discussing Issue #1, someone pipes up "Oh by the way we found Issue #2". Or having resolved Issue #1 we get asked "Thanks for fixing that. Where are you with Issue #3".

I find this incredibly annoying and it can make it tricky to unravel threads when reviewing the history of a bug report because the threads are all mixed up.

Can anyone suggest any strategies to manage this communication?
Is there a polite way to address this and keep things single task focused?
Is there a disadvantage to a single issue focus?


问:
What electronic user-story-mapping tools can you recommend?
Agile software development relies heavily on a work item type called user stories.  For example, you have a backlog full of user stories and you can select a few of them to work on during the next sprint.

But where and how do you find user stories to put into the backlog?  There is a popular technique for doing that called story mapping.  Jeff Patton invented it and here is the definitive guide on how to do it.

The question is, what electronic tools are out there that support Patton's story-mapping technique?

I've done a bit of research, found Pivotal and Rally plug-ins (but I'm not a customer of either) and I'm currently experimenting with SilverStories.

What other tools are out there?  What have you used?  What do you (not) recommend?  Why?

UPDATE: Some people who wrote comments seem to lean towards an answer that applying this technique is simply impossible with an electronic tool and we should just accept that.  Can't someone write it up as an answer?

UPDATE (to clarify the question in light of Alex Feinman's comment): the question is about identifying options for story-mapping.  Since Jeff Patton's technique can obviously be done on a white-board with stickies, the question focuses on additional options that might be provided with electronic tools.  (Premature) commitment to any particular tool or class of tools is not the point of this question.

答:
You can use tools like Gravity which comes as a chrome extension and available for free in chrome web store.

Or alternatively, if you are looking for complete Agile Management Tool for your project or development, look for VersionOne on Google. The initial trial is free and you can get the full licensed version for not a lot of money.

Hope that helps.


问:
What is the difference between 'layer of abstraction' and 'level of indirection'?
I am not sure if both terms can be used interchangeably. Maybe there is some academic distinction in computer science which is not relevant for day-to-day programming? Or can I use both term interchangeably without being wrong? Maybe it depends on the context in which I use both terms?

Edit: On reason why I find both terms possibly interchangeable is a Wikipedia entry about Abstraction layer. There you can find David Wheelers quote 'All problems in computer science can be solved by another level of indirection.'

答:
A good example of abstraction is calling a single method to store an item in a database. The method abstracts the details of connecting and calling the database. Where an example of indirection is using a struct to access interrupts. You are still accessing the interrupt when you set values in the struct. it is just indirectly through the struct by giving struct member names to specific points in memory.

So abstraction hides details of implementation where indirection simply provides an "indirect" interface through which to access something.

Abstraction is when you do not need to understand what is being hidden, where with indirection  you do.


问:
Can anyone recommend a good robot kit for learning C++ robotics programming?
Preferably something that is a combination of affordable and close to real world robotics programming and will allow me to program it with C++.</p>

答:
Look into the Arduino. It's a microprocessor that's programmable in C++. You can easily use it to make or manipulate robots.
It's not a robot itself, but it is the brains. You can do much more than just robotics with it. I'm currently using one to monitor and stabilize a greenhouse where I grow a Miracle Fruit tree.</p>