问:
Why is Python slower than Java but faster than PHP
I have many times seen various benchmarks that show how a bunch of languages perform on a given task.

These benchmarks always reveal that Python is slower than Java, and faster than PHP, and I wonder why that's the case.

Java, Python, and PHP run inside a virtual machine

All three languages convert their programs into their custom byte codes that run on top of the OS -- so none is running natively

Both Java and Python can be "compiled" (.pyc for Python) but the __main__ module for Python is not compiled

Python and PHP are dynamically typed, and Java statically -- is this the reason Java is faster, and if so, please explain how that affects speed.

And, even if the dynamic-vs-static argument is correct, this does not explain why PHP is slower than Python -- because both are dynamic languages.

You can see some benchmarks here and here, and here

答:
There is a general problem with this question in that it is too absolute.  It does not really make sense to say "language X is faster than language Y".  A computer language itself isn't "fast" or "slow" because it is merely way of expressing an algorithm.  The actual question should be something on the order of "why is the implementation X1 of language X faster than implementation Y1 of language Y for this particular problem domain?"

Some speed differences are certainly going to fall out of the language itself as certain languages are easier to implement certain domains than others.  But  much of what makes an implementation fast isn't the language.  For instance, you can't really say "Python is slower than Java" without considering whether you are talking about CPython, IronPython or PyPy.  This is particularly true for languages that use a VM as the speed is going to be directly impacted by the quality of the VM.

As an aside, I work with a system that for various reasons can't use JIT on our device with a very popular JavaScript VM that normally supports it.  This means that our JavaScript runs far, far slower than it would on a PC with a similar processor.  That one change, which is not directly related to the language itself, takes JavaScript from being "a few times slower than C++" to being "orders of magnitude slower than C++" for the tasks we care about.

Also consider is that languages differ in performance characteristics in ways that are not directly comparable.  Too many benchmarks just translate a program from language A to language B and don't take into account that languages differ in what features are fast.  (You can see this in any reasonable benchmark comparison such as those you link to as they often have notes like "thanks to so-and-so for showing me how to implement it in language Foo.)

For instance, Take this Java code:

```<code>for(int i=0;i<10;i++) {
    Object o = new Object;
    doSomething(o);
}
</code>```

It would be tempting to "rewrite" this in C++ and compare run times:

```<code>for(int i=0;i<10;i++) {
    Object *o = new Object;
    doSomething(o);
    delete(o);
}
</code>```

The thing is, any competent C++ programmer will immediately see that in C++, this is not the fastest way to do something.  You can easily speed things up by changing it to be more appropriate to C++:

```<code>for(int i=0;i<10;i++) {
    Object o;
    doSomething(&o);
}
</code>```

