答:
Tests are valuable. At the very least, they record that somebody considered that they should spend time writing them, so presumably they had some value to somebody once. With luck, they will contain a complete record of all the features and bugs that the team has ever worked on – though they may also just have been a way to hit some arbitrary test coverage number without being carefully thought through. Until you look at them, you won't know which is the case here.

If most of your tests pass most of the time, then just bite the bullet and invest the time in figuring out what the few tests that fail were trying to do, and either fixing or improving them so that the job will be easier next time. In that case, skip forward to the Determine the intent for each test section, for some advice on what to do with a small number of failing tests.

On the other hand, you may be faced with a Red build now, and hundreds or even thousands of tests which haven't passed for a while, and Jenkins hasn't been Green for a long time. At this point, the Jenkins build status has become useless, and a key indicator of problems with your check-in is no longer working. You need to fix this, but can't afford to stop all forward progress while you tidy up the mess in your living room.

In order to keep your sanity while performing the required archaeology to determine what value can be recovered from the tests which have been failing, I'd recommend the following steps:

Temporarily disable the failing tests.

There are several ways you could do this, depending on your environment, which you don't clearly describe so I can't really recommend any particular one.

Some frameworks support the notion of expected failures. If yours does, then this is great, as you'll see a countdown of how many tests are left in this category, and you'll even be informed if some of them start passing unexpectedly.

Some frameworks support test groups, and allow you to tell Hudson only to run some of the tests, or to skip a group of the tests. This means you can occasionally run the test group manually to see if any are now passing.

Some frameworks allow you to annotate or otherwise mark single tests to be Ignored. It is harder to run them as a group in this case, but it stops them from distracting you.

You might move the tests to a source tree that isn't normally included in the build.

In extremis, you could delete the code from the HEAD of the version control system, but this will then make it harder to recognise when the third phase has been completed.

The goal is to get Jenkins to go Green as soon as possible, so you can start moving in the right direction as soon as possible.

Keep tests relevant.

Resolve to add new tests as you add or modify code, and commit to keeping all the passing tests passing.

Tests may fail for a variety of reasons, including the fact that they weren't well-written tests to start with. But once you get Jenkins green, keeping it that way is really important.

Get used to writing good tests, and make it a big deal if tests start failing.

Determine the intent for each test.

Go through the disabled tests one by one. Start with the ones that affect the modules that you change most frequently. Determine the intent of the test, and the reason for failure.

Does it test a feature that was removed from the code base on purpose? Then you can probably delete it.

Is it catching a bug that nobody has noticed yet? Reinstate the test and fix the bug.

Is it failing because it was making unwarranted assumptions (e.g. assuming button text would always be in English, but now you have localised your application for multiple languages)? Then figure out how to make the test focus on a single thing, and isolate it from unrelated changes as best you can.

Does the test sprawl through the whole application, and represent a System test? Then remove it from your main Jenkins test suite and add it to the Regression suite that runs less frequently.

Has the architecture of the app changed beyond recognition, so the test no longer does anything useful? Delete it.

Was the test added to artificially increase code coverage statistics, but actually does nothing more than confirm that the code compiles correctly and doesn't go into an infinite loop? Or else, the test simply confirms that your selected mocking framework returns the results you just told it to? Delete it.

As a result of this, some tests will stand, some be modified, some split into multiple independent, bite-size chunks, and some removed. As long as you are still making progress with new requirements, setting aside a little time to deal with technical debt like this is the responsible thing to do.


问:
Print Call Stack Tree of Recursive Python Function
I want to write a program in Python that illustrates the tree-like nature of recursion. Given a recursive function (for instance fibonacci(n)) there should be a way to print the tree-like call trace of the recursive function. With the following function:

```<code>def fibonacci(n):
  if n == 1 or n == 2:
     return 1
   else:
     return fibonacci(n-1) + fibonacci(n-2)
</code>```

The print out for n=5 could look something like:

```<code>                             fibo(5)
               fibo(4)                    fibo(3)
       fibo(3)         fibo(2)      fibo(2)        fibo(1)
 fibo(2)      fibo(1)
</code>```

The solution should be as "general" as possible and not specific to Fibonacci numbers as I want to implement it for additional recursive functions.

答:
You can't just modify fibo to get what you want. For instance,  the order in which the different calls to fibo happen is not the one in which you have to write their arguments to the console, and because you don't know the width of your tree to begin with, you don't know how far to the right to start with the root.

What you have to do is to collect the calls and their arguments in a temporary data structure as they happen, likely also a tree, and then traverse that data structure after the first recursion has terminated.

ContentLicense: CC BY-SA 3.0


答:
You can pass another argument to the recursive function that starts from 0 and increments by 1 in every call in order to determine the depth of recursion tree. Then you can use stacks to store "function(x)" strings and finally print them according to depth.

e.g. fibo(5,0) -> fibo(4,1),fibo(3,1) -> fibo(3,2),fibo(2,2),fibo(2,2),fibo(1,2) ->...

Title: Print Call Stack Tree of Recursive Python Function

Body:
I want to write a program in Python that illustrates the tree-like nature of recursion. Given a recursive function (for instance fibonacci(n)) there should be a way to print the tree-like call trace of the recursive function. With the following function:

```<code>def fibonacci(n):
  if n == 1 or n == 2:
     return 1
   else:
     return fibonacci(n-1) + fibonacci(n-2)
</code>```

The print out for n=5 could look something like:

```<code>                             fibo(5)
               fibo(4)                    fibo(3)
       fibo(3)         fibo(2)      fibo(2)        fibo(1)
 fibo(2)      fibo(1)
</code>```

The solution should be as "general" as possible and not specific to Fibonacci numbers as I want to implement it for additional recursive functions.


问:
Implementing a complexity hiding layer
As part of the dependencies that the project I'm working on has, we use several core services. These services, to which we can't make big changes, are a big mess. Depending on the method we invoke, we need to convert our parameters (and return values) to different encodings, locales and time zones.

Since we generate these parameters in multiple places in our own code, we perform these conversions in multiple places. Some times where we generate them, before passing them around in our side; some times right before invoking the method in the core service. So the mess is spreading throughout our code, and I want to introduce a layer to isolate it.

My question is what's the best approach for that. Initially I thought of just creating a service/method corresponding to each service/method that we need to use. These methods would simply perform the conversion, delegate to the core services and perform conversion of the return value. But this seems somehow unwieldy.

Then I thought of using annotations, but I'm not completely sure of how to use them. And as I understand it, ideally I would need to annotate the invoked method. For instance, I could annotate the parameters with @converToUtc, and do the conversion in the annotation implementation. Is this correct? Of course, this is hard because it's not our code and it'll break code currently using those methods in projects other than our.

What's the best approach for this situation?

答:
First of all, you (or your team) need to agree on a "standard" format that you will use in your own code. For example:

Encoding: UTF-8

Locale: en_UK

Timezone: UTC

Only after, you could write a layer that will adapt the values to the formats requested from your dependancies (I don't think it's unwieldy).

As Mike Nakis said, I also don't see any benefit to use annotations to solve this problem.

Title: Implementing a complexity hiding layer


问:
How is encapsulation broken by getters/setters, even when using MVC model
I was thinking about encapsulation in Java and then I thought how getters/setters break encapsulation. After I went through this , I saw many recommendations like to avoid getters/setters on fields not necessary, or some policies on how to implement them.

What I failed to understand is in-case of a MVC model, how do getters/setters break encapsulation. Incase if someone wants to take an example MVC framework, I would like to consider Spring-MVC.

So, basically, in MVC the data is manipulated generally by the business code, implementing an interface. The business code is getting orders from Controller, which is not messing with Model at all.

This way, I see that the model is nicely isolated or buried across 2 layers i.e Controller and Business. Can anyone explain me why in an MVC model as well, getters and setters break encapsulation.

I hope my question was clear. If anything is missing, kindly let me know. Thank you.

Edit

Perhaps people have not been reading but just flagging around. My question mainly deals with MVC and encapsulation rather than why getter/setters are justified. My point of focus still remains on MVC, that's why I have not accepted the answer.

答:
Its down to the fact that a getter/setter exposes the same data as a public variable would, as they're simply method call wrappers around the variable.

Once people realised that public variables were a bad idea - they could be modified externally to the object without constraint. The solution to this is to make all member variable private and introduce methods that act upon them to allow for more control and to expose an interface that made sense in terms of what the class was designed to do (ie not how it does it).

But unfortunately, the syntactic sugar of properties was introduced to fudge the distinction - so now we have methods that allow access to the variables which pretend to be part of the class interface, when they're plainly nothing more than method-equivalents of public variable access.

For an example, imagine a Person class that holds your age. You can set this in a member variable and allow a caller to set p.age = 20; if it was a public variable. Or, you could have a property and it becomes p.age_set(20); instead (effectively, I know the syntactic sugar is there to make it look like a variable assignment). Or you could have a p.Age(20); that calculates a year of birth and stores that in a variable, ignoring any age member variable.

This latter is maintaining encapsulation - the caller does not know, or care how the person object tracks your age, only that there are ways to set and fetch the data. Its the difference between designing a struct and a class (or data-driven design as opposed to behaviour-driven. The latter is far better for maintenance and system use)


