答:
I have used both standard library and boost as references for naming conventions. However, there is a problem with this solution.

The standard library uses a naming convention designed to attempt to reduce collisions with your code. Part of the solution is to use all lower case letters. Hence the use of underscores instead of camelCase.

I find that camelCase is readable. PascalCase is often used for class names as it represents the equivalent of a proper noun. However, I will break that rule for functors which are more representative of a verb.

I try not to use macros. However when I do, macros are made to look like functions when they can. I also use const values or enums instead of manifest constants, further avoiding all upper case. I typically prefix these symbols with a 'k' to indicate that they are constant.

```<code>// instead of a manifest constant
#define HOURS 24

// use const
const int kHours = 24;

// or enum
enum {
    kHours   = 24,
    kMinutes = 60
};
</code>```

Body:
I have used both standard library and boost as references for naming conventions. However, there is a problem with this solution.

The standard library uses a naming convention designed to attempt to reduce collisions with your code. Part of the solution is to use all lower case letters. Hence the use of underscores instead of camelCase.

I find that camelCase is readable. PascalCase is often used for class names as it represents the equivalent of a proper noun. However, I will break that rule for functors which are more representative of a verb.

I try not to use macros. However when I do, macros are made to look like functions when they can. I also use const values or enums instead of manifest constants, further avoiding all upper case. I typically prefix these symbols with a 'k' to indicate that they are constant.

// instead of a manifest constant
#define HOURS 24

// use const
const int kHours = 24;

// or enum
enum {
    kHours   = 24,
    kMinutes = 60
};


问:
Is hungarian notation a workaround for languages with insufficiently-expressive static typing?
In Eric Lippert's article What's Up With Hungarian Notation?, he states that the purpose of Hungarian Notation (the good kind) is to

extend the concept of "type" to encompass semantic information in addition to storage representation information.

A simple example would be prefixing a variable that represents an X-coordinate with "x" and a variable that represents a Y-coordinate with "y", regardless of whether those variables are integers or floats or whatever, so that when you accidentally write xFoo + yBar, the code clearly looks wrong.

But I've also been reading about Haskell's type system, and it seems that in Haskell, one can accomplish the same thing (i.e. "extend the concept of type to encompass semantic information") using actual types that the compiler will check for you. So in the example above, xFoo + yBar in Haskell would actually fail to compile if you designed your program correctly, since they would be declared as incompatible types. In other words, it seems like Haskell's type system effectively supports compile-time checking equivalent to Hungarian Notation

So, is Hungarian Notation just a band-aid for programming languages whose type systems cannot encode semantic information? Or does Hungarian Notation offer something beyond what a static type system such as Haskell's can offer?