The point is not that C++ can be fast but rather than writing benchmarks to compare languages is really, really hard.  To do it appropriately, you have to be an expert in both languages, and write from scratch in both languages.  Even then, you can easily run into to areas where one language excels at a particular task.  For example, I can write a version of Towers of Hanoi in C++ that will run faster than Java on any reasonable compiler.  I can do that by essentially cheating, using C++ templates, evaluated at compile time (http://forums.devshed.com/c-programming-42/c-towers-of-hanoi-using-templates-424148.html)

The point there is not that I could say that "C++ is faster than Java" because my program returned instantly while the Java version ran for minutes (and hoping nobody noticed my program took a half hour to build.)  The point is that for this vary narrow case, C++ is faster.  For other narrow cases it might be the other way around.  So it isn't "C++ is faster", it is "C++ is faster in instances where you can evaluate the expression at build time using templates."  Less satisfying, but true.

Speed differences in languages are mostly about the implementation.  Compiled languages are going to be faster than interpreted languages.  Compiling to native code is going to be faster than compiling to byte code.  This will have much more effect than questions like whether than language is statically typed or not.  And of course, good implementations are going to be faster than bad ones.

And don't forget that good programmers are going to produce faster code than bad programmers, often to an extent that quite outweighs language differences.

Body:
There is a general problem with this question in that it is too absolute.  It does not really make sense to say "language X is faster than language Y".  A computer language itself isn't "fast" or "slow" because it is merely way of expressing an algorithm.  The actual question should be something on the order of "why is the implementation X1 of language X faster than implementation Y1 of language Y for this particular problem domain?"

Some speed differences are certainly going to fall out of the language itself as certain languages are easier to implement certain domains than others.  But  much of what makes an implementation fast isn't the language.  For instance, you can't really say "Python is slower than Java" without considering whether you are talking about CPython, IronPython or PyPy.  This is particularly true for languages that use a VM as the speed is going to be directly impacted by the quality of the VM.

As an aside, I work with a system that for various reasons can't use JIT on our device with a very popular JavaScript VM that normally supports it.  This means that our JavaScript runs far, far slower than it would on a PC with a similar processor.  That one change, which is not directly related to the language itself, takes JavaScript from being "a few times slower than C++" to being "orders of magnitude slower than C++" for the tasks we care about.

Also consider is that languages differ in performance characteristics in ways that are not directly comparable.  Too many benchmarks just translate a program from language A to language B and don't take into account that languages differ in what features are fast.  (You can see this in any reasonable benchmark comparison such as those you link to as they often have notes like "thanks to so-and-so for showing me how to implement it in language Foo.)

For instance, Take this Java code:

for(int i=0;i<10;i++) {
    Object o = new Object;
    doSomething(o);
}

It would be tempting to "rewrite" this in C++ and compare run times:

for(int i=0;i<10;i++) {
    Object *o = new Object;
    doSomething(o);
    delete(o);
}

The thing is, any competent C++ programmer will immediately see that in C++, this is not the fastest way to do something.  You can easily speed things up by changing it to be more appropriate to C++:

for(int i=0;i<10;i++) {
    Object o;
    doSomething(&o);
}

The point is not that C++ can be fast but rather than writing benchmarks to compare languages is really, really hard.  To do it appropriately, you have to be an expert in both languages, and write from scratch in both languages.  Even then, you can easily run into to areas where one language excels at a particular task.  For example, I can write a version of Towers of Hanoi in C++ that will run faster than Java on any reasonable compiler.  I can do that by essentially cheating, using C++ templates, evaluated at compile time (http://forums.devshed.com/c-programming-42/c-towers-of-hanoi-using-templates-424148.html)

The point there is not that I could say that "C++ is faster than Java" because my program returned instantly while the Java version ran for minutes (and hoping nobody noticed my program took a half hour to build.)  The point is that for this vary narrow case, C++ is faster.  For other narrow cases it might be the other way around.  So it isn't "C++ is faster", it is "C++ is faster in instances where you can evaluate the expression at build time using templates."  Less satisfying, but true.

Speed differences in languages are mostly about the implementation.  Compiled languages are going to be faster than interpreted languages.  Compiling to native code is going to be faster than compiling to byte code.  This will have much more effect than questions like whether than language is statically typed or not.  And of course, good implementations are going to be faster than bad ones.

And don't forget that good programmers are going to produce faster code than bad programmers, often to an extent that quite outweighs language differences.


问:
Designing complex query builders in java/jpa/hibernate
I need to build complex sql queries programatically, based on large filter conditions.

For example, below are few sample/hypothitical filter conditions, based on which i need to fetch users

Country: india

States: Andhra Pradesh(AP), Gujarat(GUJ), karnataka(KTK)

Districts: All districts in AP except 3 district, 5 any districts from GUJ, all district from KTK except 1 district

Cities: All cities in AP, all cities except few, include only 50 specific cities from KTK

Villages: similar conditions like above with varies combinations...

Currently, we have a query builder, which is very complex in nature, and not easy to modify/re-factory for improvements. So, thinking of complete re-design of it.

Any suggesations on how to build this kind of complex query builders programmatically using some best practices/deisgn patterns?

答:
I am sure your queries can be divided into "N" different kinds of queries;
E.G. some queries for geographical location, some for counts, etc.

If your database supports SELECTing from views, why don't you define one or
more views for each type of query, and then do a SELECT
from the view to filter by the parameter for that view?

You may also be able to rename columns in the view to standardized
search parameters passed in from the application: E.G.
in one case STATE could be PARAM1, CITY could be PARAM2,
in another case, STATE could be PARAM1, ZIPCODE could be PARAM2.
Having views with the some of the same column names will save
your modules from having to be completely different.  (You
can have a lookup table that maps the views and parameters;
this will allow you to easily add new types of searches).

For example, SEARCH1 contains PARAM1 and PARAM2; PARAM1
is STATE, and PARAM2 is city, and the view name and parameters
for SEARCH1 are all stored in a lookup table.

This might make it easier for you to write your
application; you can have one module for each kind of view etc.

ContentLicense: CC BY-SA 3.0


问:
Is it worth it to translate an Android app into Spanish and other languages?
I have the "user's side" of the story, I think they want it better if it's on Spanish. But, what about the programmers? Do you make your programs multi-language? Why? Why not?
Who translate your software? Are you ok with paying somebody to translate your app or you prefer doing it yourselves? Is the benefit bigger than the costs?</p>

答:
I believe one should also consider the negative consequences of providing localizations.

People will be offended by bad translations, especially if they could use the English version before and now they are auto-detected and forced to use the translated version.

Users of languages left out will feel offended if you provide a translation for another language, especially again if you force them to use it through regional/linguistic match.

French <-> Belgian Dutch

Simplified Chinese <-> Traditional Chinese

European French <-> Canadian French

and many more

ContentLicense: CC BY-SA 2.5


问:
File Processing Times
I have a very simple program in Ruby that opens a dictionary file, sorted-words.txt and prints out all the words in pig-latin. I tested its speed, and the first time I ran it, the program finished in about 1.6 seconds. The second time I ran the program, it took about 2.1 seconds. Between the two runs, there was maybe about a 10 second wait, me looking at the results and running the program again. I waited a minute, ran it again, and it ran in 1.8 seconds. Although the variation is slight, it is still there. Why is there this variation?

答:
Variations like that are typically due to Operating System and hardware variance.

In the Operating System, it runs processes like your program on a time shared basis so that even for a very small and simple program the multitasking of background programs will slightly affect the results.

On a hardware level you've several things going on but mostly it's file I/O. In file I/O the program loads to RAM, then communicates with the CPU which is multitasking. It then has to send to, wait and receive from the hard drive. Since the Hard Drive is a sequential device, you have variances in access and read time since it may not be in the same place every time. To test this, get a solid state drive and a standard hard drive and test them in the same system. There should be less variance in the Solid State system. If not, it's some other issue.

Title: File Processing Times


问:
What's the utility of encouraging users to learn SQL and possibly the ability to execute it?
Facing a situation where I can't possibly get all the features that are requested into each version of the LOB I support, I've evolved a number SQL query templates that users have and send to me, which I then execute.

This then led to a password protected SQL execution dialog which users with write access can execute for themselves with an understanding that if they make the wrong typo they could do damage.  While this makes me nervous, the upside of having the functionality outweighs the risk in this situation.

Then there is the change in how people view the functionality.  It seems less magical when they understand more about how the database works.  On the other side of this, however, new users can potentially walk into a culture where the lingo includes something totally foreign to them.

Any advice on weather this direction has relative utility?

答:
Decide on a reporting suite of software asap.  (SQL server reporting services, for example)

Let your users tell you queries and parameters they need often and actually make repeatable reports out of them.   If some of your users have gotten a good hold of SQL, think about setting up a development database for them to make reports against.

I worked for a company that didn't have a reporting suite, but had a lot of need for reports and it was a huge mess.  Any reasonably sized business is going to have monthly/weekly reports.

Trying to build them yourself into your application (when you have a really critical report you HAVE to build for the user) becomes a nightmare.  Then later it's a maintenance nightmare.  Not buying a reporting suite but having lots of reports is taking on technical debt if you ask me.. you will end up writing so much boilerplate that you could buy off the shelf and/or you're doing risky things like letting your users execute SQL.

Letting your users run their own queries is asking for issues.  Deadlock is the first thing that comes to mind.


答:
It depends on the culture.

There is something to be gained from having users skilled in SQL. But if they go about it in a half ass way they can also get misleading results. You have to really understand what they actually want.

NEVER give the user the ability to hurt the company.

If you want to do this you can set up a reporting server that subscribes to the production db. Or you can set up some views and only give them access to them.

In either case you can mold the data to make it easier to use. For example create month, year, day columns instead of just date columns. Denmoormalize the data to eliminate the need for joins. etc. Then only.

Title: What's the utility of encouraging users to learn SQL and possibly the ability to execute it?

Body:
Facing a situation where I can't possibly get all the features that are requested into each version of the LOB I support, I've evolved a number SQL query templates that users have and send to me, which I then execute.

This then led to a password protected SQL execution dialog which users with write access can execute for themselves with an understanding that if they make the wrong typo they could do damage.  While this makes me nervous, the upside of having the functionality outweighs the risk in this situation.

Then there is the change in how people view the functionality.  It seems less magical when they understand more about how the database works.  On the other side of this, however, new users can potentially walk into a culture where the lingo includes something totally foreign to them.

Any advice on weather this direction has relative utility?


问:
"how bad" is unrelated code in try-catch-finally block?
This is a related Q:
Is use of finally clause for doing work after return bad style/dangerous?

In the referenced Q, the finally code is related to the structure used and the necessity of pre-fetching.  My question is a little different, and I believe it's germane to the broader audience.  My particular example is a C# winform app, but this would apply to C++ / Java finally usage as well.

I'm noticing quite a few try-catch-finally blocks where there is a lot of code unrelated to exceptions and exception handling / cleanup buried within the block.  And I will admit my bias towards having very tight try-catch-finally blocks with the code closely related to the exception and handling. Here are some examples of what I'm seeing.

Try blocks will have lots of preliminary calls and variables being set leading up to the code that could throw.  Logging information will get setup and run in the try block as well.

Finally blocks will have form / module / control formatting calls (despite the app being about to terminate, as expressed in the catch block), as well as creating new objects such as panels.

Roughly:

```
    methodName( ... )
    {
        try
        {
            // Lots of code for the method ...
            // code that could throw ...
            // Lots more code for the method and a return ...
        }
        catch( something )
        { // handle exception }
        finally
        {
            // some cleanup due to exception, closing things
            // more code for the stuff that was created (ignoring that any exceptions could have thrown) ...
            // maybe create some more objects
        }
    }
```

The code works, so there is some value to it.  It is not well encapsulated and the logic is a bit convoluted.  I'm (painfully) familiar with the risks in shifting code around as well as refactoring, so my question boils down to wanting to know others' experience with similarly structured code.

Does the bad style justify making the changes?  Has anyone been badly burned from a similar situation?  Would you care to share the details of that bad experience?  Leave it be because I'm over-reacting and it's not that bad of style?  Gain the maintenance benefits of tidying things up?

答:
I've been through a very similar situation when I had to deal with a terrible legacy Windows Forms code written by developers that clearly didn't know what they were doing.

First of all, you're not overacting. This is bad code. Like you said, the catch block should be about aborting and preparing to stop. It's not time to create objects (specially Panels). I can't even start explaining why this is bad.

That being said...

My first advice is: if it's not broken, don't touch it!

If your job is to maintain the code you have to do your best not to break it. I know it's painful (I've been there) but you have to do your best not to break what is already working.

My second advice is: if you have to add more features, try keeping the existing code structure as much as possible so you don't break the code.

Example: if there's a hideous switch-case statement that you feel could be replaced by proper inheritance, you must be careful and think twice before you decide to start moving things around.

You will definitely find situations where a refactoring is the right approach but beware: refactoring code is more likely to introduce bugs. You have to make that decision from the application owners perspective, not from the developer perspective. So you have to think if the effort (money) necessary to fix the problem is worth a refactoring or not. I've seen many times a developer spending several days fixing something that is not really broken just because he thinks "the code is ugly".

My third advice is: you will get burned if you break the code, it doesn't matter if it's your fault or not.

If you've been hired to give maintenance it doesn't really matter if the application is falling apart because somebody else made bad decisions. From the user perspective it was working before and now you broke it. You broke it!

Joel puts very well in his article explaining several reasons why you should not rewrite legacy code.

http://www.joelonsoftware.com/articles/fog0000000069.html

So you should feel really bad about that kind of code (and you should never write anything like that) but maintaining it is a whole different monster.

About my experience: I had to maintain the code for about 1 year and eventually I was able to rewrite it from scratch but not all at once.

What happened is that the code was so bad that new features were impossible to implement. The existing application had serious performance and usability issues. Eventually I was asked to make a change that would take me 3-4 months (mostly because working with that code took me way more time than usual). I thought I could rewrite that whole piece (including implementing the desired new feature) in about 5-6 months. I brought this proposition to the stakeholders and they agree to rewrite it (luckily for me).

After I rewrote this piece they understood I could deliver much better stuff than what they already had. So I was able to rewrite the entire application.

My approach was to rewrite it piece by piece. First I replaced the entire UI (Windows Forms), then I started to replace the communication layer (Web Service calls) and last I replaced the entire Server implementation (it was a thick client / server kind of application).

A couple years later and this application has turned into a beautiful key tool used by the entire company. I'm 100% sure that would've never been possible had I not rewritten the whole thing.

Even though I was able to do it the important part is that the stakeholders approved it and I was able to convince them it was worth the money. So while you have to maintain the existing application just do your best not to break anything and if you're able to convince the owners about the benefit of rewriting it then try to do it like Jack the Ripper: by pieces.


答:
You can start with a limited knowledge of sql, but you may need to do some of the heavy lifting for them. I've worked at many companies that did this with databases for in-house and third party applications. Formal training was provided. Don't authorize users until they are prepared.

Here are some things to consider:

Create a reporting version of your database instead of using the production transaction database if possible. Discuss how timely the data need to be. There are probably very few custom queries that rely on up to the minute data. A virtual server that can be resurected once they blow it up can be very handy.

Don't allow direct access to tables. Create some views or whatever database objects are appropriate for the users. Take care of any complex joins and try to force using some type of parameter as much as possible to limit the amount of data retrieved.

Make access read-only.

Use a report writing tool. Much of their needs will be aggregating data at various levels determined by your business with different filters and sorting.

Start with a small number of available fields. If you leave it up to them, they'll want them all because they feel if they don't give you a list of 500 fields today, it will take too long to process a request for new fields.

Brush up on your database knowledge or work with a DBA who can help regulate the amount of resourses these queries will be allowed to use. Again, be stringent, but let users know you can quickly handle new requests with this system much quicker than before, so there is no need to demand everything all at once.


问:
License of current JDK
I am wondering which license the current JDK 7 (NOT the OpenJDK) is using as I know it was once under GNU GPL but with the change of the Distributor License for Java I would like to know whether they changed the allover license, too.

答:
Both JDK and JRE download sections link to this license. The same license seems to apply to both JDK and JRE.

I'm not a lawyer but the following extract looks like they (not only JRE but also JDK) could be fairly freely redistributed as parts of your own programs:

Oracle grants you a non-exclusive, non-transferable, limited license without fees to reproduce and distribute the Software, provided that (i) you distribute the Software complete and unmodified and only bundled as part of, and for the sole purpose of running, your Programs, (ii) the Programs add significant and primary functionality to the Software, (iii) you do not distribute additional  software intended to replace any component(s) of the Software, (iv) you do not remove or alter any proprietary legends or notices contained in the Software, (v) you only distribute the Software subject to a license agreement that: (a) is a complete, unmodified reproduction of this Agreement; or (b) protects Oracle's interests consistent with the terms contained in this Agreement and that includes the notice set forth in Section H, and (vi) you agree to defend and indemnify Oracle and its licensors from and against any damages, costs, liabilities, settlement amounts and/or expenses (including  attorneys' fees)  incurred in connection  with any claim, lawsuit or action by any third party that arises or results from the use or distribution of any and all Programs and/or Software.

