答:
I think that one of the main benefits of Agile is the ability to get more detailed requirements for each feature overall. When the client gives all of their requirements upfront, each feature tends to be a vague idea, with a bit of functionality defined. Agile forces the client to revisit each feature and focus on exactly what they want and how the feature will fit into the bigger picture. To get this same amount of detail (enough detail to implement the features) into the spec, waterfall really requires you to do one of two things:

Guess. Implement until you run into something that is vague, then make a judgement on how you feel the feature would best be implemented. This is obviously not ideal, since it leads to the "Wait, that's not what I asked for!" scenario.

Put far more emphasis on design upfront. Essentially, when the client throws their half-baked spec at you on day one, plan to go through every minute detail before implementing anything. Ask the client to clarify everything ad nauseum to the point where you know every implementation detail for the entire project. While not perfect, this is better than option 1. You still might run into details that you had not anticipated, and it might even send the client running for the hills, but if they really do not want to be in communication during development and you are not psychic, this is a necessity. This is basically waterfall, and it comes with all of the associated downsides, including being extremely difficult to execute properly.

Take the half-baked spec, but ask for clarification as you go anyway. Work until you reach a vague part of the spec, then ask the client to clarify. Of course, this is not what the client asked for, but if they do not want an application as murky as the spec and refuse to define the spec upfront, this is the one remaining option. It does not have all of the benefits of Agile (such as regular client approval to make sure everyone is on the same page), however, it does allow you to get the information you need to develop. Since option 1 will probably leave you with a sub par product, option 2 is wasteful and frustrating to the client (you will probably need to spend at least twice as much time on design and spec gathering overall if you do it entirely up front), this is really not such a bad option. The key here is to be diligent in modifying time lines and price with each change that comes up. If you do it right, you might find that the majority of the Agile practices are compatible with this arrangement, even if the client does not know it. IMHO, this is really in keeping with the spirit of Agile, in that you are supposed to adapt the methodologies to your particular arrangement.

If the client really cannot live with the consequences of any of these three options or full blown Agile, I have a hard time imagining how this client could really be worth your while.


问:
What is the difference between writing test cases for BDD and TDD?
I have been learning writing test cases for BDD (Behavior Driven Development) using specflow. If I write comprehensive tests with BDD, is it necessary to write TDD (Test Driven Development) test separately? Is it necessary to write test cases for both TDD and BDD separately, or are they effectively the same thing?

It seems to me that both are same, the only difference being that BDD test cases can be understood by non developers and testers.

答:
The difference between BDD and TDD is that BDD begins with a B and TDD begins with a T. But seriously, the gotcha with TDD is that too many developers focused on the "How" when writing their unit tests, so they ended up with very brittle tests that did nothing more than confirm that the system does what it does.

BDD provides a new vocabulary and thus focus for writing a unit test. Basically it is a feature driven approach to TDD.

ContentLicense: CC BY-SA 3.0


问:
God Namespace just as bad as God Object?
We have about 3/4 different projects, each sharing a certain level of data.  Some data is not shared, but all the data access has ended up in a single namespace that is included in every project.

Utility methods and other "shared functionality" is continually added to this root namespace, and is ultimately fairly organized, but it all ends up in a single dll to be included in projects.

To me it seems overly centralized but does it qualify to labeled a God Namespace? (does that term even make sense?)

答:
I would say it's definitely not as bad as a God Object or Super Object.  Those are a whole different animal that is hard to write, maintain, debug, and test and they should be avoided at all costs.

As far as the namespace goes, that's definitely a legitimate concern, and if you are finally getting to the point where your namespace is becoming overcrowded I don't see a problem with splitting it up across a boundary that makes sense.

So, to answer the question in your title: no

Should you add additional namespaces?  only if it makes writing and maintaining code easier.

This answer is somewhat generic, but I'm not sure I can be much more help without more details.


答: I don't think that there is single yes or no question, but anything that ends up being "God" is not a good sign. You don't provide any details about the language that you are using, but IMHO putting everything in a single namespace is as bad as using namespace std is in C++. In general you should try to avoid namespace pollution. You can find some more arguments about the pros/cons of single/multiple namespaces on c2.com

Title: God Namespace just as bad as God Object?

Body:
We have about 3/4 different projects, each sharing a certain level of data.  Some data is not shared, but all the data access has ended up in a single namespace that is included in every project.

Utility methods and other "shared functionality" is continually added to this root namespace, and is ultimately fairly organized, but it all ends up in a single dll to be included in projects.

To me it seems overly centralized but does it qualify to labeled a God Namespace? (does that term even make sense?)


问:
How viable is it to switch stacks for setting up a startup
I am currently employed with a company for 2.5 years and I have been working with the .net stack for the entire duration mainly on the MVC framework. I believe I have some cool ideas for a startup but I am not sure if I should continue in this stack or switch to some other stack like Ruby on Rails.

The reason why I am consider this switch is due to the Infrastructure required to host a dot net application and scaling it successfully as compared to setting up a live running site on some other stack.

I have a really good domain expertise in dot net at this moment but I believe it should be not so hard to move onto a new stack and adopt the best practices that I have picked up in the past two years.

Let me know if I am missing something in the puzzle and if I am taking the right decision? Are there any complications of learning a new stack and building on it?

Please guide me in the right direction.

答:
First, let's debunk the myth. It costs absolutely nothing to get started on the Microsoft platform. Through the Bizspark program, you can get an MSDN Ultimate Subscription (including monthly Windows Azure usage credit) for up to 5 developers free for three years. Once you have a prototype running in Azure, you can certify it (for free) to qualify for the Cloud Essentials program. This gives you Office 365 (with desktop Office Licenses) for up to 250 users for free, and Dynamics CRM for free.

Deploying to Windows Azure is as easy as deploying to a local IIS installation.

On to the task of migrating platforms. I ALWAYS cringe whenever I hear someone saying, "I can just apply what I learned on language X to language Y." Even taking the time to learn a new Syntax out of the picture, it takes time to get comfortable with a platform and productive let alone efficient. Think of how much you've learned in .NET over the past 2 and a half years. You can assume that it will take you at least 75% of that time to become as efficient in a new platform. Instead you could spend the next few years diving deeper into .NET.

I'm not saying that it's not a good thing to learn and gain exposure to new languages/platforms (I'm personally learning Erlang because I feel that it can provide a lot of benefits as a supplement for .NET). But there are already too many variables involved in starting up a company. Don't voluntarily add one to it.


答:
You are worrying about the wrong thing.

If you want to get something off the ground, get it off the ground the quickest way possible. Read up on a Minimum Viable Product.

Do you think Facebook was started with something like this as a major concern? Here's a hint, it wasn't. They used what they knew and built it as quickly as possible.

Be more concerned about getting something that people will use up and running and when you need to worry about something like this it will become apparent and clear.

Facebook has been re-written several times over in its short history in internet time. They didn't lock themselves into a "stack", re-writing isn't a waste of resources things change, being able to adapt it more valuable , concerning yourself about scaling for something that doesn't exist, that is the wrong mindset.

Title: How viable is it to switch stacks for setting up a startup

Body:
I am currently employed with a company for 2.5 years and I have been working with the .net stack for the entire duration mainly on the MVC framework. I believe I have some cool ideas for a startup but I am not sure if I should continue in this stack or switch to some other stack like Ruby on Rails.

The reason why I am consider this switch is due to the Infrastructure required to host a dot net application and scaling it successfully as compared to setting up a live running site on some other stack.

I have a really good domain expertise in dot net at this moment but I believe it should be not so hard to move onto a new stack and adopt the best practices that I have picked up in the past two years.

Let me know if I am missing something in the puzzle and if I am taking the right decision? Are there any complications of learning a new stack and building on it?

Please guide me in the right direction.


问:
The Joel Test's equivalent for measuring a programmer
I understand that to measure a project or code, we can use The Joel Test, but is there any simple standard test (like The Joel Test) that is able to measure and filter how good a programmer is?

My plan is to have this test as a quick filter first before going to a more detail test.

答:
I would turn the Joel test around:

Have they used source control?

Do they know how to automate a one step build?

...

The only one that doesn't seem particularly applicable is the have testers question.  The others that seem kind of off turn in to a this is how we handle it how have you handled it in the past sort of questions(This is how we handle keeping our schedule up to date how have you handled scheduling in the past?).

edit:

Basically you don't get the stuff in the Joel test for free, you have to hire people who can make it happen. You want to establish their ability to make that happen.


问:
Query language for JSON
I have a server which is returning very big JSON message and my client application is only dependent on part of this response. Client application needs to check if "xyz" property exist in JSON message and depending on the result run a specific usecase.

For this requirement converting the whole JSON message to object sounds bit expensive to me and hence this question.

Is there a standard JSON query language like one we have for XML? If yes what are best know implementation of this query language in java.

FYI : Changing or adding new service on server side is not an option.

答: "Measure, don't guess". Yes object serialisation and deserialisation my be expensive in theory, but what are the performance goals of your application? If the object (de)serialisation doesn't push your performance to unacceptable levels, then don't worry about it :-). The key of course is to know what the performance boundaries should be (e.g. Response time to user in 2 seconds) and to measure each part of the request/response cycle.</p>

Title: Query language for JSON