(Of course, I'm using Haskell as an example. I'm sure there are other languages with similarly expressive (rich? strong?) type systems, though I haven't come across any.)

To be clear, I'm not talking about annotating variable names with the data type, but rather with information about the meaning of the variable in the context of the program. For example, a variable may be an integer or float or double or long or whatever, but maybe the variable's meaning is that it's a relative x-coordinate measured in inches. This is the kind of information I'm talking about encoding via Hungarian Notation (and via Haskell types).

答:
Remember, there was a time when IDEs didn't have popup hints telling you what they type of a variable is.  There was a time when IDEs didn't understand the code they were editing so you couldn't jump from usage to declaration easily.  There was also a time, when you couldn't refactor a variable name without manually going through the whole of the codebase, making the change by hand and hoping you didn't miss one.  You couldn't use search & replace because searching for Customer also gets you CustomerName...

Back in those dark days, it was helpful to know what type a variable was where it was being used.  If properly maintained (a BIG if because of the lack of refactoring tools) Hungarian notation gave you that.

The cost these days of the horrible names it produces is too high but that's a relatively recent thing.  A lot of code still exists that predates the IDE developments I've described.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Why is C not considered an 'object-oriented' language?
It seems that C has its own quasi-objects such as 'structs' that can be considered as objects (in the high-level way that we would normally think).

And also, C files themselves are basically separate "modules", right? Then aren't modules kind of like 'objects' too? I'm confused as to why C, which seems so similar to C++, is considered a low-level "procedural" language where as C++ is high-level "object-oriented"

*edit: (clarification) why and where, is the line drawn, for what an 'object' is, and isn't?

答:
Object Oriented refers to both an architectural pattern (or even a meta-pattern), and, the languages that have features to help implement or mandate using this pattern.

You can implement an "OO" design (Gnome desktop is perhaps the best example of OO done in pure C), I have even seen this done with COBOL!

However being able to implement an OO design dose not make the language OO. Purists would argue that Java and C++ are not truly OO as you cannot override or inherit the basic "types" such as "int" and "char", and, Java does not support multiple inheritance. But as they are the most widely used OO languages and support most of the paradigm most "real" programmers who get paid to produce working code regard them as the OO languages.

C on the other hand supports only structures (as do COBOL,Pascal and dozens of other procedural languages), you could argue that supports multiple inheritance in that you can use any function on any piece of data but most would regards this as a bug rather than a feature.


答:
Let's just look at the definition of OO:

Messaging

Encapsulation

Late Binding

C provides none of those three. In particular, it doesn't provide Messaging, which is the most important one.

Title: Why is C not considered an 'object-oriented' language?

Body:
It seems that C has its own quasi-objects such as 'structs' that can be considered as objects (in the high-level way that we would normally think).

And also, C files themselves are basically separate "modules", right? Then aren't modules kind of like 'objects' too? I'm confused as to why C, which seems so similar to C++, is considered a low-level "procedural" language where as C++ is high-level "object-oriented"

*edit: (clarification) why and where, is the line drawn, for what an 'object' is, and isn't?


问:
Why do we need a Heap if everything can be done much more efficiently on the Stack?
This is actually somewhat related to the question I asked yesterday about why both a Stack and a Heap are necessary in the applications we use today (and why we can't just go with a Heap instead of both, in order to have a simple & singular standard to go by).

However, many of the responses indicated that a Stack is irreplaceable due to the fact that is many hundreds (or thousands) of times faster than trying to allocate/reference the Heap. I know there is a problem with dynamic storage allocation if we do away with the Heap, but isn't there a way around this, or perhaps, a way to improve on the Stack so that it can handle dynamic memory allocation?

答: For another example, closures.  If you stack pop, then you can lose your closure's activation record.  So if you want that anonymous function and its data to persist you've got to store it somewhere other than the runtime stack.</p>


问:
When to use C over C++, and C++ over C?
I've been introduced to Computer Science for a little over a year now, and from my experience it seems that C and C++ are both considered to be "ultrafast" languages, whereas others such as Python and such scripting languages are usually deemed somewhat slower.

But I've also seen many cases where a software project or even a small one would interleave files where a certain number n of those files would be written in C, and a certain number m of those files would be written in C++.

(I also noticed that C++ files almost always have corresponding headers, while C files not so much). But my main point of inquiry is to get a general sense of intuition on when it is appropriate to use C over C++, and when it is better to use C++ over C. Other than the facts that (1) C++ is object-oriented whereas C is not, and (2) the syntaxes are very similar, and C++ was intentionally created to resemble C in many ways, I am not sure what their differences are. It seems to me that they are (almost) perfectly interchangeable in many domains.

So it would be appreciated if someone could clear up the situation! Thanks

答:
(given you have equal familiarity with both languages)

Go with C++ unless there is no C++ compiler for your platform.  You can write C++ code without whatever portion of the language you don't like (no classes, exceptions, virtual inheritance, whatever personal restrictions you wish to apply), and then at some time in the future, if you decide you want some of those features after all, then you can easily use them.  Nothing in C++ prevents you from writing C-style code.

(given equivalent toolsets and developer knowledge) There is no reason to choose C over C++ provided your platform has a C++ compiler.  You can simply limit yourself to the subset of the language you wish to today, while leaving the door open for extension later.

Title: When to use C over C++, and C++ over C?


问:
Are there any real-world cases for C++ without exceptions?
In When to use C over C++, and C++ over C? there is a statement wrt. to code size / C++ exceptions:

Jerry answers (among other points):

(...) it tends to be more difficult to produce truly tiny executables with C++. For really small systems, you're rarely writing a lot of code anyway, and the extra (...)

to which I asked why that would be, to which Jerry responded:

the main thing is that C++ includes exception handling, which (at least usually) adds some minimum to the executable size. Most compilers will let you disable exception handling, but when you do the result isn't quite C++ anymore. (...)

which I do not really doubt on a technical real world level.

Therefore I'm interested (purely out of curiosity) to hear from real world examples where a project chose C++ as a language and then chose to disable exceptions. (Not just merely "not use" exceptions in user code, but disable them in the compiler, so that you can't throw or catch exceptions.) Why does a project chose to do so (still using C++ and not C, but no exceptions) - what are/were the (technical) reasons?

Addendum: For those wishing to elaborate on their answers, it would be nice to detail how the implications of no-exceptions are handled:

STL collections (vector, ...) do not work properly (allocation failure cannot be reported)

new can't throw

Constructors cannot fail

答:
It's kind of important in C++ library design.  Often times with a C-interface it's kind of nasty to throw an exception out of your 3rd party library to the client.  Point being that if your library throws, you're cutting out a set of clients who would have used it, given that it had a no-throw guarantee (for whatever reason that client has for a restriction on exceptions).

Personally I've seen exceptions abused when the team is told to "throw in an exception" whenever something not-so-terrible happens.  Of course you see the error here- the exception was thrown in the code before anyone figured out what to do with it.  That project had a few crashes as these deep-throws would rear out occasionally.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
Meeting/Conference Rooms

If your programmers are going to be sharing a space, you might want some smaller conference room(s) off to the side for groups to meet and discuss projects without interfering with others.

ContentLicense: CC BY-SA 2.5


答:
I would say "Yes".

As you say, the purpose of Hungarian Notation is to encode information in the name that cannot be encoded in the type. However, there are basically two cases:

That information is important.

That information is not important.

Let's start with case 2 first: if that information is not important, then Hungarian Notation is simply superfluous noise.

The more interesting case is number 1, but I would argue that if the information is important, it should be checked, i.e. it should be part of the type, not the name.

Which brings us back to the Eric Lippert quote:

extend the concept of "type" to encompass semantic information in addition to storage representation information.

Actually, that's not "extending the concept of type", that is the concept of type! The whole purpose of types (as a design tool) is to encode semantic information! Storage representation is an implementation detail that doesn't usually belong in the type at all. (And specifically in an OO language cannot belong in the type, since representation independence is one of the major prerequisites for OO.)

Title: Is hungarian notation a workaround for languages with insufficiently-expressive static typing?

Body:
In Eric Lippert's article What's Up With Hungarian Notation?, he states that the purpose of Hungarian Notation (the good kind) is to

extend the concept of "type" to encompass semantic information in addition to storage representation information.

A simple example would be prefixing a variable that represents an X-coordinate with "x" and a variable that represents a Y-coordinate with "y", regardless of whether those variables are integers or floats or whatever, so that when you accidentally write xFoo + yBar, the code clearly looks wrong.

But I've also been reading about Haskell's type system, and it seems that in Haskell, one can accomplish the same thing (i.e. "extend the concept of type to encompass semantic information") using actual types that the compiler will check for you. So in the example above, xFoo + yBar in Haskell would actually fail to compile if you designed your program correctly, since they would be declared as incompatible types. In other words, it seems like Haskell's type system effectively supports compile-time checking equivalent to Hungarian Notation

So, is Hungarian Notation just a band-aid for programming languages whose type systems cannot encode semantic information? Or does Hungarian Notation offer something beyond what a static type system such as Haskell's can offer?

(Of course, I'm using Haskell as an example. I'm sure there are other languages with similarly expressive (rich? strong?) type systems, though I haven't come across any.)

To be clear, I'm not talking about annotating variable names with the data type, but rather with information about the meaning of the variable in the context of the program. For example, a variable may be an integer or float or double or long or whatever, but maybe the variable's meaning is that it's a relative x-coordinate measured in inches. This is the kind of information I'm talking about encoding via Hungarian Notation (and via Haskell types).


问:
Is there a common capitalization convention in C++?
I do a lot of work in Python and Java, and both those languages have fairly common (though not universal) conventions on how capitalization should be used in identifiers: both use PascalCase for class names and ALL_CAPS for "global" constants, but for other identifiers a lot of Java code uses mixedCase whereas a lot of Python code uses underscore_delimiters. I know that no language or library enforces any particular capitalization, but I've found that when I stick to the standard conventions for the language I'm using, my code seems much more readable.

Now I'm starting a project in C++, and I'd like to apply the same idea. Is there any most common convention for capitalization that I should know about?

答:
I usually tend to stick with the convention that I see most in existing codebases for the language. In the case of C++, I usually see camelCase. In the case of Ruby or PHP I usually see stuff_like_this.

Realistically speaking, though, the most important thing is that you pick a style convention that isn't totally insane (dOnT_dO_tHiS) and be consistent with it. Make it so the style doesn't change throughout the code for a particular project. If you are working on an existing project, you'll want to go with the style that is already there.


问:
How can I tactfully suggest improvements to others' badly designed code during review?
I'm a great believer in clean code and code craftsmanship, though I'm currently at a job where this isn't regarded as a top priority. I sometimes find myself in a situation where a peer's code is riddled with messy design and very little concern for future maintenance, though it's functional and contains little to no bugs.

How do you go about suggesting improvements in a code review when you believe there is so much that needs changing, and there's a deadline coming up? Keep in mind that suggesting the improvements be made after the deadline may mean they'll be de-prioritized altogether as new features and bug-fixes come in.

答:
Code reviews aren't always aimed at making improvements.

A review near the end of a project as seems to be the case here is just so that everyone knows where to start looking when bugs come in (or for a better designed project what may be available for later reuse). Whatever the result of the review, there simply isn't time to change anything.

To actually make changes you need to be discussing the code and design much earlier in the project - code is a lot easier to change when it only exists as talk about possible approaches.


答: If the code functions without serious bugs, and a major deadline (as in effects P&L or corporate PR) is imminent, it's too late to suggest improvements that require major changes.  Even improvements to code can create risks to project deployment.  The time for improvements was earlier in the project, when there was more time to invest in the future robustness of the code base.</p>

Title: How can I tactfully suggest improvements to others' badly designed code during review?

Body:
I'm a great believer in clean code and code craftsmanship, though I'm currently at a job where this isn't regarded as a top priority. I sometimes find myself in a situation where a peer's code is riddled with messy design and very little concern for future maintenance, though it's functional and contains little to no bugs.

How do you go about suggesting improvements in a code review when you believe there is so much that needs changing, and there's a deadline coming up? Keep in mind that suggesting the improvements be made after the deadline may mean they'll be de-prioritized altogether as new features and bug-fixes come in.


答:
Among many other reasons for allocating heap storage.

If you want to pass the address of an object back to a calling program, you should not pass the address of a stack variable, as, the stack storage will be reused and possibly overwritten by the next function called. You need to get the required storage using malloc() to ensure it will not be overwritten by calls to subsequent functions.

You can pass addresses of stack items from your function to functions you call, because you can guarantee they will exist until your program "returns()". But as soon as your function returns all the stack storage is up for grabs.

Title: Why do we need a Heap if everything can be done much more efficiently on the Stack?

Body:
This is actually somewhat related to the question I asked yesterday about why both a Stack and a Heap are necessary in the applications we use today (and why we can't just go with a Heap instead of both, in order to have a simple & singular standard to go by).

However, many of the responses indicated that a Stack is irreplaceable due to the fact that is many hundreds (or thousands) of times faster than trying to allocate/reference the Heap. I know there is a problem with dynamic storage allocation if we do away with the Heap, but isn't there a way around this, or perhaps, a way to improve on the Stack so that it can handle dynamic memory allocation?


答:
Double-check your motivation. If you think the code should be changed, you ought to be able to articulate some reason why you think it should be changed. And that reason should be more concrete than "I would have done it differently" or "it's ugly." If you can't point to some benefit that comes from your proposed change, then there's not much point in spending time (a.k.a. money) in changing it.

Every line of code in the project is a line that has to be maintained. Code should be as long as it needs to be to get the job done and be easily understood, and no longer. If you can shorten the code without sacrificing clarity, that's good. If you can do it while increasing clarity, that's much better.

Code is like concrete: it's more difficult to change after it's been sitting a while. Suggest your changes early if you can, so that the cost and risk of changes are both minimized.

Every change costs money. Rewriting code that works and is unlikely to need to be changed could be wasted effort. Focus your attention on the sections that are more subject to change or that are most important to the project.

Form follows function, and sometimes vice versa. If the code is messy, there's a stronger likelihood that it also contains bugs. Look for those bugs and criticize the flawed functionality rather than the aesthetic appeal of the code. Suggest improvements that make the code work better and make the operation of the code easier to verify.

Differentiate between design and implementation. An important class with a crappy interface can spread through a project like cancer. It will not only diminish the quality of the rest of the project, but also increase the difficulty of repairing the damage. On the other hand, a class with a well-designed interface but a lousy implementation shouldn't be a big deal. You can always re-implement the class for better performance or reliability. Or, if it works correctly and is fast enough, you can leave it alone and feel secure in the knowledge that its cruft is well encapsulated.

To summarize all the above points: Make sure that your proposed changes add value.


问:
"sell" coding my next project in an unfamiliar language
I want to code my next work project in a language I'm unfamiliar with (python). I can think of plenty of reasons from my point of view why its a good idea (not least of all because it sounds fun). However my manager will probably ask me why. I'm a little stumped on the advantages from his point of view.

EDIT: I normally code in C#

EDIT2 My reasons for wanting to code in another language;

It will make an easy project much harder so I will learn more and it will be more interesting

I have just read a book on python. I want the chance to apply it in a business application so I properly understand it

It will increase my skill set and make me more employable

Python looks fun

答:
Where's the value for your company?

My reasons for wanting to code in another language;
  1) It will make an easy project much harder so I will learn more and it will be more interesting

And in the process, make the project take longer and increase the risk of a total failure.  There is no clear benefit to the company here, only costs / risks.

2) I have just read a book on python. I want the chance to apply it in a business application so I properly understand it

No benefit to the company here, unless Python is a technology that they want to embrace anyway.

3) It will increase my skill set and make me more employable

... and more likely to get a job elsewhere?

4) Python looks fun

So does water skiing.  Both are irrelevant to the company.

OK, there are benefits to having staff enjoy their work, but no manager is going to buy into the idea that having fun is more important than actually doing the required work efficiently and with minimum risk.