Title: License of current JDK


问:
variable comparison without initialising
I am working with a project in VC++ which involves co-ordinate system having x,y,z axis.

I am trying to check for if a variable(Point with x,y,z values) is assigned on the coordinate system or its a default point(uninitialized) .

Since a coordinate system I cannot assign a default value to the variable to be either negative or positive  or even zero since all these are valid values.

My approach over here is to have a Boolean variable associated with my Point variable. If the Boolean is set then Point assigned else not. Now I have to check for each and every statement where the value can be assigned and set the Boolean.

Now I tried with this approach which is pretty bad and you may consider it as wrong. What I am doing here is taking an uninitialized float variable (since x,y,z members of Point are float) and comparing it with x,y,z members of Point variable.

Since in the case where Point is uninitialized both float variable and members of Point match and I can declare its uninitialized. I have tried to test this on different compilers and I get the result as expected.

Obvious I get a compiler warning for uninitialized variable used for comparison

My question, Is the second approach really bad or is there any workarounds over this.

答:
An uninitialised variable always has a value - it's just not going to be a value which is any use to you, instead it'll be a value which has been leftover in memory from the last time that particular chunk of memory had been used.   The compiler is warning you that the effect of using an uninitialised variable in a comparison will be undefined, unpredictable behaviour.

if your Point objects need to be able to represent an internal state which indicates whether the coordinates are valid, then your first idea of adding a bool in your Point class would be a more reliable solution.   You're going to need to check something so why do you not want to add a bool?    Giving your Point class an internal state also lets you validate the state internally, which could be acheived by having a state-getter, or by throwing an exception.


答:
Instead of using uninitialized coordinates you could initialize them to NaN (see here) if your compiler supports it.

Then you are always sure whether a point is undefined or it represents a real point in the 3-D space.

Title: variable comparison without initialising

Body:
I am working with a project in VC++ which involves co-ordinate system having x,y,z axis.

I am trying to check for if a variable(Point with x,y,z values) is assigned on the coordinate system or its a default point(uninitialized) .

Since a coordinate system I cannot assign a default value to the variable to be either negative or positive  or even zero since all these are valid values.

My approach over here is to have a Boolean variable associated with my Point variable. If the Boolean is set then Point assigned else not. Now I have to check for each and every statement where the value can be assigned and set the Boolean.

Now I tried with this approach which is pretty bad and you may consider it as wrong. What I am doing here is taking an uninitialized float variable (since x,y,z members of Point are float) and comparing it with x,y,z members of Point variable.

Since in the case where Point is uninitialized both float variable and members of Point match and I can declare its uninitialized. I have tried to test this on different compilers and I get the result as expected.

Obvious I get a compiler warning for uninitialized variable used for comparison

My question, Is the second approach really bad or is there any workarounds over this.


答:
You can see the JVM both as a software and as a standard. As a software we would like to be able to modify it anytime we want and distribute modified versions, like the recent Gnome to Maté fork.

As a standard, it is a good thing to avoid situations like Javasctipt, where you have often to check what browser you are running on. In my opinion this is the reason why the Oracle JSK 7 is not GPL. This fact avoided to the Java programmers the danger of having to be compatible with Microsoft Visual J++.

Title: License of current JDK

Body: I am wondering which license the current JDK 7 (NOT the OpenJDK) is using as I know it was once under GNU GPL but with the change of the Distributor License for Java I would like to know whether they changed the allover license, too.


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答:
Give them interesting problems to work on, and their choice of tools to work on them, then get out of their way.

Great programmers are not motivated by money, or by status within a company. They need enough money and status to be comfortable, but that's it. Great programmers are motivated by interest.

Paul Graham agrees with me.


问:
Limitations of UML?
I'm currently studying for an examination and one of the sample paper questions is to discuss the limitations of UML. Most of the material I'm finding on the net is relating to a specific UML implementation or language. I'm wondering from a generalists point of view what would you consider the limitations of UML to be? </p>

答:
Difficulties I've come up against trying to use the UML:

as a communication tool, it's slower than ad hoc diagramming. Imagine you're stood at a whiteboard, telling another developer how a callback-based interaction works. You'd probably draw two boxes representing the caller and the callee, then talk your colleague through the process while drawing arrows every time you say "this sends message foo", and writing properties in the boxes when you say "so this returns its bar". In the UML, that needs two diagrams (a class diagram for the properties and a sequence diagram for the arrows).

as a model of a complicated system (the code), it's still fairly complicated. Many people have pointed out in comments that my complaint above is invalid because there's a type of diagram that can do what I want. This represents a different problem: it's hard enough to remember the details of the UML that using it as a simple model for communication purposes is difficult.

as a documentation tool, it can require too much upfront planning. I don't remember the specifics of my problem, but a few years ago I was documenting a package structure for a (then-unwritten) Mac application. The tool I was using to construct the UML enforced the constraints baked into the language. I think I was trying to express something like "this class will consume an interface exposed by something in this package, but I haven't decided what yet so I'll keep it at the package level. As I say, I don't remember if this was my exact task, but the constraints of the UML meant the tool wouldn't let me do it.

as a code generation (or code analysis) tool, its capabilities may not map exactly onto your target language. It's designed for class-based object-oriented programming languages and for compile-time method resolution. I have difficulties getting more than the simplest representation of Objective-C or Javascript out of it. Taking Objective-C as an example I've got more experience of dealing with the UML in, you can't easily express categories. The difference between a protocol (like a Java interface) and an abstract class needs to be expressed via custom sterotypes. To make an effective round-trip ObjC—UML tool means encapsulating all of these differences in a metadata schema on top of the existing language. As I say this is all dependent on the programming language you're trying to represent: C++ programmers don't have any of these problems.

Finally a minor bugbear of mine which isn't much of a limitation but does cause cognitive problems when using the UML to represent ObjC: in ObjC + and - mean class and instance methods, while in the UML they mean public and private.

Title: Limitations of UML?


问:
Where does Objective-C come from? C++ or C?
I am very confused about this programming language, Objective-C, which I heard is used to develop iOS applications.

I know that it uses the principles of OOP. Would it be easier to learn if I already knew C++?
What about it's name? is it a combination between the C programming language and the OOP principles I use in C++?

答:
Brad Cox and friends added a thin layer of Smalltalk on top of C.

Objective-C thus has much more in common with Smalltalk's highly dynamic message-sending style OO than C++'s.

One major difference is that in Objective-C you don't worry too much about what class something is: you care about what messages something understands. You can have objects that change the set of messages they understand, at runtime.

Having said that the two languages have very different ideas of what OO is, many ideas/principles are still shared: inheritance, delegation, polymorphism, and so on. You'll easily find many examples of the various OO patterns in code written in either language.


问:
How to TDD that the correct results are returned
I'm starting a new project, and trying very very hard to use TDD to drive the design.  I've been pushing for years, and finally got approval to spend the extra time on this project to use it while I learn how to do it properly.

This is a new module, to tie into an existing system.  Currently, all data access happens through webservices, which for the most part are just a thin wrapper over database stored procedures.

One requirement is that for a given store, I return all Purchase Orders that are considered valid for this application.  A PO is considered valid if it's ship date falls withing a given range from the stores opening date (this is for new stores).

Now, I can't put this logic in the application code, as I'm not going to bring back a million POs just to get the dozen that apply to could apply to this store given the constraint above.