答: What you're trying to do is implement the facade pattern. Basically you want to put a simpler face on the core code. You'll probably want to create a set of classes that provide a 1:1 mapping for each core class, then use the facade classes in place of the core classes. If the core services are just a bunch of methods in some big monolithic class, then you might consider breaking them down by functional domain (e.g., authentication, data access, business function, etc.) and having a different facade for each domain. Your facade should present an interface that makes sense to your code, and handle all the mapping and data conversion required to communicate with the core services.</p>

Title: Implementing a complexity hiding layer

Body:
As part of the dependencies that the project I'm working on has, we use several core services. These services, to which we can't make big changes, are a big mess. Depending on the method we invoke, we need to convert our parameters (and return values) to different encodings, locales and time zones.

Since we generate these parameters in multiple places in our own code, we perform these conversions in multiple places. Some times where we generate them, before passing them around in our side; some times right before invoking the method in the core service. So the mess is spreading throughout our code, and I want to introduce a layer to isolate it.

My question is what's the best approach for that. Initially I thought of just creating a service/method corresponding to each service/method that we need to use. These methods would simply perform the conversion, delegate to the core services and perform conversion of the return value. But this seems somehow unwieldy.

Then I thought of using annotations, but I'm not completely sure of how to use them. And as I understand it, ideally I would need to annotate the invoked method. For instance, I could annotate the parameters with @converToUtc, and do the conversion in the annotation implementation. Is this correct? Of course, this is hard because it's not our code and it'll break code currently using those methods in projects other than our.

What's the best approach for this situation?


问:
Forcing Cache Refresh

I'm updating an existing tomcat web application to read certain resources from a REST API. Currently the application reads them from flat files. Since the application is very critical, I added a caching layer so that the objects returned by REST API are always available.

In the service layer of API client, if the request item is not found in the Cache, the request will be sent to the actual API, the response is put in MapDB cache and returned to caller. The startup listener calls a bunch of APIs with different parameters so that all data is now in MapDB cache. I do not set a expiration on the items in cache because I want them to always available unless I refresh on demand.

The problem is Web App and API client are different projects. Since API client decides to read from Cache or API, I'm not able to force refresh cache value from the application.

Should I add another parameter to function calls I make to API client or

```<code>Object obj = ServiceFactory.getLanguageService()
                    .getLanguagesFromApi(env.getName(),
                            env.getEnvironmentType(),
                            env.getPhase().toString(), null, true);
</code>```

The last "true" parameter indicates forcing cache refresh.

Should I get the existing value in cache to a temporary variable, delete the entry, make API call, if no value is returned because of some error, put the entry back into the cache.

```<code>        String key = ClientUtils.concatenateList(
                Arrays.asList(ClientConstants.RESOURCE_LANGUAGE,
                        env.getName(), env.getEnvironmentType(),
                        env.getPhase(), null),
                ClientConstants.CACHE_KEY_SEPERATOR,
                ClientConstants.NULL_STRING);

        Object cachedElement = ClientCache.getCache().get(key);
        if (cachedElement != null) {
            ClientCache.getCache().delete(key);
        }

        Object obj = ServiceFactory.getLanguageService()
                .getLanguagesFromApi(env.getName(),
                        env.getEnvironmentType(),
                        env.getPhase().toString(), null);

        if (obj == null) {
            ClientCache.getCache().put(key, cachedElement);
        }
</code>```

What is the cleaner way to do this ? I feel adding parameters about caching to function makes it clumsy and add dependencies - like getUsers(String country, boolean forceAPIrequest). But deleting and adding same entries may also waste resources and heap space, causing GC over time. Also, App will directly access Client Cache to do these operations.

All this is based on strong assumption that our REST API is unreliable. Web App should not have any down time.

答: Add a method to the API client refreshCache(...) that would refresh the entire cache, similar to what is done through your startup listener. If a cache-aware application using the API client knows that it needs refreshed data before asking for specific data, make it call refreshCache first.

Title: Forcing Cache Refresh


问:
How to deal with tremendous number of failing tests?
I'm working in the development of an old project written in Java. We have more than 10 million LOC and, even worse, more than 4000 functional tests.

The tests, scheduled by Hudson, are failing like mad with every bigger code change. Verification of the test failure - if it's a problem in the product or in the test, takes months. We cannot remove the old tests because we don't know what they are testing!

What we can do? How to proceed with such amount of legacy tests?

答:
4000 tests is an intractable problem. 40 tests is more tractable. Randomly select a manageable number of tests to run and analyze. Classify the results as:

Useless test

Useful test that runs clean

Useful test that fails

If a lot of the tests fall in the first category, it may be time to throw out your current test suite and put together a useful one for the current code.

If a lot of the tests are failing in ways that tell you about a problem in your code, you need to work through the failing tests fixing things. You may find that fixing one or two bugs makes a large number of tests run.


答:
Quick answer : Using getter and setter methods in the way you describe will most likely be fine. And removing them will not solve any concrete problem.

Longer answer

Remember that encapsulation is about information hiding. Formally, what you want is a data structure - your private fields - that is only ever accessed and modified via a fixed set of routines - your methods. That improves maintenance, because if you want to change the inner data-structure, you only have to go through your finite set of routines to make the update, rather than the whole program. It's easy to see the advantage :) .

The problem in get/set come when you expose implementation information. Let's take the example of exposing a database connection. Suddenly, you declared to the world that your object talks to a database. Client code will use that connection to do other stuff. 2 years later, you remove the database, it's not needed anymore. But the client code expects a connection to the old database! You can't change your object the way you want, and you have to carry around useless junk... you have exposed details you shouldn't!

In another case, though, you don't have something to hide : A Customer is an ID, a name and a phone number. Don't hide that, it's the very thing client code needs! Multiple parts of the application require this to do their job : your UI will display a formatted version to the user, your database will save and read the value, a JSON library will serialize the information to send an order to a 3rd party. This is business information. It need to be accessible to be useful. In that case, a getter - and maybe a setter - is perfectly valid.

In your case : If the getter in your business logic hides your model, it's perfectly fine. Use them. A getter-less design may not be better.

As a finishing note : people are often against getter because of something called "tell don't ask". This is a whole different issue than encapsulation. It's a design philosophy, and the benefits are less clear than with information hiding. The latter was already known in the 70s, while the former is a more recent invention. "Tell don't ask" is wonderful for some applications - event driven ones in particular. Alas, it work poorly with CRUD applications, where the whole point is to ask about information. Assuming you're outside the specific set of problems "tell don't ask" solves, use getters without any guilt. Just remember to hide your implementation.

Title: How is encapsulation broken by getters/setters, even when using MVC model

Body:
I was thinking about encapsulation in Java and then I thought how getters/setters break encapsulation. After I went through this , I saw many recommendations like to avoid getters/setters on fields not necessary, or some policies on how to implement them.

What I failed to understand is in-case of a MVC model, how do getters/setters break encapsulation. Incase if someone wants to take an example MVC framework, I would like to consider Spring-MVC.

So, basically, in MVC the data is manipulated generally by the business code, implementing an interface. The business code is getting orders from Controller, which is not messing with Model at all.

This way, I see that the model is nicely isolated or buried across 2 layers i.e Controller and Business. Can anyone explain me why in an MVC model as well, getters and setters break encapsulation.

I hope my question was clear. If anything is missing, kindly let me know. Thank you.

Edit

Perhaps people have not been reading but just flagging around. My question mainly deals with MVC and encapsulation rather than why getter/setters are justified. My point of focus still remains on MVC, that's why I have not accepted the answer.


问:
Why is free software good for programmers?
When I say Free Software I mean it in the FSF terms. Free as in Free Speech, not as in Free Beer.

Why is it a good idea for programmers to use and write Free Software?

答:
The following is an excerpt from the FSF's free software page:

Free software is a matter of the users' freedom to run, copy, distribute, study, change and improve the software. More precisely, it means that the program's users have the four essential freedoms:

The freedom to run the program, for any purpose (freedom 0).

The freedom to study how the program works, and change it to make it do what you wish (freedom 1). Access to the source code is a precondition for this.

The freedom to redistribute copies so you can help your neighbor (freedom 2).

The freedom to distribute copies of your modified versions to others (freedom 3). By doing this you can give the whole community a chance to benefit from your changes. Access to the source code is a precondition for this.

I would have thought that the benefits of the Freedoms to "the programmer" were self-evident.  Certainly Freedoms 0 and 1 should be.  I guess Freedoms 2 and 3 assume that you might want to help your neighbor ... or have your neighbor help you.  But you would need to be pretty short-sighted (or a sociopath) not to recognize the benefits of people helping each other.

The waters get a bit muddy when you start considering corporate interests.  But it is pretty clear that companies can and do make money both building and using Free Software, even if your company's management doesn't "get it" yet.

ContentLicense: CC BY-SA 2.5


问:
Web Framework for Education Management System
Please note that I'm moving my original question from StackOverflow to here, because I think it's more on-topic here

So, I'm working on an idea and I'll go into a brief overview of that but my question is, What are some good web frameworks for this situation? I have some experience in the following languages:

C#

Python

I have considerably more experience in C# than Python, however I am expecting to learn new things.