Learn Python on your own time on your own projects.  When you are good at it, and when you've gathered a sound body of evidence to bolster your case, talk to your manager about whether it is in the company's interest to adopt it.  (And be prepared for a pragmatic response of "No" or "Not yet".)


问:
What do you think of "Planning Poker"?
Planning Poker

Summary, in case you don't want to read the wiki article:

Get a list of tasks you want to do for the upcoming iteration

For each task:

2.1 Discuss with the group what it entails

2.2 Everyone writes down / selects an estimation of how much effort is required for the task

2.3 Everyone reveals their estimation

2.4 The highest and lowest outliers explain their reasoning

2.5 Repeat until a consensus is reached

Usually something similar to numbers from the Fibonacci sequence like 0, ½, 1, 2, 3, 5, 8, 13, 20, 40, 100 are the allowed values, so you don't get long arguments over close values like 23 vs 27.

Further, the numbers represent a unit-less value of effort, whose value is determined by a baseline task that everyone agrees equals about a 1, and all else is relative to that.

Ultimately, the goal is to get a good feel for a given team's "velocity", which is the number of these points that can be completed in a given iteration.  With that, it's possible to make reasonably accurate estimates of how long any given feature will take.

We did this at iteration planning meetings at one company I worked at, and I thought it was one of the few good things about that particular company.  So, what I'm wondering is, has anyone used this?  Do you think it's a useful tool for estimation?  Does it work in all situations, or does it lend itself to certain teams, projects, etc?

答:
We use it in our company for the project I'm involved in.  Some notes about planning poker are expressed in my recent blog post, and here's a bigger list of why it's cool:

It makes everyone agree.  People are not forced to accept any result; instead they're forced to make their own estimate!  The time to defend their own estimates is also allocated, if it's necessary.

It keeps everyone busy.  You can't slack during the meeting, while trying to show that you're so involved. Also, necessity of moving your hands constitutes a good physical exercise to keep you off of sleeping.

However, a downside of this is that sometimes you do need to do something else (for example, take some notes and write down the details of the agreement you've just reached).

It keeps meetings faster.  There's no need for a constant involvement of a meeting leader to keep everything on pace.  The game with clear rules is way better for that.  Yes, you need to make some extra moves to put cards on, reveal them, et cetera, but these pay their way.

A lot of people just like to play cards, especially poker :-)  This increases motivation.

A company that sells decks of such cards accompanied their site with an article about Planning Poker, which is also worth reading.

Title: What do you think of "Planning Poker"?


问:
What is the best setup for distributing a PHP application?
What is a recommended setup in terms of source control, builds, testing, bug tracking, and deployment for a downloadable PHP application (a la Wordpress, phpBB, Magento, etc.)? As a developer working on the application, what would you expect? What about as a user of the application? Please describe a setup and workflow, as well as any resources you think might be relevant or helpful.</p>

答:
I've found the following approach to be workable for the app I maintain:

The app is distributed as a single zip, that just has to be unzipped on a working PHP server.

Navigating to the app automatically runs a set of sanity checks (PHP environment, app configuration). Errors explain in simple terms how to fix any issue that crops up.

At first run, if the sanity checks pass, a configuration wizard is launched. This is disabled as soon as a settings file exists.

All customer modifications are done in a special subfolder of the app, that they can copy over from old installs (backwards compatibility is maintained for this folder). Being able to do upgrades by unzipping files and copying around a few folders is a useful feature.

The zip file itself is built with a command-line PHP script that is checked into the source repository. Doing a build is as simple as svn update followed by a call to build.php.

Developer builds are made the same way as release builds, only with a "-no-optimize" flag passed to the build script to prevent minification and concatenation.

The fact that the build script is itself PHP means that any developer can make changes to how the builds are made, without even having to log into our build server.


答:
Code review must be integrated with the culture and development cycle to work. It is not likely that scheduling a big code review at the end of the the development of feature X will work. First of all, making the changes will be harder and someone is likely to feel embarrassed - creating resistance to the activity.

You should have early and frequent commits, coupled with reviews at the commit level. With code analysis tools in place, most reviews will be quick. Automated code analysis/review tools such as FindBugs and PMD will help you get a big class of design errors out of the door. They will not however, help you fish out architectural level issues so you must have a solid design in place and judge the overall system against that design.


答:
The whole purpose of types (as a design tool) is to encode semantic information!

I liked this answer and wanted to follow up on this answer ...

I don't know anything about Haskell, but you can accomplish something like the example of xFoo + yBar in any language that supports some form of type safety such as C, C++ or Java. In C++ you could define XDir and YDir classes with overloaded '+' operators that only take objects of their own type. In C or Java, you would need to do your addition using an add() function/method instead of the '+' operator.

I have always seen Hungarian Notation used for for type information, not semantics (except insofar as semantics might be represented by type).  A convenient way to remember the type of a variable back in the days before "smart" programming editors that display the type for you in one way or or another right in the editor.


答:
Code review serves 3 purposes:

Checking for bugs

Checking to see where the code could be improved

Teaching tool for whoever wrote the code.

Evaluating design/code quality are of course about #2 and #3.

As far as #2:

Make it VERY clear what the benefits are from proposed changes vs costs to fix. As any business decision, this should be about cost/benefit analysis.

E.g. "X approach to design would significantly reduce the likelyhood of bug Y from occuring when doing change Z, and we know this piece of code undergoes changes of type Z every 2 weeks. The cost of handling production outage from bug Y + finding the bug + fixing and releasing the fix + opportunity cost from not delivering the next set of featires is $A; whereas the cost of cleaning up the code now and opportunity cost (e.g. price of shipping late or with less features) is $B. Now, evaluate - or rather have your team leader/manager - evaluate $A vs $B and decide.

This will help the smart team leads to effectively manage this. E.g. they will make a rational decision using FULL information

This will (especially if you word this well) raise YOUR status - e.g. you are someone intelligent enough to see the benefits of better design, AND smart enough not to religiously demand it without weighing business considerations.

AND, in the likely event that bug Z happens, you gain all that much more leverage on the next set of suggestions.

As far as #3:

VERY clearly delineate "must fix" bugs/issues from "This is a best practice and really ought to be fixed IF we can spare resources - see attached pro/con analysis" design improvements (attache the stuff described for #2 above) vs "These are general guidelines that I think would help you improve your code robustness so you can more easily maintain the code" optional changes. Please note the wording - it's not about "making your code like what I want" - it's "if you do this, YOU gain benefits a, b, c". The tone and approach matters.


答:
There is a sweet-spot for adding value through refactoring. Changes need to accomplish three things:

improve code that is likely to change

increase clarity

cost least effort

Considerations:

We know that clean code is less expensive to write and maintain, and is more fun to work on. Your job is to sell that idea to people in your company. Think like a salesman, not like an arrogant grouch (ie. not like me).

You can't win, you can only loose less.

Focus on adding real value - not just beauty. I like my code to look nice, but sometimes have to accept that inexpensive matters more.

A good way to find the sweet spot is to follow the Boy Scout Principle - when you work on an area of code, always leave it in better shape than you found it.

A small improvement is better than no improvement.

Make good use of automated tools. For example, tools that just clean up a bit of formatting can make a world of difference.

Sell other ideas that incidentally improve code clarity. For example, unit testing encourages decomposing big methods into smaller ones.


答:
Pick your battles, if a deadline is coming up then do nothing. The next time someone else is reviewing or maintaining code and they keep having trouble with it then approach them with the idea that as a team you should be more focused on code quality when reviewing code so that you won't have so much trouble later.

They should see the value before doing the extra work.


问:
Why are there so many competing filesystem designs?
Just a quick question, but why are there so many file systems still competing and in use today? (ntfs, fat32, ext3(ffs), etc)

It seems that file system designers could agree upon the best aspects of each type of system and implement a "best" filesystem, no? Just a thought, since these filesystems have been around for a while now, and it should be at least somewhat apparent which ones have good qualities over others, and we could just combine the good in each and create an ultimate system that is much better

答:
I think a very important fact is missing. Most of the time programmers tend to think that their way of doing something is superior to all other ways and therefore they look at a File System design and come up with problems and solutions that seem to be more general, elegant, fast, right... And if this feeling is strong enough they are free to build their own file system.

This leeds to competition, fragmentation, confustion and I hope in the end better solutions and more options to choose a matching solution for you.


问:
What kinds of development jobs require knowledge of advanced concepts?
When I was in university, I participated in a programming contest; the problems turned out to be extremely difficult and boring, and they required previous knowledge about a particular set of problem, e.g. graph theory, algebra.

Our team failed completely at that competition, without solving any problems at all.

After I graduated and got my first job as programmer, my daily tasks have revolved around business logic and have nothing to do with the difficult problems I encountered in university. Most of the calculations involve mathematics and nothing more; besides that we only need some general database and good database design knowledge.

What kinds of job require knowledge about those advanced problems that I encountered in university?

答:
Actually, you write code using this all the time. Memory allocation, DB, collections, or whatever lib you use probably already does that.

But, as you said, most programmers fails (as you did) miserably on thoses tasks, so system are designed to abstract all thoses stuff.

At some point or another, you'll be imited to crappy software or will have to understand thoses algs. Because abstraction are always leaky at some point.


答:
Well, there are plenty of jobs that probably require complex mathematics: Games programming, financial market analysis and scientific research all spring readily to mind. Who knows how complex Google's search algorithms are? But you are correct that you're opening yourself up to a lot more possibilities if you can analyse a basic manufacturing-industry business model and translate that to code.

I don't think the point of a university programming contest is to find the person who's most likely to get a decent-enough job in programming forever. The point of these contests is to have fun out-geeking each other, and possibly to draw other people into programming, and maybe (if you're really lucky) identify someone with special skills.

In that context, modelling purchase orders, contracts, customers, components and products really isn't going to be as effective as modelling the 3D motion of a space shuttle or, better still, Superman.

Title: What kinds of development jobs require knowledge of advanced concepts?

Body:
When I was in university, I participated in a programming contest; the problems turned out to be extremely difficult and boring, and they required previous knowledge about a particular set of problem, e.g. graph theory, algebra.

Our team failed completely at that competition, without solving any problems at all.

After I graduated and got my first job as programmer, my daily tasks have revolved around business logic and have nothing to do with the difficult problems I encountered in university. Most of the calculations involve mathematics and nothing more; besides that we only need some general database and good database design knowledge.

What kinds of job require knowledge about those advanced problems that I encountered in university?


答:
Ergonomic keyboard trays

If you're going to be typing for most of the day, RSI will hit you at some point in your career.  These help relieve the stress.

Title: Stuff every programmer needs while working

Body:
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed


答:
Not a bad question.

If you are going to call c an OO language you would need to called just about all procedural languages OO too.  So it would make the term meaningless.  c has no language support for OO.  If has structs, but structs are types no classes.

Actually c doesn't have a lot of features at all compared to most languages.  It's mostly use for it's speed, simplicity, popularity and support including tons of libraries.


问:
How should I go about fixing code from a less-experienced programmer?
A little background: I am one of two programmers for our department of 10 people (the rest are artists and management). The two of us do all of the coding required to make things flow well, and develop any projects that come up. I've been programming for about 4 years now, where this is his first "real" job (as he puts it). We generally are working on different projects at any point in time.

A couple months ago I developed a (by no means perfect) set of classes that were to be used for a later project. A large portion of that project was delegated to him (for billing reasons) to design and program a GUI interface. Since he was new, I helped a bit with the designing, and said to ask for help if he needed it with the rest. He finished up the interface a few weeks ago, which he demo'd to show that it worked, although a little slow.

The next part of that project has started which I'm working on. I opened up the interface to start with the next steps, and immediately ran into issues (a little slow was a little understatement, errors on common actions, etc.). I looked in to the code for a few issues and am finding O(n^n) on calls that should be O(n), type assumptions with no error checking (it's in Python), references to the GUI added to the original code, and so on.

Now, I definitely would like to teach him what was wrong and how to fix it, but he's already moved on to his next project, and this was a few weeks ago. I'm afraid me saying "Go back and do it right!" (with help of course) is too harsh, and we still have other projects to get done in the meantime. Should I just fix the code myself for now and try to catch things in the future?

答:
Share your knowledge.

I would offer him help on his new project in exchange to some teaching from a senior to a junior.

Why not pair programming on both projects?


答:
There are a number of key ingredients to OO, but the big ones are that the majority of code does not know what is inside an object (they see the surface interface, not the implementation), that the state of an object is a managed unit (i.e., when the object ceases to be, so does its state), and when some code invokes an operation on an object, they do so without knowing exactly what that operation is or involves (all they do is follow a pattern to throw a “message” over the wall).

C does encapsulation just fine; code which does not see the definition of a structure can't (legitimately) peek inside it. All you need to do that is to put a definition like this in a header file:

struct FooImpl;
typedef struct FooImpl *Foo;
```

Of course, there will be a need for a function that builds Foos (i.e., a factory) and that should delegate some of the work to the allocated object itself (i.e., through a “constructor” method), and also to have a way of disposing of the object again (while letting it clean up via its “destructor” method) but that's details.

Method dispatch (i.e., messaging) can also be done through the convention that the first element of the structure is actually a pointer to a structure full of function pointers, and that each of those function pointers must take a Foo as its first argument. Dispatch then becomes a matter of looking up the function and calling it with the right argument rewrite, which isn't that hard to do with a macro and a little cunning. (That table of functions is the core of what a class really is in a language like C++.)

Furthermore, that gives you late binding too: all the dispatch code knows is that it is invoking a particular offset into a table pointed at by the object. That only needs to be set during the allocation and initialization of the object. It's possible to go with even more complex dispatch schemes that buy you more runtime dynamism (at a cost of speed) but they're cherries on top of the basic mechanism.

Yet that doesn't mean that C is an OO language. The key is that C leaves you to do all the tricky work of writing the conventions and dispatch mechanism yourself (or use a third-party library). That's a lot of work. It also doesn't provide syntactic or semantic support, so implementing a full class system (with things like inheritance) would be unnecessarily painful; if you're dealing with a complex problem that is well described by an OO model, an OO language will be very useful in writing the solution. The extra complexity can be justified.

Body:
There are a number of key ingredients to OO, but the big ones are that the majority of code does not know what is inside an object (they see the surface interface, not the implementation), that the state of an object is a managed unit (i.e., when the object ceases to be, so does its state), and when some code invokes an operation on an object, they do so without knowing exactly what that operation is or involves (all they do is follow a pattern to throw a “message” over the wall).

C does encapsulation just fine; code which does not see the definition of a structure can't (legitimately) peek inside it. All you need to do that is to put a definition like this in a header file:

struct FooImpl;
typedef struct FooImpl *Foo;

Of course, there will be a need for a function that builds Foos (i.e., a factory) and that should delegate some of the work to the allocated object itself (i.e., through a “constructor” method), and also to have a way of disposing of the object again (while letting it clean up via its “destructor” method) but that's details.

Method dispatch (i.e., messaging) can also be done through the convention that the first element of the structure is actually a pointer to a structure full of function pointers, and that each of those function pointers must take a Foo as its first argument. Dispatch then becomes a matter of looking up the function and calling it with the right argument rewrite, which isn't that hard to do with a macro and a little cunning. (That table of functions is the core of what a class really is in a language like C++.)

Furthermore, that gives you late binding too: all the dispatch code knows is that it is invoking a particular offset into a table pointed at by the object. That only needs to be set during the allocation and initialization of the object. It's possible to go with even more complex dispatch schemes that buy you more runtime dynamism (at a cost of speed) but they're cherries on top of the basic mechanism.

Yet that doesn't mean that C is an OO language. The key is that C leaves you to do all the tricky work of writing the conventions and dispatch mechanism yourself (or use a third-party library). That's a lot of work. It also doesn't provide syntactic or semantic support, so implementing a full class system (with things like inheritance) would be unnecessarily painful; if you're dealing with a complex problem that is well described by an OO model, an OO language will be very useful in writing the solution. The extra complexity can be justified.


问:
Is having trouble with data structures common for beginners?
I'm taking my second course on Java. We are getting into data structures. I have done an assignment on a linked list, and now a stack. I had a hard time with the linked list. The stack gave me a little trouble, but was much easier.

Should I be worried about having a hard time with these algorithms and data structures? I just feel like I didn't really grasp it.

答:
I had trouble with calculus and had to take it a second time.  The second time I discovered I was smart but the first math teacher was basically useless :)

You are going to find a lot of people in IT who can't communicate well, even teachers.  On the other hand some people in IT are truly great writers and master communicators.

Sometimes outside reading can really help.  Computer books vary hugely in quality.  Get on Amazon and see what book people like actually liked.

Good luck.


答: The programmers bill of rights</p>

Body: The programmers bill of rights


答:
Yes, though many languages which have otherwise strong enough type systems still have a problem - expressibility of new types that are based on/similar to existing types.

i.e. In many langugaes where we could use the type system more we don't because the overhead of making a new type that is basically the same as an existing type other than name and a couple of conversion functions is too great.

Essentially we need some sort of strongly typed typedefs to kill thoroughly hungarian notation in these languages (F# style UoM could also do it)


问:
Does Microsoft have a free version of Visual Studio?
Not a trial, but a truly free version that they offer users to download....

I was wondering in case I somehow missed the option on their website. Any version of Visual Studio will do.

If not, are there any open-source alternatives (that have similar functionality, or possibly degraded equivalent) of Visual Studio? I am running on Windows 7 if that makes any difference...

答:
Well, you can use the free version of Visual Studio Express.
For alternatives, you can try:

Sharpdevelop

Quicksharp

Emacs

Zeus

Webbo - Web Editor

Personally, I prefer vim for development work (obviously on Linux).


问:
Is this use of conditionals an anti-pattern?
I've seen this a lot in our legacy system at work - functions that go something like this:

bool todo = false;
if(cond1)
{
  ... // lots of code here
  if(cond2)
    todo = true;
  ... // some other code here
}

if(todo)
{
  ...
}
```

In other words, the function has two parts. The first part does some sort of processing (potentially containing loops, side effects, etc.), and along the way it might set the "todo" flag. The second part is only executed if the "todo" flag has been set.

It seems like a pretty ugly way to do things, and I think most of the cases that I've actually taken the time to understand, could be refactored to avoid using the flag. But is this an actual anti-pattern, a bad idea, or perfectly acceptable?

The first obvious refactorization would be to cut it into two methods. However, my question is more about whether there's ever a need (in a modern OO language) to create a local flag variable, potentially setting it in multiple places, and then using it later to decide whether to execute the next block of code.

答:
I don't know about anti-pattern, but I'd extract three methods from this.

The first would perform some work and return a boolean value.

The second would perform whatever work is performed by "some other code"

The third would perform the auxiliary work if the boolean returned was true.

The extracted methods would probably be private if it was important that the second only (and always) be called if the first method returned true.

By naming the methods well, I hope it would make the code clearer.

Something like this:

public void originalMethod() {
    bool furtherProcessingRequired = lotsOfCode();
    someOtherCode();
    if (furtherProcessingRequired) {
        doFurtherProcessing();
    }
    return;
}

private boolean lotsOfCode() {
    if (cond1) {
        ... // lots of code here
        if(cond2) {
            return true;
        }
    }
    return false;
}

private void someOtherCode() {
    ... // some other code here
}

private void doFurtherProcessing() {
    // Do whatever is needed
}
```

Obviously there is debate to be had over whether early returns are acceptable, but that is an implementation detail (as is the code formatting standard).

Point is that the intent of the code becomes clearer, which is good...

One of the comments on the question suggests that this pattern represents a smell, and I would agree with that. It is worth looking at it to see if you can make the intent clearer.

Body:
I don't know about anti-pattern, but I'd extract three methods from this.

The first would perform some work and return a boolean value.

The second would perform whatever work is performed by "some other code"

The third would perform the auxiliary work if the boolean returned was true.

The extracted methods would probably be private if it was important that the second only (and always) be called if the first method returned true.

By naming the methods well, I hope it would make the code clearer.

Something like this:

public void originalMethod() {
    bool furtherProcessingRequired = lotsOfCode();
    someOtherCode();
    if (furtherProcessingRequired) {
        doFurtherProcessing();
    }
    return;
}

private boolean lotsOfCode() {
    if (cond1) {
        ... // lots of code here
        if(cond2) {
            return true;
        }
    }
    return false;
}

private void someOtherCode() {
    ... // some other code here
}

private void doFurtherProcessing() {
    // Do whatever is needed
}

Obviously there is debate to be had over whether early returns are acceptable, but that is an implementation detail (as is the code formatting standard).

Point is that the intent of the code becomes clearer, which is good...

One of the comments on the question suggests that this pattern represents a smell, and I would agree with that. It is worth looking at it to see if you can make the intent clearer.


答:
todo is a really bad name for the variable, but I think that might be all that's wrong. It's hard to be entirely sure without the context.

Let's say that the second part of the function sorts a list, built by the first part. This should be much more readable:

bool requiresSorting = false;
if(cond1)
{
    ... // lots of code here
    if(cond2)
        requiresSorting = true;
    ... // some other code here
}

if(requiresSorting)
{
    ...
}
```

<p>However, Bill's suggestion is also correct. This is more readable still:</p>

<pre class="lang-cs prettyprint-override"><code>bool requiresSorting = BuildList(list);
if (requiresSorting)
    SortList(list);
</code>```

Title: Is this use of conditionals an anti-pattern?

Body:
I've seen this a lot in our legacy system at work - functions that go something like this:

bool todo = false;
if(cond1)
{
  ... // lots of code here
  if(cond2)
    todo = true;
  ... // some other code here
}

if(todo)
{
  ...
}
```

In other words, the function has two parts. The first part does some sort of processing (potentially containing loops, side effects, etc.), and along the way it might set the "todo" flag. The second part is only executed if the "todo" flag has been set.

It seems like a pretty ugly way to do things, and I think most of the cases that I've actually taken the time to understand, could be refactored to avoid using the flag. But is this an actual anti-pattern, a bad idea, or perfectly acceptable?

The first obvious refactorization would be to cut it into two methods. However, my question is more about whether there's ever a need (in a modern OO language) to create a local flag variable, potentially setting it in multiple places, and then using it later to decide whether to execute the next block of code.

Body:
todo is a really bad name for the variable, but I think that might be all that's wrong. It's hard to be entirely sure without the context.

Let's say that the second part of the function sorts a list, built by the first part. This should be much more readable:

bool requiresSorting = false;
if(cond1)
{
    ... // lots of code here
    if(cond2)
        requiresSorting = true;
    ... // some other code here
}

if(requiresSorting)
{
    ...
}

However, Bill's suggestion is also correct. This is more readable still:

bool requiresSorting = BuildList(list);
if (requiresSorting)
    SortList(list);


答:
I think the ugliness is due to the fact that there is a lot of code in a single method, and/or variables are badly named (both of which are code smells on their own right - antipatterns are more abstract and complex things IMO).

So if you extract most of the code into lower level methods as @Bill suggests, the rest becomes clean (to me at least). E.g.

bool registrationNeeded = installSoftware(...);
if (registrationNeeded) {
  registerUser(...)
}
```

<p>Or you may even get rid of the local flag completely by hiding the flag check into the second method and using a form like</p>

<pre class="lang-cs prettyprint-override"><code>calculateTaxRefund(isTaxRefundable(...), ...)
</code>```

Overall, I don't see having a local flag variable as necessarily bad per se. Which option of the above is more readable (= preferable to me) depends on the number of method parameters, the names chosen, and which form is more consistent with the inner logic of the code.

Body:
I think the ugliness is due to the fact that there is a lot of code in a single method, and/or variables are badly named (both of which are code smells on their own right - antipatterns are more abstract and complex things IMO).

So if you extract most of the code into lower level methods as @Bill suggests, the rest becomes clean (to me at least). E.g.

bool registrationNeeded = installSoftware(...);
if (registrationNeeded) {
  registerUser(...)
}

Or you may even get rid of the local flag completely by hiding the flag check into the second method and using a form like

calculateTaxRefund(isTaxRefundable(...), ...)

Overall, I don't see having a local flag variable as necessarily bad per se. Which option of the above is more readable (= preferable to me) depends on the number of method parameters, the names chosen, and which form is more consistent with the inner logic of the code.


问:
What do you consider to be the prime cause of software defects (and how to minimize them)
I define defect as :

"something within the application design or code which prevents it functioning as per requirements."

I'm looking for ideas about the causes of defects, eg the human factor, lack of testing, lack of prototyping, and possible ideas to mitigate these.

答:
Rushing into things without fully understanding them. Starting to write code without fully understanding the functional requirements or the technical architecture.

Programming should be almost automatic, just writing down that which is self-evident and has been already worked out in the mind. In practice, I see a lot of flailing in code to try to get a handle on exactly what the code is supposed to do. I've been guilty of this myself many times.


答:
It depends really. If the code guarded by todo (I hope you're not using that name for real as it's totally un-mnemonic!) is conceptually clean-up code, then you've got an anti-pattern and should using something like C++'s RAII or C#'s using construct to handle things instead.

On the other hand, if it is conceptually not a cleanup stage but rather just additional processing that is sometimes needed and where the decision to do it needs to be taken earlier, what is written is fine. Consider whether individual code chunks would be better refactored into their own functions of course, and also whether you've captured the meaning of the flag variable in its name, but this basic code pattern is OK. In particular, trying to put too much into other functions might make what is going on less clear, and that would definitely be an anti-pattern.


问:
Is web application startup time really that important?
Had a conversation with someone about adding some initialization code on application startup and he complained about that causing an increasing in the startup time. He couldn't really state a reason (gut feeling or something, don't know). This is not a heavy use application and starts in about a minute or so, we deploy a few times a year.