I was thinking, I could pass the date range to a GetValidPOs proc, and have it use those values to return the valid POs.  But, what if we add another requirement to what is considered a valid PO?

And how do I test this and verify it keeps working?  We are not using an ORM, and it's unlikely to happen.  And I can't call the DB in my test.

I'm stuck.

My other thought, is have some mocks that return valid data, others that return some bad data, and have the local repository throw an exception if bad data occurs, and test that the exception gets thrown if invalid data is returned by GetValidPOs proc (or the mock used in testing).

Does this make sense?  Or is there a better way?

UPDATE:
I am able to use EF it would seem.  Now I just need to figure out how to use it, and make it testable, while still being able to rely on stored procedures, and the difficulty of having data scattered across several databases.

答:
My advise is to divide and conquer. Forget about database and persistence for the time being and concentrate on testing fake implementations of your repositories or data access objects.

Now, I can't put this logic in the application code, as I'm not going
  to bring back a million POs just to get the dozen that apply to could
  apply to this store given the constraint above.

I would mock the repository that returns purchase orders. Create a mock with twenty odd purchase orders.

I was thinking, I could pass the date range to a GetValidPOs proc, and
  have it use those values to return the valid POs. But, what if we add
  another requirement to what is considered a valid PO?

Stub a call to GetValidPOs so that it calls your mock, rather than database procedure.

And how do I test this and verify it keeps working? We are not using
  an ORM, and it's unlikely to happen. And I can't call the DB in my
  test.

You need a unit-test to make sure correct data is returned from a mock.

You also need an integration test to make sure correct data is returned from a database. Integration test would require some configuration and clean-up. For example, before running integration test, seed your database by running a script. Verify that your script has worked. Query the database by calling your stored procedures. Verify that your results are correct. Clean up the database.

My other thought, is have some mocks that return valid data, others
  that return some bad data, and have the local repository throw an
  exception if bad data occurs, and test that the exception gets thrown
  if invalid data is returned by GetValidPOs proc (or the mock used in
  testing).

As I already said, you need a mock that returns at least some data that you can query.

When you query data you want to make sure that your system can handle exceptions gracefully. Therefore you mock behaviour so that it throws exceptions in certain scenarios. You then write tests to ensure that your system can handle these exceptions gracefully.


问:
Years experience over unfinished degree?
I'm currently in my placement year and working for a great software development company. It was always my intention of getting to this stage through university, getting enough academic experience as well as the year’s placement and then try to get a full time programming job without the need to finish my degree. I decided this from an early stage as I have never really liked the whole university environment. I was so unhappy at university and I’m so happy now I’m on my placement year, I really don’t know if I can go back.

My question is, do you think companies will take me on if I apply for other jobs after my placement year and not penalize me for not finishing my degree?

I guess at the end of the day I don't want to look back on my life and think "god, why didn't I just spend one more year being unhappy to have a job I love" but I know that even if I get a degree I could still end up without a programming job and this worries me more than anything.

答:
Unfinished degree without an exceptional reason for not finishing it indicates a lack of commitment.

Years of experience mean nothing. You can work in one company for a year and learn as much as your colleague has learnt in another company after eight years.

Proven track record is an indicator of your experience. Unfinished degree significantly undermines your proven track record.

Many exceptionally good companies won't consider offering you an interview for a reasonably good job if you have an unfinished degree


答:
If there is no need to change the code, leave it as it is. But if you have to change the code because you have to fix some bug or change some functionality, you will have to change it, if you like it or not. IMHO it is often more safe and less error-prone, if you first refactor it into smaller, better understandable pieces and then add the functionality. When you have automatic refactoring tools at hand, this can be done relatively safe, with only a very small risk of introducing new bugs. And I recommend that you should get a copy of Michael Feathers book

http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052

which will give you valuable hints how to make the code more testable, add unit tests and avoid breaking the code when adding new features.

If you do it right, your method will hopefully become simple enough the the try-catch-finally will not contain any unrelated code at the wrong places any more.

Title: "how bad" is unrelated code in try-catch-finally block?

Body:
This is a related Q:
Is use of finally clause for doing work after return bad style/dangerous?

In the referenced Q, the finally code is related to the structure used and the necessity of pre-fetching.  My question is a little different, and I believe it's germane to the broader audience.  My particular example is a C# winform app, but this would apply to C++ / Java finally usage as well.

I'm noticing quite a few try-catch-finally blocks where there is a lot of code unrelated to exceptions and exception handling / cleanup buried within the block.  And I will admit my bias towards having very tight try-catch-finally blocks with the code closely related to the exception and handling. Here are some examples of what I'm seeing.

Try blocks will have lots of preliminary calls and variables being set leading up to the code that could throw.  Logging information will get setup and run in the try block as well.

Finally blocks will have form / module / control formatting calls (despite the app being about to terminate, as expressed in the catch block), as well as creating new objects such as panels.

Roughly:

```
    methodName( ... )
    {
        try
        {
            // Lots of code for the method ...
            // code that could throw ...
            // Lots more code for the method and a return ...
        }
        catch( something )
        { // handle exception }
        finally
        {
            // some cleanup due to exception, closing things
            // more code for the stuff that was created (ignoring that any exceptions could have thrown) ...
            // maybe create some more objects
        }
    }
```

The code works, so there is some value to it.  It is not well encapsulated and the logic is a bit convoluted.  I'm (painfully) familiar with the risks in shifting code around as well as refactoring, so my question boils down to wanting to know others' experience with similarly structured code.

Does the bad style justify making the changes?  Has anyone been badly burned from a similar situation?  Would you care to share the details of that bad experience?  Leave it be because I'm over-reacting and it's not that bad of style?  Gain the maintenance benefits of tidying things up?


问:
Would you show your production code to candidates at the interview?
I have seen this happen multiple times:

The candidate likes the company, succeeds at the interview. Then comes to work and at the end of the first day he is sure the codebase/project is not what he would like to spend time with. So he leaves quickly.

I think that introducing candidates to the codebase at the interview could potentially solve this problem. Maybe even better: mixing this with interview questions like "how would you improve this part of the code?" This way, it would be obvious if the candidate is a "good fit for the codebase".

Have you seen this approach applied anywhere? Would you show your own codebase to the candidates at the interview: if they asked/as part of the interview process?

答:
Yes, if the code in question didn't belong to a client.

Last time I interviewed someone, the person rocked up and felt completely overwhelmed at the size of the codebase, and soon left.

If the code belonged to a client, it wouldn't (in my opinion) be ethical to show the source, because your client's code is your client's, not yours. (Of course, if you asked your client for permission, and you got it, then there's no problem.)


问:
Static objects and concurrency in a web application
I'm developing small Java Web Applications on Tomcat server and I'm using MySQL as my database.

Up until now I was using a connection singleton for accessing the database but I found out that this will ensure just on connection per Application and there will be problems if multiple users want to access the database in the same time. (They all have to make us of that single Connection object). I created a Connection Pool and I hope that this is the correct way of doing things.

Furthermore it seems that I developed the bad habit of creating a lot of static object and static methods (mainly because I was under the wrong impression that every static object will be duplicated for every client which accesses my application).

Because of this all the Service Classes ( classes used to handle database data) are static and distributed through a ServiceFactory:

```<code>public class ServiceFactory {

private static final String JDBC = "JDBC";
private static String impl;

private static AccountService accountService;
private static BoardService boardService;

public static AccountService getAccountService(){
    initConfig();

    if (accountService == null){
        if (impl.equalsIgnoreCase(JDBC)){
            accountService = new JDBCAccountService();
        }
    }

    return accountService;
}

public static BoardService getBoardService(){
     initConfig();

    if (boardService == null){
        if (impl.equalsIgnoreCase(JDBC)){
            boardService = new JDBCBoardService();
        }
    }

    return boardService;
}
private static void initConfig(){
    if (StringUtil.isEmpty(impl)){
        impl = ConfigUtil.getProperty("service.implementation");

        // If the config failed initialize with standard
        if (StringUtil.isEmpty(impl)){
            impl = JDBC;
        }
    }
}
</code>```

This was the factory class which, as you can see, allows just one Service to exist at any time. Now, is this a bad practice? What happens if let's say 1k users access AccountService simultaneously?

I know that all this questions and bad practices come from a bad understanding of the static attribute in a web application and the way the server handles this attributes. Any help on this topic would be more than welcomed. Thank you for your time!

