问:
How to read thousands lines of code without any documentation?
Previously I was searching for a good TimeLine control for a WPF project. I found an answer in Here which direct me to this CodePlex project.

Now I want to change code to feed my culture needs. But there are some mismatches!

My question is:

How you interact with such thousands lines of code?

EDIT:

Any shortcut will be great!

答: Different people have different learning styles, so YMMV. The first thing I do in this situation is read the entire code base through at least once. That gives me a general idea of where everything is. Then I choose a section to examine in more detail. Data structures would be a good place to start. Once I have a general idea of what's going on, I do the same with another portion of the code that interacts with the first. After enough iterations, I have a good sense of how the code works.</p>


问:
Storing a value vs calling reference for repeated use in Java
I have an old habit of avoiding calling references multiple times, both for easier to read/maintain code, and for possible efficiency.  But I'm wondering which is more efficient (memory, performance, both?).

For example when working with XML using a VTD parser

```<code>if( vn.toString( vn.getCurrentIndex() ).equalsIgnoreCase( "broken-label" ) == false )
        {
            do
            {
                if( parentNode != null )
                {
                    currentNode = parentNode.addChildNode( vn.toString( vn.getCurrentIndex() ) );
                }
                else
                {
                    currentNode = new xmlNode( vn.toString(vn.getCurrentIndex()), null );
                    treeNodes.add( 0, currentNode );
                }
</code>```