I remember reading such advice on questions on SO some time ago, people advising to initialize on startup instead on access of page with the "if you can afford the penalty" stamp on.

I've worked with web apps that started from 30 seconds to 4-5 minutes but once online they rocked.

So what am I missing? Unless it's a vital application like... I don't know... for the financial market, medical applications, space exploration etc, is it really that important the startup time?

P.S. I'm strictly referring to web apps, desktop apps are bound to start lightning fast.

答:
It can be a big factor during development: if your platform does not support changing code in a running application, then the startup time becomes part of your feedback cycle, and there, even 30 seconds are painful and a threat to productivity.

For the production environment, it really does not matter; either a little downtime is acceptable and 5 minutes are still not much, or it's not and you have to implement some sort of live switchover.


答:
In the event of cripplingly bad design, your focus should be on maximising the encapsulation. That way, it becomes easier to replace the individual classes/files/subroutines with better designed classes.

Focus on ensuring that the public interfaces of the components are well designed, and that the internal workings are carefully concealed. Also, Data Storage wrappers are essential. (Large amounts of stored data can be very hard to change, so if you get "implementation bleed" into other areas of the system, you're in trouble).

Once you've got the barriers between the components up, focus on the components most likely to cause major issues.

Repeat until deadline or until system is "perfect".


问:
Should I use Java applets or JavaScript/PHP to make my site more interactive?
I have a website that is about electronics. I want to make some functional calculators such as calculation for analog filters which will have to show lots of plots and stuff like that. This is a sample of what I am looking for and obviously it is only PHP and its graphic functions.

I want to have similar thing but much more interactive with realtime sliders and stuff like that.

What should I go for? Java Applets? or stick to JavaScript/PHP? I am asking this because I can do it with Java much faster (know it better than JavaScript and PHP). But I am afraid of browser incompatibility, security options for Applets and similar things. What is your suggestion?

答:
I am asking this because I can do it with JAVA much faster (know it better than javascript and php). But I am afraid of browser incompatibility, security options for applets and similar things. What is your suggestion?

Depends mainly on whether you want to support mobile devices (read: iPad - I don't think the iOS browser will ever support Java applets) and whether you expect users to either have or be willing to install a JVM.

If these are not show-stopper issues, go with Java. While Applets are ridiculously out of fashion, that does not matter to end users. On a modern machine, JVM startup time is not a problem, and browser incompatibility less of a factor than with JavaScript. Applet-specific security is irrelevant as long as you only draw stuff and don't want to do things like access the user's harddisk.


答:
I believe this is the case when Hegel's famous dialectical principle of transition from quantity to quality actually works.

You see, timing always is important. I agree with Michael Borgwardt's words about importance of quick build during development/testing, but I insist that (may be in some other way) it is also very important for production.

Each developer who deployed some bad code to production knows that hotfix provided in 5 minutes and in 1 minute are really, really different things.

Title: Is web application startup time really that important?

Body:
Had a conversation with someone about adding some initialization code on application startup and he complained about that causing an increasing in the startup time. He couldn't really state a reason (gut feeling or something, don't know). This is not a heavy use application and starts in about a minute or so, we deploy a few times a year.

I remember reading such advice on questions on SO some time ago, people advising to initialize on startup instead on access of page with the "if you can afford the penalty" stamp on.

I've worked with web apps that started from 30 seconds to 4-5 minutes but once online they rocked.

So what am I missing? Unless it's a vital application like... I don't know... for the financial market, medical applications, space exploration etc, is it really that important the startup time?

P.S. I'm strictly referring to web apps, desktop apps are bound to start lightning fast.


问:
How to convince a teammate, who sees oneself as senior, to learn SVN conceptual basics?
To start with some background, I took up a new developer position this summer and ended up being the newest member on the team, yet with most experience under the belt.

So far I have managed to push sanity initiatives through easily enough because of low adoption costs (in terms of time and effort). However things have leveled up a bit.

One of my teammates, although experienced, does not really understand SVN. Naturally, blank areas on his mental map depicting oceans of SVN cause him to adopt rather strange usage patterns.

For example, he had declared a policy of "1 SVN commit per day per developer" because otherwise "the server would soon run out of disk space". When I explained him that SVN commits are deltas, not full copies, he responded with doubt and even today I'm not entirely sure if he understands what it means.

We also had a heated argument about whether to include Eclipse .project configuration in SVN. My teammate insisted we should, although it has caused numerous pointless conflicts. I was against keeping individual developer configuration files in SVN. Finally, it turned out that my teammate had a practice of re-checkouting the entire source tree after every commit to just make sure "code committed into repository works". That was the reason he was so adamant in keeping the project configuration in SVN - so it would be easy to re-import the project. When I explained that commit synchronizes working copy to remote byte-by-byte which makes re-checkout unnecessary, my teammate responded with doubt again and eventually waved the whole issue off as insignificant.

In my opinion, our team wastes time by resolving SVN conflicts in project configuration files which contain only developer-specific settings that need not be shared to SCM at all. All this mess because someone tailored the process around incorrect assumptions.

How can I convince a teammate, who sees oneself as senior, to get a better understanding of SVN basics?

答:
IMO it is best to separate those issues which cause direct problems/harm to the project from those which affect only that single developer. E.g. if he prefers to checkout everything multiple times a day, it will slow him down, but otherwise won't affect others. So you can just let him do that (until there is a noticeable performance lag in his work), and save yourself from the trouble of arguing over it.

Other issues you mention, like keeping Eclipse .project files in the repo, or 1 commit per day, are where you should focus, to allow the team to progress as smoothly as possible. First of all, you should ask/collect feedback from the other team members, whether this causes problems for them too. If there are others, together you can exert more pressure, and if needed, you can easier escalate an issue towards management.

Regarding the "SVN runs out of disk space", it would be easy to refute his belief by doing an experiment (potentially in a separate test repo). You just need to monitor the size of the physical repo file hierarchy before and after committing changes into one huge text file, or even lots of files. If that doesn't convince him, nothing can.

In that case, unfortunately you probably have an authority issue, where the other guy sees accepting advice from someone "lower in the rank" as a loss of his dignity. Such conflicts can't be resolved by logical argument. You need to escalate it towards management, but be careful to ensure you have enough support (from teammates and/or management) before you do so. Such a move may be perceived by the other guy as an open attack, thus can have problematic consequences (to either of you, and/or the peace of the whole team). So think thrice, and discuss with your supportive colleagues before you make that move.


答:
Point him to some learning material about how SVN works and what are the best practices when using SVN. </p>

<p>As @Peter says - choose your battles carefully and don't waste your energy on fighting with someone that obviously don't understand the basics. SVN isn't exactly bleeding edge technology and it's been here for a while so there's enough information about it. </p>

Title: How to convince a teammate, who sees oneself as senior, to learn SVN conceptual basics?

Body:
To start with some background, I took up a new developer position this summer and ended up being the newest member on the team, yet with most experience under the belt.

So far I have managed to push sanity initiatives through easily enough because of low adoption costs (in terms of time and effort). However things have leveled up a bit.

One of my teammates, although experienced, does not really understand SVN. Naturally, blank areas on his mental map depicting oceans of SVN cause him to adopt rather strange usage patterns.

For example, he had declared a policy of "1 SVN commit per day per developer" because otherwise "the server would soon run out of disk space". When I explained him that SVN commits are deltas, not full copies, he responded with doubt and even today I'm not entirely sure if he understands what it means.

We also had a heated argument about whether to include Eclipse .project configuration in SVN. My teammate insisted we should, although it has caused numerous pointless conflicts. I was against keeping individual developer configuration files in SVN. Finally, it turned out that my teammate had a practice of re-checkouting the entire source tree after every commit to just make sure "code committed into repository works". That was the reason he was so adamant in keeping the project configuration in SVN - so it would be easy to re-import the project. When I explained that commit synchronizes working copy to remote byte-by-byte which makes re-checkout unnecessary, my teammate responded with doubt again and eventually waved the whole issue off as insignificant.

In my opinion, our team wastes time by resolving SVN conflicts in project configuration files which contain only developer-specific settings that need not be shared to SCM at all. All this mess because someone tailored the process around incorrect assumptions.

How can I convince a teammate, who sees oneself as senior, to get a better understanding of SVN basics?

Body:
Point him to some learning material about how SVN works and what are the best practices when using SVN.

As @Peter says - choose your battles carefully and don't waste your energy on fighting with someone that obviously don't understand the basics. SVN isn't exactly bleeding edge technology and it's been here for a while so there's enough information about it.


答:
Instead of direct upfront criticism of someone's code , its always better to be cosntructive in our comments during code review.

One way that I follow is

it will be optimal if we do it this way.

Writting it in this way will make it run faster.

Your code will be much more readable if you do "this" "this" and "this"

Such comments will be taken seriously even though your deadlines are coming up. And probably will be implemented in the next development cycle.


答: Just talk to them. Look, I'm a senior developer, but there are things I don't know. That's the nature of the business. If they become defensive or aggressive that's a personality issue with the developer in case and that should be dealt with by the team leader, or if they are the team leader, by their boss.</p>


答: Personally I'd avoid Java applets. Generally speaking people don't like them. Corporates don't like them and they don't run in all browsers. Assess who is going to use it and establish the impact on them. If your target users are fine with it, and you feel more comfortable working in Java then fine.</p>

Title: Should I use Java applets or JavaScript/PHP to make my site more interactive?

Body:
I have a website that is about electronics. I want to make some functional calculators such as calculation for analog filters which will have to show lots of plots and stuff like that. This is a sample of what I am looking for and obviously it is only PHP and its graphic functions.

I want to have similar thing but much more interactive with realtime sliders and stuff like that.

What should I go for? Java Applets? or stick to JavaScript/PHP? I am asking this because I can do it with Java much faster (know it better than JavaScript and PHP). But I am afraid of browser incompatibility, security options for Applets and similar things. What is your suggestion?


答:
Well, I'm writing "scientific" software, so obviously I use lots of +-*/ , often functions from standard math library, and sometimes more advanced math libraries such as LAPACK. Yes, knowing some math is useful.

But: still, 90+ % of the time goes to something else: trying to understand users and their needs, figuring out how to make the user interface and workflow intuitive, working around all sort of bugs and issues that have absolutely nothing to do with scientific algorithms or anything sexy: Why is the firewire adapter randomly corrupting data when we have chipset x and graphics controller (!) y and Windows XP SP II OEM, but now with any other combination? This user says that fonts are too small, this other user says that the fonts are unnecessarily large - well, maybe we should make them adjustable, except that oops, our window layout broke.

To be honest, I've never needed any graph theory. The spirit of the Big O notation is good to know and acknowledging floating point issues is mandatory, but other than that, it's better to just try out (prototype) the algorithm and measure it rather than try some meticulous analysis on paper. Virtually all solvable algebraic problems have been solved in off-the-shelf math library packages, so why should I know how to implement them? All I need to know is that it's a black box, I put something in and get something out, and don't forget that there are limitations, so always check that the output makes sense, and if needed, find the edge cases where it fails. Again, by prototyping. (If you want to sound more scientific, call it "simulation".)

What is essential is the skill to find what has already been made and understand how to make use of it, instead of wasting your time on re-inventing solutions to problems that already have been adequately solved. Stand on the shoulders of giants, think hard and try things out.

Addition: I'm of course biased towards what I do (as we all are), so don't take my word for it. According to user SK-logic in comment below, the following positions require knowing advanced theoretical concepts: game dev., engineering graphics dev. (CAD/CAE/...), compilers, finacial math (high freq. trading and such), database engines, complex business logic (e.g., in logistics), AI and NLP (machine learning, etc.), and many many more.


答:
If your company uses wiki, write some high quality posts about SVN:

Why should you use it?

When should you use it?

What problems does it solve?

etc.

It will catch CTO's eye, and everyone who refuse to use will have to use :)


答:
Using pdr's example above, as it is a nice example, I'll go one step further.

He had:

bool requiresSorting = BuildList(list);
if (requiresSorting)
    SortList(list);
```

<p>So I realised that the following would work:</p>

<pre class="lang-cs prettyprint-override"><code>if(BuildList(list))
    SortList(list)
</code>```

But isn't as clear.

So to the original question, why not have:

BuildList(list)
SortList(list)
```

And let SortList decide if it requires sorting?

You see your BuildList method seems to know about sorting, as it returns a bool indicating as such, but that makes no sense for a method that is designed to build a list.

Body:
Using pdr's example above, as it is a nice example, I'll go one step further.

He had:

bool requiresSorting = BuildList(list);
if (requiresSorting)
    SortList(list);

So I realised that the following would work:

if(BuildList(list))
    SortList(list)

But isn't as clear.

So to the original question, why not have:

BuildList(list)
SortList(list)

And let SortList decide if it requires sorting?

You see your BuildList method seems to know about sorting, as it returns a bool indicating as such, but that makes no sense for a method that is designed to build a list.


答:
There's a lot of superstition around source control. It's counter-intuitive, the math is arcane, and it involves the single most important asset a software company owns.  I have to admit there's a part of me that still doesn't trust it. But I wouldn't do without it for a minute.

One solution might be to offer to take over responsibility for taking care of the repo.  Of course, if you present it as "it's a lot of work for you, and this just happens to be an area where I have some experience", rather than "you don't know what you're doing" that'll have a better chance of working.

If "sees himself as senior" means what I think it does, he won't let go of it because he sees it as a source of authority and control.  So workaround for you might be to use Git locally to manage sane commit units and branches, then just push to svn once a day like he requests.  Git is designed as a peer-to-peer system and to have a full repo copy on each local machine. You could offer git to other developers who would prefer doing it that way, and it can remain just a supplement to SVN that individual working groups (whether one or more developers, formal or ad-hoc) use internally. And when the day comes that senior guy relents, moves on to another department or company, or paints himself into an unrecoverable corner with his SVN policies, you have a head-start on cleaning it all up.


答: Say hello to enterprise programming, where your day is spent patching together various librarys, classes and pieces of code that already exist. Usually building on top of something that already exists, instead of something new.</p>


答:
Sometimes I find I need to implement this pattern.  Sometimes you want to perform multiple checks before proceeding with an operation.  For efficiency reasons, calculations involving certain checks aren't done unless it seems absolutely necessary to check.  So you typically see code like:

// Check individual fields for proper input

if(fieldsValidated) {
  // Perform cross-checks to see if input contains values which exist in the database

  if(valuesExist) {
    try {
      // Attempt insertion
      trx.commit();
    } catch (DatabaseException dbe) {
      trx.rollback();
      throw dbe;
    }
  } else {
    closeConnection(db);
    throwException();
  }
} else {
  closeConnection(db);
  throwException();
}
```

<p>This could be simplified by separating validation from the actual process of performing the operation, so you'd see more like:</p>

<pre class="lang-java prettyprint-override"><code>boolean proceed = true;
// Check individual fields for proper input

if(fieldsValidated) {
  // Perform cross-checks to see if input contains values which exist in the database

  if(!valuesExist) {
    proceed = false;
  }
} else {
  proceed = false;
}

// The moment of truth
if(proceed) {
  try {
    // Attempt insertion
    trx.commit();
  } catch (DatabaseException dbe) {
    trx.rollback();
    throw dbe;
  }
} else {
  if(db.isOpen()) {
    closeConnection(db);
  }
  throwException();
}
</code>```

Obviously it varies according to what you're trying to achieve, though written like this, both your "success" code and your "failure" code are written once, which simplifies logic and maintains the same level of performance.  From there, would be a good idea to fit entire levels of validation inside inner methods which return boolean indications of success or failure which further simplify things, though some programmers like extremely long methods for some strange reason.

Body:
Sometimes I find I need to implement this pattern.  Sometimes you want to perform multiple checks before proceeding with an operation.  For efficiency reasons, calculations involving certain checks aren't done unless it seems absolutely necessary to check.  So you typically see code like:

// Check individual fields for proper input

if(fieldsValidated) {
  // Perform cross-checks to see if input contains values which exist in the database

  if(valuesExist) {
    try {
      // Attempt insertion
      trx.commit();
    } catch (DatabaseException dbe) {
      trx.rollback();
      throw dbe;
    }
  } else {
    closeConnection(db);
    throwException();
  }
} else {
  closeConnection(db);
  throwException();
}

This could be simplified by separating validation from the actual process of performing the operation, so you'd see more like:

boolean proceed = true;
// Check individual fields for proper input

if(fieldsValidated) {
  // Perform cross-checks to see if input contains values which exist in the database

  if(!valuesExist) {
    proceed = false;
  }
} else {
  proceed = false;
}

// The moment of truth
if(proceed) {
  try {
    // Attempt insertion
    trx.commit();
  } catch (DatabaseException dbe) {
    trx.rollback();
    throw dbe;
  }
} else {
  if(db.isOpen()) {
    closeConnection(db);
  }
  throwException();
}

Obviously it varies according to what you're trying to achieve, though written like this, both your "success" code and your "failure" code are written once, which simplifies logic and maintains the same level of performance.  From there, would be a good idea to fit entire levels of validation inside inner methods which return boolean indications of success or failure which further simplify things, though some programmers like extremely long methods for some strange reason.


答:
Have you considered using Flex?
It is not Java exactly but it is fast to pick up AS 3 from java background and has nice browser support, good integration with Java back-end etc.</p>


答:
Try keeping a log of the 'SVN time wasting'. Every time there is a conflict/checkout/version issue that needs resolving, make a note of how long it took you/the team to resolve it.
If it turns out you're wasting a considerable amount of time every week, escalate it with him and the management. I'm sure management will soon ask for solutions if they realize productivity can be improved by simple changes in the work process.

Or try to convince your colleague to have a trial week where the team uses your system of checkins (if that's easily achievable with your current projects and codebase).
Promise him that if it doesn't work out you can switch back to the old system after the week is over. But he might come round after trying it out himself.


答:
You're running the risk of your application being considered sub-standard or worse yet, your development ability. Now, this app may be saving someone so much time and/or do such a needed task that the thankful users can look past the long startup.

It may take longer to program in such a way to lazily load the app, but only the stakeholders can determine if it is worth it. I had a report that ran in 55 sec. and we got it down to 35. No one noticed. Although I spent twice as much time getting it from 35 to 18, everyone noticed and were thankful and impressed. Going from 5 to 3 minutes for an app used a few times a year is not big deal. Users will just have less time to spend on Facebook or getting coffee.

Perception is the key. If the compay is not happy with the development teams in general and this app specifically, you may want to build up some goodwill and speed the thing up.


答:
I would look at JavaScript for the client.

It is the defacto standard to lightweight web client development.

Libraries like JQuery and ext_js make gui development as structured as java, and are fairly easy to pick up.

Applets, while still somewhat viable, are fairly heavy weight and require client installs of java.


问:
Should the admin interface of a public-facing webapp be accessible externally?
I am working on an application right now that needs a way for employees to log in to the back-end of the public facing application for some basic reporting. If you were creating this, would you put the admin interface on the public side or on the intranet side?

Update: It is the back-end of our eCommerce application. I am logging all of the transactions with the CC processor (NOT the sent data, just the response from the processor) and the processed transactions to aide in us being able to troubleshoot when a customer has a problem. Kind of a one-stop-shop instead of looking up in multiple places. They should be in the office when doing this.

This is an ASP.NET MVC project if that matters.

答:
It depends on where employees will be logging in from. Do they need to have access to this when they are out of the office? Do you have a company VPN? Do your employees ever work from home? How sensitive is the data?

Edit

So it seems basically that your backened will be accessed in your office and contains order information for an eCommerce system. Even though you don't log the information sent to the credit card provider, if you have no reason to access this data outside your company network (i.e. in the office) then I'd put it on the Intranet personally.

You never know if you'll need to log more [sensitive] information in future after client requests or new features you add.

That's not to say that making it internet facing is unsafe though, because you can of course secure it on the internet as well, but the risk is always going to be slightly greater.


答:
Both Java or Javascript would work.

On balance, I'd probably suggest Java applets for your case - applets are very well suited for embedded client-side applications in a web page, and it sounds like you already have Java experience.

The main benefit is that Java gives you a huge number of libraries / tools for layout and graphics etc. Anything that works with the Swing graphics toolkit should work - e.g. you can use fun things like the Napkin Look and Feel all the way through to fairly sophisticated visualisation tools like Processing.

Also, Java applets can achieve very good performance, certainly well ahead of Javascript. May not be a real issue in your case, but you get all the usual advantages of the JVM JIT-compiling down to native code so numeric calculations should be very fast.

Of course, the user needs to have a Java browser plug-in installed but that's true for nearly everyone nowadays..... and the plus side of this is that the Java layer means you don't have to worry about browser differences / incompatibilities so much.


答:
Your question is "How to code review badly designed code?":

The answer IMO is simple. Talk about the DESIGN of the code and how the design is flawed or doesn't meet requirements. If you point out a flawed design or "doesn't meet requirement" then the developer will be forced to change his code because it doesn't do what it needs to do.

If the code is "functionally sufficient" and/or "meets spec" and/or "meets requirements":

If you are a peer to this developer, you do not have any direct power that would let you  "tell him" to make changes.

There are a couple of options left to you:

You must use your own personal "influence" (a form of "power" that is indirect) and/or your ability to be "persuasive"

get involved with your organizations "code process" group and start making "code maintenance" a higher priority.

Bite the bullet and learn how to read crappy code faster/more-fluently so you don't get hung up (it sounds like you keep getting hung up or slowed down when you encounter crappy code) on crappy code.

This will also make you a stronger programmer.

And it will let you correct the crappy code when you are working on crappy code.

And this will also let you work on more projects because many projects have crappy code that is functional... but lots of crappy code.

Lead by example. Make your code better... but don't try to be a perfectionist.

Because then you will become "the slow guy who can't meet deadlines, is always criticizing, and thinks he is better than everyone else".

I find there is no silver bullet. You have to use all three and you have to be creative in your usage of all three.


答:
Yes, this appears to be a problem because you have to keep tracking all the places you are marking the flag ON/OFF. It is better to include the logic just inside as a nested if condition instead of taking the logic out.

Also rich domain models, in that case just one liner will do big things inside the object.


答:
Yes, you are right. Most of the time , it is implementing the business logic rather than implementing some algorithms. We rarely get the opportunity to implement/code an algorithm to solve the business problem as most of the work is already done for in the form of libraries.

There are some jobs which still needs a sharp person in algorithms like real time algorithmic high frequency trading or some start up which do bus route optimization software etc.


答:
I've done this both ways.

For a CMS system, admins could access it from anywhere. This was essential for marketing and sales people who needed to update press releases and so forth on the road, often from mobile devices.

For an ecommerce system, all admin was on the internal office network, only accessible remotely by VPN secured by RSA SecurID. These admin apps were desktop apps (older ones WinForms, newer ones WPF) although they did use some of the same web service based business objects that the consumer ecommerce website used.

Title: Should the admin interface of a public-facing webapp be accessible externally?

Body:
I am working on an application right now that needs a way for employees to log in to the back-end of the public facing application for some basic reporting. If you were creating this, would you put the admin interface on the public side or on the intranet side?

Update: It is the back-end of our eCommerce application. I am logging all of the transactions with the CC processor (NOT the sent data, just the response from the processor) and the processed transactions to aide in us being able to troubleshoot when a customer has a problem. Kind of a one-stop-shop instead of looking up in multiple places. They should be in the office when doing this.

This is an ASP.NET MVC project if that matters.


答:
In my opinion it's sometimes not about how tricky or usefull a problem is while you are in university but rather the way you approach it. It's about trying to find an answer that requires creativity and (sometimes) out of the box thinking. The earlier you get used to this the better. You go to university and study all kinds of things that you will forget almost the day you passed them but what stays is your ability to adapt to a variaty of things and this will ultimately (again in my opinion) make you a better developer.

I like to give myself challanges from time to time just to keep me going...


答:
SSL over HTTP is a given, I shouldn't have to reiterate the importance of that.  Furthermore I am assuming you have a strong authentication scheme (mandatory strong passwords, account lockout after so many failed attempts, etc...)  Even if the page is hidden, security through obscurity is no security at all.

What you need to concern yourself with is the possibility of whether public facing accounts could have access to information from your payment processor and how that affects PCI compliance.  PCI compliance is not just a standard that your payment processor is held to, there are certain security obligations on your end and making such functionality public-facing like you suggest may affect PCI compliance.  Many payment processors require their merchants to be PCI compliant anymore and they may charge you additional fees if you are not.

On a side note I would like to add that you may be incompliant with PCI Standards just by logging transaction information with your payment processor.


答:
@AndyC has some good points about accessibility.

Dig deeper on what the users expect from the site. If they're going to be running reports and wanting to dump things into a spreadsheet, make sure you can get these things to even work on a website and with how much trouble.

For basic viewing and data entry, keep it on the web.


答:
The real questions is whether the app will work without the initialization. We have new hires who obsess about "performance", my stock answer is I don't care how quickly you give the wrong results. IMHO cutting corners, mangling algorithms because "it will be faster this way", and other great ideas only introduce bugs.

If the initialization is required then do it. How much time will be wasted when the end users get the wrong results, eventually figure out the web app is wrong, call you and complain, and you have to go back and debug/fix/test/redeploy? now ask your colleague how time has been saved. (and I'd bet your server cores are 99% idle anyway)


问:
What are ways I can speed of development time when building applications?
I noticed that overtime with experience that the curve of learning shifts from trying to learn a language or technology (the way it works) to how to develop applications faster and with less code. I am very interested to see how other developers have minimized the time it takes to get applications to market.

I know for a fact that by learning just one thing it can save you a ton of time. For example I started learning lambda expressions and code that normally took 3 lines now only takes 1 and is alot faster to type.

Another angle is shortcuts and tools in an IDE itself. For instance I can't believe I didn't know how to remove unused using statements from my source code so I used to do it manually until I found out there was a tool in VS for removing them.

Are there any resources for learing faster ways of developing applications? Keyboard Shortcuts, tools, programs, references? Is there like a reference where one can learn these things? If not can you please share how you learned some of these tips?

NOTE: This question is geared towards .NET, C# and the Visual Studio IDE

答:
Programming applications faster isn't about reducing the number of lines in them.  It's about simplifying the solution.  Just because it's shorter, doesn't mean it's simpler.

The less complex the solution, the less likely it is to have mistakes.

Typing code isn't what is slow.  We aren't paid to type.  We aren't really even paid to write code.  We are paid to create solutions to problems.

Sometimes an elegant, simple, correct solution is more lines.  Some times it's less.  The key is that it's correct, and easy for you and the next developer to understand what it does.  The computer has no problem understanding what you write.  Code is for people to read.

Having said all that.  Resharper is a GREAT tool to improve the speed you can program, and aid in creating clean code that is easy to maintain.


答:
Read The Pragmatic Programmer, it contains lots of good advice to help you become faster.

A couple of them, as I remember:

(as you too noted): Learn your tools well. Learn key combinations for commands you use often. All mainstream IDEs have keymap cheat sheets. Implied: learn one tool (IDE) and use it whenever you can.

Learn a scripting language. Often you can save a lot of time by putting together a short shell / Perl / ... script instead of e.g. manually searching / processing a huge logfile.

(probably even more important in the long run): understand your problem as well as you can before you start coding. You may save time by writing shorter, more concise code, but the best saving in the long run is not having to write that code. There may be a library out there which you can reuse. Or it may be that the client doesn't actually need the feature you are thinking of (or she needs something entirely different from what you thought she wanted).

Automate everything you can: tests, build, deployment, documentation generation etc. Reduce repeated manual work to the minimum.

Continuously refine and improve your tools and processes, identify problems and fix them as you go, adapting to the changing world.

Title: What are ways I can speed of development time when building applications?

Body:
I noticed that overtime with experience that the curve of learning shifts from trying to learn a language or technology (the way it works) to how to develop applications faster and with less code. I am very interested to see how other developers have minimized the time it takes to get applications to market.

I know for a fact that by learning just one thing it can save you a ton of time. For example I started learning lambda expressions and code that normally took 3 lines now only takes 1 and is alot faster to type.

Another angle is shortcuts and tools in an IDE itself. For instance I can't believe I didn't know how to remove unused using statements from my source code so I used to do it manually until I found out there was a tool in VS for removing them.

Are there any resources for learing faster ways of developing applications? Keyboard Shortcuts, tools, programs, references? Is there like a reference where one can learn these things? If not can you please share how you learned some of these tips?

NOTE: This question is geared towards .NET, C# and the Visual Studio IDE


答:
Assuming you never have bug and never making an error….

Now in the real world,

As you don’t need access over the web, don’t provide it, just use a VPN when working from home.

Ideally you web facing machines will only have rights to access the stored procedures (or tables) it needs, so limiting the damage if (when) it is broken into.

Your internal admin app (internet or even WPF/Winforms) can run on a different machine with a database connections that have more rights.


问:
Is testing the easiest way to contribute to an Open Source Project?
I want to contribute to an open source project, but I don't know much about unit testing. I want to learn how to test and then practice my skills on an open source.

Will this also be acknowledged as a contribution.

I want to first get my name out there and then conc. on development.

答:
Those projects that practice unit testing would surely welcome decent, well-written tests. In projects that have been around a while, there's often all manner of functionality that hasn't been tested. Given that debugging and testing can be a bit of drudge work, projects often greatly appreciate someone taking the effort to do the necessary but not terribly sexy work. (Add writing documentation to the list of things-to-do!)

We see it in Squeak all the time, for instance, where an excellent way for newcomers to get their feet wet is to write tests for something that doesn't already have tests.