My idea is this, a completely web-based community-oriented Education Management System that focuses on making students and teachers day-to-day lives easier. For students it will provide a centralized place for them to do homework, study for tests, and reinforce concepts learned previously in class. For teachers it will give them a centralized place to handle assignments, attendance, homework, tests, and all other major parts of classroom management. All of that, but in a community-oriented fashion. Everything a teacher does is shared and open to constructive criticism, allowing other teachers to use their assignments/tests and for students or other teachers to comment, rate and criticize their assignments. This encourages an environment of openness that will allow teacher's to focus on teaching and student's to focus on learning. And that community wouldn't be limited to one school or school-district, this system would be completely school-independent.

Also note that I have no problem with hearing constructive criticism on this idea, however I would prefer if this post was more focused on my question.

I have somewhat explored about the following options:

Django

ASP.NET

Ruby on Rails

Silverlight

(1) I have Django installed and I played with it for a little bit, I really like how easy setting up databases are and how it handles the database completely for you. I don't really know how to use it very well and I don't quite understand the Model-View-Controller paradigm(?) for it yet but I haven't thought about it much. I also like the fact that it uses Python.

(2) I don't really like Visual Studio for developing in ASP.NET, I hate the way the web-designer works and it just feels clunky and old. I like the server-side development part though. I don't like how expensive ASP.NET and overall Visual Studio is, even if I do get it for free for now using DreamSpark

(3) I haven't been able to explore much with this, I could not get Rails (or maybe Ruby) properly installed. I first installed it within RadRails and that didn't work so I uninstalled RadRails and then installed the latest version of Ruby off the official Windows Installer and then installed Ruby on Rails through gem and even after all that it still didn't work, so I installed Netbeans and attempted to use it there but it still did not work