答:
Those are basically solved problems. Just create a new connection every time you need to access the database (or maybe just once per request, if that's easily possible), and use a database API that supports pooled connections. Just make sure you close all connections no matter what, but that's something you should be doing anyway. No need to reinvent the wheel here.

And may I note that making the database connection a singleton is a bad design decision in the first place, because of the exact problem you've run into. There is absolutely no reason to enforce that there is only ever one connection to the database from your application.


答:
IMO: Too dangerous.

As others have mentioned, even simple read-only access can break the database in horrible ways - deadlocks, performance, etc.; in principle, you are giving your users an efficient way of DoS-ing the database server. All a user needs to do is full-outer-join the largest table in the DB on itself, using a non-indexed column. Sure, you can put up all sorts of restrictions and safeguards, but this is tricky, and probably not worth the hassle.

Instead, ask yourself why this setup is a perceived necessity. What makes users demand such a never-ending flow of yet new queries? Are there any recurring patterns at all that you could distill out of all those queries? Then design a solution that allows users to flexibly generate the reports they want. Possible solutions include off-the-shelf reporting suites; a semi-sandboxed DSL that exposes the domain data model in a queryable way, but without the full destructive power of SQL; or a custom UI that users can use to compose the desired queries in a desktop-application-GUI-like way.


答:
Objective-C is C, with a layer of Smalltalk.

According to Wikipedia:

Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.

It is Object-Oriented, but is not from C++ directly.

So yes, it is C with some of the OO abilities of Smalltalk.

Title: Where does Objective-C come from? C++ or C?

Body:
I am very confused about this programming language, Objective-C, which I heard is used to develop iOS applications.

I know that it uses the principles of OOP. Would it be easier to learn if I already knew C++?
What about it's name? is it a combination between the C programming language and the OOP principles I use in C++?


问:
To design pattern, or not to design pattern
Design patterns are good, but complex. Should we use them in small projects? Implementing design patterns needs more sophisticated developers, which in turn raises project costs. On the other hand, they make code neat and clean. Are they necessary for small projects?

Update: Should we insist on using design patterns when the team is not efficient at working with them?

答:
Just to be pedantic, while recognizing Design Patterns does make it easier to understand what code does, the patterns themselves don't "make code neat and clean". It's more likely that patterns will make code messier and therefore harder to understand if they are implemented with little thought or understanding as to how to apply them.

Patterns aren't a silver bullet.  They won't solve your problems for you, and worrying to much about whether you are using the "right pattern", or whether or not you can remember every single pattern in the GoF book won't make you a better programmer.  On the other hand, understanding the language of Patterns will allow you to more clearly articulate ideas and designs in a meaningful way.

Design Patterns are merely tools which allow you to define and solve problems within the context of your code. If you try and use a lot of patterns simply because you think you need to be using patterns, you will end up heavily over-engineering relatively simple problems.  For example, you could introduce a fully fledged Observer pattern for each event you raise in your code, but if your code is the only thing that will trigger those events, and if the events are expected to trigger only a single handler, then you don't need to create Observers to do the job, whereas assigning a simple function pointer to a property and the code to trigger it will probably do just as well.  If you think you "might" need your Observer in the future, then it only "might" be worth the effort to engineer it. You risk future-proofing your code without really understanding if it will be worth the up front cost, and the result is often going to turn out to be like gold-plating when a splash of yellow paint would have been more appropriate.

Patterns often solve very specific problems, and they are just as often misused simply because they are a close yet imperfect fit for the problem at hand.  Sometimes it can be better to see a pattern emerge from the code, and use your knowledge of patterns to help guide you to a better understanding about how to approach solving the problem. It may be at times that a pattern will do the job exactly, yet at other times you are better off taking the ideas behind a pattern, but implementing a modified version of the pattern to solve your particular problem.

All of this is would seem to indicate that the Language of Patterns is probably a more important tool to the developer than the individual patterns themselves.


答:
From the horse's mouth:

Objective-C is a hybrid programming language[…]formed by grafting the
  Smalltalk-80 style of object-oriented programming onto a C language
  rootstock. Objective-C adds precisely one new data type, the object,
  to those C provides already, and precisely one new operation, the
  message expression. Like Smalltalk-80, Objective-C makes no
  compile-time distinction between different kinds (classes) of objects.

To address "Would it be easier to learn if i already knew C++?" I don't think so, but I don't think it'd hurt either. You might be more comfortable with concepts like classes and objects if you already know C++, but will find that Objective-C implements classes in a very different way to C++. To borrow some terminology from Stroustrup, all ObjC messages are "virtual" and can be redefined by subclasses, or even have their implementations swapped on the defining class. This and other subtleties probably cancels out some of the headstart you'll get from knowing C++.


问:
Best way to reliably recognize open source licenses?
In many projects these days most of the novel code consists of glue code that helps combine dozens of different libraries, plugins and helpers that are licensed under a variety of open source licenses.

In many cases the licenses are fairly obvious as they carry the name of the license in the license file or comment. In others this is a bit harder and requires memorizing certain wordings to tell the more common licenses apart.

I am wondering: Is there an easy way to recognize particularly the very similar licenses (say, MIT/BSD-2/BSD-3) without having to memorize complete license texts or check out the OSI copies as reference?

答:
Just use the most powerful pattern matching tool you have at your disposal: your eyes. I ran into the same problem some time ago (was compiling a big list of Django apps and jQuery plugins, and most of them didn't explicitly name the license they were using), in the beginning I had to compare to a reference text all the time, but it didn't take long for me to become able to identify those licenses in a glimpse. Here's what I see when I look at the MIT license:

```<code>Copyright (C) <year> <copyright holders>

Permission is hereby granted, text text text
text text text
text text text

The above copyright notice and this permission notice text text text

TEXT TEXT TEXT TEXT
TEXT TEXT TEXT TEXT
</code>```

And the Modified BSD:

```<code>Copyright (c) <year>, <copyright holder>
All rights reserved.

Redistribution text text text
* text text text
* text text text
* Neither the name of the <organization> nor the
  text text text

TEXT TEXT TEXT
TEXT TEXT TEXT
</code>```

Notice how the text layout combined with a few key words/phrases are enough to identify those two licenses, and since they are by far the most common (that don't display its own name in the header, like the GPL or the Apache) they're easy to memorize (and obviously, I can tell it's BSD-3 because it has 3 bullet points).

Now, it's always possible - though very unlikely - that the authors used a slightly different license that you could mistake for the MIT/BSD-3, but if they did and they care about the difference, you can reasonably expect them to call attention to it.

Update: check this answer to a SO question about "grepping" a page using JavaScript; maybe with a little work one could write a small tool (a bookmarklet for instance) to search the contents of a page for the text of a license among a small set of known ones (written as a regex, since you'd have to replace the <copyright holder> and such for wildcards). I avoid bookmarkets because of the security implications, but if you either wrote or is hosting (if applicable) them yourself you should be fine. I know no existing tool for that purpose though.

Personally, I don't think it's worth the trouble - the effort to carefully examine a license is only a small part of the decision to incorporate it into a big project. Usually the troublesome parts are the library dependencies, or the relative effort to integrate them with the rest of your code. So I prefer to do a quick classification into "might use" or "definitly won't use" and then, if I decide the library is really promising, take a closer look at the license.

Body:
Just use the most powerful pattern matching tool you have at your disposal: your eyes. I ran into the same problem some time ago (was compiling a big list of Django apps and jQuery plugins, and most of them didn't explicitly name the license they were using), in the beginning I had to compare to a reference text all the time, but it didn't take long for me to become able to identify those licenses in a glimpse. Here's what I see when I look at the MIT license:

Copyright (C) <year> <copyright holders>

Permission is hereby granted, text text text
text text text
text text text

The above copyright notice and this permission notice text text text

TEXT TEXT TEXT TEXT
TEXT TEXT TEXT TEXT

And the Modified BSD:

Copyright (c) <year>, <copyright holder>
All rights reserved.

Redistribution text text text
* text text text
* text text text
* Neither the name of the <organization> nor the
  text text text

TEXT TEXT TEXT
TEXT TEXT TEXT

Notice how the text layout combined with a few key words/phrases are enough to identify those two licenses, and since they are by far the most common (that don't display its own name in the header, like the GPL or the Apache) they're easy to memorize (and obviously, I can tell it's BSD-3 because it has 3 bullet points).

Now, it's always possible - though very unlikely - that the authors used a slightly different license that you could mistake for the MIT/BSD-3, but if they did and they care about the difference, you can reasonably expect them to call attention to it.

Update: check this answer to a SO question about "grepping" a page using JavaScript; maybe with a little work one could write a small tool (a bookmarklet for instance) to search the contents of a page for the text of a license among a small set of known ones (written as a regex, since you'd have to replace the <copyright holder> and such for wildcards). I avoid bookmarkets because of the security implications, but if you either wrote or is hosting (if applicable) them yourself you should be fine. I know no existing tool for that purpose though.

Personally, I don't think it's worth the trouble - the effort to carefully examine a license is only a small part of the decision to incorporate it into a big project. Usually the troublesome parts are the library dependencies, or the relative effort to integrate them with the rest of your code. So I prefer to do a quick classification into "might use" or "definitly won't use" and then, if I decide the library is really promising, take a closer look at the license.


问:
The modern way to perform error handling...
I've been pondering this problem for a while now and find myself continually finding caveats and contradictions, so I'm hoping someone can produce a conclusion to the following:

Favour exceptions over error codes

As far as I'm aware, from working in the industry for four years, reading books and blogs, etc. the current best practice for handling errors is to throw exceptions, rather than returning error codes (not necessarily an error code, but a type representing an error).

But - to me this seems to contradict...

Coding to interfaces, not implementations

We code to interfaces or abstractions to reduce coupling. We don't know, or want to know, the specific type and implementation of an interface. So how can we possibly know what exceptions we should be looking to catch? The implementation could throw 10 different exceptions, or it could throw none. When we catch an exception surely we're making assumptions about the implementation?

Unless - the interface has...

Exception specifications

Some languages allow developers to state that certain methods throw certain exceptions (Java for example, uses the throws keyword.) From the calling code's point of view this seems fine - we know explicitly which exceptions we might need to catch.

But - this seems to suggest a...

Leaky abstraction

Why should an interface specify which exceptions can be thrown? What if the implementation doesn't need to throw an exception, or needs to throw other exceptions? There's no way, at an interface level, to know which exceptions an implementation may want to throw.

So...

To conclude

Why are exceptions preferred when they seem (in my eyes) to contradict software best practices? And, if error codes are so bad (and I don't need to be sold on the vices of error codes), is there another alternative? What is the current (or soon to be) state of the art for error handling that meets the requirements of best practices as outlined above, but doesn't rely on calling code checking the return value of error codes?

答:
Lots of good stuff here, I'd just like to add that we should all be wary of code which uses exceptions as part of normal control flow.  Sometimes people get into that trap where anything which isn't the usual case becomes an exception.  I've even seen an exception used as a loop termination condition.

Exceptions mean "something I can't handle here happened, need to go out to someone else to figure out what to do."  A user typing invalid input isn't an exception (that should be handled locally by the input by asking again, etc.).

Another degenerate case of exception usage I've seen is people whose first response is "throw an exception."  This is almost always done without writing the catch (rule of thumb: write the catch first, then the throw statement).  In big applications this becomes problematic when an uncaught exception bubbles up from the nether-regions and blows up the program.

I'm not anti-exceptions, but they seem like singletons of a few years ago: used far too frequently and inappropriately.  They're perfect for the intended use, but that case is not as broad as some think.


答:
I haven't done it, but I would. If a developer thought it didn't look like something he wanted to work on, this could be a chance to find something out about the candidate's mentality: why doesn't he like it? What would he change? Would he enjoy being in a position where he could make such a change? If so, why did he originally say he didn't want to work on it?

I've seen sentiment on the daily WTF that people think if an interviewer shows you real code, she is trying to get the candidate to fix her problems for free. This is paranoid, IMO. The interviewer is trying to find out how well you can solve real world problems in a real world codebase. And you get to find out more about the project you'll be working on.

Title: Would you show your production code to candidates at the interview?

Body:
I have seen this happen multiple times:

The candidate likes the company, succeeds at the interview. Then comes to work and at the end of the first day he is sure the codebase/project is not what he would like to spend time with. So he leaves quickly.

I think that introducing candidates to the codebase at the interview could potentially solve this problem. Maybe even better: mixing this with interview questions like "how would you improve this part of the code?" This way, it would be obvious if the candidate is a "good fit for the codebase".

Have you seen this approach applied anywhere? Would you show your own codebase to the candidates at the interview: if they asked/as part of the interview process?


答: Others have pointed out that Objective-C is a SmallTalk style OO layer added to C, I'll add that C++ started as a Simula style OO layer added to C (and then templates were added to make a good measure).</p>


答:
Suppose you have six methods to call, four of which should only be called if the first completes with no error.  Consider two alternatives:

```<code>try {
     method1();  // throws
     method2();
     method3();
     method4();
     method5();
 } catch(e) {
     // handle error
 }
 method6();
</code>```

vs

```<code> try {
      method1();  // throws
 }
 catch(e) {
      // handle error
 }
 if(! error ) {
     method2();
     method3();
     method4();
     method5();
 }
 method6();
</code>```

In the second code, you are treating exceptions like return codes.  Conceptually, this is identical to:

```<code>rc = method1();
if( rc != error ) {
     method2();
     method3();
     method4();
     method5();
 }
 method6();
</code>```

If we are going to wrap every method that can throw an exception in a try/catch block, what is the point of having exceptions in a language feature at all?  There's no benefit and there's more typing.

The reason that we have exceptions in languages in the first place is that in the bad old days of return codes, we often had situations above where we had multiple methods that could return errors, and each error meant aborting all methods entirely.  In the beginning of my career, in the old C days, I saw code like this all over the place:

```<code>rc = method1();
if( rc != error ) {
     rc = method2();
     if( rc != error ) {
         rc = method3();
         if( rc != error ) {
             rc = method4();
             if(rc != error ) {
                 method5();
             }
         }
     }
 }
 method6();
</code>```

This was an incredibly common pattern, and one that exceptions very neatly solved by allowing you to go back to the first example above.  A style rule that says each method has its own exception block completely throws this out the window.  Why even bother, then?

You should always endeavor to make the try block surrond the set of code that is conceptually a unit.  It should surround code for which if there is any error in the code unit, then there's no point in running any other code in the code unit.

Going back to the original purpose of exceptions: remember that they were created because often code can't easily deal with errors right when they actually occur.  The point of exceptions is to allow you to deal with errors significantly later in the code, or further up the stack.  People forget that and in many cases catch them locally when they'd be better off simply documenting that the method in question can throw this exception.  There's too much code in the world that looks like this:

```<code>void method0() : throws MyNewException
{
    try {
        method1();  // throws MyOtherException
    }
    catch(e) {
        if(e == MyOtherException)
            throw MyNewException();
    }
    method2();
}
</code>```

Here, you're just adding layers, and layers add confusion.  Just do this:

```<code>void method0() : throws MyOtherException
{
    method1();
    method2();
}
</code>```

In addition to that, my feeling is that if you follow that rule, and find yourself with more than a couple try/catch blocks in the method, you should question whether the method itself is too complex and needs to be broken down into multiple methods.

The takeaway: a try block should contain the set of code which should be aborted if an error occurs anywhere in the block.  Whether this set of code is one line or one thousand lines doesn't matter.  (Though if you've got a thousand lines in a method, you've got other problems.)

Body:
Suppose you have six methods to call, four of which should only be called if the first completes with no error.  Consider two alternatives:

try {
     method1();  // throws
     method2();
     method3();
     method4();
     method5();
 } catch(e) {
     // handle error
 }
 method6();

vs

 try {
      method1();  // throws
 }
 catch(e) {
      // handle error
 }
 if(! error ) {
     method2();
     method3();
     method4();
     method5();
 }
 method6();

In the second code, you are treating exceptions like return codes.  Conceptually, this is identical to:

rc = method1();
if( rc != error ) {
     method2();
     method3();
     method4();
     method5();
 }
 method6();

If we are going to wrap every method that can throw an exception in a try/catch block, what is the point of having exceptions in a language feature at all?  There's no benefit and there's more typing.

The reason that we have exceptions in languages in the first place is that in the bad old days of return codes, we often had situations above where we had multiple methods that could return errors, and each error meant aborting all methods entirely.  In the beginning of my career, in the old C days, I saw code like this all over the place:

rc = method1();
if( rc != error ) {
     rc = method2();
     if( rc != error ) {
         rc = method3();
         if( rc != error ) {
             rc = method4();
             if(rc != error ) {
                 method5();
             }
         }
     }
 }
 method6();

This was an incredibly common pattern, and one that exceptions very neatly solved by allowing you to go back to the first example above.  A style rule that says each method has its own exception block completely throws this out the window.  Why even bother, then?

You should always endeavor to make the try block surrond the set of code that is conceptually a unit.  It should surround code for which if there is any error in the code unit, then there's no point in running any other code in the code unit.

Going back to the original purpose of exceptions: remember that they were created because often code can't easily deal with errors right when they actually occur.  The point of exceptions is to allow you to deal with errors significantly later in the code, or further up the stack.  People forget that and in many cases catch them locally when they'd be better off simply documenting that the method in question can throw this exception.  There's too much code in the world that looks like this:

void method0() : throws MyNewException
{
    try {
        method1();  // throws MyOtherException
    }
    catch(e) {
        if(e == MyOtherException)
            throw MyNewException();
    }
    method2();
}

Here, you're just adding layers, and layers add confusion.  Just do this:

void method0() : throws MyOtherException
{
    method1();
    method2();
}

In addition to that, my feeling is that if you follow that rule, and find yourself with more than a couple try/catch blocks in the method, you should question whether the method itself is too complex and needs to be broken down into multiple methods.

The takeaway: a try block should contain the set of code which should be aborted if an error occurs anywhere in the block.  Whether this set of code is one line or one thousand lines doesn't matter.  (Though if you've got a thousand lines in a method, you've got other problems.)


问:
Web Services as a Back end
I am contemplating a direction to take an application. The application is written in PHP which implements a MVC framework.

Some of my clients will require web services. I was thinking even building the basic PHP web interface on top of these web services (SOAP) and stopping the PHP  application from accessing the database. I want to do this so that I will only have to maintain one set of code for the main PHP apllication to access data and also any other applications developed on top of this web service. Is this a common setup? Will it slow the application a lot?

I looked at using Django framework to setup the SOAP web service but then realized it will have trouble dealing with multiple identical databases based on which client is using it.

I looked at Symfony, but worry that PHP as a backend might be seen as insecure or unprofessional by some larger future clients and not enterprise usable.

I am thinking Axis2 right now. Java might be faster as the backend and it will be marketable to potential clients.

What other Web Service framework should I consider? Is this Web Services Backend / PHP/HTML front end a usable solution?

答:
Yes, this is a very common setup in larger applications. However, every web service call will add an additional delay to your application. So you need to design your web service very well to reduce the number of round trips an to reduce the amount of data you have to fetch from the service.

I would suggest that you stick with the language your are most familiar with.

Regarding Django and multiple databases: Django has builtin support for multiple databases. You can use them on a per-query base or a per-model base (and even use different database for read/write operations of the same model).

Title: Web Services as a Back end


问:
Does Parallel Inheritance Make for Good Code?
I'm writing a database interface in PHP and I have a base dbTables class, as well as a base dbTableFields class.

dbTables has a function, getFields(), that instantiates dbTableFields objects, each of which carries essential data on each table field, and puts it into dbTableFields->fields=array();

dbTables has several children.

Now I've realized that the children need to use different versions of getFields(). But they only differ in one place: they need to instantiate dbTableFields children, rather than dbTableFields objects.

I've solved this problem. I took advantage of PHP's ability to use variables to represent class names. All I had to do was, in dbTables->getFields() replace:

```<code>$this->fields = new dbTableFields();
</code>```

with

```<code>$this->fields = new self::$field_model();
</code>```

Where self::$field_model = 'dbTableFields'; // string value for class

Now, in the child classes, I just have to override the $field_model property with the name of the appropriate dbTableFields descendents.

Is this parallel inheritance scheme good form? Or am I creating an uncompromising mess? Is there some more-elegant and more maintainable method for achieving the same effect?

答:
The principle you want is to "favor composition over inheritance."  This is a fairly classic example of where the strategy pattern would be useful: separate your "getFields" logic into several FieldStrategy objects, and reference the appropriate one for your parent and your children.

I'm not explaining this very well, but please google "strategy pattern" and play with it.


答: We not only show the candidates our code, we get them to work on it. We do pair programming, so we do interviews by pairing the candidate with one of our programmers and working on a real problem (albeit a carefully chosen one - something that doesn't need masses of contextual knowledge). They get to see our code, and we get to see their coding, and we both get to see how they fit in with our culture.</p>


答:
NO, usually.

Parallel inheritance hierarchies are bad smell in code.

I have heard that Martin Fowler indicated this as a code smell in his famous book "Refactoring : Improving the Design of Existing Code".

However, it is not something absolute. Sometimes parallel inheritance hierarchy may be the best design among the alternatives your team could come up with.

Google with "Parallel inheritance hierarchy". Who knows better design may pop-out!

Title: Does Parallel Inheritance Make for Good Code?

Body:
I'm writing a database interface in PHP and I have a base dbTables class, as well as a base dbTableFields class.

dbTables has a function, getFields(), that instantiates dbTableFields objects, each of which carries essential data on each table field, and puts it into dbTableFields->fields=array();

dbTables has several children.

Now I've realized that the children need to use different versions of getFields(). But they only differ in one place: they need to instantiate dbTableFields children, rather than dbTableFields objects.

I've solved this problem. I took advantage of PHP's ability to use variables to represent class names. All I had to do was, in dbTables->getFields() replace:

```<code>$this->fields = new dbTableFields();
</code>```

with

```<code>$this->fields = new self::$field_model();
</code>```

Where self::$field_model = 'dbTableFields'; // string value for class

Now, in the child classes, I just have to override the $field_model property with the name of the appropriate dbTableFields descendents.

Is this parallel inheritance scheme good form? Or am I creating an uncompromising mess? Is there some more-elegant and more maintainable method for achieving the same effect?


答:
I regard your second approach really bad.

First, consider whether you can change your design to make instantiation of Point object possible only when valid values for x, y, z coordinates are available. Provide only one constructor that takes all 3 parameters.

Second, consider having a single method of setting coordinates:

```<code>void setCoordinates(float x, float y, float z)
</code>```

In this method, set the state variable that you are using for marking valid values.

Body:
I regard your second approach really bad.

First, consider whether you can change your design to make instantiation of Point object possible only when valid values for x, y, z coordinates are available. Provide only one constructor that takes all 3 parameters.

Second, consider having a single method of setting coordinates:

void setCoordinates(float x, float y, float z)

In this method, set the state variable that you are using for marking valid values.


答:
This approach is pretty common and makes more sense if you are really building a platform where others will develop on it. By consuming your webservices exclusively in your own app(eating your own dogfood), you will be validating the strength of your platform. Things to make sure you cover:

On the web services platform:

Cache as much has you can for read operations, both from storing database servers in memory or memcache servers and also using a CDN for web services that are more static (i.e. web services that return lookup data (The key is to reduce the amount of disk I/O your overall system will make). As programmers we often forget that we can save alot of processing resources by offloading to external CDN servers

Dont forget to cache responses using gzip to reduce download times

Consider returning richer objects to minimize roundtrips so that client applications dont make extra calls. i.e. instead of returning a list of invoice objects you could also nest the invoice-item objects within a getinvoices type of web service. With compressed responses, it would be that much heavier and you save on roundtrips. Even better would be to allow calling applications to pass in a flag to determine how "rich" the return objects are

Issue api keys to different clients and validate so you can manage traffic, rate-limit and prevent abuse

I know you mentioned SOAP, but do you might need a plan for pure restful json/xml type apis if the consumer ecosystem will be pretty open to ease adoption

Title: Web Services as a Back end

Body:
I am contemplating a direction to take an application. The application is written in PHP which implements a MVC framework.

Some of my clients will require web services. I was thinking even building the basic PHP web interface on top of these web services (SOAP) and stopping the PHP  application from accessing the database. I want to do this so that I will only have to maintain one set of code for the main PHP apllication to access data and also any other applications developed on top of this web service. Is this a common setup? Will it slow the application a lot?

I looked at using Django framework to setup the SOAP web service but then realized it will have trouble dealing with multiple identical databases based on which client is using it.

I looked at Symfony, but worry that PHP as a backend might be seen as insecure or unprofessional by some larger future clients and not enterprise usable.

I am thinking Axis2 right now. Java might be faster as the backend and it will be marketable to potential clients.

What other Web Service framework should I consider? Is this Web Services Backend / PHP/HTML front end a usable solution?


问:
Should all public methods in an abstract class be marked virtual?
I recently had to update an abstract base class on some OSS that I was using so that it was more testable by making them virtual (I could not use an interface as it combined two). This got me thinking whether I should mark all of the methods that I needed virtual, or if I should mark every public method/property virtual. I generally agree with Roy Osherove that every method should be made virtual, but I came across this article that got me thinking about whether this was necessary or not. I am going to limit this down to abstract classes for simplicity, however (whether all concrete public methods should be virtual is especially debatable, I am sure).

I could see where you might want to allow a sub-class to use a method, but not want it overriding the implementation. However, as long as you trust that Liskov's Substitution Principle will be followed, then why would you not allow it to be overriden? By marking it abstract, you are forcing a certain override anyway, so, it seems to me that all public methods inside of an abstract class should indeed be marked virtual.

However, I wanted to ask in case there was something I might not be thinking. Should all public methods within an abstract class be made virtual?

答: It is enough for a class to contain ONE virtual method, in order for the class to become abstract. You might want to pay attention to which methods you want virtual and which not, according to the type of polymorphism you're planning to use.</p>


问:
Stored Procedures a bad practice at one of worlds largest IT software consulting firms?
I'm working at a project in one of the world's top 3 IT consulting firms, and was told by a DBA that company best practice's state stored procedures are not a "best practice".  This is so contrary to everything I've learned.

Stored procedures give you code reuse, and encapsulation (two pillars of software development), security (you can grant/revoke permissions on an individual stored proc), protect you from SQL injection attacks, and also help with speed (although that DBA said that starting with SQL Server 2008 that even regular SQL queries are compiled if they are run enough times).

We're developing a complex app using Agile software development methodology.  Can anyone think of good reasons why they wouldn't want to use stored procs?  My guess was that the DBAs didn't want to maintain those stored procs, but there seem to be way too many negatives to justify such a design decision.

答:
This is another point not mentioned yet:

Code generation tools and reverse engineering tools cannot really cope well with stored procedures. The tool generally cannot tell what the proc does. Does the proc return a resultset? Several resultsets? Does it fetch its resultsets from several tables and temporary-tables? Is the proc just an encapsulated update statement and does not return anything? Does it return a resultset, a return value and some "console output"?

So if you want to use a tool to create a data-transfer-object DTO and DAO layer automatically (such as liferay's "service builder" does) , you cannot easily do so.

Moreover, ORMs like Hibernate cannot really work properly when the data source is an SP. Data access is read-only at best.


问:
When is unit testing inappropriate or unnecessary?
It seems to be generally assumed (on Stack Overflow at least) that there should always be unit tests, and they should be kept up to date. But I suspect the programmers making these assertions work on different kinds of projects from me - they work on high quality, long-lasting, shipped software where bugs are A Really Bad Thing.

If that's the end of the spectrum where unit testing is most valuable, then what's the other end? Where are unit tests least valuable? In what situations would you not bother? Where would the effort of maintaining tests not be worth the cost?

答: Kent Beck (the man behind the idea of Unit Testing) says that it's fine not to write Unit Tests when working on an idea (eg. prototype) that you might throw away (if you decide not to work further on). On the contrary, if you write your prototype and decide to go for it, Unit Testing will be helpful for all the reasons covered in the previous answers.</p>


问:
Is it better to return NULL or empty values from functions/methods where the return value is not present?
I am looking for a recommendation here.  I am struggling with whether it is better to return NULL or an empty value from a method when the return value is not present or cannot be determined.

Take the following two methods as an examples:

string ReverseString(string stringToReverse) // takes a string and reverses it.
Person FindPerson(int personID)    // finds a Person with a matching personID.
```

In ReverseString(), I would say return an empty string because the return type is string, so the caller is expecting that.  Also, this way, the caller would not have to check to see if a NULL was returned.

In FindPerson(), returning NULL seems like a better fit.  Regardless of whether or not NULL or an empty Person Object (new Person()) is returned the caller is going to have to check to see if the Person Object is NULL or empty before doing anything to it (like calling UpdateName()).  So why not just return NULL here and then the caller only has to check for NULL.

Does anyone else struggle with this?  Any help or insight is appreciated.

答:
To me there are two cases here.  If you're returning some sort of list you should always return the list no matter what, empty if you don't have anything to put in it.

The only case where I see any debate is when you're returning a single item.  I find myself preferring to return null in case of failure in such a situation on the basis of making things fail fast.

If you return a null object and the caller needed a real object they might go ahead and try to use the null object producing unexpected behavior.  I think it's better for the routine to go boom if they forget to deal with the situation.  If something's wrong I want an exception ASAP.  You're less likely to ship a bug this way.


答:
Just an observation: People don't share their UML Models as freely as they share their code.

Even if they did, there would be compatibility issues of the software tools used (there is no exchange format, XMI is insufficient)

Regarding diagram types.
In computer books that I happen to like, the authors seem to prefer only a simplified diagram type  ("Head First Design Patterns" use only simplified class diagrams; "Portlets in action" almost exclusively uses sequence diagrams). Other diagram types seem to be much less frequently used in the computer literature. Let alone other UML constructs such as the "object constraint language".

Title: Limitations of UML?

Body: I'm currently studying for an examination and one of the sample paper questions is to discuss the limitations of UML. Most of the material I'm finding on the net is relating to a specific UML implementation or language. I'm wondering from a generalists point of view what would you consider the limitations of UML to be? </p>


问:
Estimating Cost of modifying someone elses code
I am relatively new to web development and haven't had to provide estimates for many large projects yet (my last large project was just paid for by the hour without a strict deadline or budget).

A client is asking me to provide a cost and time estimate for providing a myriad of changes to another developers code for a website (php/mysql backend).

Can anyone provide some advice or links on how to go about analyzing and estimating this? The code is horrible (the website was originally outsourced to india years and years ago) and it's hard to know if I'm going to suddenly hit hurdles and blow my estimates out of the water.

答:
I think you should not name a price from the beginning. If someone talks to you about a project, you should do enough work for free to figure out what the client wants and how much it might cost. No more or less than that.

Give them a proposal, which can be extremely brief, but give them something that describes what they want and what you will deliver. You can put a range if you want, and you could even say that this is a “good faith estimate” but that the final amount will be based on time spent.

From my experience as a freelancer, there are 3 main steps in doing this:

ask for 50% downpayment to begin work

ask for final payment before handing over the files

ask for a block of hours for ongoing work or work that will probably pop up over time

Good Luck!


答: Ask for an hourly rate.  Don't let a lot of hours build up before you invoice.</p>

Title: Estimating Cost of modifying someone elses code

Body:
I am relatively new to web development and haven't had to provide estimates for many large projects yet (my last large project was just paid for by the hour without a strict deadline or budget).

A client is asking me to provide a cost and time estimate for providing a myriad of changes to another developers code for a website (php/mysql backend).

Can anyone provide some advice or links on how to go about analyzing and estimating this? The code is horrible (the website was originally outsourced to india years and years ago) and it's hard to know if I'm going to suddenly hit hurdles and blow my estimates out of the water.


答:
Go Agile! Don't estimate a whole bunch, especially if you don't have much experience under your belt.

Talk to your client and see what needs to be implemented/delivered.

For every functionality/unit-of-work create a user story (non technical part, write proper description) and break it into one or more subtasks (technical part)

Estimate every user story

Remember, estimate by its definition is always wrong, otherwise it would be called a number! It's very important that your client understands this as well!

You should do incremental delivery. Tell the client to prioritize user stories and select those to be delivered in the first iteration. Each iteration should last 2 weeks or less, but no more than 3 weeks! When you finish a user story (all its subtasks are closed), notify the client and ask him to verify it while you're working on the next user story.

You don't have to charge upfront, you can do it after each iteration.

Happy coding!


问:
Pros and cons of an HTML/JavaScript only web app
I come from an ASP.NET forms background and have found server side coding very powerful in the past. More recently, however, I have been wanting to phase out the server side code of the front-end and replace it with pure HTML/JavaScript, which accesses the data through JSON webservices. I have no real experience in this, and so I would like to hear whether this is a tried and tested model. Also, what are the pitfalls surrounding it?

I find ASP.NET user controls very useful, so I would like to keep the theory behind it by storing markup templates in separate HTML files on the server. These will be retrieved and used through jQuery AJAX and the jQuery HTML templates plugin respectively.

Any input will be extremely appreciated.

P.S. Sorry for the noob question, but is this type of Web architecture what is referred to as web-2.0 or am I completely off-track?

答: One downside is needing to duplicate some of the logic in JavaScript and ASP.net. This might not be a big issue for you depending on your application. It often comes up because you don't want to have to ask the server to check every little thing ("Is the user allowed to press this button or select this option in this situation?") but you also don't want to depend on the client as the only one doing validation since the user has control over the client.</p>


答:
Its definitely possible, and probably encouragable as  best-practice. What you're proposing is splitting the UI from the business logic so there is a clean separation of concerns. This is really good.

Too often the frameworks we have try to muddle things together and you end up with a monolithic piece of software where the UI, the business logic and the data are all intertwined with each other. That makes it more difficult to maintain and modify.

Once you split the application into 2 pieces, you can replace the UI completely with something else - a desktop program, or another UI for mobile compared to desktop browsers.

The tricky bits you'll find when doing this is that a little bit of code that theoretically should be in the server would be better placed on the client - validation for example, its faster and more responsive for the user to put validation code on a form on the client than it is to hit the server to check, say, a text field only contains alphanumeric characters. The same often applies to data and business layers. You just have to make informed and practical decisions about when to violate the distinction between the layers.

Title: Pros and cons of an HTML/JavaScript only web app

Body:
I come from an ASP.NET forms background and have found server side coding very powerful in the past. More recently, however, I have been wanting to phase out the server side code of the front-end and replace it with pure HTML/JavaScript, which accesses the data through JSON webservices. I have no real experience in this, and so I would like to hear whether this is a tried and tested model. Also, what are the pitfalls surrounding it?

I find ASP.NET user controls very useful, so I would like to keep the theory behind it by storing markup templates in separate HTML files on the server. These will be retrieved and used through jQuery AJAX and the jQuery HTML templates plugin respectively.

Any input will be extremely appreciated.

P.S. Sorry for the noob question, but is this type of Web architecture what is referred to as web-2.0 or am I completely off-track?


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答:
IMO, stock options in startups are a bit of a scam.  It typically goes like this:

1)  A team of bright energetic young developers is recruited with promises of getting rich through stock options.

2)  The startup runs through its initial capital and second round of VC funding is injected.  The options are diluted to 1/2, 1/4 of there initial paper value.

3)  This is repeated once, twice, ...

Eventually the startup folds and the developers' options are totally worthless.  Alternatively, they are so diluted that the developers' return is tiny.

I think that you should be paying your developers a decent salary in real money.  Whether this motivates them depends on their personalities.  But at least they will be getting a fair return for their labor ... not some flim-flam.


问:
Is there a chart for helping me decide between open-source licenses?
The Open Source Initiative lists 9 different licenses in their list of "License that are popular and widely used or with strong communities".

I want to license my project as open-source. Unfortunately, I do not speak legalese. Is there some chart I could consult that will help me make the right choice, or at least point me in the right direction? For example a table summarizing the differences between the licenses, or perhaps a flow-graph using my requirements to guide me into the correct license for me?

I also intend to meet a lawyer, but any information to start with will help.

答:
A great resource for understanding open source licenses is the very comprehensive, interactive license differentiator, from Oxford Universities OSS Watch.

This asks questions which guide you towards a suitable license for your software.

There are pro's and cons to each, so read up on what restrictions they place on the code and decide who you want to be able to use it. Warning, whichever you choose someone will complain - this is holy war territory, and beyond the scope of this question.

ContentLicense: CC BY-SA 4.0