Does not store the value, perhaps saving some overhead for creating space to save  a local variable and also lowering the burden on the garbage collector (assuming this section of code is repeated thousands of times in quick succession.

My habit of cleaner/efficient code would be to replace the above with the simple change of

```<code>String label = vn.toString( vn.getCurrentIndex();

if( label ).equalsIgnoreCase( "vsled-image" ) == false )
        {
            do
            {
                if( parentNode != null )
                {
                    currentNode = parentNode.addChildNode( label ) );
                }
                else
                {
                    currentNode = new xmlNode( label, null );
                    treeNodes.add( 0, currentNode );
                }
</code>```

While this is obviously easier to read and maintain.  Are there any non-human benefits?

答:
Function calls are expensive.  In this example, by using that variable, you have eliminated four separate function calls.  Each call puts stuff on the call stack, jumps the instruction pointer around, creates the rough equivalent of brand new variables anyway, etc.  On many occasions, functions you call will create what really are new variables within their definitions as well.

So, yeah, in cases like this, it's better to just go ahead and make that extra variable up at the top.  And if you're worried to death about it, and you're willing to sacrifice modularity and maintainability, you might set up the variable outside of the function's body, before the function is called, and then just reference it within the function.

ContentLicense: CC BY-SA 3.0


问:
Handling subscriptions, balances and pricing plan changes
Preamble

My aim is to create reusable code for multiple projects (and also publish it on github) to manage subscriptions. I know about stripe and recurring billing providers, but that's not what this module is aiming for. It should just be a wrapper/helper for calculating account balance, easy notifications to renew a subscription, and handle price calculations.

There are countries you can't use recurring billing because of the providers or payment possibilities having poor or no support for it or are too expensive (micropayments). And there are people that don't want to use recurring billing but pay their bill manually / avingg an invoice at the end of the year. So please don't suggest paypal recurring billing, recurly or similar services.

Situation

Let's say you have a model that can subscribe to a subscription plan (e.g. User). This model has a field that stores the identifier of a subscription plan it is currently subscribed to. So, on every plan change, the change is recorded.

There is a model (e.g. SubscriptionPlanChanges) with the following fields recording the mentioned changes:

subscriber relating to the subscribing model (User in this case)

from_plan defining the plan identifier the model had before change

to_plan defining the plan identifier the model has selected now

created_at is a date-time field storing the change

valid_until stores the date until the actual subscription is valid

paid_at is also a date-time field that defines if (and when) subscription was paid

Of course, that layout is discussable.

Question of account balance

When a User changes his/her subscription plan, I need to compare the plan fields, get the pricings, and calculate the deduction for the new plan based on the current plan's valid_until and its price. Say: You subscribed for a year of plan A but after 6 months, you upgrade to plan B, so you get a deduction of half the paid price for the 6 months of plan A.

What I am wondering: If a user e.g. switches to the free plan, he has a credit which can be deducted if the user wants to switch again. Would you cache that value in an additional field, or calculate through all the records related to that user every time? Would you add/change something about the table layout?

Question of easy comprehensibility

When the end of a subscription period arrives, the user gets notified and has the possiblity to renew his subscription by paying again. The easiest way would be to just update paid_at and valid_until with new subscription options. However, I am not sure if you store every data someone might need, like a payment/subscription history.

Another option would be to create an additional record for this, where from_plan and to_plan are having the same identifier (thus symbolizing "no change"). But wouldn't that interfer with calculating the account balance in some way?

If someone could point me into the right direction about the logics handling such subscriptions, I'd appreciate it very much.

UPDATE

Thanks for the help by now. I think my question was too vague so I'll try to be more precisely by using less abstraction. Unfortunately, I could not solve my problem yet.

Case A

User can select Subscription Plan A. This currently stores a SubscriptionPlanChange to keep track of it. After e.g. 5 months, User upgrades his subscription to Subscription Plan B. So he pays the price for his new subscription, deducting the price of plan a for the unused 7 months.

Case B

After 3 months, User rolls back to his Subscription Plan A. He does not have to pay but receives a balance for it so that, at the end of the subscription, he gets that balance deducted for his new subscription.

Case C

User can select a subscription plan for a sub-service that has independent subscription plans. Same Case A and Case B can apply for that sub-service subscription.

_Case D_
User cancels one of his subscriptions. This results in a top up of his balance.

My question (currently, at least) mainly depends on how to store that data properly so I can reproduce a history of subscriptions for business analysis and calculate balances, get outstanding payments based on the subscriptions etc.

I am also not sure if the balance should be stored in e.g. the users model itself, or if it is not stored but can be calculated any time based on the stored data / history.

Some things to note, although I don't think that they should introduce problems:

It does not have to be a User, it could be anything, that's why the Subscriber is polymorphic

Plans do not necessarily have to be plans, but could be e.g. Magazines like mentioned. That's what I've described with Case C and Case D.

答:
In addition to the above answer, I would create a table with credits, where a credit would equal the current currency. Whenever the user switches plan to a cheaper alternative, the unused balance enters as credits.
Whenever the user has something to pay, you would use the credits first and only ask for payment if the credits run out or don't exist.
If using this alternative, create the table as a transaction-list in order to being able to reproduce the usage-scenario if ever a dispute would occur. Example:

ID,
UserId,
TransactionDate,
Credit (positive when you give the user credits and negative when user uses the credit)

Just sum the credits for the user to show him/her the balance.

Hope this is of some use to you...


问:
Does usage of advanced language features decrease maintainability?
On a code review, I've stumbled on an interesting idea, which I can't properly judge alone.

Is it OK to improve readability of code by means of not widely known language syntax? When the original writer didn't use a special syntax designated for solving a specific coding problem, and solved it by simulating with workarounds — is it worth to refactor it for clarity and conciseness? What if even the code reviewer didn't know about the language feature?

To be specific, I'll bring the exact issue I've met on the code review — but keep in mind that this is just an example.

So the original code was a little web service in Python. At some point, there arised a requirement for several request handlers to be protected with an authentication mechanism. Somebody solved it with inheritance:

class AuthOnlyAccess:
    def GET(self, *args):
        if not hasattr(self, 'PROTECTED_GET'):
            raise web.Nomethod()

        if check_auth():
            return self.PROTECTED_GET(*args)
        else:
            raise web.Unauthorised()

    def POST(self, *args):
        if not hasattr(self, 'PROTECTED_POST'):
            raise web.Nomethod()

        if check_auth():
            return self.PROTECTED_POST(*args)
        else:
            raise web.Unauthorised()

...

class FooHandler(AuthOnlyAccess):
    def PROTECTED_GET(self, a, b, c):
        handle_foo_get(a, b, c)

    def PROTECTED_POST(self, x, y, z):
        handle_spam_eggs()

...
<more handlers deriving AuthOnlyAccess>
```

<p>The refactorer found this code ugly and introduced a decorator:</p>

<pre class="lang-py prettyprint-override"><code>from functools import wraps
...

def requires_auth(wrapped_func):
    """ (a little doc telling that this is a decorator and how to use it) """
    @wraps(wrapped_func)
    def decorator(*args):
        if check_auth():
            return wrapped_func(*args)
        else
            raise web.Unauthorized()

    return decorator

...

class FooHandler:
    @requires_auth
    def GET(self, a, b, c):
        handle_foo_get(a, b, c)

    @requires_auth
    def POST(self, x, y, z):
        handle_spam_eggs()

...
<more refactored handlers>
</code>```

The reviewer argues that this change actually decreases maintainability, because most of the team doesn't know decorator syntax. So the next person visiting the refactored code could be puzzled by the construct — but not with the previous version.

There's also a convincing argument that most of the codebase isn't in Python, (the language is there only for that little web service), and hence team members aren't required to have even shallow knowledge of Python. However, to work with code, one's going to need to know its language, right?

And if you have the temptation to say that python decorators aren't that advanced syntax — please remember that this is only an example. Every language has its dark corners. (But to learn those corners means to become better.)

So the question is... Can you read unknown syntax? Is the elegance worth the surprise? At least, what are the tradeoffs and/or guidelines you can name? I do really need some opinions from the community of programming professionals.

答:
This is something that you need to take on a case by case basis. I would argue that you should use unfamiliar features of a language if it would improve clarity and make future maintenance easier (both of which your example accomplishes in my opinion).

You should never use features just because you want to be clever or because you want to use the feature for the sake of it. On the other hand, I don't think you should ever avoid using a feature that would improve the code simply because the other developers on your team don't know how to use it yet. If they are worth their salt they will soon learn and use it themselves if the idea has merit. Developers that refuse to adopt possibly superior techniques just because they've never seen or used them before should raise big red flags.


答:
If the methods are simple getters it makes no difference as they will be inlined at runtime.

If the methods do non trivial work, then calling them more often will probably take more time. To know exactly how much, you will need to profile your application.

From a readability perspective, using well chosen variables may improve your code.

Title: Storing a value vs calling reference for repeated use in Java

Body:
I have an old habit of avoiding calling references multiple times, both for easier to read/maintain code, and for possible efficiency.  But I'm wondering which is more efficient (memory, performance, both?).

For example when working with XML using a VTD parser

```<code>if( vn.toString( vn.getCurrentIndex() ).equalsIgnoreCase( "broken-label" ) == false )
        {
            do
            {
                if( parentNode != null )
                {
                    currentNode = parentNode.addChildNode( vn.toString( vn.getCurrentIndex() ) );
                }
                else
                {
                    currentNode = new xmlNode( vn.toString(vn.getCurrentIndex()), null );
                    treeNodes.add( 0, currentNode );
                }
</code>```

Does not store the value, perhaps saving some overhead for creating space to save  a local variable and also lowering the burden on the garbage collector (assuming this section of code is repeated thousands of times in quick succession.

My habit of cleaner/efficient code would be to replace the above with the simple change of

```<code>String label = vn.toString( vn.getCurrentIndex();

if( label ).equalsIgnoreCase( "vsled-image" ) == false )
        {
            do
            {
                if( parentNode != null )
                {
                    currentNode = parentNode.addChildNode( label ) );
                }
                else
                {
                    currentNode = new xmlNode( label, null );
                    treeNodes.add( 0, currentNode );
                }
</code>```

While this is obviously easier to read and maintain.  Are there any non-human benefits?


问:
Algorithm to Find the Aggregate Mass of "Granola Bar"-Like Structures?
I'm a planetary science researcher and one project I'm working on is N-body simulations of Saturn's rings.  The goal of this particular study is to watch as particles clump together under their own self-gravity and measure the aggregate mass of the clumps versus the mean velocity of all particles in the cell.  We're trying to figure out if this can explain some observations made by the Cassini spacecraft during the Saturnian summer solstice when large structures were seen casting shadows on the nearly edge-on rings.  Below is a screenshot of what any given timestep looks like.  (Each particle is 2 m in diameter and the simulation cell itself is around 700 m across.)

The code I'm using already spits out the mean velocity at every timestep.  What I need to do is figure out a way to determine the mass of particles in the clumps and NOT the stray particles between them.  I know every particle's position, mass, size, etc., but I don't know easily that, say, particles 30,000-40,000 along with 102,000-105,000 make up one strand that to the human eye is obvious.

So, the algorithm I need to write would need to be a code with as few user-entered parameters as possible (for replicability and objectivity) that would go through all the particle positions, figure out what particles belong to clumps, and then calculate the mass.  It would be great if it could do it for "each" clump/strand as opposed to everything over the cell, but I don't think I actually need it to separate them out.

The only thing I was thinking of was doing some sort of N2 distance calculation where I'd calculate the distance between every particle and if, say, the closest 100 particles were within a certain distance, then that particle would be considered part of a cluster.  But that seems pretty sloppy and I was hoping that you CS folks and programmers might know of a more elegant solution?

Edited with My Solution:  What I did was to take a sort of nearest-neighbor / cluster approach and do the quick-n-dirty N2 implementation first.  So, take every particle, calculate distance to all other particles, and the threshold for in a cluster or not was whether there were N particles within d distance (two parameters that have to be set a priori, unfortunately, but as was said by some responses/comments, I wasn't going to get away with not having some of those).

I then sped it up by not sorting distances but simply doing an order N search and increment a counter for the particles within d, and that sped stuff up by a factor of 6.  Then I added a "stupid programmer's tree" (because I know next to nothing about tree codes).  I divide up the simulation cell into a set number of grids (best results when grid size ≈7 d) where the main grid lines up with the cell, one grid is offset by half in x and y, and the other two are offset by 1/4 in ±x and ±y.  The code then divides particles into the grids, then each particle N only has to have distances calculated to the other particles in that cell.

Theoretically, if this were a real tree, I should get order N*log(N) as opposed to N2 speeds.  I got somewhere between the two, where for a 50,000-particle sub-set I got a 17x increase in speed, and for a 150,000-particle cell, I got a 38x increase in speed.  12 seconds for the first, 53 seconds for the second, 460 seconds for a 500,000-particle cell.  Those are comparable speeds to how long the code takes to run the simulation 1 timestep forward, so that's reasonable at this point.  Oh -- and it's fully threaded, so it'll take as many processors as I can throw at it.

答:
I think you're after a machine learning clustering algorithm.

This page from the Python SciKit Learn toolkit has pictures that suggest the DBSCAN algorithm (Wikipedia) could be what you're looking for.  It seems ideal as it's input parameter is the neighbourhood size, while most other clustering algorithms want the number of clusters, which you would not know in advance.

"A Density-Based Algorithm for Discovering Clusters in Large Spatial Databases with Noise" Ester, M., H. P. Kriegel, J. Sander, and X. Xu, In Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining, Portland, OR, AAAI Press, pp. 226–231. 1996


问:
How to create unit/integration tests for my web app?
I am currently developing an Ajax chat application that uses PHP on the back-end. Some of the features it has right now are different types of users (admin/mod/banned), public and private rooms, commands, and announcements. I recently learned about unit/integration testing and it sounds like a good alternative to manually testing everything every time I release a new feature.

How can I get started with adding testing functionality into my PHP application?

BTW: The app uses long polling (where PHP holds the connection through usleep() and constantly queries the database until new information is returned) so I think that might be a problem when testing it.

答:
Make sure to understand the difference between unit tests and integration/system tests.

A unit test deals with a part of the code which is granular enough to be able to narrow the search of a bug if the unit test fails. There is no long polling here. No REST calls. No AJAX. No database access. REST, access to files, database calls and all those operations which are exterior to the tested code are mocked, i.e. a mock or a stub is created for everything your tested unit needs.

If you're testing the filtering of products, you'll use a stub which will replace the database and provide sample products to use for testing purposes.

If you're testing whether the purchase action decreases the quantity of the product in the warehouse, you'll use a mock which will ensure that it was indeed called by the tested unit and asked to decrease the quantity.

Depending on the ecosystem and from person to person, the strictness of what can be in an unit test and what cannot vary a lot: you may indeed see some skillful persons using for example database access in their unit tests, while others will find it awful. It's up to you to determine how much you're a purist, and what common sense dictates to you, given your language of choice and the community.

Once you have unit tests covering the critical parts of the application, you can start assembling the parts. Interfaces between different components of a system are good places for mistakes, so the integration of components needs to be tested as well. This is what integration tests are about.

Once all bricks are combined into a system, this system may not be functioning as expected, even if integration tests haven't revealed anything wrong. Here, system tests come into play.

Note that those tests are not the only tests available for a developer or a QA department. There are functional testing, acceptance testing, etc. For example, one of the tests which would hopefully become popular consist of taking a diff image of a webpage, and inspect the possible differences in order to detect both purely client-side rendering as well as server-side processing mistakes.

All this testing may serve for regression testing, i.e. the testing which enables you to ensure a change haven't broken anything. Combined with continuous integration, it enables you to identify exactly what was broken and when, and makes it possible to use continuous delivery, those tests mitigating the risk for a broken revision to be automatically pushed into production.


答:
The refactored example is objectively superior because it has less repeated code. Therefore, that implementation is actually simpler, and probably shorter. There is also the argument that the original code in your example is an ad-hoc implementation of traits (or an awkward expression of the strategy pattern), the result being unnecessarily complex code.

In this case, you should be using decorators, even when most of your devs don't know them. This adds only a single extra concept to that piece of code, which is very cheap considering that programming is generally rich in fancy new concepts. The necessary information can and should be added in a terse comment explaining this feature, which should also contain a link to the relevant docs.

For other language features, the same considerations should be made:

Which version is simpler and expresses a solution closer to the language of the problem domain?

What is the cost of educating future maintainers? Can everything be explained in a short comment, or would you have to hold a lecture on category theory?

What is the cost of not educating future maintainers? Just two extra lines here, or having to write baby code to the end of your life?

Give a man a fish and you feed him for a day.

  Teach a man to fish and feed him for his life.

  Dumb down your code for a programmer and he can understand it at once.

  Teach a programmer advanced techniques, and he'll understand all your future code on his own.

Title: Does usage of advanced language features decrease maintainability?

Body:
On a code review, I've stumbled on an interesting idea, which I can't properly judge alone.

Is it OK to improve readability of code by means of not widely known language syntax? When the original writer didn't use a special syntax designated for solving a specific coding problem, and solved it by simulating with workarounds — is it worth to refactor it for clarity and conciseness? What if even the code reviewer didn't know about the language feature?

To be specific, I'll bring the exact issue I've met on the code review — but keep in mind that this is just an example.

So the original code was a little web service in Python. At some point, there arised a requirement for several request handlers to be protected with an authentication mechanism. Somebody solved it with inheritance:

class AuthOnlyAccess:
    def GET(self, *args):
        if not hasattr(self, 'PROTECTED_GET'):
            raise web.Nomethod()

        if check_auth():
            return self.PROTECTED_GET(*args)
        else:
            raise web.Unauthorised()

    def POST(self, *args):
        if not hasattr(self, 'PROTECTED_POST'):
            raise web.Nomethod()

        if check_auth():
            return self.PROTECTED_POST(*args)
        else:
            raise web.Unauthorised()

...

class FooHandler(AuthOnlyAccess):
    def PROTECTED_GET(self, a, b, c):
        handle_foo_get(a, b, c)

    def PROTECTED_POST(self, x, y, z):
        handle_spam_eggs()

...
<more handlers deriving AuthOnlyAccess>
```

<p>The refactorer found this code ugly and introduced a decorator:</p>

<pre class="lang-py prettyprint-override"><code>from functools import wraps
...

def requires_auth(wrapped_func):
    """ (a little doc telling that this is a decorator and how to use it) """
    @wraps(wrapped_func)
    def decorator(*args):
        if check_auth():
            return wrapped_func(*args)
        else
            raise web.Unauthorized()

    return decorator

...

class FooHandler:
    @requires_auth
    def GET(self, a, b, c):
        handle_foo_get(a, b, c)

    @requires_auth
    def POST(self, x, y, z):
        handle_spam_eggs()

...
<more refactored handlers>
</code>```

The reviewer argues that this change actually decreases maintainability, because most of the team doesn't know decorator syntax. So the next person visiting the refactored code could be puzzled by the construct — but not with the previous version.

There's also a convincing argument that most of the codebase isn't in Python, (the language is there only for that little web service), and hence team members aren't required to have even shallow knowledge of Python. However, to work with code, one's going to need to know its language, right?

And if you have the temptation to say that python decorators aren't that advanced syntax — please remember that this is only an example. Every language has its dark corners. (But to learn those corners means to become better.)

So the question is... Can you read unknown syntax? Is the elegance worth the surprise? At least, what are the tradeoffs and/or guidelines you can name? I do really need some opinions from the community of programming professionals.


问:
Why I'm not selected in an interview?
I'm working in development for 4 years, and 3.5 in PHP - why I don't seem to be able to be selected in an interview.

I want to know what special things the interviewer wants to see in candidates - for senior PHP developer roles.

Interviewer asks me 10 questions and I'm able to answer only 5. Does selection depend on these things? It doesn't mean that I can't solve the problem, I can google the question, I can ask on forums. Why don't they understand that a man can't remember all the answers for each and every question? Especially programming ones.

Please advise.

答:
Another point is how many people are applying for these jobs?  If there are a dozen or more being interviewed and you all have an equal chance of getting the position, the probability is around 8.3% you realize, right?  Sometimes it can come down to a numbers game where you have to go through many interviews to get somewhere.

How many people can match your PHP experience but may have more education or some other differentiating factor?  When you don't answer a question, are you saying that you'd go to Google and have it answer the question for you?  How you phrase something like that could make it come off like the company is hiring someone when they should just get a contract with Google to get the answers.  While some may think that is ridiculous, there are many things in this world that are rather ridiculous yet exist.

Last but not least, there can also be the potential for you wanting something that a company isn't going to give.  For example, how many companies would pay a developer $1,000,000,000 (US) or more?  Very few if any, I'd think.  What kinds of questions are you asking the company?  What kinds of signs are you showing that you want the job and would fit into their culture?  If you make it sound like the company should be lucky that you are even considering working there, that arrogance may well be a contributing factor on why a company doesn't like you.

ContentLicense: CC BY-SA 2.5

Title: Why I'm not selected in an interview?


问:
Discovering functionality from parallel class hierarchy
I have an abstract syntax tree which I want to compile down to different representations. I am now struggling to arrange the classes in a way that new representations can be added easily.

The easiest way to achieve this is to add a method for each representation, e.g. compile_to_foo, compile_to_bar. Additional representations can be added by monkey patching. The problem with this is that the compilation implementations are spread all over the place, and that it violates the single responsibility principle. The advantage is that compilation can be inherited.

Now, I could also define a compilation function containing a giant switch which dispatches on argument type. But this looses advantages of polymorphism, and makes inheriting behavior of the compilation more difficult. This is not a viable option.

An interesting solution would use an abstract factory:

This design looks fairly promising, but has some disadvantages:

The AST Node hierarchy cannot be extended without also extending the AbstractCompiler, and in turn all concrete compilers and their parallel hierarchies of concrete nodes.

The subtyping information of the AST nodes is spead across the whole system. it has to be specified between the AbstractNodes in order to share behaviour (I will be using roles), between the ConcreteNodes in order to share compile implementations, and in at least in the AbstractCompiler to provide default implementations (e.g. method NodeA() { return Node() }). This could be partially solved via metaprogramming.

When an AST is built, this can only compile down to one representation. If I want to have multiple outputs, I need to rebuild the AST with a different ConcreteCompiler.

Ideally, I would just pass a concrete compiler instance as a parameter to the compile method:

… but I have no idea how the compile method could obtain the actual implementation from a parallel class hierarchy (without again using a giant switch on the node type).

I also investigated the Bridge pattern, but the solution does not seem applicable to my problem without creating a thousand little bridges.

I carefully read through this previous question: “Designing a robust architecture for multiple export types?”. The key difference is that the input data (there: equivalent, standalone data represenations) are now hierarchical AST nodes, so that inheritance between the compilation implementations is crucial.

The system will be implemented in Perl, so I'm not restricted to classic OOP, but can also use Metaprogramming, Roles (aka. traits), and Functional Programming.

What am I missing? Is there an architecture I could use to elegantly structure this system? How can I make the corresponding class from the parallel class hierarchy discoverable to the node classes, without sacrificing polymorphism?

答:
If I'm understanding your problem correctly this is exactly the kind of thing the Visitor pattern was designed to solve. Your AST nodes should implement a visit() method that takes a reference to a Visitor base class. The visit method on the AST node calls a method on the Visitor object that corresponds to the type of node it is (passing along any relevant information) then passes the Visitor node to its children.

The Visitor object is what emits your different representations. It has callbacks for each type of AST node you are going to visit, and simply gets passed to each AST node via the node's visit() method. The Visitor will also track any necessary state, etc. If you do things this way then you can easily switch out what you compile to by implementing different Visitors (or specialize similar Visitors in different ways via inheritance, etc.)

This is essentially a way of implementing your "giant switch" in a cleaner more easily extensible way. The only downside is that if you add new types of AST node, you may have to add a new callback for the node type in all your Visitor objects.


问:
Using private vs company devices for development at work
I'm employed at a mobile app development company since 4 months as Android developer. Currently I'm using my two private Android devices for development. Is it common practice that developers use their own hardware devices for development in mobile development companies, or should I ask for company devices?</p>

答:
The answer greatly depends upon the legal jurisdiction you live within.

But let's take the easy considerations first.  As brought up in the comments: what happens when your device breaks or your device injects malware into your team's development stream?

So then you need to ask:

Who pays to fix your device?

Who is responsible to replace your device if you turn it into a brick as part of the development activities?

Who detects that your device is running some malware that has managed to adulterate the application you're distributing?  Who is responsible for fixing all of that?

How do you handle all-night load testing when you need to go home and take your phone with you?

Who pays for the data usage on your phone?

BYOD starts looking ugly in cases like those.

But wait, it gets worse.

Your employer is generally expected to provide the resources you need for you to do your job. That help enables their claim to own the work that you produce.

When you use your equipment to develop for both your employer and your own personal projects, how do you draw the line as to what portions of your time were spent on what projects?  It matters because in the absence of detailed time logs, courts rely upon the resources that were used as part of the work.  Using your employer's resources enables your employer to say the development was done on their time and resource.  So they have a cleaner claim to owning the work you create.

But that's just a generality and each significant legal jurisdiction has nuances upon that generality.  So your particular predicament will be answered by local, legal norms.

A strong intellectual property agreement can help with some of those concerns, but the companies that "expect" developers to bring devices generally don't have strong IP agreements in place.

In general, it's a bad idea.

For the company, the potential claims against intellectual property ownership are significant.  For the developer, it's a bad idea - loaded with negatives and providing minimal direct benefits.


问:
Structuring an input file
I am in the process of structuring a small program to perform some hydraulic analysis of pipe flow. As I am envisioning this, the program will read an input file, store the input parameters in a suitable way, operate on them and finally output results. I am struggling with how to structure the input file in a sane way; that is, in a way that a human can write it easily and a machine can parse it easily. A sample input file made available to me for a similar program is just a stream of comma-separated numbers that don't make much sense on their own, so that's the scenario I am trying to avoid.

Though I am giving the details of my particular problem, I am more interested in general input-file structuring strategies. Is a stream of comma-separated values my best bet? Would I be better off using some sort of key:value structure? I don't know much about this, so any help will probably put me in a better track than I am now.

答:
Take a look at YAML. It is a data serialization language that is designed to be human readable. Here's a sample from the link:

```<code>--- !clarkevans.com/^invoice
invoice: 34843
date   : 2001-01-23
bill-to: &id001
    given  : Chris
    family : Dumars
    address:
        lines: |
            458 Walkman Dr.
            Suite #292
        city    : Royal Oak
        state   : MI
        postal  : 48046
</code>```

There are parsers available for all mainstream languages.

Title: Structuring an input file

Body:
Take a look at YAML. It is a data serialization language that is designed to be human readable. Here's a sample from the link:

--- !clarkevans.com/^invoice
invoice: 34843
date   : 2001-01-23
bill-to: &id001
    given  : Chris
    family : Dumars
    address:
        lines: |
            458 Walkman Dr.
            Suite #292
        city    : Royal Oak
        state   : MI
        postal  : 48046

There are parsers available for all mainstream languages.


问:
Helper functions - well defined inputs or well defined outputs?

Problem

In Codeigniter (PHP framework), I am trying to create a helper function that will inject an ActiveRecord (for MySQL) command into a chain of existing ActiveRecord calls. The reasoning for this is that the current ActiveRecord commands available are not reliable enough, and produce differing results depending on what parameters are passed in.

For example:

```<code>$param = "";
$this->db->where('field', "");
</code>```

produces

```<code>WHERE `field` = ""
</code>```

This would provide a result set where only blank fields were returned.

This is not always the intended behavior, as the input comes from a web form, and may be the result of no specific query being submitted - thus all results should be returned instead.

Attempted solution

What I decided to come up with, was a helper method that would take in a set of unknown inputs, and return a result set that would match my desired behavior (eg. return all results or return none).

Using test cases and a test method to abstract the desired set of inputs and outputs away, I hoped to produce an easy-to-call method for coercing the database results into my desired behavior. This would be easier then say, coercing the input into an expected type, and then using the unreliable behavior of Codeigniter's ActiveRecord commands.

My main concern however, is that my helper function may be trying to do too much - my colleague described it as a magic method that takes anything and may have arcane implementation details. It would thus be less readable than the ActiveRecord convention (which is more well-known) and harder to maintain.

Is my function the best way to go about it, or are there better alternatives out there?

答:
Active Record is just a CRUD pattern... it maps tables and columns in a database to corresponding data structures in a programming language, and provides Create, Read, Update and Delete mechanisms.  It has little to do with business logic, which is what you're describing.

Every method is a "magic" method, according to your colleague's interpretation.  A method is a black box; you pass it parameter data, it returns some corresponding output.  The logic in-between can be almost anything.

Once the logic of that method is proven, you shouldn't have to be concerned with its internal implementation. In fact, that's the basis for test-driven development: you should be able to change the underlying implementation and, if your tests still pass, your application should still exhibit the same behavior.

So to be clear, your helper method is more of a repository or service method.  It really doesn't have much to do with Active Record, except that Active Record may be used by your method to retrieve the necessary data.

This is the whole point of methods, to encapsulate complex behavior.  Your approach is totally sound.


答:
I would use XML files for this, also with an xml schema you set the allowed structure of the input file. This would ensure that everyone creating input files used the exact same format (humans are humans), also more importantly ensures that the program parsing the input file gets exactly what it expects

XML parsing is supporting by all programming languages, is efficient, and is easily read by humans.

Title: Structuring an input file

Body:
I am in the process of structuring a small program to perform some hydraulic analysis of pipe flow. As I am envisioning this, the program will read an input file, store the input parameters in a suitable way, operate on them and finally output results. I am struggling with how to structure the input file in a sane way; that is, in a way that a human can write it easily and a machine can parse it easily. A sample input file made available to me for a similar program is just a stream of comma-separated numbers that don't make much sense on their own, so that's the scenario I am trying to avoid.

Though I am giving the details of my particular problem, I am more interested in general input-file structuring strategies. Is a stream of comma-separated values my best bet? Would I be better off using some sort of key:value structure? I don't know much about this, so any help will probably put me in a better track than I am now.


问:
Can a beginner in programming start learning game development?
I'm very new to programming and I'm using Java. I got interested to learn programming because I want to create games. I love playing computer games and I know that game developers make money. I told myself that instead of just playing why not create my own game and probably make some money.

I read some articles about game development using java and I learned about JMonkey. I just installed it in my Ubuntu PC.

Should I learn first the basics of Java or I can start learning JMonkey and Java at the same time?

I know that JMonkey is game engine built using Java and it provides libraries to help developers create Java games efficiently but its kinda advanced for a dummy like me.

答:
Sure you can - I learnt a lot about Java when I started by writing a simple game.

Just be sure to start with something simple so that you can focus on the basics and don't get discouraged - which is a risk if you take on an ambitious project too soon..

You will probably find it easier to write a simple 2D game (using a library like Slick2D) rather than immediately embarking on a 3D masterpiece (using something like jMonkeyEngine)


答:
I don't know JMonkey, but if you don't know anything about programming, you're going to have a bad time translating your game ideas into code.

Let alone debugging, performance, data structures, control flow, best practices and so on. But that's only the 'game engine' part, have you thought about your game's content?

I think it'll be way easier to just try and create games in something like Unity or GameMaker while learning to program separately.

Title: Can a beginner in programming start learning game development?

Body:
I'm very new to programming and I'm using Java. I got interested to learn programming because I want to create games. I love playing computer games and I know that game developers make money. I told myself that instead of just playing why not create my own game and probably make some money.

I read some articles about game development using java and I learned about JMonkey. I just installed it in my Ubuntu PC.

Should I learn first the basics of Java or I can start learning JMonkey and Java at the same time?

I know that JMonkey is game engine built using Java and it provides libraries to help developers create Java games efficiently but its kinda advanced for a dummy like me.


答:
I come from the ancient era of "we had to code all by ourselves" and that is what I still do. So, I do not know these new "next-generation" 3D engines/environments where you just apply a bit of code here and there and it miraculously turn into a game. (no, its not really like that, just the way I see them)

That is why I am offering my opinionated answer for you to learn java (as that is your choice, it could be any language) by How to;

Make simple application

Draw a shape (circle as an example)

Another shape attached to mouse location (learn about mouse)

Check if these two shapes collide (how collision of circle and square would be different?)

A wild'ish example, which I would suggest to do. From there you can use those learned elements to make simple games like so many mouse clicking games. Learn how to measure time and you can make such game more complex by making player compete against his own reaction times, etc... let your mind think of more things and you stumble on more to learn.

While you do simple thing(s) like this, you are learning all the time and most importantly learning programming language of your choice (java for you).

While you learn more about java, nothing stops you from playing around with jMonkey also. In case you feel stuck in jMonkey, go program simple things in java and feel success, if you get stuck with simple java programming, search stackoverflow... I know from experience that SO has huge coverage in answers to java game programming.
 See, when its not about jMonkey, when its about general java game programming, there is way more answers, so many good tricks and tips to learn.


答:
When you start programming, you have to write something, so it might as well be games. And in fact, yes, you can start writing games right away. Just bear in mind that if your programming skills are basic, then your games will be too. So not Skyrim or even Minecraft. More like "guess the random number."

As your knowledge of programming techniques and patterns progresses, you can comfortably build more complex programs. But bear in mind that it will likely be years before you are at the level where you can build games like those that are popular now.

Starting into programming so you can write games is like starting into metalwork so that you can build cars. Yes, that is certainly a reasonable goal. But just remember that you don't start out working at that level.

Learn the basics first. All of the basics. Because whatever development framework you decide to use for game engines will assume that you already know all of the basics.


问:
ExtJs License for free application
I read much about GPL license. But it couldn't clear my doubt.

I want to develop a small web application using ExtJs because of its features. I won't use much of it. But some features are very good.

Now, as my understanding I think I can give this app to my friend for free for his business needs, right?
Or should I take commercial license for ExtJs?

答:
Yes you can distribute to any of your friends for personal or business needs. But he should share or provide the source code. Which I think any business user will not comply with. I have copied below phrase from ExtJS home page for your reference:

open source application under a license compatible with the GNU GPL license v3. Although the GPLv3 has many terms, the most important is that you must provide the source code of your application to your users so they can be free to modify your application for their own needs.

Link here: ExtJs Licence, Open Source FAQ, GNU, GPL Licence Terms

It's suggested to buy the commercial licence for all commercial applications and support their developers.

Title: ExtJs License for free application


答:
Start with writing very simple game related excercises. Write programs that solve logic and maths problems. Write some animations and graphics effects. Write a lot of really simple stuff, always strive to write neat code, try things out, be creative.

After some months of training you could try writing a simple game. I recommend starting with a simple turn based game, like tic tac toe.

Check out Project Euler. I have found it very useful when learning a new language. It also helps training basic mathematical skills. You are going to need those when writing games.

I also recommend checking out Robocode. It allows you to get into programming some game logic (AI) easily and works as a sandbox for training basic programming skills.

Don't expect to make any money. Have fun instead. If you don't find programming enjoyable, you aren't probably going to make money by programming games.


问:
Rails: Useful example of delegate and Law of Demeter
I am currently learning about delegate and the Law of Demeter. I understand the Law of Demeter, but I can't seem to find a good example of where using delegate to avoid breaking the law would actually even be useful.

I want to find an example related to my project, since I have to give a presentation. The only line of code that I found that could possibly be breaking the Law of Demeter is the following:

@game.promotions.find_by_promo_type("cross")

The model Game has_many Promotions and it is reaching across another model to execute a find call based on promotions attribute promo_type. From my understanding this is a violation of the Law of Demeter, and I should implement the following solution.

```<code>class Game < ActiveRecord::Base
   has_many :promotions

   delegate :find_by_promo_type, :to => :promotion
end
</code>```

Can you give me an example where this would actually be useful besides "the Law of Demeter says so".

The only thing I can think of, is for some reason I wanted to change the name of promotions to promos, then the solution would be useful because I would only need to make the following change and :find_by_promo_type will still work for Game

```<code>class Game < ActiveRecord::Base
   has_many :promos

   delegate :find_by_promo_type, :to => :promos
end
</code>```

The only thing is, I believe this argument is flawed. If I were to change a models name, I would also have to refactor code in many other places that don't even break the Law of Demeter. It's hard to believe that this is all the Law of Demeter can accomplish in regards to this example.

Can somebody please help me understand this.

答:
Let's say, for example, you wanted to cache or log that promotion, only when you access it through Game. Having broken the Law of Demeter, you cannot do this easily. You have to find every reference to .promotions.find_by_promo_type and identify the ones that are applied to Games and change them to .find_promotion_by_promo_type before you can add that code.

If you've delegated it in your code then you simply replace that with a full-blown method (and then rename it, if necessary).

That said, the Law of Demeter should really be called the Guideline of Demeter. It's a very good principle to bear in mind but, as you identified, it can add maintenance to common updates, to avoid a major problem if you make a change that you are 99% sure you'll never make.


问:
Web programming, standard way to deal with a response that takes time to complete
With normal form submission I use the pattern Post / Redirect / Get, when processing the forms.

I have a database application built with Django. I want to allow the users to select a number of items from the database, then launch a computationally intensive task based on those items.

I expect the task to take between 10 minutes and 2 hours to complete.

Is there a standard approach to dealing with requests like this (i.e. that don't return immediately)? Ideally there would be some way to display the progress.

答: I would trigger a job (e.g. a worker-thread) for this which is able to report the progress and finish the current request. And for displaying the process, i would poll the progress of this job via ajax or similar.</p>


答:
The actual thread doing the work must be separate from its association with the session (although you can link it to the user performing the work).  Have a application-scoped class (lets call it JobQuery) which receives job requests and answers queries about current jobs.

Your web application therefore becomes stateless once again.  Whenever you want to know the status of a job, the web application performs an inquiry using JobQuery.

In the case of error, a database component comes in handy.  If the web server crashes or other unexpected problems occur, your JobQuery, in addition to starting jobs, should also keep tabs by writing the status to the database.  If something were to happen, JobQuery can indicate the error status of incompleted jobs or even pick up where it left off.

What's important here is that the session-scoped side of your web application is free to continue responding to the user and continues to be stateless while ensuring that 2 hour jobs are not lost in the void in the case of problems.

Title: Web programming, standard way to deal with a response that takes time to complete

Body:
With normal form submission I use the pattern Post / Redirect / Get, when processing the forms.

I have a database application built with Django. I want to allow the users to select a number of items from the database, then launch a computationally intensive task based on those items.

I expect the task to take between 10 minutes and 2 hours to complete.

Is there a standard approach to dealing with requests like this (i.e. that don't return immediately)? Ideally there would be some way to display the progress.


问:
Unit Testing of JavaScript - Are we testing the logic of the code or the behavior against a browser
[Warning]: I am new to the whole unit testing and have been trying to learn as much as possible.

I am working on a MS CRM 2011 project and I have been trying to introduce unit testing in my company. For unit testing JavaScript web resources, I found this link at MSDN blog.

The Solutions Architect in my company suggest that this is a bad approach as we are not even testing against the IE's JS engine but testing using CScript (Windows Host) and while I agree to that point, isn't the whole idea of Unit Testing all about testing the individual function's functionality and not about the dependency.

For testing whether it will work within IE, would a testing tool such as Selenium not be better?

Or am I missing something?

答:
According to Wikipedia, "JScript" in IE is based on the same scripting engine as JScript in Windows Scripting Host. So generally, the approach to use the WSH / CScript for unit testing of JScript functions targeting at IE is fine. You should, however, make sure that the IE version (or the JS version which is supported in the related IE versions) matches the WSH version you are using for your tests.

In fact, what you indeed cannot test by the CScript approach is how your code behaves within the browser, especially when you have functions using the rendering engine of the IE, or which are relying on browser events. For those parts of your code, a browser automation tool like Selenium maybe more appropriate. However, with Selenium you are typically creating automated integration tests, not unit tests.

For a good test suite, you probably need both - unit tests for browser-independent functions and (automated) integration tests for browser-dependent functions. So it should not be a decision of "either this or that", use both, and each tool for the specific kind of test.

ContentLicense: CC BY-SA 4.0


答:
Celery is a setup for django which is designed for exactly this type of situation. You can launch a background task and let it run asynchronously as its own worker thread.

Someone has also made an AJAX loading bar to show the progress of the job.


问:
Why do some big projects, like Git and Debian, only use a mailing list and not an issue tracker?
Bug tracker for any decent sized project seem like a bit of a no-brainer to me - it makes it really easy to organise hundreds or thousands issues, without issues colliding or getting mixed up.

So when I see some really big projects, like Git, using a mailing list as the main method of coordinating maintenance and development, I get a bit blown away. Examples:

Git - Community page:

...Bug reports should be sent to this mailing list.

Debian bug tracking system, per Wikipedia:

...Its unique feature is that it doesn't have any form of web-interface to edit bug reports - all modification is done through email.

Many modern bug trackers have very good integration with email (you can receive comments or notifications about bugs you're watching, or that get assigned to you), as well as to version control systems (commits can be marked as resolving an issue, etc.). Much of this would have to be done manually with a mailing list, and you get tons of emails about bugs you're not interested in.

So what are the main advantages of a mailing list over a web-based bug tracker? Why do some big projects only use a mailing list?

答:
Debian does use a bug tracker, its default interface is email. And it is convenient. Lucas Nussbaum, current Debian Project Leader, posted a few days ago:

debbugs is the piece of software behind the Debian Bugs Tracking System
  (BTS). It is also used by the GNU project. Despite often being
  perceived as old-style, it features several unique features, such as the
  tracking of the status of bugs in each version and branch of a package
  ), or the ability to perform all interactions via email, making it very easy to work offline or in poorly-connected environments.

The last part is a killer feature here - just queue those reports in your local mail queue until you got off the plane!


问:
Empty interface to combine multiple interfaces
Suppose you have two interfaces:

```<code>interface Readable {
    public void read();
}

interface Writable {
    public void write();
}
</code>```

In some cases the implementing objects can only support one of these but in a lot of cases the implementations will support both interfaces. The people who use the interfaces will have to do something like:

```<code>// can't write to it without explicit casting
Readable myObject = new MyObject();

// can't read from it without explicit casting
Writable myObject = new MyObject();

// tight coupling to actual implementation
MyObject myObject = new MyObject();
</code>```

None of these options is terribly convenient, even more so when considering that you want this as a method parameter.

One solution would be to declare a wrapping interface:

```<code>interface TheWholeShabam extends Readable, Writable {}
</code>```

But this has one specific problem: all implementations that support both Readable and Writable have to implement TheWholeShabam if they want to be compatible with people using the interface. Even though it offers nothing apart from the guaranteed presence of both interfaces.

Is there a clean solution to this problem or should I go for the wrapper interface?

UPDATE

It is in fact often necessary to have an object that is both readable and writable so simply seperating the concerns in the arguments is not always a clean solution.

UPDATE2

(extracted as answer so it's easier to comment on)

UPDATE3

Please beware that the primary usecase for this is not streams (although they too must be supported). Streams make a very specific distinction between input and output and there is a clear separation of responsibilities. Rather, think of something like a bytebuffer where you need one object you can write to and read from, one object that has a very specific state attached to it. These objects exist because they are very useful for some things like asynchronous I/O, encodings,...

UPDATE4

One of the first things I tried was the same as the suggestion given below (check the accepted answer) but it proved to be too fragile.

Suppose you have a class that has to return the type:

```<code>public <RW extends Readable & Writable> RW getItAll();
</code>```

If you call this method, the generic RW is determined by the variable receiving the object, so you need a way to describe this var.

```<code>MyObject myObject = someInstance.getItAll();
</code>```

This would work but once again ties it to an implementation and may actually throw classcastexceptions at runtime (depending on what is returned).

Additionally if you want a class variable of the type RW, you need to define the generic at the class level.

答:
If there is a place where you need myObject as both a Readable and Writable you can:

Refactor that place? Reading and writing are two different things. If a method does both, perhaps it doesn't follow the single responsibility principle.

Pass myObject twice, as a Readable and as a Writable (two arguments). What does the method care whether it is or isn't the same object?


答:
Yes, you can declare your method parameter as an underspecified type that extends both Readable and Writable:

```<code>public <RW extends Readable & Writable> void process(RW thing);
</code>```

The method declaration looks terrible, but using it is easier than having to know about the unified interface.

Title: Empty interface to combine multiple interfaces

Body:
Suppose you have two interfaces:

```<code>interface Readable {
    public void read();
}

interface Writable {
    public void write();
}
</code>```

In some cases the implementing objects can only support one of these but in a lot of cases the implementations will support both interfaces. The people who use the interfaces will have to do something like:

```<code>// can't write to it without explicit casting
Readable myObject = new MyObject();

// can't read from it without explicit casting
Writable myObject = new MyObject();

// tight coupling to actual implementation
MyObject myObject = new MyObject();
</code>```

None of these options is terribly convenient, even more so when considering that you want this as a method parameter.

One solution would be to declare a wrapping interface:

```<code>interface TheWholeShabam extends Readable, Writable {}
</code>```

But this has one specific problem: all implementations that support both Readable and Writable have to implement TheWholeShabam if they want to be compatible with people using the interface. Even though it offers nothing apart from the guaranteed presence of both interfaces.

Is there a clean solution to this problem or should I go for the wrapper interface?

UPDATE

It is in fact often necessary to have an object that is both readable and writable so simply seperating the concerns in the arguments is not always a clean solution.

UPDATE2

(extracted as answer so it's easier to comment on)

UPDATE3

Please beware that the primary usecase for this is not streams (although they too must be supported). Streams make a very specific distinction between input and output and there is a clear separation of responsibilities. Rather, think of something like a bytebuffer where you need one object you can write to and read from, one object that has a very specific state attached to it. These objects exist because they are very useful for some things like asynchronous I/O, encodings,...

UPDATE4

One of the first things I tried was the same as the suggestion given below (check the accepted answer) but it proved to be too fragile.

Suppose you have a class that has to return the type:

```<code>public <RW extends Readable & Writable> RW getItAll();
</code>```

If you call this method, the generic RW is determined by the variable receiving the object, so you need a way to describe this var.

```<code>MyObject myObject = someInstance.getItAll();
</code>```

This would work but once again ties it to an implementation and may actually throw classcastexceptions at runtime (depending on what is returned).

Additionally if you want a class variable of the type RW, you need to define the generic at the class level.

Body:
Yes, you can declare your method parameter as an underspecified type that extends both Readable and Writable:

public <RW extends Readable & Writable> void process(RW thing);

The method declaration looks terrible, but using it is easier than having to know about the unified interface.


答:
First of all, I would say that coding conventions are a place where restrictions on language usage are stored. Otherwise every time people will have different idea about what is familiar for a team and what isn't.

When choosing a subset you create a new language. It certainly shares many things with "host" language, but is different. Some things may become simpler, some - harder.

Why define subset:

Host language has features considered dangerous (e.g. limiting preprocessor in C++)

Your needs are much smaller than language abilities (e.g. JSON as a subset of JavaScript)

You have specific needs (e.g. supporting old versions of a compiler without support for the newest language features)

Why stick to the whole language:

The new features are there for a reason (e.g. your case)

Better support ("how to solve it in LISP?" will be answered faster than "how to solve this in LISP without lambda functions")

Hiring new developers simpler (for subset the candidates should be able and comfortable to work under restrictions you have)

You trust that the whole language was designed by better language designer(s) than you :)


问:
Should selenium tests be written in imperative style?
Is an automation tester supposed to know concepts of OOPS and design patterns to write Tests in a way where changes & code re-use are possible?

For example, I pick up Java to write cucumber step definitions that instruct a selenium webdriver.

Should I be using a lot of inheritance, interfaces, delegation etc. to make life easier or would that be overly complicated for something that should just line by line instructions?

答:
Test code is code that needs to be read, executed and maintained, just like production code, so it should be subjected to the same standards as production code.

Just use inheritance, interfaces, whatnot, where it makes sense and where it helps you build a maintainable selenium script.

P.S.: the PageObject is a commonly used pattern for Selenium, where you create a class that exposes the buttons, fields, etc. of a page as properties and methods of a class. See PageObjects for more.


问:
Construct your solution logic in syntax or in a faster and more efficient mental model?
I am a newbie, studying programming and I came across this question today:

How can I make sure that I'm actually learning how to program rather than simply learning the details of a language?

A commenter, ChaosPandion, had asked the question if the programmer thinks in syntax or in a faster mental model.

I, while writing a solution will always think about the number of loops or condition to be used (for example). Am I doing it wrong? If so, how can I correct myself and what should I learn?

答:
Just keep programming. Given enough and diverse practice you will notice one day (may be a year from now), that you are at the new height and can "program everything".

Hard to tell about programmers in general, but I do not think it's "thinking in syntax". One just translates thought to syntax, which usually becomes a habbit. That is why dynamic and expressive languages like Python are so popular: they allow to write at the speed of thought.

So yes, with practice you will arrive at faster mental model, which, with even more practive, will encompass even more entities at a time.

Do not forget to read some theory on data structures and algorithms, because, while not critical to get programming skills, it adds diversity to your thinking.

Syntax is what conveys semantics. And programmer deals with semantics of solution, syntax being a mean to tell semantics to computer compiler/interpreter.

Number of loops may need to be counted if you are using too many nested loops. But analizing complexity of an algorithm is a theory of it's own.

Also, IMHO, programming is a skill like riding a bike: once learned (you will notice the jump to the new level!), it's there with you. There are different paradigms and approaches (imperative, functional, logical, you name it), but the core skill spans them well, and is not unlike to core of mathematical thinking, i.e. ability to formalize and operate with symbols.


问:
Emacs-as-OS: obsolete?
In an attempt to reach at least beginner status with such a legendary editor, I have been coding in Emacs for the last two months.  I try to keep an open heart, but I find myself continally disagreeing with one core design choice: that Emacs allow its users to never have to leave.  In a 2010 world, I just think that every side feature of Emacs is hopelessly behind dedicated software:

I would never use its built-in browser; Chrome is years ahead.

I would never use its dired feature; Path Finder (Mac OS X) suits my needs.

I would never use its built-in email; the Gmail web interface has more relevant features like Priority Inbox.

Etc.

Sure, I might occasionally dip into Emacs to use regexps, etc. for one of the above tasks, but other than regexps, I really see no reason to ever touch those side features.  I'm a completely newbie, yet I have a strong gut feeling that Emacs-as-an-OS is obsolete.

Emacs experts, do you think that Emacs' choice to be a comprehensive environment is the right choice for 2010 and the future?  Are there particular peripheral features that are still at or ahead of their time compared to alternatives?

答:
Choose the right tool for the job.

Try running Chrome or Path Finder through an ssh connection - here you will need alternative toolings and Emacs was designed to run in a terminal.

Title: Emacs-as-OS: obsolete?


问:
clone/copy constructor and child class
I just want feedback on what one considers 'most elegant design' for a situation like this.

I have an object that is immutable with some (sort of) copy constructors to allow creating a similar but modified version of my immutable object.  So something like this:

```<code>class ImmutableObject{
   Fee fee;
   Fi  fi;
   Fo fo;

   public ImmutableObject(Fee fee, Fi fi, Fo fo){
        this.Fee=fee;
        this.fi=fi;
        this.fo=fo;
   }

   public ImmutableObject(ImmutableObject cloneObj, Fee fee){
      this.fi=cloneObj.fi;
      this.fo=cloneObj.fo;
      this.fee=fee;
   }

   public ImmutableObject(ImmutableObject cloneObj, Fi fi){
      this.fee=cloneObj.fee;
      this.fo=cloneObj.fo;
      this.fi=fi
   }

   public ImmutableObject(ImmutableObject cloneObj, Fo fo){
      this.fi=cloneObj.fi;
      this.fee=cloneObj.fee;
      this.fo=fo;
   }
}
</code>```

I'm now expanding this by creating a sub-class with extra behavior:

```<code> Class ImmutableChild extends ImmutableObject{

   Fum fum;

   ImmutableChild(Fee fee, Fi fi, Fo fo, Fum fum){
      super(fee, fi, fo);
      this.fum=fum;
   }
</code>```

The problem is that I have a collection of 'ImmutableObjects' that contain both original and child classes.  When I try to clone them to get a new object with one modifid element My copy constructors will always create a class of parent type 'ImmutableObject' type and completely loose the state of 'fum' if I'm actually cloning the child class.

I can easily refactor this to meet any solution I want, copy constructor, clone methods etc.  However, while I can get the behavior I want, I'm not sure what would be considered both elequant and non-ridged solution.  What is the cleanest method to allow a method that will create a 'clone' of my object with one value modified which works well with children classes that expand functionality?

答:
Were it not for the complication of accepting possible modifying arguments you would simply provide a virtual clone() method in ImmutableObject that instantiates and then returns a pointer to an ImmutableObject.  Derived classes override the function and instantiate their own derived type but still return it as ImmutableObject.

As for the extra arguments passed to the "copy constructors", the code doing the copying or calling the clone() method is aware of these differences so can simply clone the object and then change the clone if and how required.

You might want to consider carrying simple type information in the base class - an enumeration would do - if you need to downcast a cloned object later.

Title: clone/copy constructor and child class


答:
How a programmer thinks about a problem (and a solution) depends greatly on how they think about things in general, the problem itself and their level of experience in particular. Let's go through them in order:

How people think in general

Different people learn, and think differently. Personally, I am an extremely visual thinker, and tend to use a lot of intuition about how things "fit". That's literally because I have a mental model for different patterns, modules and dependencies within the code. When I can't arrange them into a nice shape, I know the solution isn't adequate.

Others are very logical, they have sets of facts that they look to reduce into a result. Yet others are tied to verbal or auditory sort of learning. They need to hear a problem described to understand the relations and emphasises of it. And of course, nobody is "just" visual or "just" verbal. They mix and match at different levels.

The problem itself

Different problems require different solutions. When I'm designing a architecture to handle thousands of transactions a second, I think about it differently than I do trying to make a scheduling algorithm. They have different needs, and using different problem solving approaches allow me to be more effective than using the same approach for everything.

The Programmer's experience level

When beginners start out, they know syntax and (if they're lucky) they have a good grasp of the concept of variables. When presented with a programming problem, they're going to tackle it with these concepts, because that is what they know.

As they gain experience (especially with different languages/paradigms) they begin to abstract away the concrete syntax into concepts. Instead of thinking "oh make a class that inherits from XYZ" they can think "I need some sort polymorphism here". Design Patterns (when used well) are the sort of thing that extends this further so that the programmer can think about tools that encompass broader swaths of syntax.

This is the primary reason that "learn a variety of programming language paradigms" is a common suggestion in the development of programmers. It's also why C++ has greatly fallen out of favor as a first programming language (in some circles) - you spend too much time thinking about syntax and not learning how to solve problems.

(tl;dr) In general, for most problems, programmers move from thinking in syntax to thinking in their own mental model as they gain more experience.

Title: Construct your solution logic in syntax or in a faster and more efficient mental model?

Body:
I am a newbie, studying programming and I came across this question today:

How can I make sure that I'm actually learning how to program rather than simply learning the details of a language?

A commenter, ChaosPandion, had asked the question if the programmer thinks in syntax or in a faster mental model.

I, while writing a solution will always think about the number of loops or condition to be used (for example). Am I doing it wrong? If so, how can I correct myself and what should I learn?


答:
If you need to Unit Test in the browser, I wholly recommend you look  at Karma. You can run your test simultaneously on any number of browsers, on any number of devices.

And your architect is right : you must test in the correct runtime. Otherwise, you may end up using something that does not work correctly on a supported browser ( for example Array#map which does not work on IE8 ). The same way you should run .NET4.0 unit tests in a .NET4.0 runtime. With JavaScript, especially with older IEs, assume that even basic stuff can break and should be tested.

If your looking for a good tutorial for unit testing JavaScript, you may want to look at James Shore JavaScript TDD. It really explain not only how to do Unit Test, but also how to do a proper test driven development and how to structure your application and development for tests. Its a bit biaised toward node.js but you can skip the server part. First week is free! If you're new to unit test you will probably learn a lot.

Title: Unit Testing of JavaScript - Are we testing the logic of the code or the behavior against a browser

Body:
[Warning]: I am new to the whole unit testing and have been trying to learn as much as possible.

I am working on a MS CRM 2011 project and I have been trying to introduce unit testing in my company. For unit testing JavaScript web resources, I found this link at MSDN blog.

The Solutions Architect in my company suggest that this is a bad approach as we are not even testing against the IE's JS engine but testing using CScript (Windows Host) and while I agree to that point, isn't the whole idea of Unit Testing all about testing the individual function's functionality and not about the dependency.

For testing whether it will work within IE, would a testing tool such as Selenium not be better?

Or am I missing something?


答:
I don't even use the built-in therapist that much, but I do use Emacs and I like it, not because of it's comprehensive nature but because it is endlessly configurable and powerful as a text editor. Also I know a lot of the keystrokes for it. Successful text editing is all about the keystrokes.

If you want to develop your productivity with it, Steve Yegge has some good tips.

Title: Emacs-as-OS: obsolete?

Body:
In an attempt to reach at least beginner status with such a legendary editor, I have been coding in Emacs for the last two months.  I try to keep an open heart, but I find myself continally disagreeing with one core design choice: that Emacs allow its users to never have to leave.  In a 2010 world, I just think that every side feature of Emacs is hopelessly behind dedicated software:

I would never use its built-in browser; Chrome is years ahead.

I would never use its dired feature; Path Finder (Mac OS X) suits my needs.

I would never use its built-in email; the Gmail web interface has more relevant features like Priority Inbox.

Etc.

Sure, I might occasionally dip into Emacs to use regexps, etc. for one of the above tasks, but other than regexps, I really see no reason to ever touch those side features.  I'm a completely newbie, yet I have a strong gut feeling that Emacs-as-an-OS is obsolete.

Emacs experts, do you think that Emacs' choice to be a comprehensive environment is the right choice for 2010 and the future?  Are there particular peripheral features that are still at or ahead of their time compared to alternatives?


问:
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?

答:
Let's clarify some terminology first.  When the FSF says a license is compatible with the GPL they don't mean what many people interpret that to mean.  Many interpret "compatible" to mean the two pieces of software can happily co-exist in the same application.

That's close to what the FSF means, but the copyleft provision of the GPL takes things a little bit further.

From the GPL FAQ, emphasis mine.

It means that the other license and the GNU GPL are compatible; you can combine code released under the other license with code released under the GNU GPL in one larger program.

  All GNU GPL versions permit such combinations privately; they also permit distribution of such combinations provided the combination is released under the same GNU GPL version.

So a license is compatible with the GPL if its terms can be absorbed underneath the GPL.

So let's look at the APLv2 and the GPLv3.

APLv2_Lib + GPLv3_Lib => Combined lib as GPLv3 is okay.

APLv2_Lib + GPLv3_Lib => Combined lib as APLv2 is not okay.

And Apache says as much here:

We avoid GPLv3 software because merely linking to it is considered by the GPLv3 authors to create a derivative work. We want to honor their license.

But you're working with a daemon that was licensed under GPLv2, not v3.

FSF is pretty clear that what you want to do is not acceptable for a public distribution.

Please note that this license is not compatible with GPL version 2, because it has some requirements that are not in that GPL version. These include certain patent termination and indemnification provisions.

So, to answer your question:

No, you may not distribute the combined daemon using GPLv2 and APLv2 licensed material.

FSF explicitly calls out that combination as not allowable for public distribution.

Alternatives:

You are allowed to use it privately.

You would also be okay to re-write the APLv2 functionality and then combine your new work with the GPLv2 work.

You could see if the daemon can be changed to GPLv3.  If so, you would then be in the clear to merge the APLv2 work into the now GPLv3 daemon.


答:
Your statement that you sometimes think about the "number of loops or condition to be used" is actually a particularly good discussion point.

Observe this code here where you have to explicitly think about the number of loops and the condition:

```<code>for(i=0; i<data.size(); ++i) { action_func(data[i]); }
</code>```

and this code here - which achieves the same result - where you don't:

```<code>std::foreach(data.begin(), data.end(), action_func);
</code>```

My interpretation of what is an efficient/faster mental model of programming is that someone who has one, doesn't add complexity when it isn't needed and sees right to the core problem and not the peripheral ones. This is important because programming is about seeing layers of abstraction from the highest to the lowest level - it is about working vertically in a stack through these layers - not complicating things horizontally.  That's the only way to achieve the writing of application code that actually works in a reasonable timescale. Embellishment within a layer comes later. Think Agile - getting from A to B (e.g. client GUI to server-side database) as quickly as possible.

So in the example above, there is no need to talk about loops or conditions - it's not what is trying to be achieved so you don't worry about it and you use the programming constructs at your command that avoid that issue (and a whole class of bugs associated with it). Maybe later, if action_func becomes something more complex you might need to explicitly count the loop.
Programming is about expressing what you want to do in the most concise way. In many ways you don't care about syntax - the compiler/interpreter will help you get it right. You care more about the conceptual exactness of what you are trying to do (then you simply search SE for how to write that with correct syntax :)

As to the question - what to learn? My advice is to learn functional programming techniques/learn a functional language where there is a clear separation between algorithm and secondary effects and most concepts you'll learn will have mileage in all mainstream programming languages.

Body:
Your statement that you sometimes think about the "number of loops or condition to be used" is actually a particularly good discussion point.

Observe this code here where you have to explicitly think about the number of loops and the condition:

for(i=0; i<data.size(); ++i) { action_func(data[i]); }

and this code here - which achieves the same result - where you don't:

std::foreach(data.begin(), data.end(), action_func);

My interpretation of what is an efficient/faster mental model of programming is that someone who has one, doesn't add complexity when it isn't needed and sees right to the core problem and not the peripheral ones. This is important because programming is about seeing layers of abstraction from the highest to the lowest level - it is about working vertically in a stack through these layers - not complicating things horizontally.  That's the only way to achieve the writing of application code that actually works in a reasonable timescale. Embellishment within a layer comes later. Think Agile - getting from A to B (e.g. client GUI to server-side database) as quickly as possible.

So in the example above, there is no need to talk about loops or conditions - it's not what is trying to be achieved so you don't worry about it and you use the programming constructs at your command that avoid that issue (and a whole class of bugs associated with it). Maybe later, if action_func becomes something more complex you might need to explicitly count the loop.
Programming is about expressing what you want to do in the most concise way. In many ways you don't care about syntax - the compiler/interpreter will help you get it right. You care more about the conceptual exactness of what you are trying to do (then you simply search SE for how to write that with correct syntax :)

As to the question - what to learn? My advice is to learn functional programming techniques/learn a functional language where there is a clear separation between algorithm and secondary effects and most concepts you'll learn will have mileage in all mainstream programming languages.


问:
Is inline SQL still classed as bad practice now that we have Micro ORMs?
This is a bit of an open ended question but I wanted some opinions, as I grew up in a world where inline SQL scripts were the norm, then we were all made very aware of SQL injection based issues, and how fragile the sql was when doing string manipulations all over the place.

Then came the dawn of the ORM where you were explaining the query to the ORM and letting it generate its own SQL, which in a lot of cases was not optimal but was safe and easy. Another good thing about ORMs or database abstraction layers were that the SQL was generated with its database engine in mind, so I could use Hibernate/Nhibernate with MSSQL, MYSQL and my code never changed it was just a configuration detail.

Now fast forward to current day, where Micro ORMs seem to be winning over more developers I was wondering why we have seemingly taken a U-Turn on the whole in-line sql subject.

I must admit I do like the idea of no ORM config files and being able to write my query in a more optimal manner but it feels like I am opening myself back up to the old vulnerabilities such as SQL injection and I am also tying myself to one database engine so if I want my software to support multiple database engines I would need to do some more string hackery which seems to then start to make code unreadable and more fragile. (Just before someone mentions it I know you can use parameter based arguments with most micro orms which offers protection in most cases from sql injection)

So what are peoples opinions on this sort of thing? I am using Dapper as my Micro ORM in this instance and NHibernate as my regular ORM in this scenario, however most in each field are quite similar.

What I term as inline sql is SQL strings within source code. There used to be design debates over SQL strings in source code detracting from the fundamental intent of the logic, which is why statically typed linq style queries became so popular its still just 1 language, but with lets say C# and Sql in one page you have 2 languages intermingled in your raw source code now. Just to clarify, the SQL injection is just one of the known issues with using sql strings, I already mention you can stop this from happening with parameter based queries, however I highlight other issues with having SQL queries ingrained in your source code, such as the lack of DB Vendor abstraction as well as losing any level of compile time error capturing on string based queries, these are all issues which we managed to side step with the dawn of ORMs with their higher level querying functionality, such as HQL or LINQ etc (not all of the issues but most of them).

So I am less focused on the individual highlighted issues and more the bigger picture of is it now becoming more acceptable to have SQL strings directly in your source code again, as most Micro ORMs use this mechanism.

Here is a similar question which has a few different view points, although is more about the inline sql without the micro orm context:

https://stackoverflow.com/questions/5303746/is-inline-sql-hard-coding

答:
What you are describing as "Inline SQL" should really be called "string concatenation without parameterization," and you don't have to do that to use a Micro ORM safely.

Consider this Dapper example:

```<code>string sql = "SELECT * from user_profile WHERE FirstName LIKE @name;";
var result = connection.Query<Profile>(sql, new {name = "%"+name+"%"});
</code>```

It's fully parameterized, even though string concatenation is taking place.  See the @ sign?

Or this example:

```<code>var dog = connection.Query<Dog>("select Age = @Age, Id = @Id",
          new { Age = (int?)null, Id = guid });
</code>```

which is roughly equivalent to the following ADO.NET code:

```<code>List<Dog> dog = new List<Dog>();
using(var cmd = connection.CreateCommand()) {
    cmd.CommandText = "select Age = @Age, Id = @Id";
    cmd.Parameters.AddWithValue("Age", DBNull.Value);
    cmd.Parameters.AddWithValue("Id", guid);
    using(var reader = cmd.ExecuteReader()) {
        while(reader.Read()) {
            int age = reader.ReadInt32("Age");
            int id = reader.ReadInt32("Id");
            dog.Add(new Dog { Age = age, Id = id });
        }
    }
}
</code>```

If you need more flexibility than this, Dapper provides SQL Templates and an AddDynamicParms() function.  All SQL Injection safe.

So why use SQL strings in the first place?

Well, for the same reasons you would use custom SQL in any other ORM.  Maybe the ORM is code-generating sub-optimal SQL, and you need to optimize it.  Maybe you want to do something that is difficult to do in the ORM natively, like UNIONs.  Or, maybe you simply want to avoid the complexity of generating all those proxy classes.

If you really don't want to write a SQL string for every CRUD method in Dapper (who does?), you can use this library:

https://github.com/ericdc1/Dapper.SimpleCRUD/

That will get you extremely simple and straightforward CRUD, while still giving you the flexibility of hand-written SQL statements.  Remember, the ADO.NET example above was the way everyone did it before ORM's came along; Dapper is just a thin veneer over that.

Body:
What you are describing as "Inline SQL" should really be called "string concatenation without parameterization," and you don't have to do that to use a Micro ORM safely.

Consider this Dapper example:

string sql = "SELECT * from user_profile WHERE FirstName LIKE @name;";
var result = connection.Query<Profile>(sql, new {name = "%"+name+"%"});

It's fully parameterized, even though string concatenation is taking place.  See the @ sign?

Or this example:

var dog = connection.Query<Dog>("select Age = @Age, Id = @Id",
          new { Age = (int?)null, Id = guid });

which is roughly equivalent to the following ADO.NET code:

List<Dog> dog = new List<Dog>();
using(var cmd = connection.CreateCommand()) {
    cmd.CommandText = "select Age = @Age, Id = @Id";
    cmd.Parameters.AddWithValue("Age", DBNull.Value);
    cmd.Parameters.AddWithValue("Id", guid);
    using(var reader = cmd.ExecuteReader()) {
        while(reader.Read()) {
            int age = reader.ReadInt32("Age");
            int id = reader.ReadInt32("Id");
            dog.Add(new Dog { Age = age, Id = id });
        }
    }
}

If you need more flexibility than this, Dapper provides SQL Templates and an AddDynamicParms() function.  All SQL Injection safe.

So why use SQL strings in the first place?

Well, for the same reasons you would use custom SQL in any other ORM.  Maybe the ORM is code-generating sub-optimal SQL, and you need to optimize it.  Maybe you want to do something that is difficult to do in the ORM natively, like UNIONs.  Or, maybe you simply want to avoid the complexity of generating all those proxy classes.

If you really don't want to write a SQL string for every CRUD method in Dapper (who does?), you can use this library:

https://github.com/ericdc1/Dapper.SimpleCRUD/

That will get you extremely simple and straightforward CRUD, while still giving you the flexibility of hand-written SQL statements.  Remember, the ADO.NET example above was the way everyone did it before ORM's came along; Dapper is just a thin veneer over that.


问:
What to call requirements that are "assumed"/"invisible"/"very obvious"
I'm looking for an umbrella term for all the nitty-gritty requirements that it's helpful to have specified up front but which the client never thinks about in his excitement about the product.

In the client's mind, they think of the headline requirements, the main user stories such as "I need to be able to view the status of all equipment" and "I need to receive automatically any notification equipment failure". But at times the mundane ones are there but the client never mentions them until the result differs from his unspoken expectations: "Well of course a user must be able to change his own password" and "Of course the user's session must time out after 30 mins"

Any development team can anticipate what's likely to be needed but is there a name for this category of requirements? Obvious/infrastructural/boring/details?

答:
Infrastructure details are called "non-functional" requirements.  It's a weird term describing those requirements that are not visible to the end-user, but are still necessary for the application to function properly.

However,

The application shall provide a mechanism for allowing the user to change his password

and

The user session must time out after 30 minutes

are not non-functional requirements, and they are not obvious.  Always capture such requirements, and put them in your requirements matrix.


答: I'd categorize those as "implicit" requirements.  Like "User must be able to log in" implies that there is the notion of a User (with an associated database table/store of some sort), some notion of a password or other credentials, and the requirement to store the user ID or some other token in the session.  This further implied (to me, anyway) that there must be some kind of user maintenance process for adding and removing users, and probably a report of some kind showing user name, first login date, last login date, associated e-mail account and anything else you're keeping track of.</p>

Title: What to call requirements that are "assumed"/"invisible"/"very obvious"

Body:
I'm looking for an umbrella term for all the nitty-gritty requirements that it's helpful to have specified up front but which the client never thinks about in his excitement about the product.

In the client's mind, they think of the headline requirements, the main user stories such as "I need to be able to view the status of all equipment" and "I need to receive automatically any notification equipment failure". But at times the mundane ones are there but the client never mentions them until the result differs from his unspoken expectations: "Well of course a user must be able to change his own password" and "Of course the user's session must time out after 30 mins"

Any development team can anticipate what's likely to be needed but is there a name for this category of requirements? Obvious/infrastructural/boring/details?


问:
Why I'm not selected in an interview?
I'm working in development for 4 years, and 3.5 in PHP - why I don't seem to be able to be selected in an interview.

I want to know what special things the interviewer wants to see in candidates - for senior PHP developer roles.

Interviewer asks me 10 questions and I'm able to answer only 5. Does selection depend on these things? It doesn't mean that I can't solve the problem, I can google the question, I can ask on forums. Why don't they understand that a man can't remember all the answers for each and every question? Especially programming ones.

Please advise.

答:
I always tell people to try asking the interviewer that turned you down what might have improved your candidacy. Even if you get a response from 1 out of 10 interviewers, you won't be guessing (or asking others to guess).

I ask every time, have only ever had one person refuse, and I always get great feedback. The sample size is low though (4).

Title: Why I'm not selected in an interview?


答:
I think that the closest thing that I can think of would be a "derived requirement". These are requirements that are generated by the development team, based on a number of sources such as regulatory agencies, corporate guidelines, and past experiences on similar projects.

However, even after you derive additional requirements from the customer/user requirements, it's important to validate them with the customer/user to ensure that they are correct. After you validate them, you track them just like every other requirement. Note that just because some guideline or experience suggests a requirement doesn't mean that the customer wants it. In fact, it could be contrary to what is expected from the system.