(4) I like Silverlight in some extents, I've played with this one the most, it's very similar to WPF (which I've used the most) in a lot of ways but I don't like how database connectivity works, at least in comparison to Django. I also dislike how expensive everything with Microsoft is, even if I get it for free for now with DreamSpark.

I would like to hear some suggestions from experienced web-developers as to what I should use and why, or at least what some good options are for my scenario

答:
First off, I'm biased, python is the greatest imperative language ever designed and if you don't agree, you haven't used it enough.

I got into web development through Django and I've found Django is perfect for writing the kinds of sites it was designed for - publishing sites. If you want to write Yet More Blogging Software™, or you're starting out and writing something fairly simple you cannot beat it.

However, ultimately it is inflexible. I've found the templates, orm, forms and authentication system all to be inflexible. The other problem is that because it is so monolithic, it is difficult to just substitute in more suited components.

So I'd suggest against Django, but that doesn't mean you should give up on MVC.

I did look a little at the other python frameworks and found there weren't any that won me over. So in order to do web development, I've actually been rolling my own framework, it's easy to find good components in pypi, but I wouldn't suggest this either, it's a lot of work. In the future when it's more polished, I'm going to open-source it.

But for now, I'm not sure I can think of anything I can really recommend.


答:
We cannot remove the old tests because we didn't know what they are
  testing!

That's exactly why you should remove the old tests! If you don't know what they are doing, then failure is meaningless and running them is a waste of time. Throw them out and start over.

Title: How to deal with tremendous number of failing tests?

Body:
I'm working in the development of an old project written in Java. We have more than 10 million LOC and, even worse, more than 4000 functional tests.

The tests, scheduled by Hudson, are failing like mad with every bigger code change. Verification of the test failure - if it's a problem in the product or in the test, takes months. We cannot remove the old tests because we don't know what they are testing!

What we can do? How to proceed with such amount of legacy tests?


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: That writing software is actually about writing code.</p>


答:
The most important thing I would do is go back to the fundamentals of what testing is supposed to do, and what the business needs to keep moving.  Testing's job is to identify issues before they become expensive to fix later.  I think the key word in that sentence is "expensive."  These issues need a business solution.  Are expensive issues showing up in the field?  If so, testing is failing outright.

Your management and you need to come to a reality check.  You are finding that development costs are skyrocketing because of a legacy set of tests.  How do those costs compare to the costs of delivering a faulty product because you disabled tests?  How do they compare to the onerous task of actually figuring out what behaviors users need (which are the things that should be tested)?

These are issues that need business solutions because they touch the business side of the job.  You are delivering product to a customer, and that is a boundary which business is very interested in.  They may be able to identify solutions that you, as a developer, cannot.  For example, it may be reasonable for them to provide two products: one "legacy" product for those who need reliability and are willing to forgo new features, with one "visionary" product which may have more faults, but is pioneering ahead.  This would give you an opportunity to develop two independent sets of tests... one legacy one with 4000 tests, and one with more of the tests you think need to be done (and document them so this process doesn't repeat).

Then, the art begins: how can you manage this two-headed beast so that advances in one branch also help the other branch?  How can your updates to the "visonary" branch flow back towards the "legacy" branch, despite rigid testing requirements.  How can continued customer requests on the "legacy" branch better shape your understanding of the requirements your legacy customers would need if you eventually re-merged the products?


问:
Working with external translators in .NET
I am working on a .NET project (happens to be an MVC website) that is being deployed in 5 languages. We have several hundred text strings in various .resx files, which is working great.

However, the process for adding or changing strings is slow, as the translation is being done by another department and we don't have a great system in place for tracking or coordinating changes. They apparently use WorldServer, which has some resources on file formats and import/export, but not much on workflow for my side of the equation.

WorldServer or no, what is the best way to coordinate ongoing translation efforts and integrate the results with existing translations in .NET?

答:
In the interest of full disclosure, I'm the author of a commercial (".resx") localization tool for Visual Studio developers. I won't be mentioning anything about my product here though so as not to violate the site policy.

The program is a Visual Studio add-in that developers use to extract all strings from their ".resx" files into a single, proprietary file for shipping to their translator. Their translator can then download a free program from my site (no cost to them whatsoever), translate the strings and send the file back. The same add-in that created the file in the first place is then used to import those strings back into the programmer's solution. To this end, the application does many things that will presumably solve your "workflow" issues. It was designed for this from the ground up.

For instance, if a programmer changes a string in their solution, then their existing translations will require updating of course, so the program will flag them for review. This means that the next time they ship their strings to their translator, the translations will be highlighted in red, meaning they need to be reviewed and updated. The program also has many other bells and whistles, including a lot of error and consistency checking. For example, if a programmer changes a string in their solution while it's out being translated, it'll be brought to their attention when the strings are later returned.


问:
Fix bugs, or wait for the customer to find them?
Do other people fix bugs when they see them, or do they wait until there's crashes/data loss/people die before fixing it?

Example 1

```<code> Customer customer = null;
 ...
 customer.Save();
</code>```

The code is clearly wrong, and there's no way around it - it's calling a method on a null reference. It happens to not crash because Save happens to not access any instance data; so it's just like calling a static function. But any small change anywhere can suddenly cause broken code that doesn't crash: to start crashing.

But, it's also not inconceivable that correcting the code:

```<code>Customer customer = null;
...
customer = new Customer();
try
   ...
   customer.Save();
   ...
finally
   customer.Free();
end;
</code>```

might introduce a crash; one not discovered through unit tests with complete coverage, and manual user testing.

Example 2

```<code>float speed = 0.5 * ((G * mass1 * mass2) / R) * Pow(time, 2);
</code>```

People knowing physics will recognize that it's supposed to be R2 in the denominator.

The code is wrong, it's absolutely wrong. And overestimating the speed will cause the retro-rockets to fire too soon, killing all the occupants of the spacecraft.

But it's also possible perhaps having it over-estimate the speed is masking another issue: the air-bags can't deploy while the shuttle is moving too fast. If we suddenly fix the code:

```<code>float speed = 0.5 * ((G * mass1 * mass2) / Pow(R, 2)) * Pow(time, 2);
</code>```

Now the speed is accurate, and suddenly airbags are deploying when they shouldn't.

Example 3

Here's an example that i had recently, checking if a string contains invalid characters:

```<code>if (StrPos(Address, "PO BOX") >= 0)
{
   //Do something
}
</code>```

What if it turns out there's a bug in the Do something branch? Fixing the obviously incorrect code:

```<code>if (StrPos("PO BOX", Address) >= 0)
{
   //Do something
}
</code>```

Fixes the code, but introduces a bug.

The way I see it there are two possibilities:

fix the code, and get blamed for breaking it

wait for the code to crash, and get blamed for having a bug

What do you politically do?

Example 4 - Today's real world bug

I am constructing an object, but calling the wrong constructor:

```<code>Customer customer = new Customer();
</code>```

Turns out that the "parameterless" constructor is actually an parameterized constructor from  further back in the inheritance chain:

```<code>public Customer(SomeObjectThatNobodyShouldBeUsingDirectly thingy = null)
public Customer(InjectedDependancy depends)
</code>```

Calling it is a mistake, since it bypasses all the subsequent constructors.

I could change the object's lineage to not expose such a dangerous constructor, but now I have to change the code to:

```<code>Customer customer = new Customer(depends);
</code>```

But I can't guarantee that this change won't break anything. Like my Example 1 above, perhaps someone, somewhere, somehow, under some esoteric conditions, depends on the constructed Customer to be invalid and full of junk.

Perhaps the Customer object, now that it is properly constructed will allow some code to run that previously never did, and now I can get a crash.

I can't bet your wife's life on it.

And I can test it from here to Tuesday, I can't swear on your daughter's life that I didn't introduce a regression.

Do I:

Fix the code and get blamed for breaking it? or

Leave the bug, and get blamed when the customer finds it?

答:
The right course of action is neither to ignore the bug, nor to "fix" it on the spot; for the very reasons that you identified in your question.

I think, you should try to understand the code first. If the code you are seeing has some age, and no-one noticed the "bug" yet, there is likely a reason for that. Try to find this reason. Here is what I would want to look at before making a decision:

History: Use your version control software to answer the questions: Who touched the code? What did they change? And with what commit messages did they check it in? Can you infer a reason why the code looks like it does?

Use: What code uses the faulty code? And how? Is the code dead? Is there other code that relies on the faulty behavior?

Author: If you can't reach a conclusion quickly using the information above, ask the author of the code (at least if that is possible) why the code looks the way it does. Usually you will either get a "Oups, that should be fixed!" or a "No! Don't change it!!! It's needed that way!" right away.


问:
Why are HDL IDEs so user-unfriendly when compared to generic-purpose language (like Java/C) IDEs?
I've been programming for a while now, and I've covered a lot of languages. And this trend that I noticed is that all HDL languages have so painful IDEs!

In general, any development environment having some Hardware related development has very crappy UI.

I'm talking about uVision, ModelSim, VHDL Simili, Xilinx etc, compared with Netbeans, Eclipse, Visual Studio etc.

Why do hardware-guys hate their developers?

NOTE: There are exceptions (LABView is awsome!). Can you think of any more?

答:
You are right that the GUIs of Hardware tools today are really bad compared to software tools. Why? Two reasons: first there are a lot more software engineers than hardware design engineers (say a hundred to one). If you are going to build a development tool and make money from it, your better guess is to aim for software tools.
Second, if software people don't like the software they use, they just build new software to build better software. (are you still with me?) They have the means, motive and opportunity to build better software tools, and so they do.

Now for a solution: having lived between the software and the hardware world, I have noticed the same thing you have. I founded a company, Sigasi, and usability is key to us. Established companies may or may not shift their attention to user-centric software, but some of the younger companies are.

Philippe Faes
www.sigasi.com


答:
If this statement is true,

The tests ... are failing like mad with every bigger code change.

then that implies that if you rollback to the code just before a "bigger code change", then many of the tests will pass again. After doing that, grab a smaller chunk of changes and see which tests are newly failing. This will help you better isolate which code changes are causing which tests to fail. For each test, once you have isolated the problem, you should then be able to determine if the new code was flawed, or the test was. If it is a problem with the new code, make sure to compare it with the latest version just in case that particular bug has already been fixed.

Repeat until you have the latest code base.

This may seem like an overwhelming task, but it's very likely that once you go down this path and begin isolating some of the problems, a pattern will begin to emerge which may greatly speed up the process. For example:

You may notice that many tests are dependent on something else that is flawed. Fixing that one piece may fix many tests.

You may notice that many tests are flawed and need to be fixed or removed.

You may notice that a particular developer has a much higher frequency of causing tests to break. That developer may need more training or supervision.


问:
Eliminating thread affinity requirements when converting an STA COM object into an MTA COM object
Suppose I need to convert an STA COM object into an MTA object.  Single threaded apartments guarantee not just that only one thread will call the object at a time, but that it's always the same thread (thread affinity).

I think I understand the first requirement: the object and its shared data needs to be read and written in a thread safe manner.

I am less clear on what I need to ensure that my object does not require thread affinity.  I am aware of two concerns:

Thread local storage

Locks

Are there any other common (or uncommon) issues that would cause an object to fail without an outside guarantee of thread affinity?

答:
The STA COM objects were guaranteed to be thread safe by the COM subsystem itself. If used correctly by the client, the COM object doesn't have to be concerned about its own thread safety.

The MTA apartment turned that on its head. The COM object now has to deal with its own thread safety entirely. The COM subsystem makes no promises about the thread access on the object, it could be from multiple threads and concurrently.

Issues to be aware of include all the thread safety issues moving a class from being thread unsafe to thread safe.

When choosing to change the apartment supported by the object, it is generally a good idea to first analyse how it is used.

If it is only (or generally) used in an STA, the there is no need to change it and no real benefit.

If the object is generally used by many other MTA objects, then changing it may be a good idea.

If the object is marshaled between many STA apartments, then again consider the MTA support, but only if there is a measurable improvement in performance.


问:
Does Serialization preclude the use of Dependency Injection?
Simple question: I understand that Serialization in C# requires default constructors. This would eliminate the possibility of using Constructor injected DI (which is generally the favored style of DI, in my reading[citation needed]). So is it really an either-or situation, or am I missing something?

(Side question): Do IoC containers side-step this tradeoff somehow?

答:
I'm solving this problem like that: injecting factories of dependencies. In those factories, first resolve dependency as it is registered in container, then "deserializing" all remaining data: json.net allows to populate fields in existing object.

As factories code goes along with wiring code of IoC container, I don't think using container.Resolve inside factory violates the rule, that container have to be used just in one place in code: where all wiring happens.

As of now, I'm trying to make this process automatic (as opposed to what I've been testing that approach at) using reflection. Yes, there is not much what does remain from json.net deserialization itself, part of it is substituted with custom code, but I think, why bother.

Also, what was your final thoughts/decision on the matter? After reading this post i see two ways: deserialize, then inject; or inject, then deserialize (populate). And i still find my way is better. Will be glad to hear arguments in opposition to this (i'm regarding, that my way may be better for my case, but can't vividly imagine good alternative cases, where it fails, just some minor guesses)


问:
User Inputs: Bounding Box, best practice?
I am creating a function in matlab that takes in two lat/long coordinates (opposite corners of a rectangle) and returns information about data in the region.

How do I group my inputs?

e.g. [lat1,long1] and [lat2,long2]; or [lat1,lat2], [long1,long2].

To make it easy on the user I currently have the lats and longs grouped together like the latter example, but am thinking the former is a bit more appropriate for science/math.

答: In MATLAB a rectangle in Cartesian coordinates is typically represented as a 4-element row vector of the form [x, y, width, height], where [x,y] are the coordinates of the upper-left corner. You may consider following the same convention with latitude and longitude.</p>


问:
Should I deploy 32-bit only or both 32- and 64-bit versions for Windows?
I have a cross-platform application written in a compiled language.

For Linux it is customary to have both amd64 and i386 builds available to user, so user can choose version, suitable for its current environment.

In Mac it is customary to make Universal Binary, so it could support multiple versions of Apple computers. Or just provide 64-bit version, as all current Apple computers use 64-bit architecture and OS.

I don't want to confuse users, asking "What architecture are you?", but deploying 32-bit only is bad idea, as this program uses some 64-bit optimization magic and runs much faster on these machines.

My ideas:

Install both 32- and 64-bit versions of application and choose at run-time. (Requires wrapper, so making click-and-launch application (like uTorrent) will be difficult).

Detect architecture using User-agent on the website, so user could download appropriate version automatically (and make link to "alternative versions"). (It is Google Chrome style)

Force user to use 32-bit application and make 64-bit version "expert-only"? (like VLC)

What should I do in Windows?

答:
I really don't think its a huge complexity for the end user to have to select either a 32bit or 64bit option when downloading.  But if you can use the user-agent strings to make a suggestion all the better.

Another option is to have your installer detect and install the correct binary for the user's platform.  That makes for a larger download, but then the user doesn't have to think about it.  If you go that approach, you'll want to provide some way for the user to override the detection in case they need a specific build for whatever reason.


问:
Qt, LGPL, Android and GooglePlay licensing
So, you can build Qt apps and deploy them to android.

Taking a look at this post, I was wondering if making a game using Qt would be fine with LGPL legal terms given the following facts:

The app would be at GooglePlay so, using third party libraries is a concern

Source code for the app would be public

Possible in-game purchasing. I don't really know if this is ok with making the code public, since I ignore what info is needed in the app for achieving this.

Would it be ok to use Qt LGPL license with all that? does any point fails at using LGPL? if so, which one?

答:
After some research, quoting from here:

As Qt for Android uses the LGPL version of Qt, and it's perfectly
  possible (and also recommended and supported) to dynamically link in
  the Qt libraries when creating an app - there are no problems for app
  developers using Qt for Android. The app developers can develop closed
  source code and publish the app - no worries.

Only if you statically link with the Qt libs could there be a problem
  with closed source apps.


问:
What type of Password Reset/Forgot Password (verification) mechanism would you recommend
I am looking for ways to verify the user in order to reset their passwords. 2 commonly used ones:

Email verification

Secret question

I wonder which will you recommend? I am trying to avoid having to use email at all (users won't need to provide emails, most hosts limit emails sent). But Secret Question alone seems a little unsecure. What do you think?

答:
For Earth sake, do not use secret questions. In a week I usually have no idea what I could have answered there less in a year.

Email verification will do just fine.

And never send the password in plain text per email. Never even store the password, store a hash of it.


答:
Personally, secret questions annoy me a lot. The predefined questions are either so easy that someone could simply google and/or guess the answer. Or the question are so obscure, that I don't know the right answer and give a fake one (which leads to problems if you really try to recover your password) ... really I can't remember the name of my teacher in 1st grade!

Worse, if you let the users define their own question and answer they will do really, really dumb stuff (like putting the password in the question!).

Title: What type of Password Reset/Forgot Password (verification) mechanism would you recommend

Body:
I am looking for ways to verify the user in order to reset their passwords. 2 commonly used ones:

Email verification

Secret question

I wonder which will you recommend? I am trying to avoid having to use email at all (users won't need to provide emails, most hosts limit emails sent). But Secret Question alone seems a little unsecure. What do you think?


问:
Elegant way to handle multiple pathways based on compound condition
Consider the following:

```<code>if (x == 5 || x == 10 || x == 12) {
    if (x == 5) {
        doSomething()
    } else if (x == 10) {
        doSomethingElse()
    } else {
        doSomeOtherThing()
    }

    doMoreThings()
}

doThingsAfterThat()
</code>```

The second set of conditions feel repetitive, as I have specified them in the original condition. I could separate this into two conditionals, but then I would be repeating `doSomeOtherThings()'.

What is the most elegant way to handle this?

Edit:

This is not a duplicate of Elegant ways to handle if(if else) else. The reasons being:

In the potential duplicate question, the internal condition is testing a different value than is being tested in the original condition. In this question, the internal conditions being tested are the same as the original condition.

In this question, one has to give consideration to multiple if, else if statements. The potential duplicate question does not consider this.

答:
It might help if you give names to the conditions but I think it is questionable in this simple example.  With more complex conditions, the benefit would be clearer.  If some day you decide to change one condition, you'll only have to do so in one place and don't risk introducing an inconsistency.

final boolean someP = (x == 5);
final boolean elseP = (x == 10);
final boolean otherP = (x == 12);

if (someP) {
    doSomething();
}
if (elseP) {
    doSomethingElse();
}
if (otherP) {
    doSomeOtherThing();
}
if (someP || elseP || otherP) {
    doMoreThings();
}

doThingsAfterThat();
```


答:
Use email verification.

The Secret Question approach has multiple problems.

I may have forgotten the answer

I would have spelled the answer differently (with a leading upper case word, and that programmer would have forgotten a equalsIgnorecase)

The actual problem is that the user forgot the password. And the secret question approach wants him to remember 4 other things since he forgot something.

Many users end up taking a screenshot of the question answer screen for future reference - the very purpose of the password is lost.


答:
why not to use case for individual if and one if for or condition.

```<code>switch (x) {
 case 5: doSomething5();
        break;
   case 10: doSomething10();
        break;
case 12 : doSomething12();
        break;
}

if (x==5 || x == 10 || x == 12){
doMoreThings();
}
doThingsAfterThat();
</code>```

doMoreThings can be inside the case also. But it will be repititive.

```<code>switch (x){

case 5: doSomething5();
         doMoreThings();
        break;
case 10: doSomething10();
         doMoreThings();
        break;
case 12 : doSomething12();
         doMoreThings();
       break;
       }
</code>```

*if conditions are complex then simple variable check, this will not work.

Title: Elegant way to handle multiple pathways based on compound condition

Body:
Consider the following:

```<code>if (x == 5 || x == 10 || x == 12) {
    if (x == 5) {
        doSomething()
    } else if (x == 10) {
        doSomethingElse()
    } else {
        doSomeOtherThing()
    }

    doMoreThings()
}

doThingsAfterThat()
</code>```

The second set of conditions feel repetitive, as I have specified them in the original condition. I could separate this into two conditionals, but then I would be repeating `doSomeOtherThings()'.

What is the most elegant way to handle this?

Edit:

This is not a duplicate of Elegant ways to handle if(if else) else. The reasons being:

In the potential duplicate question, the internal condition is testing a different value than is being tested in the original condition. In this question, the internal conditions being tested are the same as the original condition.

In this question, one has to give consideration to multiple if, else if statements. The potential duplicate question does not consider this.

Body:
why not to use case for individual if and one if for or condition.

switch (x) {
 case 5: doSomething5();
        break;
   case 10: doSomething10();
        break;
case 12 : doSomething12();
        break;
}

if (x==5 || x == 10 || x == 12){
doMoreThings();
}
doThingsAfterThat();

doMoreThings can be inside the case also. But it will be repititive.

switch (x){

case 5: doSomething5();
         doMoreThings();
        break;
case 10: doSomething10();
         doMoreThings();
        break;
case 12 : doSomething12();
         doMoreThings();
       break;
       }

*if conditions are complex then simple variable check, this will not work.


答:
Procedures (or functions or methods) exist because of the need to apply the same pattern of actions in many situations. Thus there's nothing wrong with repeating a method call a few times. Repeating a call three times is not a problem.

So keep it simple, avoid needless nesting, minimize lines of code and minimize executed steps.

```<code>if (x == 5) {
    doSomething();
    doMoreThings();
} else if (x == 10) {
    doSomethingElse();
    doMoreThings();
} else if (x == 12) {
    doSomeOtherThing();
    doMoreThings();
}
doThingsAfterThat();
</code>```

Body:
Procedures (or functions or methods) exist because of the need to apply the same pattern of actions in many situations. Thus there's nothing wrong with repeating a method call a few times. Repeating a call three times is not a problem.

So keep it simple, avoid needless nesting, minimize lines of code and minimize executed steps.

if (x == 5) {
    doSomething();
    doMoreThings();
} else if (x == 10) {
    doSomethingElse();
    doMoreThings();
} else if (x == 12) {
    doSomeOtherThing();
    doMoreThings();
}
doThingsAfterThat();


问:
Objective-C class cluster pattern
I have many sublcasses of one class. I choose concrete class based on type (simple enum). I like idea of class cluster. Should i use it or just create factory class (but each class in objective-c is actually a factory)?

What is the difference between factory pattern and class cluster pattern.
When to use it in your code and why?

答: The class cluster means fewer things to remember: rather than thinking "I have to make a ThingFactory then call [factory thingForCase: foo]" they just look at the initialiser for Thing, which is what you'd probably reach for by default.</p>

Title: Objective-C class cluster pattern


答:
Nowadays, people and sites tend to handle this by themselves and let the user choose if they want to. So using User-agent string is a good way to go. IMO that also make your application and site looks more professional (people like stuff more if it is capable of making related adjustments by themselves).

Placing a choose version link/choice is good since some experts or people who wants to get a different version can go and get it.

You can also place a sticky note on the choose version page (one similar to this one) explaining how the users can check the OS System Type (a.k.a. right click Computer and choose properties blah blah...) so curious humans can check and be sure that what you offer is the right version.

Title: Should I deploy 32-bit only or both 32- and 64-bit versions for Windows?

Body:
I have a cross-platform application written in a compiled language.

For Linux it is customary to have both amd64 and i386 builds available to user, so user can choose version, suitable for its current environment.

In Mac it is customary to make Universal Binary, so it could support multiple versions of Apple computers. Or just provide 64-bit version, as all current Apple computers use 64-bit architecture and OS.

I don't want to confuse users, asking "What architecture are you?", but deploying 32-bit only is bad idea, as this program uses some 64-bit optimization magic and runs much faster on these machines.

My ideas:

Install both 32- and 64-bit versions of application and choose at run-time. (Requires wrapper, so making click-and-launch application (like uTorrent) will be difficult).

Detect architecture using User-agent on the website, so user could download appropriate version automatically (and make link to "alternative versions"). (It is Google Chrome style)

Force user to use 32-bit application and make 64-bit version "expert-only"? (like VLC)

What should I do in Windows?


答: Have a 32bit installer which doesn't contain the executable. Have it detect the target platform it runs on and then downloads the correct binary from your server.</p>


问:
Is order of arguments in an arithmetic expression important to achieve as most exact result as possible (speed is not necessary)?
Actually, in this question I do not ask about particular language or architecture, however I understand there might be some differences.

In physics / engineering it is usually better to handle greater numbers than smaller ones, because of better absolute accuracy. For example when I need to calculate the area of a circle, having its diameter, I'd use the equation S = d * d / 4 * pi rather than S = pi * (d / 2) * (d / 2) (in both cases calculating from left to right).

How does it look in programming languages?

Is it important to provide "better" order of arguments? Are there any compilers that can optimize calculation for this?

Do such constructions make sense:

```<code>// finding a result of a*b/c
if (abs(c)<1){
    result = a / c * b;
} else {
    result = a * b / c;
}
</code>```

(in the example one should also test values of a and b but let's assume they are large numbers)?

I know that using too large numbers I am risking an overflow. I know there is a difference between integer numbers (which are better in addition/subtraction) and float (which are better in multiplication / division).

There is also an issue with integer division, for example in Pascal there is common * multiplication operator and if both numbers are Integer, the result is Integer too, if one of them is Real (equivalent to float), the result is Real too. For division there are two operators: / which always results with Real number and div which takes only Integers and the result is Integer. So in this language it would be better first calculate multiplications and then divisions because Integer divisions may lead to losing the fractional part, and it is better to lose it later than earlier.

But for float numbers, which are stored with mantissa and exponent order of multiplications/divisions seems to be not necessary.

What I want to achieve is as most exact result as possible (speed is not necessary).

答:
In fact I do not have much knowledge or idea whether using large numbers is better or not. But I can share two points that I know...

First is Operator Priority, that is something that you probably know. Some operators have higher priority than others (like * will be executed before + in 2 * 3 + 1 unless you use parenthesis).

For exact results; there are two points too. First is, float to int (or reverse) conversion is specific to programming language and different languages may act differently. Even the different versions of the same language may act differently.

Second point in exact results is the float type, because it is known that Floating Point Math may look Broken, because computers used to calculate using binary (base 2) so the number is represented as the power of two. It is not easy to represent 0.2 by the power of 2's and what you get is 0.001100110011001... or such. Using multiplication or division many times on floating point values causes this difference to get bigger and bigger. David Goldberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic have great information on that topic.

Python have Decimal which can calculate and store exact value of a decimal represented number. Most programming languages have similar data types like that.


答:
In physics / engineering it is usually better to handle greater
  numbers than smaller ones, because of better absolute accuracy.

I don't think this is true at all. There is indeed a point when you add a small number to a big number.
But regarding multiplication division there is a risk of overflow when you multiply numbers that are both greater than 1, so for example

99999999999999999999999/9999999999999999999x999999999999999999999999999

is better than

99999999999999999999999x999999999999999999999999999/9999999999999999999 because the later can (in some machines) result in an overflow.

On the other hand if you divide several times an expression by a big number you can get an underflow. So if you do have a good idea of the order of magnitude of the number involved it is a good idea to interleave multiplications and divisions to keep the intermediate results within the range of numbers the computer can represent.

In your area calculation S = pi * (d / 2) * (d / 2) is worse because there is one more operation than S = d * d / 4 * pi.

Title: Is order of arguments in an arithmetic expression important to achieve as most exact result as possible (speed is not necessary)?

Body:
Actually, in this question I do not ask about particular language or architecture, however I understand there might be some differences.

In physics / engineering it is usually better to handle greater numbers than smaller ones, because of better absolute accuracy. For example when I need to calculate the area of a circle, having its diameter, I'd use the equation S = d * d / 4 * pi rather than S = pi * (d / 2) * (d / 2) (in both cases calculating from left to right).

How does it look in programming languages?

Is it important to provide "better" order of arguments? Are there any compilers that can optimize calculation for this?

Do such constructions make sense:

```<code>// finding a result of a*b/c
if (abs(c)<1){
    result = a / c * b;
} else {
    result = a * b / c;
}
</code>```

(in the example one should also test values of a and b but let's assume they are large numbers)?

I know that using too large numbers I am risking an overflow. I know there is a difference between integer numbers (which are better in addition/subtraction) and float (which are better in multiplication / division).

There is also an issue with integer division, for example in Pascal there is common * multiplication operator and if both numbers are Integer, the result is Integer too, if one of them is Real (equivalent to float), the result is Real too. For division there are two operators: / which always results with Real number and div which takes only Integers and the result is Integer. So in this language it would be better first calculate multiplications and then divisions because Integer divisions may lead to losing the fractional part, and it is better to lose it later than earlier.

But for float numbers, which are stored with mantissa and exponent order of multiplications/divisions seems to be not necessary.

What I want to achieve is as most exact result as possible (speed is not necessary).


答:
There are two cases to consider: multiplication (including division) and addition (including subtraction). Because floating point numbers are stored in exponential form (i.e as m*2^e), these operations are performed on the mantissa (m) and exponent (e) as separate values, not on the whole numbers involved.

Multiplication (basically) involves multiplying the mantissae (which are always between 1 and 2) and adding the exponents (which are integers). It follows that unless the integer addition of the exponents overflows, the absolute magnitude of the numbers makes no difference to the precision of the result.

For addition, however, things are different. To add floating point numbers, one of the mantissae is shifted by an appropriate number of bits to make the exponents equal, and then the mantissae are added. This shifting operation loses precision proportionally to the difference in exponents. Thus, addition is more precise when the operands are closer in magnitude. In practice this means that if you are adding many floating point numbers that may vary wildly in magnitude, it is best to start with the smallest (closest to zero) and progress out to add the larger magnitude.numbers at the end. If you don't know the relative magnitudes in advance, put them in an array and sort the array by magnitude before summing it. If you do, use an accumulator variable and add the smaller numbers first.


问:
Ruby Sinatra best practices for project structure
Many people praise Sinatra's ability to create simple projects in a single file.  This is great and all but what if I want to use Sinatra for slightly larger project?

I'm fairly new to Ruby as a whole but have already found a couple ways to create a Sinatra application with separate models files, partitioning different groups or URLs into individual files, etc... But is there any best practice for this?

答:
One thing that helps me keep the routes manageable is to make the lines more compact by using lambdas. As you can see this is just a single line. If you need more work done in the block then just put that in a helper file and require it.

```<code>get '/', &block = lambda { haml :index }

get '/my_markdowns', &block = lambda { markdown :"graph", to_erb }
</code>```

"graph" is a markdown page and the to_erb method is in a helper to render it with erb layout. Haml has a :markdown tag but you still have to indent a lot for haml syntax.

Body:
One thing that helps me keep the routes manageable is to make the lines more compact by using lambdas. As you can see this is just a single line. If you need more work done in the block then just put that in a helper file and require it.

get '/', &block = lambda { haml :index }

get '/my_markdowns', &block = lambda { markdown :"graph", to_erb }

"graph" is a markdown page and the to_erb method is in a helper to render it with erb layout. Haml has a :markdown tag but you still have to indent a lot for haml syntax.


答:
The best solution is the one which minimizes the amount of code that you need to write, and therefore the amount of code that you need to read in order to understand what is happening.  We generally read any given piece of code far more times than we write it, so clarity is the most important quality of code.  (Besides correctness, of course.)

In light of this, the code in your own question is the best option.

"Come from"'s answer is quite good too, but what it boils down to is which way is more natural for you to think of the solution to the problem that your code is solving.  Presumably you wrote your code your way and not "come from"'s way because that was the most natural way for you to think of solving your problem. So, that's (almost by definition I'd say) the best way.

Any other option would further complicate your code, and for what? in order to avoid writing a couple of more statements, whether they be if statements or function call statements.

Note that the fact that you write those statements twice does not necessarily mean that they will be emitted by the compiler twice, or executed twice: rest assured that the compiler will do its best to restructure the emitted code so as to prevent any unnecessary duplication. (And if it can't, then there will be a tiny bit of duplication. So what?)

Essentially, since the compiler is free to do whatever it pleases behind the scenes, the sole remaining purpose for your code is to explain what is to happen in an as clear way as possible.  Conciseness is also a noble goal, but never at the expense of clarity.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
lexical scope for lambdas (using another keyword then function)
(or block syntax to create an proper lexical scope?)

make lambdas in object properties callable

always imply semicolon with lambda closing braces

fucking add use() for normal functions!!

traits

ability to intercept instanceof / is_a()

generators

open up Exception for runtime modification

a function to check against interfaces without implementing it


问:
When to really use a branch in git?
I have automated a few test cases and pushed them for review. However I need to continue developing other testcases in the same code. I cannot create a new sandbox everytime as my changes are not really in the stream and hence I dont get them in my newly created local. Is branching really the way to work? If so how do I keep my currently working changes private and isolated so that nobody is aware of it.. Not even the master?</p>

答:
Saying you have pushed cases for review indicates you are working in an organisation that uses git to do code review. So presumably they have a plan for how to do this, whether written down or just 'common knowledge'.

So you should follow what the organisation does. Git is just a toolbox with a variety of tools in in, one of which is called 'branch'. So there is no generic answer to your question based on solely knowing the fact you use git.

Any more than there is a valid answer to the question 'I have a hammer, what should I hit?'

Title: When to really use a branch in git?


问:
Premature memoization on obvious cases
In the code below there will be several instances of MainClass.

```<code>class MainClass(object):

    def f(self, x):
        # expensive operations.
        # ...
        return 'something'
</code>```

Each instance calls f(x) several times and x has a specific value that doesn't change during those calls.

Since f() is somewhat expensive, I can use the decorator @functools.lru_cache() to memoize the calls.

However, I am worried that this is premature optimization.

Questions:

Would it be dangerous to use lru_cache() from now?

Should I not care at all about which pieces of my code can be
optimized (even if they are obvious to spot, and easy to optimize)?

Should I ignore memoization on obvious cases completely, or perhaps note it (e.g. #TODO comments) so that it's easier later on when time for optimization comes?

(Note: My actual code is +10k LOC and I am the only dev working on it.)

答:
I don't see how this would be “dangerous” (The additional maintenance burden you take on is very modest, after all.) but you should benchmark it to be sure that is actually improves something.

If benchmarking sounds like too much trouble at this point, then it probably is a premature optimization and you should just forget about it for now.  Profile your code later when you encounter a need for optimization and see if this is a point where your optimization efforts will be well spent.

Title: Premature memoization on obvious cases


答:
You would typically use memoization where you have established that the problem that your function is trying to solve has optimal substructure.  This means that the larger problem can be broken well into a series of small subproblems.  It sounds as if you were successful in realizing this and that you solved this in a recursive way, which is also a way of breaking down a large problem into subproblems.

If you have working code and it satisfies all requirements including non-functional requirements on performance and scalability then you don't necessarily need to improve the performance of the code by using memoization.  Delaying the release of working software to optimize is generally the spirit of "Avoid premature optimization" in my humble opinion.

Would it be dangerous to use lru_cache() from now?

It depends on how you define danger.  If you have a working recursive solution without memoization then the only real danger here is possibly adding more complexity which increases the risk of introducing a bug into your logic.  The other risk is that you might delay the release of the software to work on an optimization that isn't necessary based on clearly defined non-functional requirements.

I might even argue though that if you have a long running recursive function then there might actually be danger in NOT using memoization!

What I mean by this is that for a sufficiently large dataset you run the risk of blowing the stack or running out of memory.  You should do adequate stress testing to ensure that your recursive solution is fine.

Should I not care at all about which pieces of my code can be optimized (even if they are obvious to spot, and easy to optimize)?

If it is an easy optimization then by all means go for it.  Premature optimization avoidance isn't so much a hard and fast rule as it is a guideline for living ones life as a developer.  It is inspired by some other subjective guidelines like YAGNI and KISS.

Should I ignore memoization on obvious cases completely, or perhaps note it (e.g. #TODO comments) so that it's easier later on when time for optimization comes?

Absolutely.  I think TODO's are a great way to leave little post-its for yourself and other developers about where something could be improved or done better.  That is also a matter of personal preference though.  Pro-TODO and Anti-TODO developers though have very strong opinions on either side and they both make good points.

Title: Premature memoization on obvious cases

Body:
In the code below there will be several instances of MainClass.

```<code>class MainClass(object):

    def f(self, x):
        # expensive operations.
        # ...
        return 'something'
</code>```

Each instance calls f(x) several times and x has a specific value that doesn't change during those calls.

Since f() is somewhat expensive, I can use the decorator @functools.lru_cache() to memoize the calls.

However, I am worried that this is premature optimization.

Questions:

Would it be dangerous to use lru_cache() from now?

Should I not care at all about which pieces of my code can be
optimized (even if they are obvious to spot, and easy to optimize)?

Should I ignore memoization on obvious cases completely, or perhaps note it (e.g. #TODO comments) so that it's easier later on when time for optimization comes?

(Note: My actual code is +10k LOC and I am the only dev working on it.)


答:
If the expensive operations have side-effects then they should be preserved. In other words this function will then not be a candidate for memoization.

If they don't and the output is constant like in your example, then why is there an expensive operation there in the first place?

Whether memoization actually helps depends on how it's used. Is the result cached anyway then it won't make a difference (it'll actually be worse because of the caching logic).

Title: Premature memoization on obvious cases


答:
As I understand your question you have created a branch (lets call it A) and submitted it for review before it can be merged into master. And you now need to do more work that builds on top of work in branch A. This work will be done in a new branch that we'll call B.

Obviously, if you create a new branch off of master you wont have the new features you've introduced in A. So, you have two options.

One. Branch B off of A rather than master.

Two. Branch B off of master and then do a merge from A.

In either case, you include all work from A in branch B. B, of course, can't be merged until A has been merged without effectively also merging in A.

The risk factor here is that if your work in A gets rejected, your work on B may need to be extensively rewritten, but that is a risk you cannot avoid without waiting for the review of A to be complete.

Eventually A gets merged into master and the problem goes away. If branch A gets revised during the review process you will, of course, have to merge those changes into B.

Title: When to really use a branch in git?

Body: I have automated a few test cases and pushed them for review. However I need to continue developing other testcases in the same code. I cannot create a new sandbox everytime as my changes are not really in the stream and hence I dont get them in my newly created local. Is branching really the way to work? If so how do I keep my currently working changes private and isolated so that nobody is aware of it.. Not even the master?</p>


问:
iOS Core data & NSUserDefaults
I am creating an App where users can search items from an external API. If the users likes an item they can store them into their personal "favourites item list".

My question is, is it a good practice to save this data as part of core data or NSUserDefault. Currently the data is stored within my database. Every time the user tries to access their favourites list I have to make an HTTP command to retrieve the data from the database.

This process is slow, so I want to save the favourites list data into core data or NSUserDefault. Is this a good approach.

Keeping in mind that the list could grow fast, depends on the users.

Is it a good idea to store large amount of data in core data or UserDefault?

答:
Is it a good idea to store large amount of data in core data or UserDefault.

I'd vote for "leave it server side".

One advantage to storing the data server side is that you get the same favorites whether you're connecting from your phone or tablet.

When I used to program for mobile, I tended to treat the entire device as a Presentation layer.  For example, if you had 1,000 "favorites", I might send only a couple hundred names of favorites in the initial HTTP call.

As you scrolled, I'd send down more names.  I wouldn't send down the details until you either stopped scrolling for a second or you actually selected a single favorite to view.  (If you stopped scrolling I might download the details for the dozen or so favorites currently visible on the screen).

Of course, this only works if you have a reliable network connection.  If you have to function offline, then your only choice is to cache the data locally, probably in core data.

Title: iOS Core data & NSUserDefaults


问:
Functional programming, compared to the process of a computer
In functional programming, it is considered bad practice (at least from my observations) to use state changes. Since computers operate in an imperative-language-like matter (performing one operation at a time, changing states of RAM), isn't functional programming contradictory to the way a computer operates?

Note: I'm not trying to say that a functional language cannot exist, because obviously there are several out there that do exist and work very well.

Further note: Besides the difference in processes, wouldn't a functional language be inherently extremely slow, due to the amount of operations involved?

答:
All programming languages and programs are generalized abstractions.  We simulate those abstractions on a machine that does things its own way.  Were we confined to the way a computer works, we would all be using languages like C or Forth, which are "close to the metal" languages.  Computers are general-purpose machines; we are free to create whatever paradigm over the processor's instruction set that we see fit.  It is this quality of computers that is what makes them so powerful: the ability to adapt them to any problem domain.

In other words, functional abstractions properly belong to the programming language being used, not the underlying machine that executes it.

In the 1980's Xerox and MIT built machines that could execute Lisp, a functional language, directly.  We don't do that anymore because we have processors that are fast enough to translate from one language (the one you write programs in) to another (the processor instruction set), and it's better to have a general-purpose machine that can execute any programming language.


问:
Too many REST API calls on a page?
A web app designed with highly modular, small components (in this case using AngularJS directives but could just as easily be WebComponents, ReactJS components, or any other technology).  Components often have asynchronous REST API calls, upon initialization or upon user interaction.  This design is causing many API calls per page (sometimes 20+).  Is there any problem with this design?  Some are suggesting we condense the API calls into larger client-side services that act as singletons.  So 10 API calls may be reduced to 1, even though a page may only use a portion of that data.  Are there any red flags, or problems with this design?  Which should be preferred?</p>

答:
This design is causing many API calls per page (sometimes 20+). Is there any problem with this design?

There shouldn't be. The fact that each request is small and async means you can greatly speed up your web app, rather than having to wait for a single large request to complete which blocks everything.

Just make sure your javascript is properly asynconious and can do things while your other requests are waiting and you will end up with a much better app than if you had one massive request that fetched everything.

After all browsers are designed to handle loading of many URLs in tandem, even a typical standard webpage may have tens if not hundreds of requests to images, css, javascript, iframes etc etc

Title: Too many REST API calls on a page?


答:
Well, first find out whether using a 64-Bit version would ever be beneficial:

Could the dataset processed ever be big enough to need a 64 Bit address-space to work?

Is the 64 Bit version ever more efficient or faster?

Are there any interoperability-scenarios sensitive to your programs bitness, changing the interface to make it insensitive to bitness isn't an option, and the bitness isn't yours to dictate anyway?

If the answer is no to all, consider not having a 64-Bit version at all.

Now, if there's a tangible advantage to using 64 Bit when you can:

Make it as comfortable as you can for your users without unduely penalizing those who know.

Provide a single download if that's not too much overhead, which installs the best version by default (allow overriding with a command-line option or such for experts wanting the 32-Bit build on 64-Bit).

Otherwise provide both separate downloads (if the potential advantage to using 64-Bit is small enough, hide that one a bit).

While you could provide a downloader for selecting and downloading only the parts needed, which can potentially reduce download-size by orders of magnitude if there are huge optional parts, mark that prominently as an online-installer and link also to an offline-installer.

(You can (and probably should) allow re-use of what it downloads, include an option to download everything, at least if you don't provide a full offline-installer.)


问:
If I want to build an application to transfer files between client and server, does it have to use port 21?
I'm taking an introduction Networking course and one of the first assignments is to make a simple file transfer application using socket API and TCP or UDP.  There is a server and a client. The client can connect to the server and request to get files from the server and store them locally. The client can also send local files over to store them on the server. (side note: I'm not sure if it's relevant information but I believe the files being transferred will be regular text files)

While I was reading a textbook, I stumbled on information about 'port 21' and how the File Transfer Protocol (FTP) is assigned to that port number. I don't know much at all about FTP but my application will be "file transferring".

Therefore, my question is: will I need to set my program up to use 'Port 21' or can I use any port number? If I can use any port number then is it more 'correct' to use Port 21?

答:
FTP is a specific type of transfer system and is defined by a standards document (RFC 959). Unless you plan on implementing RFC 959, your file transfer system won't be FTP and shouldn't be on port 21.

In fact, anything up to and including port 1023 is reserved for those types of well-known protocols. Ports 1024 and above are technically fair game for custom applications like yours, but there are a lot of registered port numbers in the 1024–49151 range and you may run into a conflict if you choose randomly.

Instead, I'd assign your application a port above 49151. You should generally be safe there.


答:
Email verification is good enough for most applications

It may not be perfect but most people expect and accept this kind of approach. Overall, a good process is as follows

User clicks "Forgot password"

System generates a one-time token (UUID), stores it in the database marking it as new

Email containing a HTTPS password reset link with the UUID sent to user email account. This is the weakness because it assumes that the user is authorised by their access to their email account, not the secret information you previously shared.

User clicks the link and the system verifies that the UUID is unused

Assuming all is well, the user is taken through the password reset process, which first marks the UUID as used and then accepts password updates.

The password is salted and hashed and then stored in the database. The plaintext version of the password is never persisted. Ever.

Valuable data?

If the data you are trying to protect is much more valuable (tax returns, bank details etc) then you need a stricter implicit authorisation process (see step 3 previously). This is usually in the form of a letter containing the UUID (usually hidden within a tamperproof envelope). The user is then expected to activate the password reset process and manually enter the UUID.

Extreme data

Finally, if the above is not enough then you're into the realms of identity management. You'll be breaking out the proof of address, driving license, passport, birth certificate, personal references and all the other frippery necessary to establish beyond reasonable doubt that the user is who they say they are. And then you proceed to step 5.


问:
REST API security: HMAC/key hashing vs JWT
I just read this article that is a few years old but describes a clever way of securing your REST APIs. Essentially:

Each client has a unique public/private key pair

Only the client and the server know the private key; it is never sent over the wire

With each request, the client takes several inputs (the entire request itself, the current timestamp, and the private key) and runs them through an HMAC function to produce a hash of the request

The client then sends the normal request (which contains the public key) and the hash to the server

The server looks up the client's private key (based on the provided public key) and does some timestamp check (that admittedly I don't understand) that verifies the request is not a victim of a replay attack

If all is well, then the server uses the private key and the same HMAC function to generate its own hash of the request

The server then compares both hashes (the one sent by the client as well as the one it generated); if they match, the request is authenticated and allowed to proceed

I then stumbled across JWT, which sounds very similar. However the first article does not mention JWT at all, and so I am wondering if JWT is different than the above auth solution, and if so, how.

答:
Let's get this started with a very basic answer.

JWT (as used in the context of OAuth and OpenID) does not require shared secrets between client and API. There are 3 components and pairs of 2 share a secret each: client <-> identification server, identification server <-> API.

This moves most complexity from the API to the identification server, the API just has to check that the token was issued by the identification server and was not tempered with. To verify that the API checks that the JWT-signature is valid with the known single shared secret between identification server and API. That's it!

How the identification server validates the user identity can vary widely (in many cases it's the old username+password pair over a TLS-connection), but is of no effect on your API.

Privacy and security of the message and the token itself when using JWT are handled by TLS, JWT is ignorant of such issues.


问:
Reducing the complexity of a class
I have looked at some answers and searched on Google, but I could not find anything helpful (i.e., that wouldn't have awkward side effects).

My problem, in abstract, is that I have an object and need to perform a long sequence of operations on it; I think of it as a sort of assembly line, like building a car.

I believe these objects would be called Method Objects.

So in this example at some point I would have a CarWithoutUpholstery on which I would then need to run installBackSeat, installFrontSeat, installWoodenInserts (the operations do not interfere with one another, and might even be done in parallel). These operations are performed by CarWithoutUpholstery.worker() and yield a new object which would be a CarWithUpholstery, on which I would then run maybe cleanInsides(), verifyNoUpholsteryDefects(), and so on.

The operations in a single phase are already independent, i.e., I am already grappling with a subset of them that may be executed in any order (front and rear seats may be installed in any order).

My logic currently uses Reflection for simplicity of implementation.

That is, once I have a CarWithoutUpholstery, the object inspects itself for methods called performSomething(). At that point it executes all these methods:

```<code>myObject.perform001SomeOperation();
myObject.perform002SomeOtherOperation();
...
</code>```

while checking errors and stuff. While order of operation is unimportant, I have assigned a lexicographic order in case I ever discover some order is important after all. This contradicts YAGNI, but it costed very little - a simple sort() - and it could save a massive method renaming (or introducing some other method of performing tests, e.g. an array of methods) down the line.

A different example

Let us say that instead of building a car I have to compile a Secret Police report on somebody, and submit it to my Evil Overlord. My final object will be a ReadyReport. To construct it I start by gathering basic information (name, surname, spouse...). This is my Phase A. Depending on whether there is a spouse or not, I may then have to proceed to phases B1 or B2, and gather sexuality data on one or two people. This is made of several different queries to different Evil Minions controlling night life, street cams, sex shop sales receipts and what not. And so on and so forth.

If the victim has no family, I will not even enter the GetInformationAboutFamily phase, but if I do, then it's irrelevant whether I first target the father or the mother or the siblings (if any). But I cannot do that if I haven't performed a FamilyStatusCheck, which therefore belongs to an earlier phase.

It all works wonderfully...

if I need some additional operation I only need to add a private method,

if the operation is common to several phases I can have it inherited from a superclass,

operations are simple and self-contained. No value from one operation is ever required by any of the others (operations that do are performed in a different phase),

objects down the line do not need to perform many tests since they could not even exist if their creator objects hadn't verified those conditions in the first place. I.e., when placing inserts in the dashboard, cleaning the dashboard and verifying the dashboard, I needn't verify that a dashboard is actually there.

it allows for easy testing. I can easily mock a partial object and run any method on it, and all operations are deterministic black boxes.

...but...

The problem arose when I added one last operation in one of my method objects, which caused the overall module to exceed a mandatory complexity index ("less than N private methods").

I have already taken the matter upstairs and suggested that in this case, the wealth of private methods is not a telltale of disaster. The complexity is there, but it's there because the operation is complex, and actually it's not all that complex - it's just long.

Using the Evil Overlord example, my problem is that the Evil Overlord (aka He Who Shall Not Be Denied) having requested all dietary information, my Dietary Minions telling me that I need to query restaurants, kitchenettes, street vendors, unlicensed street vendors, greenhouse owners etc., and the Evil (sub)Overlord - familiarly known as He Who Also Shall Not Be Denied - complaining that I'm performing too many queries in the GetDietaryInformation phase.

Note: I am aware that from several points of view this is not a problem at all (ignoring possible performance issues etc.). All that's happening is that a specific metric is unhappy, and there is justification for that.

What I think I could do

Apart from the first, all these options are doable and, I think, defensible.

I have verified that I can be sneaky and declare half my methods protected. But I'd be exploiting a weakness in the testing procedure, and apart from justifying myself when caught, I don't like this. Also, it's a stopgap measure. What if the number of required operations doubles? Unlikely, but what then?

I can split arbitrarily this phase into AnnealedObjectAlpha, AnnealedObjectBravo and AnnealedObjectCharlie, and have one third the operations being performed at each stage. I am under the impression that this actually adds complexity (N-1 more classes), with no benefit except for passing a test. I can of course hold that a CarWithFrontSeatsInstalled and a CarWithAllSeatsInstalled are logically successive stages. The risk of a Bravo method being later required by Alpha is small, and even smaller if I play it well. But still.

I can bunch different operations, remotely similar, in a single one. performAllSeatsInstallation(). This is only a stopgap measure and it does increase the complexity of the single operation. If I ever need to do operations A and B in a different order, and I have packed them inside E = (A+C) and F (B+D), I'll have to unbundle E and F and shuffle the code around.

I can use an array of lambda functions and neatly sidestep the check altogether, but I find that clunky. This is however the best alternative so far. It would get rid of reflection. The two problems I have is that I would probably be asked to rewrite all method objects, not only the hypothetic CarWithEngineInstalled, and while that would be very good job security, it really doesn't appeal all that much; and that the code coverage checker has issues with lambdas (which are solvable, but still).

So...

Which, you think, is my best option?

Is there a better way I haven't considered? (perhaps I'd better come clean and ask directly what is it?)

Is this design hopelessly flawed, and I'd better admit defeat and ditch - this architecture altogether? Not good for my career, but would writing ill-designed code be any better in the long term?

Is my current choice actually the One True Way, and I need to fight to get better quality metrics (and/or instrumentation) installed? For this last option I'd need references... I can't just wave my hand at the @PHB while murmuring These aren't the metrics you're looking for. No matter how much I'd like to be able to

答:
Somehow the problem reminds me of dependencies. You want a car in a specific configuration. Like Greg Burghardt, I'd go with objects/classes for each step/item/….

Each step declares what it adds to the mix (what it provides)(can be multiple things), but also what it requires.

Then, you define the final required configuration somewhere, and have an algorithm that looks at what you need, and decides which steps need to executed/what parts need to be added/which documents need to be gathered.

Dependency resolution algorithms are not that hard. The simplest case is where each step provides one thing, and no two things provide the same thing, and the dependencies are simple (no 'or' in the dependencies). For the more complex cases: just look at a tool like debian apt or something.

Finally, building your car then reduces to what possible steps there are, and letting the CarBuilder figure out the steps needed.

One important thing however is that you must find a way to let the CarBuilder know about all the steps. Try to do this using a configuration file. Adding an extra step would then only need an addition to the config file. If you need logic, try adding a DSL in the config file. If all else fails, you're stuck defining them in the code.

Title: Reducing the complexity of a class