问:
Sanity of design for my in-memory object representations of database rows
I've been trying to revise the structural design of the  C#.NET-based system I'm currently working on. The new design involves a rather light-weight object-relational mapping framework (we're trying to stay away from ADO or linq2sql). Sorry, this came rather lengthy, but I cannot describe it shorter - it's a bit complex.

The system has two primary functions:

Retrieve rows from an SQL relational disk-based database, then serve them up using [DataContract]-marked objects via ASP to a web-based client, as well as receive UPDATEs to those and reroute them to the database.

Read off and serve the same kinds of objects to server-side / distributed modules which work with these, generate some result, and push it back to the database.

The results (some might ask: "why're you storing generated data?") of module computation do have to be stored in the database due to both size and length of computation required to obtain them, only to be retrieved in parts by the web-client through the (1) function.

Currently, all row-representing objects are defined as separate C# classes with a common trend but little to no inheritance, and no common base class. I want to completely break this pattern, and instigate more extensive inheritance based on a tree of abstract classes and possibly interfaces.

I've whipped up a "due-for-test" implementation in the past few days, but I'm concerned about the sanity of this design. Obviously, there is the object-relational impedance mismatch, which I deal with by only initializing the database-column-backed fields unless the other encapsulated objects are provided to the constructor. I'm not so concerned about that, and it's an issue for the old system design as well.

Here's what I have so far:

A DatabaseColumnAttribute class, which targets fields, and defines

name of the column where the data for the field resides.

database type (enum-backed locally) for this column. There's a fixed set of
database types this system is designed to support, so be it.

whether or not the column is nullable.

read phrase(i.e. how do we represent this column in a SELECT query within an sql statement): this is generated automatically based on column type. There's a fixed number of types the data can be accessed in, so if there's a conversion involved when reading data from a column this will include it. Otherwise, just the column name.

write wrapper (i.e. database function that converts the data sent into the column from C# to the appropriate representation) - also generated based on column type.

All this is used within a DatabaseFieldColumnWrapper object, which contains all the methods required to transfer the data from the column to the field or vice-verse.

The DatabaseFieldColumnWrapper is constructed for each location in the code where a DatabaseColumnAttribute is used, meaning it's not quite "static", but rather class-based, since it modifies fields of derived classes. The fields can back properties, there's a BackedByFieldAttribute class as well, I'll skip it for brevity.

All of these are used within an abstract DataElement class, root of hierarchy.
It defines the following abstract members:  function that provides the backing-table's name for this class of objects, a read-only public Id property, a private function to set the Id (which corresponds to the primary key of the row in the table).

It also provides a protected static helper function to retrieve the DatabaseFieldColumnWrapper objects for specific fields based on Linq Expressions (to avoid "magic strings"). This can be used in derived types to easily synch the database representation for specific fields/columns.

It provides a Delete() method, which is (not a destructor, but a function) responsible for only deleting the database representation. The whole system is designed to allow asynchrony and multiple memory representations unless otherwise specified.

Here is the "less sane" part:

There is a DataElementAttribute class, which is designed to modify non-abstract derived types. It is not fully constructed completely right away where it's defined, instead filled-in in a thread-safe manner upon the construction of the first object of a derived type. It not inherited, and contains only data specific to the derived class required to speed up construction (i.e. construct all the necessary DatabaseFieldColumnWrapper objects before-hand and associate them with the fields).

This basically violates the C# OO model, since it's "static only with respect to current class in the hierarchy", not static to the whole chain. Basically, it makes the DataElmentAttribute object associate with a particular Type object. It's like a convenience structure, which is generated according to the rules specified in the base class only, but initializes its members based on the fields marked as columns for each derived type. Each instance of that particular type has a reference to it.

I don't know how to circumvent this issue, it seems to be best in terms of "code reuse", but it also seems like I'm violating a lot of things I shouldn't be when I do it. Any ideas, suggestions?

In a more "question"-form: do you know of any better way to associate things with Types (without inheritance) and have these accessible from each instance of that Type, which conforms to the OO model?

P.S. I'm not looking for a "you shouldn't" kind of answer, since that wouldn't allow us to reuse more code.

答:
If you're looking for dynamic runtime polymorphism, have you checked out the dynamic keyword in C# 4.0? If it meets your need, I would imagine it's a lot simpler than what you're trying to do.

See Rob Conery's work with Massive, where he demonstrates how to build a dynamic ORM in C# 4.0 using 400 lines of code.

Creating proxy classes at runtime is not exactly an unprecedented technique, see Castle Dynamic Proxy and FasterFlect. If your only worry is that you're breaking some architectural austronaut's rule book, I'm not sure it's worth worrying about.


问:
How should I deal with external data sinks?
I recently took on a contract job that will largely involve generating data feeds from my client's data and sending it to external partners, via feeds and API invocations.

I've always found this particular kind of coding to be frustrating, for a number of reasons:

You have to rely on specs, which often diverge from the actual implementation or simply don't go into sufficient detail

You have little to no ability to see into the external system, to ensure that your data has been accepted and interpreted properly

If there's any kind of problem with data you've generated, it's not always straightforward to back out the changes and try again

External testing and staging environments frequently diverge from production logic and the production database

What are some best practices for doing this kind of work?

Creating mocks and stubs won't necessarily resolve my problems, as my real concern is: do my feeds have the correct effect on another system, which is basically a black box? Mocks simply duplicate my assumptions.

答:
I've done a bit of work in recent years with EDI, and it has all the problems you've mentioned.  The biggest problem is that partners don't follow their own specs and when you point it out, they say, "this is a deviation" but they never document it.

Here's how I deal with it and manage to sleep at night:

Create a framework for building and maintaining lots of unit tests.  At first you'll just test the spec plus your assumptions, but eventually (every time you find a deviation) you have to write another batch of tests to check those new facts.

Your system must log everything.  It must log everything that happened, when it happened, who did it, what it received, what it wrote, where, etc.  You will need this when you go toe-to-toe with your counterpart on the other end, not just to troubleshoot, but as evidence to prove that your system is doing everything it's supposed to do.  Confirmations are particularly important to log.  These logs are invaluable when you go to write new tests.

Build in the ability to retry with modifications.  When something happens, you'll want to be able to tweak the data and submit it again.

Avoid intermediaries (aka "3rd parties").  Unfortunately in our case we actually have 3 different systems our data travels through between us and the ultimate destination (two of which are called "value added resellers", or VARs, which is complete BS because from my perspective they add no value at all).  When something goes wrong, we get contacted by the end-user at the other end, and then we have to go up one level on our end, ask them to check, and then they go up a level and talk to their VAR, who has to talk to the other VAR, etc.  It's frustrating.  If you have the ability to communicate with the other system directly, do it.


问:
How to match responses from a server with their corresponding requests?
There is a server that responds to requests on a socket. The client has functions to emit requests and functions to handle responses from the server.

The problem is that the request sending function and the response handling function are two unrelated functions. Given a server response X, how can I know whether it's a response to request X or some other request Y?

I would like to make a construct that would ensure that response X is definitely the answer to request X and also to make a function requestX() that returns response X and not some other response Y.

This question is mostly about the general programming approach and not about any specific language construct. Preferably, though, the answer would involve Ruby, TCP sockets, and PHP.

My code so far:

```<code>require 'socket'

class TheConnection
    def initialize(config)
        @config = config
    end
    def send(s)
        toConsole("--> #{s}")
        @conn.send "#{s}\n", 0
    end
    def connect()
        # Connect to the server
        begin
            @conn = TCPSocket.open(@config['server'], @config['port'])
        rescue Interrupt
        rescue Exception => detail
            toConsole('Exception: ' + detail.message())
            print detail.backtrace.join('\n')
            retry
        end
    end
    def getSpecificAnswer(input)
        send "GET #{input}"
    end
    def handle_server_input(s)
        case s.strip
            when /^Hello. (.*)$/i
                toConsole "[ Server says hello ]"
                send "Hello to you too! #{$1}"
            else
                toConsole(s)
        end
    end
    def main_loop()
        while true
            ready = select([@conn, $stdin], nil, nil, nil)
            next if !ready
            for s in ready[0]
                if s == $stdin then
                    return if $stdin.eof
                    s = $stdin.gets
                    send s
                elsif s == @conn then
                    return if @conn.eof
                    s = @conn.gets
                    handle_server_input(s)
                end
            end
        end
    end
    def toConsole(msg)
        t = Time.new
        puts t.strftime("[%H:%M:%S]") + ' ' + msg
    end
end
@config = Hash[
    'server'=>'test.server.com',
    'port'=>'2020'
]
$conn = TheConnection.new(@config)
$conn.connect()
$conn.getSpecificAnswer('itemsX')

begin
    $conn.main_loop()
rescue Interrupt
rescue Exception => detail
    $conn.toConsole('Exception: ' + detail.message())
    print detail.backtrace.join('\n')
    retry
end
</code>```

答: You mentioned that the question is more about the programming method than the language. What I'm concerned about this seems to be a reinvention of stuff that already exists out there? I mean what about building servers that support REST or SOAP apis? What about querying servers using AJAX? There's a bunch of stuff that's out there and you'll be conforming to establish industry protocols and that means you can rapidly design and test your servers using HTML and JavaScript.</p>


问:
Can Agile be accomplished without client involvement?
I couldn't write a book on Agile.  I have worked in several shops that call their process Agile.  One of the main points of Agile development is regular client involvement.  After a sprint, the work can be demo'd to the client to obtain their feedback.  Rinse and repeat.

The problem I come across is that many clients do not want to be that involved.  They would much prefer a waterfall approach.  Gather the requirements up front, then come back when you are done.  In my experience, waterfall does not work.  Clients do not know what they want until they see it.  The waterfall dilemma is further propagated by a large community of developers that want to have all the requirements up front.  This way they know what they are building, they can architect accordingly, and the client is to blame because they "signed off" on said requirements.

Am I incorrect?  Can Agile work without client involvement?  If so, how and how do you overcome the issues I discussed?

答:
I think it's difficult but still possible. I think Robert's proxy idea works but it's necessary for the proxy to spend as much time as possible with the 'real' client so they can see things from their point of view. That way the proxy can ascertain what features are really important and get a feel for the user experience the client expects/desires.

But at some point you'll need to show the software to the 'real' client...


答:
It is possible to avoid real customers, in fact sometimes it is needed for the regulatory.
Usually the customers of medical software are not involved.
In those cases other entities may substitute the customer role, for example the marketing team can be considered the customers. </p>

Title: Can Agile be accomplished without client involvement?

Body:
I couldn't write a book on Agile.  I have worked in several shops that call their process Agile.  One of the main points of Agile development is regular client involvement.  After a sprint, the work can be demo'd to the client to obtain their feedback.  Rinse and repeat.

The problem I come across is that many clients do not want to be that involved.  They would much prefer a waterfall approach.  Gather the requirements up front, then come back when you are done.  In my experience, waterfall does not work.  Clients do not know what they want until they see it.  The waterfall dilemma is further propagated by a large community of developers that want to have all the requirements up front.  This way they know what they are building, they can architect accordingly, and the client is to blame because they "signed off" on said requirements.

Am I incorrect?  Can Agile work without client involvement?  If so, how and how do you overcome the issues I discussed?


问:
Lines of Code vs. Optimal Language
I was wondering whether it is possible to give any advice as the the maximum number of lines of code at which one should consider switching from say MATLAB to a more low level language?

Is it even the case that at a certain point it makes more sense to manage a certain degree of complexity of a given program in a proper object oriented language rather then MATLAB?

I should say I am a newbie in both MATLAB and Java, so I have no hidden agenda in this question even though I m aware of the heated discussions that people sometimes engage in over whether MATLAB is a proper programming language. I'm not experienced enough to even think about participating in such an exchange and I'm just looking for advice whether there is a cut off point where one really needs to go to a different language?

Also I should add I understand the code may become longer when you move to lower level, however I was under the impression that object oriented programming makes it easier to manage the complexity of bigger programs. (Maybe lines of code was a bad choice as a proxy for complexity?) Is the choice of low vs. high level just one of performance? (which in the end you have to pay for with a bigger programming task at your hands for the low level language?)

答: There's really no absolute threshold in terms of lines of code. Matlab provides functions that would required a LOT of Java code to mimic, specially for matrix manipulation. However, if you are not taking advantage of them, complexity may be higher than Java and it's going to be slower.</p>

OwnerDisplayName: PeeJay

Title: Lines of Code vs. Optimal Language

OwnerDisplayName: Diego


答: The only reason to ever switch a language after even one line of code is that the language being used can't do what you need it to do. With the single exception of no one knows how to use the language something is written in.</p>

Title: Lines of Code vs. Optimal Language

Body:
I was wondering whether it is possible to give any advice as the the maximum number of lines of code at which one should consider switching from say MATLAB to a more low level language?

Is it even the case that at a certain point it makes more sense to manage a certain degree of complexity of a given program in a proper object oriented language rather then MATLAB?

I should say I am a newbie in both MATLAB and Java, so I have no hidden agenda in this question even though I m aware of the heated discussions that people sometimes engage in over whether MATLAB is a proper programming language. I'm not experienced enough to even think about participating in such an exchange and I'm just looking for advice whether there is a cut off point where one really needs to go to a different language?

Also I should add I understand the code may become longer when you move to lower level, however I was under the impression that object oriented programming makes it easier to manage the complexity of bigger programs. (Maybe lines of code was a bad choice as a proxy for complexity?) Is the choice of low vs. high level just one of performance? (which in the end you have to pay for with a bigger programming task at your hands for the low level language?)


答:
The short answer to your question is 'no'. Here are comments on some parts of your question. To be accurate most of the answers are based on my personal experience and observation.

In my experience, waterfall does not work.

Waterfall is a sound methodology for delivering systems of varying complexity. It is unfortunate that it is not well presented or understood. One reason for that is that it does not make enough money competing with the methodology of the day that keep on popping up. You may surprised to know that many of the banking, insurance and manufacturing systems were built only using Waterfall approach and many of those are still in production today. It is sad that the software industry is based on hype more than science.

Clients do not know what they want until they see it.

This is a myth. A big one too. This may be the case in web page design/layout but for business data processing, most users want something that works. Some of those users still use AS/400 screens and 3270 CICS monitors with RGB and they can get their business done with those tools. Also, those same users accepts SAP and ORACLE ERP systems without having any say in the design of the interface (and some times in the functionality). Most business users will even adapt their work habits and flows if the system is producing the correct function. The stress here is on function not looks. Business people understand how they do their work very well 90% of the time.

The waterfall dilemma is further propagated by a large community of developers that want to have all the requirements up front. This way they know what they are building, they can architect accordingly, and the client is to blame because they "signed off" on said requirements.

You can't blame developers for wanting to know what they are building because those developers want to go home cook dinner and press their shirts for another drill after they spend 3 hours or so learning the next tech. that will replace their current skill set! The blame game makes no one a winner. Think in terms of each party's roles and responsibilities and the picture will be very clear.

In conclusion, Project managers,Programmers, and Web Designers are no replacement for Business Analysts whom should know how to collect requirements from end users regardless of the methodology.


答:
I do not think it has to do with the number of lines of codes because in case of Java and most probably MATLAB, a number of lines can be automatically generated.

I think you should take in consideration other criteria like:

How much time is going to take in the given language ?

Should I have to write all the algorithm or some parts of the algorithm is already implemented by the language ?

Am I going to plot my results in a graph ?

Do I want to share the algorithm dynamically with others ?

The list is probably not complete

Title: Lines of Code vs. Optimal Language


问:
Best approach to selecting programming languages and 3D graphics API for simulating physics experiments
I am starting a research project and need to nail down a programming language and 3D graphics API where I will be creating an environment in the field of molecular cell biology where I will be simulating a large range of experiments in silico. This will be an ongoing project which will keep expanding and growing in size. The experiments will be done in discrete time and will encompass a complex physics engine. Pretty graphics are not of importance nor is is audio. I run Ubuntu and this is the environment I will be developing in.

The pairs I have investigated thus far are:

java : flexible,scalable,lib/dependency organization (maven),oo

jogl: full control of graphics

jMonkeyEngine: full game library, includes jBullet, maybe a bit overkill for what I need.

c++ : High speed, low level, oo

opengl:full control of graphics

maya:built in physics engine, infrastructure already in place, proprietary, not free

matlab : Heavily math based, but difficult to maintain and scale

simulink : proprietary, not free

I am least familiar with Maya but it was suggested to me by a friend as a good approach. When would Maya be a good solution and would it be a good selection for this type of case? Just as thinking jMonkey would be overkill this is kinda my feeling on Maya.

Are there any other pairings I should investigate?

Also has anyone had any experience modifying an existing physics library and the flexibility or complexity of doing so (ie Bullet, JBullet, jinngine)? Unsure at this point if I should start from scratch or try and modify/expand an existing one.

Any thoughts, feedback, input or any other suggestions would be greatly appreciated.

Thanks

答:
First, what you are doing sounds as though it matches up VERY closely with Chandrajit Bajaj's (bajaj@cs.utexas.edu) research work in computational biology and molecular visualization.  Bounce an email off of him and see what suggestions he has.  (I suspect he will say C++ and OpenGL.)  (Full Disclosure: During a period of refresher work while between jobs, I took the undergrad computer graphics class from him.  I learned quite a bit and had a great time.)

Also, Jim Browne (browne@cs.utexas.edu) did his very early work in computational physics, and might have some valuable insights.  I think Jim is retired now, and he may not answer the email.  (Full Disclosure: I took a graduate operating systems class from him, and learned a LOT.  He is, PERSONALLY, the reason UT Austin first built their Computer Science department.  It was establish the department or lose him to Queen's University of Belfast.)

Second, whenever some describes something as "expensive", you should ALWAYS ask "Compared to what?"  MATLAB is dirt-cheap compared to what it would cost you to develop and debug all their code from scratch.

Third, if interactivity is not a big deal, it is not that hard to rig a C++ program to write a file that can then be fed to MATLAB for intense number-crunching.  During the aforementioned refresher work, I repeated the undergrad introductory numerical methods class.  We crunched numbers in C++ and plotted results with MATLAB.  (I had a LOT of fun in that class!)  That was with Todd Arbogast (arbogast@ma.utexas.edu, I think).  He is SHARP, and he might have some suggestions as well.


答: Eh, I have qualm with the wording at the start. It's not "have you used X" or "Do you know of Y", it's a matter of actually using and doing. Any programmer that hasn't touched or heard of the items on the Joel test is simply disconnected and needs to get a clue. But you're right, code-shops fail the Joel test because people in the shops let it fail. The only defense I can see runs along the lines of "I tried, but did not have the authority. And now I'm applying here". </p>

Title: The Joel Test's equivalent for measuring a programmer

Body:
I understand that to measure a project or code, we can use The Joel Test, but is there any simple standard test (like The Joel Test) that is able to measure and filter how good a programmer is?

My plan is to have this test as a quick filter first before going to a more detail test.


答:
Is it even the case that at a certain point it makes more sense to manage a certain degree of complexity of a given program in a proper object oriented language rather then Matlab ?

No.

Avoid thinking of languages as "proper" or "improper".   Languages are just tools to solve problems.  For a given problem, some will be more effective than others.

Is the choice of low vs. high level just one of performance ?

Mostly yes.  Ceteris paribus, it is less expensive to formulate a solution in a higher-level language.  Performance and other considerations may make it less expensive to deploy a solution written in a lower-level language.

Title: Lines of Code vs. Optimal Language


答:
Why not use both?  With a Java-to-Matlab API you can use all the algorithms and visualizations of Matlab, but still design using features of an OOP language.

Although, it's always nice if you can avoid mixing languages, multiple languages can give you the best of both worlds.  On the web, multiple languages is almost a given.

Title: Lines of Code vs. Optimal Language


问:
Rigorous Definition of Syntactic Sugar?
It seems like in language holy wars, people constantly denigrate any feature they don't find particularly useful as being "just syntactic sugar".  The line between "real features" and "syntactic sugar" tends to get blurred in these debates.  What do you believe is a reasonable and unambiguous definition of syntactic sugar that avoids it being defined as any feature the speaker/writer doesn't find useful?</p>

答:
I think the term syntactic sugar indicates an alternate syntax to express the same underlying semantics.

Take for example a programming language A that has an operation sum that can add up a list of integers of arbitrary length. In this language we can write the expressions

```<code>sum []
sum [3, 4, 5, 1]
sum [2, 7]
</code>```

whose results are 0, 13, and 9, respectively.

Now, suppose that we realize that 90% of the times we use sum with two arguments, and therefore we introduce, for convenience, the new notation

```<code>2 + 7
</code>```

which is just syntactic sugar for sum [2, 7].

Now take a second language B that has no addition operation whatsoever. We may have operators like <, =, allowing us to compare numbers, but no way to add numbers. In release 2 of language B, we introduce a new addition operation with syntax

```<code>2 + 7
</code>```

which adds numbers as usual.

In the context of language A, the + notation is syntactic sugar (it is an alternate, simplified and ad-hoc notation that can be used instead of the sum [...] notation). Similarly, as has been pointed out in Hoa Long Tam's answer, in C the notation p->field is syntactic sugar for (*p).field.

In the context of language B, the + notation is not syntactic sugar (it is the only valid syntax used for the sum operation). Similarly, if C could only access struct members through pointers and if did not have the notation (*p).field, then the notation p->field would not be syntactic sugar.

In my opinion, there are some misunderstandings about syntactic sugar that can be traced back to a confusion regarding programming language semantics. The reasoning goes like this:

The semantics of a program is what a program computes.

The expressive power of a programming language is represented by the computations that can be described in that language.

Two programming languages that can describe all computable functions (as defined using Turing machines) have the same expressive power...

... and therefore only differ in syntax.

Corollary: any extension of a Turing-complete language is only syntax (syntactic sugar) because you do not change the expressive power of the language.

The above line of reasoning leads to generic assertions like "syntactic sugar cannot be defined properly", it is a "matter of taste", or "every programming language feature is, after all, just syntactic sugar".

I think the main problem in the above argument is that semantics is not only about what can be computed by a program, but also about how it is computed, i.e. what primitive constructs are used and how they are combined.

So for example, objects are not syntactic sugar for the underlying bit configurations and bit transformations, they are a construct that allows to model data and operations and to describe computations. Computing with objects, methods, method calls, is not the same as computing with bytes, processor registers, memory addresses (even if the two computations have the same result, and even if the second computation is used to implement the first).

I made this description a bit long but I think it is an important aspect that I haven't seen addressed in other answers.

Bottom line: syntactic sugar is an alternate (possibly more convenient) syntax for a construct that is already in a language and has already a well-defined syntax and semantics. The new syntax (syntactic sugar) differs from the existing one but has the same semantics. If you introduce a new construct in a language and new syntax for it, then you do not have syntactic sugar.

ContentLicense: CC BY-SA 2.5

Title: Rigorous Definition of Syntactic Sugar?

Body:
I think the term syntactic sugar indicates an alternate syntax to express the same underlying semantics.

Take for example a programming language A that has an operation sum that can add up a list of integers of arbitrary length. In this language we can write the expressions

sum []
sum [3, 4, 5, 1]
sum [2, 7]

whose results are 0, 13, and 9, respectively.

Now, suppose that we realize that 90% of the times we use sum with two arguments, and therefore we introduce, for convenience, the new notation

2 + 7

which is just syntactic sugar for sum [2, 7].

Now take a second language B that has no addition operation whatsoever. We may have operators like <, =, allowing us to compare numbers, but no way to add numbers. In release 2 of language B, we introduce a new addition operation with syntax

2 + 7

which adds numbers as usual.

In the context of language A, the + notation is syntactic sugar (it is an alternate, simplified and ad-hoc notation that can be used instead of the sum [...] notation). Similarly, as has been pointed out in Hoa Long Tam's answer, in C the notation p->field is syntactic sugar for (*p).field.

In the context of language B, the + notation is not syntactic sugar (it is the only valid syntax used for the sum operation). Similarly, if C could only access struct members through pointers and if did not have the notation (*p).field, then the notation p->field would not be syntactic sugar.

In my opinion, there are some misunderstandings about syntactic sugar that can be traced back to a confusion regarding programming language semantics. The reasoning goes like this:

The semantics of a program is what a program computes.

The expressive power of a programming language is represented by the computations that can be described in that language.

Two programming languages that can describe all computable functions (as defined using Turing machines) have the same expressive power...

... and therefore only differ in syntax.

Corollary: any extension of a Turing-complete language is only syntax (syntactic sugar) because you do not change the expressive power of the language.

The above line of reasoning leads to generic assertions like "syntactic sugar cannot be defined properly", it is a "matter of taste", or "every programming language feature is, after all, just syntactic sugar".

I think the main problem in the above argument is that semantics is not only about what can be computed by a program, but also about how it is computed, i.e. what primitive constructs are used and how they are combined.

So for example, objects are not syntactic sugar for the underlying bit configurations and bit transformations, they are a construct that allows to model data and operations and to describe computations. Computing with objects, methods, method calls, is not the same as computing with bytes, processor registers, memory addresses (even if the two computations have the same result, and even if the second computation is used to implement the first).

I made this description a bit long but I think it is an important aspect that I haven't seen addressed in other answers.

Bottom line: syntactic sugar is an alternate (possibly more convenient) syntax for a construct that is already in a language and has already a well-defined syntax and semantics. The new syntax (syntactic sugar) differs from the existing one but has the same semantics. If you introduce a new construct in a language and new syntax for it, then you do not have syntactic sugar.


问:
Using a try-finally (without catch) vs enum-state validation
I have been reading the advice on this question about how an exception should be dealt with as close to where it is raised as possible.

My dilemma on the best practice is whether one should use a try/catch/finally to return an enum (or an int that represents a value, 0 for error, 1 for ok, 2 for warning etc, depending on the case) so that an answer is always in order, or should one let the exception go through so that the calling part would deal with it?

From what I can gather, this might be different depending on the case, so the original advice seems odd.

For example, on a web service, you would always want to return a state of course, so any exception has to be dealt with on the spot, but lets say inside a function that posts/gets some data via http, you would want the exception (for example in case of 404) to just pass through to the one that fired it. If you don't, you would have to create some way to inform the calling part of the quality of the outcome (error:404), as well as the outcome itself.

Though it IS possible to try-catch the 404 exception inside the helper function that gets/posts the data, should you? Is it only I that use a smallint to denote states in the program (and document them appropriately of course), and then use this info for sanity validation purposes (everything ok/error handling) outside?

Update: I was expecting a fatal/non-fatal exception for the main  classification, but I didn't want to include this so as not to prejudice the answers. Let me clarify what the question is about: Handling the exceptions thrown, not throwing exceptions. What the desired effect is: Detect an error, and try to recover from it. If recovery isn't possible, provide the most meaningful feedback.

Again, with the http get/post example, the question is, should you provide a new object that describes what happened to the original caller? If this helper was in a library you are using would you expect it to provide you with a status code for the operation, or would you include it in a try-catch block? If you are designing it, would you provide a status code or throw an exception and let the upper level translate it to a status code/message instead?

Synopsis: How do you chose if a piece of code instead of producing an exception, returns a status code along with any results it may yield?

答:
Some good advice I once read was, throw exceptions when you cannot progress given the state of the data you are dealing with, however if you have a method which may throw an exception, also provide where possible a method to assert whether the data is actually valid before the method is called.

For example, System.IO.File.OpenRead() will throw a FileNotFoundException if the file supplied does not exist, however it also provides a .Exists() method which returns a boolean value indicating whether the file is present which you should call before calling OpenRead() to avoid any unexpected exceptions.

To answer the "when should I deal with an exception" part of the question, I would say wherever you can actually do something about it. If your method cannot deal with an exception thrown by a method it calls, don't catch it. Let it raise higher up the call chain to something that can deal with it. In some cases, this may just be a logger listening to Application.UnhandledException.


答:
use a try/catch/finally to return an enum (or an int that represents a value, 0 for error, 1 for ok, 2 for warning etc, depending on the case) so that an answer is always in order,

That's a terrible design.  Don't "mask" an exception by translating to a numeric code.  Leave it as a proper, unambiguous exception.

or should one let the exception go through so that the calling part would deal with it?

That's what exceptions are for.

dealt with as close to where it is raised as possible

Is not a universal truth at all.  It's a good idea some times.  Other times it's not as helpful.

Title: Using a try-finally (without catch) vs enum-state validation

Body:
I have been reading the advice on this question about how an exception should be dealt with as close to where it is raised as possible.

My dilemma on the best practice is whether one should use a try/catch/finally to return an enum (or an int that represents a value, 0 for error, 1 for ok, 2 for warning etc, depending on the case) so that an answer is always in order, or should one let the exception go through so that the calling part would deal with it?

From what I can gather, this might be different depending on the case, so the original advice seems odd.

For example, on a web service, you would always want to return a state of course, so any exception has to be dealt with on the spot, but lets say inside a function that posts/gets some data via http, you would want the exception (for example in case of 404) to just pass through to the one that fired it. If you don't, you would have to create some way to inform the calling part of the quality of the outcome (error:404), as well as the outcome itself.

Though it IS possible to try-catch the 404 exception inside the helper function that gets/posts the data, should you? Is it only I that use a smallint to denote states in the program (and document them appropriately of course), and then use this info for sanity validation purposes (everything ok/error handling) outside?

Update: I was expecting a fatal/non-fatal exception for the main  classification, but I didn't want to include this so as not to prejudice the answers. Let me clarify what the question is about: Handling the exceptions thrown, not throwing exceptions. What the desired effect is: Detect an error, and try to recover from it. If recovery isn't possible, provide the most meaningful feedback.

Again, with the http get/post example, the question is, should you provide a new object that describes what happened to the original caller? If this helper was in a library you are using would you expect it to provide you with a status code for the operation, or would you include it in a try-catch block? If you are designing it, would you provide a status code or throw an exception and let the upper level translate it to a status code/message instead?

Synopsis: How do you chose if a piece of code instead of producing an exception, returns a status code along with any results it may yield?


问:
What's a generation in Software Development?
I've heard about software and apps going into Generation 1.2 or 2.6, is there an actual methodology behind this? or it's more of a marketing thing?

Currently we are using Scrum as our methodology in agile software development and it's based on sprints, but I haven't been able to find any information detailing what's actually a generation in software development (neither on Agile based methodologies and non-agile).

http://en.wikipedia.org/wiki/Sprint_%28scrum%29#Sprint

答:
It's a marketing term, mostly. Consider 3G and 4G on your cell phone. Most phone companies were selling so-called 4G phones before such a thing even existed.

In other words, it's intended to confuse you into thinking you're buying something new and improved. Think: Superviederflagen XLS 4D.

See also Does 4G Exist?

tl;dr: Most serious software development organizations use versions.


问:
When does it become mandatory to sign up with the Bluetooth Special Interest Group (SIG)?
My company is looking to add Bluetooth functionality to our hardware, so that we can integrate connectivity to our products with various tablet devices.

To do this, we are looking to purchase an all-in-one chip that we can integrate into our boards.

Everyone within the development team is new to Bluetooth integration and as I am doing my research, I am finding a lot of references and material that points me back to Bluetooth.org and mention becoming a Special Interest Group (SIG) member.  This has raised various questions regarding the necessity for us as a company to join the SIG.  We would rather not have to go through that process because that would involve paying various fees and dragging corporate lawyers into the process.  We've already had to jump through a few legal hoops (ahem, MFi anyone?) and would prefer not to have to go through any of that again for the sake of development time.

If we want to integrate simple Bluetooth connectivity into our devices, do we have to go through the process of joining the Bluetooth SIG or are we covered and allowed to promote our devices as Bluetooth enabled since the all-in-one chips we will be integrating will becoming from a major manufacturer who has already become a SIG member and has had there chipset certified by the SIG?

答:
From the bluetooth.org "About -> FAQ"

https://www.bluetooth.org/ticketing/view_article.cfm?action=article_comment&aid=257

Essentially, it looks like because 'Bluetooth' is a registered trademark, they will get ya if advertise that feature as part of a 'complete' solution -- whether in a product or 'complete' design.

The vendor for your all-in-one chip might have some specific guidance that might ease or fast-track the process.

EDIT: For clarification..

Chip and component designers and manufacturers, despite their membership and specific design approval with and by Bluetooth SIG can not provide system and sub-system builders with downstream, automatic certification/approval.  The Bluetooth SIG apparently demands whole system evaluation and approval.


问:
Static Analysis tools to detect architectural patterns
Currently for school we are working on a research project. The central question of this project is: Which architectural patterns can be detected using static code analysis? With architectural pattern is meant the architectural patterns from the book: Patterns of Enterprise Application Architecture written by Martin Fowler.

During our literature research we didn't find any studies/articals/journals that adress this problem. So for our approach for this rpoject we where thinking to create a prototype of this kind of tool. But first we have to know if there are any (open-source)tools with the same functionality?(detect architectural patterns with a static code analysis)

So my question is do you know a tool that kind detect architectural patterns? We know of the existence of tools that can detect design patterns of the Gang of Four.
And do you have any suggestions for our approach?

Thanks in advance

答:
Anything that is a measurable, well-defined pattern can be parsed.

A deeper question is why would this be important (and important enough to measure and evaluate it with a tool)?  How would you meaningfully 'score' or quantify the results, and how would you use those scores?  The answer to those questions will tell you why there aren't many tools with that kind of capability, and the ones that are out there with a feature-set advertising this kind of capability are limited, either: pricey, fragile, or some blended combination of the two.

In the past, at least six or eight years ago, I saw these features in the upper end editions of UML tools, like Rational and Sparx Systems (architect/enterprise oriented editions of each respective version).  From what I can remember, these products could sometimes 'see' EAA patterns in models of imported/analyzed source.  They would suggest complementing patterns and naming for other facets that were participating somehow.  Or they would let you 'stub-in' skelatons of these patterns (somewhat useful, but counter to a degree in how patterns are supposed to more often than not, organically emerge).

Identifying patterns of any kind was a very new concept at the time, and in one of the first sets of tools that would incorporate this kind of built-in feature, finding patterns of any kind, but also including EAA patterns. I haven't really looked at them since, so perhaps they are now more refined, stable, and economically feasible.

Perhaps they are also available from someone where the tools operate directly on source (instead of a model), but I am not aware of it.


问:
How to unit test Visual Basic 6 legacy code?
I am doing legacy software programming in Visual Basic 6.0.

How do I unit test it?

答:
Does your IDE support unit testing? If not, you can always create your own unit test framework in any programming language by creating assertion methods Assert.AreEqual, Assert.IsTrue, etc. and designing a custom build which runs them on every build.

You can also use one of the multiple unit test frameworks for Visual Basic 6.


问:
Can a GPLv2 program rely on Apache-licensed libraries?
Can a software program licensed GPL (version 2) rely upon libraries licensed under APLv2 without running afoul of the GPL?  The language here suggests to me perhaps not.

In my specific case I'm looking at a daemon that uses some APLv2-licensed external libraries.

UPDATE
(In response to answers/comments.)

For the purpose of this question, I cannot relicense the main program (the daemon)

The main program has been extended with functionality that uses apr-util and perhaps other APLv2 components

My question is, can I release the extended daemon under the GPLv2, or is this something I need to keep to myself (no distribution) and/or re-implement without APLv2 if I am committed to (a) releasing this extension, and, (b) keeping the daemon GPL'd?

答:
My view is in agreement with OP based on the text of OP's ASF link.

ASF (Apache Software Foundation) doesn't like the idea of ASFv2 code being any part of a system that uses GPLv2, based on the limited information of your case and my understanding of the various FOSS licenses: regardless of whether the umbrella project has GPLv2, or the umbrella project is GPLv2, attempting to include ASFv2.

Further it seems a ASFv2 umbrella project that has GPLv3 code should not happen, but a GPLv3 umbrella project can have ASFv2 code.

The caveot, perhaps (according to Gnu), is how they interact with each other.  If linked, sharing the same copies of data during execution, they are one in the same program; however, if they are working as seperate processes (ie. forked) passing data between different distinct processes, what you are doing might be permissible because they are, to them, seperate programs.  If it uses shared data-space during execution, and doesn't operate with distinct processes, then what you are doing might not be allowed, because to them, they are the same or too tightly coupled to be distinct or independant.


问:
Is there a way you'd implement a fast tree traversal method that would support dated versioning?
I've got a catalog at work and I want to juke it up a bit because I'm tired of it being extremely slow. I'd like to support the modified preorder tree traversal storage method for the category tree of the catalog but i'd have to support dated versionning.

I've thought about creating versions of trees based on dates, so as soon as something changes I create a copy of the tree at hand at current date and then create my modifications. But the problem with that is that an import of a catalog that occurs every night would create, at long range, an extremely heavy table of tree traversal elements. Combined with the fact that a user could go and change a date anytime in the admin, it could then again generate another tree version.

Most of our catalogs are comprised of 100-250 categories, so a few versions would not create more than a few thousand elements, but mix that to a year of operation, that would easily go up to 90000 entries just to store the tree that can change.

So my question is this:

Is there a way you'd implement a fast tree traversal method (preferably modified preorder with left and right columns) that would support dated versioning?

答:
Confluently Persistent Tries for Efficient Version Control

http://erikdemaine.org/papers/ConfluentTries_Algorithmica/

We consider a data-structural problem motivated by version control of
  a hierarchical directory structure in a system like Subversion. The
  model is that directories and files can be moved and copied between
  two arbitrary versions in addition to being added or removed in an
  arbitrary version. Equivalently, we wish to maintain a confluently
  persistent trie (where internal nodes represent directories, leaves
  represent files, and edge labels represent path names), subject to
  copying a subtree between two arbitrary versions, adding a new child
  to an existing node, and deleting an existing subtree in an arbitrary
  version.


答:
Generally speaking, this is a term that rarely applies to software as we tend to think of our product lines advancing through versions and releases rather than generations.

That said, a software generation is much like a hardware generation, where the underlying technologies all play a part in defining the generation of the software. To give you a really rough idea about what I mean, let's use the Windows operating system as an example. You could say that every 2 or 3 versions of Windows is a generation based on the technologies that make each few versions stand out from the Windows versions that came before.

Off the top of my head (and I may not be remembering all of this correctly), Windows Generations might be roughly described as follows.

Generation 1: Windows 1 - 2

Generation 2: Windows 3 - 3.11

Generation 3: Windows 95, 98, ME

Generation 4: Windows NT, 2000, XP

Generation 5: Vista, Windows 7

That's probably an oversimplification and misses lots of variants, but in terms of technologies, interfaces, hardware compatibility and so on, each major advance (and effectively each near total re-write) would be a distinct generation.

Using the term "Generation" can be helpful if you want to look at things historically, or to define when your development should bypass all of the refactoring and other "longevity and compatibility measures" you might take to extend the lifetime of your products, however the reality is that keeping track of these things is more useful to the marketers than your average developer, and even then, the marketing spin probably won't have as much impact with your customers as simply bumping the Major version number up +1 on your product and listing all of the new features.

Title: What's a generation in Software Development?

Body:
I've heard about software and apps going into Generation 1.2 or 2.6, is there an actual methodology behind this? or it's more of a marketing thing?

Currently we are using Scrum as our methodology in agile software development and it's based on sprints, but I haven't been able to find any information detailing what's actually a generation in software development (neither on Agile based methodologies and non-agile).

http://en.wikipedia.org/wiki/Sprint_%28scrum%29#Sprint


问:
Why is DRY important?
Quite simple, why would I want to write code that works for all cases and scalable data when all I need to do is repeat the same process a few times with a few minor tweaks?

I'm unlikely to need to edit this again any time soon.

It looks like a lot of less work to just go...

```<code>function doStuff1(){/*.a.*/}
function doStuff2(){/*.b.*/}
function doStuff3(){/*.c.*/}
</code>```

And if I ever need to add something...

```<code>function doStuff4(){/*.d.*/}
</code>```

And if I need to remove it, I remove it.

It's harder to figure out how to make all of those into one straight-forward pattern that I can just feed data into and deal with all the cases, and make a bunch of changes I don't feel like I'm ever going to have to do.

Why be DRY when it looks like a quick cut+paste is going to be so much less work?

答:
While I actually agree with the other posters comments about maintainability etc. all of which are valid.

I would like to add a small dissenting voice to the debate.

Its only important to programmers. The people who pay your wages couldn't care less as long as the software passes UAT.

In terms of importance it ranks well below items like getting the correct requirements, listening to the project sponsors and delivering on time.

Title: Why is DRY important?


答:
Agile does require the tight loop to replace big up-front design which is Hard--Quite hard but actually it can be done, agile is not the only way.

You may want to find one of the modifications of Agile--there are many and one probably addresses this specific problem, but if not make up your own if you think you can.

All these processes were made up by smart people--and smart people can make any process work.  You don't think waterfall was invented because it never worked for anyone do you?  It evolved because some people could make it work, and others looked on and said "I have to refine that and feed it to MY team that can't seem to produce as effectively"--at that point it probably worked better than what they were doing, but if you don't recognize that not every programmer can solve every problem it can really baffle you why two teams using the same process can have different results.

The problem is that many processes require talent to implement them--we're talking talent as rare as pro sports players out of a pool of everyone who has ever played a sport--chances are most of us have never met someone capable of making the crappy processes like waterfall work and that's why so many people think it can't succeed--they've never seen it work.

It takes much less talent to make Agile work, yet it requires some very specific investments such as having the customer look at what you are doing constantly so that errors can't propagate, and things like ruthless refactoring so that you don't build up a technical debt that the team can't unravel a few months down the line.


问:
What is the most effective way to add functionality to unfamiliar, structurally unsound code?
This is probably something everyone has to face during the development sooner or later.

You have an existing code written by someone else, and you have to extend it to work under new requirements.

Sometimes it's simple, but sometimes the modules have medium to high coupling and medium to low cohesion, so the moment you start touching anything, everything breaks. And you don't feel that it's fixed correctly when you get the new and old scenarios working again.

One approach would be to write tests, but in reality, in all cases I've seen, that was pretty much impossible (reliance on GUI, missing specifications, threading, complex dependencies and hierarchies, deadlines, etc).

So everything sort of falls back to good ol' cowboy coding approach. But I refuse to believe there is no other systematic way that would make everything easier.

Does anyone know a better approach, or the name of the methodology that should be used in such cases?

答:
Basically, you have three approaches:

Write from scratch. It may work for small applications, but you can't use it for large codebase.

Note that for small to medium-size codebase, it's not the worst scenario to avoid at all costs.

There is a good reason to not rewriting from scratch: an old codebase is generally expected to be tested, to contain tricks which make the code working in some circumstances, etc., and when rewriting everything, you will introduce a bunch of bugs which were already solved.

This is an invalid argument in cases you're talking about, since you mentioned that the code has a very low quality: not tested, with missing specifications, never refactored, etc. Don't rewrite from scratch rule, on the other hand, must be limited to the high quality, QA-tested code.

Use cowboy coding approach: change everything, then test. This may fail or succeed depending mostly on the context.

Example 1: you are modifying the business-critical application. You know that your customer would be angry if you break something in existent code, and this customer is convinced that the actual product not only works well, but is also correctly written (or the customer just doesn't understand what is crappy spaghetti code vs. well-written code).

Here, you can't use cowboy coding, since you must not introduce new bugs. This means that you need to use one of two other approaches.

Example 2: your customer tells you that his experience with the previous developer was a disaster. The product doesn't even work half of the time, and is totally unusable as is. The customer understands that modifying the source code so badly written can introduce even more bugs.

Here, on the other hand, cowboy coding can be a good solution, if you're sure that it will reduce the overall cost, compared to two other solutions.

Start by refactoring the initial code, adding unit tests (and other testing required in specific cases), documenting it, etc., then add your modifications. This may be a good approach when the code is not too crappy and has some value. For example, if I know that the code was written by my more skilled colleague under time pressure and low budget constraints, I'll certainly use this approach since:

There are parts of code which are cleverly done,

You'll learn lots of things from the code you refactor.

Even under time pressure and low budget constraints, a code by a better skilled developer is still a code of certain level. It means that if there is a trick to make the application work in some circumstances, the skilled developer will still leave you a comment explaining why the following line of code was added.

I don't think there is one perfect solution: compare all three for each project or task, assess their respective cost, and select the best one depending on the circumstances.

In general, follow these two rules:

Rule 1: the better skilled are the developers who wrote the code, the more refactoring vs. rewriting from scratch you must use.

Rule 2: the larger is the project, the more refactoring vs. rewriting from scratch you must use.

Refactor a large database written by somebody more skilled than you. Rewrite from scratch small pieces of code or code written by unskilled programmers.

ContentLicense: CC BY-SA 4.0


答:
One approach would be to write tests,

I believe that you sort of half answered your own question. There are a number of ways that you could look at this, however with experience I've found that it always seems to gravitate towards applying some of the standard Agile practices, and do everything in a systematic manner in the same way that you would approach any difficult to solve technical problem.

This is the way I personally approach this sort of situation:

Start with a period of study, take notes, draw diagrams, and ask yourself (and/or a nearby 'local expert') lots of questions. You need to read the code, and get a nice big picture overview of the problem at hand.

Identify several obvious problem areas and assess the risk of messing with them.  Spike a few changes to see how the failures will occur and get an idea about how much additional effort would be required to either follow the path your spike was following, or to do something else entirely.

Pick a problem, and write tests. Use existing tests if they are available, and if not write new ones that protect the business logic as much as you possibly can.

Write your test to fail, then fix your test to pass, then change your code to fail as a double check, then restore your code to pass again. Use the last "code failure" step as an opportunity to step through the code and identify anything obvious you may have otherwise missed.

Design and Plan your change for how you believe the code should be written to fix the problem.  This is where you need to go back to the requirements and the spec (assuming you have one), and write your tests as you would your user stories or features, or whatever method you would usually use.

Write new tests to match your new stories (aka your revised spec)

Refactor your code in little steps. Start by extracting methods, then look to extracting classes, then look to moving methods and classes, and then combining/deleting classes. Always do all of the easy refactorings first, because this will make the more difficult refactorings easier later on. I'd suggest reading both Refactoring and Refactoring To Patterns if you are looking for a little help or inspiration to guide your efforts.

As you refactor, you are aiming to keep your original tests passing, and aiming towards having your new tests passing once the refactoring is complete.  As you do this, you may find yourself throwing out some of the original tests, or you may be lucky enough to have both old and new tests passing together.

This is a process that I have found works well for me.  It is time-consuming, and it can sometimes be tedious, but it works and always gives me a good result.  I have never found code that I couldn't improve given the time and resources to do so. Tthe thing is, you may find that during your initial investigations and spikes that you identify some very difficult problems or even show-stoppers based on the time and effort you estimate it all taking, and estimating this sort of thing can be very difficult to do with any certainty.  You may find that in the end it will be better to start over, or you may find that the code is of great commercial value to the company you work for.  Give your best estimate to get the work done, and if you have a full understanding of the problem domain, give your best estimate to start things over.  Present a few cases and scenarios to your boss, and then let management decide where to spend the money.  That takes the heat off you and puts it firmly back with them.

As I said, this approach works for me, it might not work exactly the same for you.  You may wish to tweak the process, or look at solving the problem another way. The point is that you can only solve these difficult problems by thinking laterally and not seeing a mess in code as simply a lost cause. Think of it instead as a difficult problem and a challenge, and with any problem, there is always a systematic way to solve it. You just need to find an approach that works for you.  Personally, when I rise to such a challenge and once I have a few wins under my belt, I take a great deal of pride in turning a poorly designed application into a beautifully crafted product.

Title: What is the most effective way to add functionality to unfamiliar, structurally unsound code?

Body:
This is probably something everyone has to face during the development sooner or later.

You have an existing code written by someone else, and you have to extend it to work under new requirements.

Sometimes it's simple, but sometimes the modules have medium to high coupling and medium to low cohesion, so the moment you start touching anything, everything breaks. And you don't feel that it's fixed correctly when you get the new and old scenarios working again.

One approach would be to write tests, but in reality, in all cases I've seen, that was pretty much impossible (reliance on GUI, missing specifications, threading, complex dependencies and hierarchies, deadlines, etc).

So everything sort of falls back to good ol' cowboy coding approach. But I refuse to believe there is no other systematic way that would make everything easier.

Does anyone know a better approach, or the name of the methodology that should be used in such cases?


问:
What precisely does "Applicative" mean in computer science?
I know what an "applicative Functor" is, but I've been reading papers recently that refer to other "applicative" things, particularly "purely applicative data structures".

The trouble is, I'm not sure precisely what "applicative" means in this context, and Google has so far failed me. I can get a general English (ie useless) definition of "applicative", but as soon as I add "computer science" to the search all I get is definitions of computer science.

I have a vague sense that this relates to keeping them pesky effects in their place, but I could use a precise definition.

I found this - http://foldoc.org/applicative - but I'm not sure "applicative language == functional language" really helps.

答:
The best general definition I can think of is "respects the principle of extensionality".

An applicative functor given equal structures produces equal structures. Contrast with a generative functor, which produces a "fresh" structure each time---that is, the equality of structures depends on "where" and/or "when" they were produced.

An applicative data structure is one where the information is represented by "how the data structure is put together", rather than external things like memory locations. This sense of "applicative" requires a certain perspective, common in programming language semantics, that separates "values" from "the store" (an abstraction of mutable memory). For algebraic data types, extensionality equates two values of the same type iff they were produced by the same constructor applied to the same arguments. The upshot is that mutation and "object identity" are forbidden.

There's also another usage: "applicative order of evaluation". I'm not sure that use is related to the others.


答:
That's basically my day-to-day. There are cases where writing small tests is just too impractical for the reasons you mentioned. You should always keep big tests though, but covering all bases is often impossible. The best approach I find is to spiral outward.

Instead of rewriting from the start, get a good understanding of elements. If there are long functions, seek to cut them in logical chunks. Decouple/detangle the smaller elements, the least complicated non-circular dependencies. Start a parallel library, which you understand well, and start migrating small functions in generic bits.

Do this, and you will slowly unravel the system, and work towards bigger and bigger chunks of code which will also become more modular.

Document like it's a drug and you're addicted to it. I don't mean to write a novel in your code, but chances are the code is not all too documented, so do it .NET or Doxygen style: what the function does, input, output (and if need be what global variables or properties you're using or changing).

Last trick: define default behaviour. If there are options or parameters to the program as a whole, define what is the default, implement an easy way to deploy with all defaults (I did it with a simple INI file. Very useful) explicitly laid out. Then you can add in other options and functionality as new options that tie in to the original system.


答:
I agree with S.Lott.  Catching the exception as close as possible to the source may be a good idea or a bad idea depending on the situation.  The key to handling exceptions is to only catch them when you can do something about it.  Catching them and returning a numeric value to the calling function is generally a bad design.  You just want to let them float up until you can recover.

I always consider exception handling to be a step away from my application logic.  I ask myself, If this exception is thrown how far back up the call stack do I have to crawl before my application is in a recoverable state?  In a lot of cases, if there isn't anything I can do within the application to recover, that might mean I don't catch it until the top level and just log the exception, fail the job and try to shut down cleanly.

There is really no hard and fast rule to when and how to set up exception handling other than leave them alone until you know what to do with them.


问:
How should I add functionality to an object that already exists?
I have an interface that has a certain amount of well-defined functionality. Let's say:

```<code>interface BakeryInterface {
  public function createCookies();
  public function createIceCream();
}
</code>```

This works well for most implementations of the interface, but in a few instances, I need to add some new functionality (like perhaps rolled into a new method, createBrownies()). The obvious/naive approach to doing this would be to extend the interface:

```<code>interface BrownieBakeryInterface extends BakeryInterface {
  public function createBrownies();
}
</code>```

But has a pretty big downside in that I can't add the new functionality without modifying the existing API (like changing the class to use the new interface).

I was thinking about using an adapter to add the functionality after instantiation:

```<code>class BrownieAdapter {
  private brownieBakery;

  public function construct(BakeryInterface bakery) {
    this->brownieBakery = bakery;
  }

  public function createBrownies() {
    /* ... */
  }
}
</code>```

Which would net me something like:

```<code>bakery = new Bakery();
bakery = new BrownieBakery(bakery);
bakery->createBrownies();
</code>```

This seems like a good solution to the problem, but I'm wondering if I'm awakening the old gods by doing it. Is the adapter the way to go? Is there a better pattern to follow? Or should I really just be biting the bullet and just extending the original interface?

答:
You have encountered the expression problem. This article by Stuart Sierra discusses clojures solution, but he also gives an example in Java and lists the popular solutions in classic OO.

There's also this presentation by Chris Houser that discusses pretty much the same ground.


问:
When is method overloading appropriate?
Suppose I am working on an existing, reasonably large system. I have an object, myObject of class MyClass (for the example's sake, suppose I'm working in Java). myObject is a composition containing a Collection, say, a List and other objects which (I think) are irrelevant. It contains delegate methods which just serve to call upon the methods of the List it is composed of, in order to ensure the List it has is not exposed (sorry if I've got my terminology wrong).

Let's say that this List is a List<String> but, for some reason, the main access method is a mask method for class SomeOtherClass. If I wanted to insert a new value pair into my List, then I'd have an object of SomeOtherClass called someObject. I'd call myObject.insert(someObject) and inside the insert method there would be some magic that would retrieve a String to put into the List<String>.

Supposing now that I've only got a String value, and no SomeOtherClass object to insert. Assuming I can't modify the insert method because it would break everything in this system. Then should I overload the insert method? Or should I create a new object of SomeOtherClass every time I want to call insert?

I guess if I did overload it, it would look something like this...

```<code>public void insert(String s) {
    ...
}

public void insert(SomeOtherObject obj) {
    this.insert(obj.magicStringMethod());
}
</code>```

(This example is a contrived puzzle based upon a similar (slightly more complex) situation regarding overloading that I encountered yesterday. I'll expand it if there's anything that was unclear)

Would this be an appropriate place to overload a method? If not, when should I overload a method?

答:
Essentially to have the parameters of the method dictate how the method will behave.

A quick example would be:

```<code>class Calc{
    //...
    public int sum(int a, int b){
        return a+b;
    }
    public double sum(double a, double b){
        return a+b;
    }
    //...
}
</code>```

If you pass the method sum(a,b) a couple of integers it knows that it should call the first implementation, since the method call coincides with the method signature (i.e. double sum(double,double) will not work if you give the sum method two integers).

The signature of the call must match the available implementations, so trying to call sum(string, string) will not work unless you have this:

```<code>class Calc{
    //...
    public int sum(int a, int b){
        return a+b;
    }
    public double sum(double a, double b){
        return a+b;
    }
    public string sum(String a, String b){
        return "" + (Double.parseDouble(a) + Double.parseDouble(b));
    }
    //...
}
</code>```

tl;dr: To have the class handle the correct method according to whatever parameters you give a method with the same name.

When inheriting, it is called overriding

A good example of this other scenario is when you want to alter the default behavior of a class by inheriting it, and particularly when you have something similar to the template method pattern, where you have each step of some algorithm implemented in a method.

Imagine that you have class Robot and a method called fireAtTarget(Target target)... which calls fireWeaponA(target); fireWeaponB(target); fireWeaponC(target); one after each other. You also want to have a collection called robot_army to which you can only add objects of the class Robot. Robot fires machine guns by default in its fireWeaponX() methods.

Then you want to have class LazorRobot and class MissileRobot, do you implement Robot all over again?, no, just have LazorRobot and MissileRobot inherit Robot, and overload each fireWeaponX() method to use lazorz or missiles and you will have the same behavior with different weapons, without having to reimplement the rest of the methods.

tl;dr: To have the method's behavior depend on the class without breaking the interface (robot_army only accepts Robot, but accepts by extension any classes that inherit Robot).

Title: When is method overloading appropriate?

Body:
Essentially to have the parameters of the method dictate how the method will behave.

A quick example would be:

class Calc{
    //...
    public int sum(int a, int b){
        return a+b;
    }
    public double sum(double a, double b){
        return a+b;
    }
    //...
}

If you pass the method sum(a,b) a couple of integers it knows that it should call the first implementation, since the method call coincides with the method signature (i.e. double sum(double,double) will not work if you give the sum method two integers).

The signature of the call must match the available implementations, so trying to call sum(string, string) will not work unless you have this:

class Calc{
    //...
    public int sum(int a, int b){
        return a+b;
    }
    public double sum(double a, double b){
        return a+b;
    }
    public string sum(String a, String b){
        return "" + (Double.parseDouble(a) + Double.parseDouble(b));
    }
    //...
}

tl;dr: To have the class handle the correct method according to whatever parameters you give a method with the same name.

When inheriting, it is called overriding

A good example of this other scenario is when you want to alter the default behavior of a class by inheriting it, and particularly when you have something similar to the template method pattern, where you have each step of some algorithm implemented in a method.

Imagine that you have class Robot and a method called fireAtTarget(Target target)... which calls fireWeaponA(target); fireWeaponB(target); fireWeaponC(target); one after each other. You also want to have a collection called robot_army to which you can only add objects of the class Robot. Robot fires machine guns by default in its fireWeaponX() methods.

Then you want to have class LazorRobot and class MissileRobot, do you implement Robot all over again?, no, just have LazorRobot and MissileRobot inherit Robot, and overload each fireWeaponX() method to use lazorz or missiles and you will have the same behavior with different weapons, without having to reimplement the rest of the methods.

tl;dr: To have the method's behavior depend on the class without breaking the interface (robot_army only accepts Robot, but accepts by extension any classes that inherit Robot).


答:
Investigate the concept of horizontal reuse, where you can find stuff such as Traits, the still experimental but already production-proof Aspect Oriented Programming and the sometimes hated Mixins.

A direct way of adding methods to a class also depends on the programming language. Ruby allows for monkey-patching while Javascript's prototype-based inheritance, where classes don't really exist, you create an object and just copy it and keep adding to it, e.g.:

```<code>var MyClass = {
    do : function(){...}
};

var MyNewClass = new MyClass;
MyClass.undo = function(){...};

var my_new_object = new MyNewClass;
my_new_object.do();
my_new_object.undo();
</code>```

Finally, you can also emulate horizontal reuse, or runtime "modification" and "addition" of class/object behavior with reflection.

Title: How should I add functionality to an object that already exists?

Body:
I have an interface that has a certain amount of well-defined functionality. Let's say:

```<code>interface BakeryInterface {
  public function createCookies();
  public function createIceCream();
}
</code>```

This works well for most implementations of the interface, but in a few instances, I need to add some new functionality (like perhaps rolled into a new method, createBrownies()). The obvious/naive approach to doing this would be to extend the interface:

```<code>interface BrownieBakeryInterface extends BakeryInterface {
  public function createBrownies();
}
</code>```

But has a pretty big downside in that I can't add the new functionality without modifying the existing API (like changing the class to use the new interface).

I was thinking about using an adapter to add the functionality after instantiation:

```<code>class BrownieAdapter {
  private brownieBakery;

  public function construct(BakeryInterface bakery) {
    this->brownieBakery = bakery;
  }

  public function createBrownies() {
    /* ... */
  }
}
</code>```

Which would net me something like:

```<code>bakery = new Bakery();
bakery = new BrownieBakery(bakery);
bakery->createBrownies();
</code>```

This seems like a good solution to the problem, but I'm wondering if I'm awakening the old gods by doing it. Is the adapter the way to go? Is there a better pattern to follow? Or should I really just be biting the bullet and just extending the original interface?

Body:
Investigate the concept of horizontal reuse, where you can find stuff such as Traits, the still experimental but already production-proof Aspect Oriented Programming and the sometimes hated Mixins.

A direct way of adding methods to a class also depends on the programming language. Ruby allows for monkey-patching while Javascript's prototype-based inheritance, where classes don't really exist, you create an object and just copy it and keep adding to it, e.g.:

var MyClass = {
    do : function(){...}
};

var MyNewClass = new MyClass;
MyClass.undo = function(){...};

var my_new_object = new MyNewClass;
my_new_object.do();
my_new_object.undo();

Finally, you can also emulate horizontal reuse, or runtime "modification" and "addition" of class/object behavior with reflection.


答:
Any of the Handle Body patterns could fit the description, depending on your exact requirements, language, and needed level of abstraction.

The purist approach would be the Decorator pattern, which does exactly what you are looking for, dynamically add responsibilities to objects. If you are actually building bakeries, it's definitely overkill and you should just go with Adapter.


答:
I would say that overloading is appropriate when both of the methods are semantically equivalent. To steal from dukeofgaming's examples:

These are overloaded appropriately:

```<code>public int sum(int a, int b){
    return a+b;
}

public double sum(double a, double b){
    return a+b;
}
</code>```

These are not:

```<code>public int sum(int a, int b){
    return a+b;
}

public double sum(double a, double b){
    return a-b;
}
</code>```

That is an extreme example (if you didn't catch it, the last method actually subtracts instead of adds), but the idea is that if you have multiple methods in a class with the same name they should behave consistently.

In your example, from the information given they appear to be equivalent (since one calls the other) and I would think it reasonable to overload them. It can't hurt to ask someone more senior in your team if you are unsure about whether the method should be added but if you did add it I would use the same name (i.e. I would overload it).

Title: When is method overloading appropriate?

Body:
Suppose I am working on an existing, reasonably large system. I have an object, myObject of class MyClass (for the example's sake, suppose I'm working in Java). myObject is a composition containing a Collection, say, a List and other objects which (I think) are irrelevant. It contains delegate methods which just serve to call upon the methods of the List it is composed of, in order to ensure the List it has is not exposed (sorry if I've got my terminology wrong).

Let's say that this List is a List<String> but, for some reason, the main access method is a mask method for class SomeOtherClass. If I wanted to insert a new value pair into my List, then I'd have an object of SomeOtherClass called someObject. I'd call myObject.insert(someObject) and inside the insert method there would be some magic that would retrieve a String to put into the List<String>.

Supposing now that I've only got a String value, and no SomeOtherClass object to insert. Assuming I can't modify the insert method because it would break everything in this system. Then should I overload the insert method? Or should I create a new object of SomeOtherClass every time I want to call insert?

I guess if I did overload it, it would look something like this...

```<code>public void insert(String s) {
    ...
}

public void insert(SomeOtherObject obj) {
    this.insert(obj.magicStringMethod());
}
</code>```

(This example is a contrived puzzle based upon a similar (slightly more complex) situation regarding overloading that I encountered yesterday. I'll expand it if there's anything that was unclear)

Would this be an appropriate place to overload a method? If not, when should I overload a method?

Body:
I would say that overloading is appropriate when both of the methods are semantically equivalent. To steal from dukeofgaming's examples:

These are overloaded appropriately:

public int sum(int a, int b){
    return a+b;
}

public double sum(double a, double b){
    return a+b;
}

These are not:

public int sum(int a, int b){
    return a+b;
}

public double sum(double a, double b){
    return a-b;
}

That is an extreme example (if you didn't catch it, the last method actually subtracts instead of adds), but the idea is that if you have multiple methods in a class with the same name they should behave consistently.

In your example, from the information given they appear to be equivalent (since one calls the other) and I would think it reasonable to overload them. It can't hurt to ask someone more senior in your team if you are unsure about whether the method should be added but if you did add it I would use the same name (i.e. I would overload it).


问:
How should I implement a secure priority queue in C?
I have an assignment to implement a priority queue in C as well as make an app that uses it. I, however, only know basic-level C (I do know Java). My intuition says that I need to learn pointers.

What other stumbling blocks should I expect or prepare for? How do I go about making this secure?

答:
I think it would be best you learn this (pointers et. al.) faster by doing than by trying to learn first.

here are some pointers:

A queue can be easily implemented in the form of linked list. So if you have a general idea of how linked lists (single or double) are created, by keeping a pointer for next (and previous) and update them appropriately, you are more or less done.

About priority essentially you need to keep some score (as say int) on each node, so whenever you insert the node you need to traverse till the point priority is less than the priority of new entrant node. Swap the next (previous) pointers of node appropriately.

About being secure, this is not very clear -but generally, to write secure code you must ensure that you do not carry finite buffers (pointers) without known lengths - and do not write data in any buffer which can potentially write down to unknown memory areas. This needs a great deal elaboration beyond the scope here.

Tips:

Do not forget to malloc each node before insertino, and free after removal (or usage).

Create a debug function - validate_all_nodes() and just traverse the entire list to see that all nodes are proper. Use this function every time you want to debug it.