问:
Why should a builder be an inner class instead of in its own class file?
Many Builder Pattern examples make the Builder an inner class of the object it builds.

This makes some sense since it indicates what the Builder builds. However, in a statically typed language we know what the Builder builds.

On the other hand if the Builder is an inner class, you should know what class the Builder builds without looking inside of the Builder.

Also, having the builder as an inner class reduces the number of imports since it can be referenced by the outer class--if you care about that.

And then there are practical examples where the Builder is in the same package, but not an inner class, like StringBuilder. You know that the Builder should build a String because it is named so.

That being said, the only good reason I can think of for making a Builder an inner class is that you know what the class' Builder is without knowing its name or relying on naming conventions. For example, if StringBuilder was an inner class of String I probably would have known it existed sooner than I did (speculative).

Are there any other reasons to make the Builder an inner class or does it just come down to preference and ritual?

答:
I think that the reason for doing this is so that the inner class (the Builder) can access private members of the class that it is building.

From http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Non-static nested classes (inner classes) have access to other members
  of the enclosing class, even if they are declared private.

...

Consider two top-level classes, A and B, where B needs access to
  members of A that would otherwise be declared private. By hiding class
  B within class A, A's members can be declared private and B can access
  them.

...

As with instance methods and variables, an inner class is associated
  with an instance of its enclosing class and has direct access to that
  object's methods and fields.

Here's some code to try to illustrate this:

```<code>class Example {

    private int x;

    public int getX() { return this.x; }

    public static class Builder {

        public Example Create() {
            Example instance = new Example();
            instance.x = 5; // Builder can access Example's private member variable
            return instance;
        }
    }
}
</code>```

As a static class, Builder doesn't have a specific instance of Example that it is tied to. However, given an instance of Example (or one that it creates itself) Builder can still access the private members of that instance.

Body:
I think that the reason for doing this is so that the inner class (the Builder) can access private members of the class that it is building.

From http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Non-static nested classes (inner classes) have access to other members
  of the enclosing class, even if they are declared private.

...

Consider two top-level classes, A and B, where B needs access to
  members of A that would otherwise be declared private. By hiding class
  B within class A, A's members can be declared private and B can access
  them.

...

As with instance methods and variables, an inner class is associated
  with an instance of its enclosing class and has direct access to that
  object's methods and fields.

Here's some code to try to illustrate this:

class Example {

    private int x;

    public int getX() { return this.x; }

    public static class Builder {

        public Example Create() {
            Example instance = new Example();
            instance.x = 5; // Builder can access Example's private member variable
            return instance;
        }
    }
}

As a static class, Builder doesn't have a specific instance of Example that it is tied to. However, given an instance of Example (or one that it creates itself) Builder can still access the private members of that instance.


答: There is no "should" in this case. Defining a builder inside another class or having it separate is orthogonal to the Builder pattern. Many examples do this due to convenience of presenting the code in one consistent file (also for accessing private members but that depends on context as well). Feel free to do otherwise </p>

ContentLicense: CC BY-SA 3.0

Title: Why should a builder be an inner class instead of in its own class file?

Body:
Many Builder Pattern examples make the Builder an inner class of the object it builds.

This makes some sense since it indicates what the Builder builds. However, in a statically typed language we know what the Builder builds.

On the other hand if the Builder is an inner class, you should know what class the Builder builds without looking inside of the Builder.

Also, having the builder as an inner class reduces the number of imports since it can be referenced by the outer class--if you care about that.

And then there are practical examples where the Builder is in the same package, but not an inner class, like StringBuilder. You know that the Builder should build a String because it is named so.

That being said, the only good reason I can think of for making a Builder an inner class is that you know what the class' Builder is without knowing its name or relying on naming conventions. For example, if StringBuilder was an inner class of String I probably would have known it existed sooner than I did (speculative).

Are there any other reasons to make the Builder an inner class or does it just come down to preference and ritual?


问:
My organization is relatively small; how can I follow ISO9000/1 as a matter of best practice?
I work for a company of <60 people. I understand that larger companies typically are ISO9000/9001 certified, as a matter of quality assurance. I also understand that for a company my size, such certification is not cost-effective. However, one could still make a case that as a matter of QA best-practice, I think it makes sense to try to follow the ISO standards anyway, at least insofar as reasonably practical. Am I correct in all these beliefs? If all the above is correct, are there any "high points" that would be particularly beneficial for a company my size to follow, or any parts of the standards that seem less relevant?</p>

答:
Here's ISO9000 in a nutshell:

Have a measurable process to develop things

Make sure everyone involved understands and follows the measurable process

Build things following the measurable process

Measure your progress while you follow the process of building things

Finish building things

Evaluate how the things measure against what the process said they should be

If there are issues then either fix the process or fix the thing or both

Rinse & repeat

Nothing within that nutshell says anything about the size of the organization.  Which is intentional because company size really has no bearing on whether or not it can meet ISO9000 requirements.  Larger companies have an advantage because they have more resources and can potentially better afford the overhead of all that measuring, but small companies can do the same thing too.

So how can you follow ISO9000?  Look at the summary steps above and go from there.  The key elements are:

have a process

measure building progress based upon the process

Fix the thing or the process when stuff is broken


问:
When would you choose *not* to update a third-party library to a newer version?
Using third party libraries for productivity gains in software development is common.  Unfortunately, along with the library's functionality we also import its bugs. Some of them get fixed in subsequent releases.  So, to upgrade or not to upgrade, this is the question.

I am interested in learning from experiences when upgrading to a newer version of the library was desirable, but after a cost/benefit analysis the conclusion was that upgrading was not a good solution "in the grand scheme of things". I am interested in finding out what forces influence the decision towards not upgrading.

答:
The short answer is that the new version could introduce new bugs, as Robert Harvey mentioned in the comments.

To be honest, I think you are approaching this the wrong way.  In my experience, the better approach is to default to sticking with the version you have.  Presumably, your team has already tested the version you use and how it integrates with your system.  If not, then your clients have.

Sure, when a new version comes out, your team should see if it addresses any bugs you have encountered, provides features you could take advantage of, or improves overall performance.  Only after running it through testing again should you actually start using it.

The problem with approaching upgrades as something which is done by default and only halted if someone finds a problem is that it is too easy to become lax on the vetting process.  Eventually, this will bite you when a new version introduces new issues.

If you stick with the version you have, you know that the overall system behavior will not change.


问:
unit tests for a csv parser
What tests should I use to unit test a csv parser?

I have a simple csv parser in C#, and I want to be sure I have good unit test coverage of all the common (and uncommon) edge cases. What tests should I use to identify potential problems and boundary cases?

答:
I just found https://github.com/maxogden/csv-spectrum:

A bunch of different CSV files to serve as an acid test for CSV
  parsing libraries. There are also JSON versions of the CSVs for
  verification purposes.

The goal of this repository is to capture test cases to represent the
  entire CSV spectrum.

Title: unit tests for a csv parser


问:
How big can a mobile development team be without being too big?
I work for a company that is moving heavily into mobile. We find the majority of our customers use our mobile app pretty regularly.

We have tons of things we want to add to it -- as well as to deliver all these new features on Andriod- and iOS-native apps.

But I wonder how big we could possible make a mobile development team without making it too big to be practical. Can we have a mobile team that's 5 people? 10? 50? 100?

If it made sense for us to build that many new features, from an Engineering standpoint is it practical? Or is there some limit of the amount of Engineers that could support a single app (across multiple platforms)?

答:
The upper limit for any team size is dictated by the governance in place within the company and the individual projects.  As the team grows larger, more governance is required in order to continue to remain productive.

Communication without governance grows by an exponential rate (n*(n-1)) because each team member needs to check in with every other team member in order to introduce significant changes.  Remember that communication paths are one-way in this case.

Small development teams get away with less communication because a team of 3 developers only has 6 communication paths.

A=>B; A=>C; B=>A; B=>C; C=>A; C=>B

A team of 4 developers has 12 paths.

A=>B; A=>C; A=>D; B=>A; B=>C; B=>D; C=>A; C=>B; C=>D; D=>A; D=>B; D=>C

Now this is usually manageable for small projects, but things start to break down when the sheer number of communication paths gets to be too much.

How much is too much?  It depends.  A well modularized application staffed by top-notch A-players can probably sustain a lot more developers with less (formal) governance then a poorly structured application with neophyte developers.

The point of the governance is to eliminate some of the communication pathways, and this is where specialization comes into play.  Developers start identifying themselves as "front-end" or "back-end" or "database" or whatever type developers.  It usually occurs as the application gets too large for any one person to really understand.

Governance comes into play because Front-end dev Sven normally never needs to talk to the database folk, and he very rarely needs to talk with Todd who is the team lead (or architect) for the back-end devs, and Sven almost never needs to talk to Jane who rules the database layer / roost.  Governance allows each developer to work within their normal sphere and minimize who they need to coordinate changes with.

So with a team of 12 developers, instead of having 132 communication paths, you have 3 groups of 12 communication paths plus 6 more communication paths between the 3 team leads.

So that was some fun, fancy-dancy, high-browed intellectual thoughts about teams.  Let's use your specifics for a little less abstraction.

You want to have iOS and Android apps.  That's fine, that's two teams there.

You have a ton of features you want to add.  That's fine too.  You're going to need teams for UI work, web services, database changes, etc ...  You now have more groupings to use to limit the total number of communication paths with.

Don't forget to designate folk to coordinate with other teams.  Some companies call these architects, other places call them team leads.  Call them what you want, just make sure that you don't duplicate too much effort between various teams.  Again, governance and process play a critical role here so that people focus only on the area they need to change in order to code up the necessary features.


问:
Push vs Poll when large delay (hours) is acceptable
It seems commonsense nowadays that polling is a bad practice and pushing is the way to go when developing mobile applications that require to constantly receive data from a remote server.

All major mobile shops provide their version of a push notification service:

Apple Push Notification Service

Google Cloud Messaging for Android

Microsoft Push Notification Service

However I'm wondering to what extent this assumption is valid. I mean, if I have an application that polls a remote server only a couple of times a day, and to which "notifications" don't need to be delivered instantly (a large delay is acceptable), then would it be a good decision to poll for data instead of pushing it?

Thanks in advance!

答:
Of course. It's also easier (just beware of pull spikes if everyone is pulling on the same schedule).

That said, I would challenge the assumption that 'a large delay is acceptable', considering mobile users expectations. ('Maps are not updated in real time! Unacceptable!' - or - 'I know it's the weather service, but I'm going to keep pushing that refresh button every five seconds until forecast for tomorrow turns sunny!')

ContentLicense: CC BY-SA 4.0


答:
I am actually going to suggest that you don't touch ISO at all if you're really interested in QA best practices. What ISO really boils down to is making sure that you "say what you do" and is completely unconcerned with whether or not what you say actually has any impact on the quality of what you produce. It's the quintessential example of a bureaucratic process that is more concerned with making sure that the process itself is followed rather than that it make sense (probably why it's so popular with the government).

We actually had an official auditor tell us that he didn't care if our documented deployment process was to burn our software to a disk and throw it out of a 3rd story window so long as we followed it.

To answer some of your actual questions: the big benefit you'd gain from ISO is that it would force you to actually sit down, think about, and document all your processes and periodically revisit them to see if you're sticking to them (and ideally revise them if necessary). There would be benefit to that but honestly, you really don't need ISO for any of that unless the only way to get the time and resources to do so is to sell upper management on it by use of a buzzword.

Title: My organization is relatively small; how can I follow ISO9000/1 as a matter of best practice?

Body: I work for a company of <60 people. I understand that larger companies typically are ISO9000/9001 certified, as a matter of quality assurance. I also understand that for a company my size, such certification is not cost-effective. However, one could still make a case that as a matter of QA best-practice, I think it makes sense to try to follow the ISO standards anyway, at least insofar as reasonably practical. Am I correct in all these beliefs? If all the above is correct, are there any "high points" that would be particularly beneficial for a company my size to follow, or any parts of the standards that seem less relevant?</p>


问:
Algorithm for defragmenting cross-pipe issues in a network for routing signals through?
I have a network I'm responsible for routing signals through.  You can think of the network as a directed graph of nodes (hardware) but each edge is really a pipe capable of fitting a specific bandwidth, I can route signals to any index on that pipe and may have multiple signals of different 'size' going across the pipe.  For what it's worth the signals are predetermined sizes and will not always be simple multiple of twos.

I know how to defragment a single 'pipe' easily enough.  However,  it's theoretically possible that I could have to move signals around across multiple pipes to create enough room to fit a new signal.  In a trivial example I could have two edges from A to B with enough space to fit a signal of size '4' available, and a signal of size '8'.  To fit the signal across I would have to move some signals from pipe 2 to 1 so that 1 is completely freed, living a full '8' slots available for my new signal to routed in.

How to detect and properly defragment these sort of cross-pipe issues?

Of course in the real world I may have to route signals through completely different devices, perhaps having signals take less-direct routes, to free up enough space for my new signal on any given pipe.

So in short across an entire system of these networks I want to

find a method to get a signal from input to destination in a crowded environment where I may have to move multiple signals to take a different path to their destination in order to free up sufficient space on a given pipe

figure out how to do the above with the minimum number of signals physically moved

have an approach that minimizes the need of running the above steps by minimizing fragmentation as much as possible.

This is a complicated series of requirements on their own, and I'm not looking for an answer on how to do it all, though such an answer is welcome.

答:
I don't think you have a graph problem, I think you have a bin packing problem.

To my understanding, graph theory is worried about length of the route (shortest, longest, # of edges, etc...) whereas the bin packing issue is concerned with most efficient utilization of some container.

In your case, the network pipes are your containers and the bandwidth of the signals is what you're packing into your pipes.

The Wikipedia article on bin packing briefly describes a few algorithms or approaches to consider.  It is an NP-hard problem, but optimal solutions can be found if you're able to "cheat" the rules.  I suspect that a "good enough" solution can be readily found for your case, and there are some suggested implementations linked within the article.

In the simpler case, you'll have a cascaded series of bins to optimize for.  Each layer in the series would represent one step across your network mesh.  This approach assumes that you can either switch nodal paths on-the-fly or that the signal bandwidth remains fixed for the configuration interval.  In essence, this is a divide-and-conquer approach using a bin packing algorithm to optimize bandwidth usage.

If you need to deal with the more complex case where you have to consider the capacity of the full, multi-step path, you'll need to modify your approach to the bin packing algorithm.  You might run into this case if you can't configure on-the-fly.  The challenge in this case is that any given signal could have multiple paths through the mesh, but you need to account for the capacity consumed by the signal based upon the path it actually takes.

I would cheat the more complex case by starting with the lesser of the number of signals or the number of potential paths.  The first-fit algorithm may be a reasonable place to start in this case.  You will likely need to roll through a number of iterations, and you'll need to implement some sort of memory within the algorithm to avoid starting scenarios that didn't end up resolving.

Another consideration in order to help the algorithm converge is to not worry about the "ideal" or "most efficient" utilization of the capacity.  The reality is that "good enough" means all of the signals get through within a reasonable number of hops.  Quibbling over the efficiency once you get past good enough is unlikely to provide as beneficial returns on your effort.

Finally, if there is a degree of variance within your signal capacities, then I would either add in a reserve capacity per pipe or overestimate the signal bandwidth in order to provide headroom for the excursions outside of the norm.


答:
Polling should be fine in your case.  And you won't have to integrate with yet another system (or multiple systems for multiple platforms).

Device specifics may be an issue, though.  Can you reliably poll when the app isn't front and center on the device? (may or may not be an issue for you).  Your ability to do so may depend on the techonolgy you are using for developing the app.

Title: Push vs Poll when large delay (hours) is acceptable

Body:
It seems commonsense nowadays that polling is a bad practice and pushing is the way to go when developing mobile applications that require to constantly receive data from a remote server.

All major mobile shops provide their version of a push notification service:

Apple Push Notification Service

Google Cloud Messaging for Android

Microsoft Push Notification Service

However I'm wondering to what extent this assumption is valid. I mean, if I have an application that polls a remote server only a couple of times a day, and to which "notifications" don't need to be delivered instantly (a large delay is acceptable), then would it be a good decision to poll for data instead of pushing it?

Thanks in advance!


答:
Polling is always acceptable when real-time isn't a necessity. What you have to ask yourself is why would you use one instead of the other?

The purpose of a push service is a couple things; it can be considerably less traffic for you to deal with if your pushes are broadcasts and a 3rd party provider does the broadcast - this allows you to send one message and have thousands receive it. But as you note, the biggest boon of a push service is the realtime nature that allows for immediate updates to reach your consumers. However when doing pushes you really don't ever want to be pushing large data sets if you're broadcasting, and you're also at the mercy of the third party push service you utilize (if you utilize one).

The purpose of a poll is to check for data differences periodically, where the update period can have an acceptable SLA of inaccuracy up to a certain time period. A poll will require all your clients to request the data periodically which will mean a connection being requested for every running client, and the necessity of a live service able to monitor that data accurately to serve it up to the pollers. Having accurate data to serve up means some data persistence which will take up disk and maintenance time.

So from this we can see that if you have concerns about network traffic or the maintenance of a service (which means possibly authenticating/authorizing requests, logging them which takes up disk space, all the normal requirements of maintaining a service) then you don't want to force clients to poll. However if the use case requires transmitting a particularly large data set or you can't be tethered to a third party's API which may change in time as well as their SLA or charges, then a home grown polling system may be applicable, though the maintenance overhead may be significantly more. Alternatively you may already be running service and have the data persisted such that the polling is a light addition to already in-place infrastructure, which makes polling more desirable.

Though to the central point you make you are correct; if real-time is necessary, polling will not do. If it is not, then you just have to do the math on how periodic the data can be checked multiplied by your client base multiplied by your data set size to decide if the network cost is going to be worth it, or if a push service would be better where you can always just push a change event that let's them request the large data set in a secondary step (though atomicity of these steps may be something you need to be careful of depending on the criticality of the data).


问:
Priority list of tasks stored in a database
I am trying to think of the best way to do the following:

I have a list of tasks stored in the database. A task has a priority assigned to it. You can change the priority of a task to reorder the order they should be carried out.

I am thinking of something very similar to Pivotal Tracker.

So imagine we had the following:

```<code>1 Task A
2 Task B
3 Task C
4 Task D
5 Task E
</code>```

We decide that E is now the most important task

```<code>1 Task E
2 Task A
3 Task B
4 Task C
5 Task D
</code>```

I need to update all 5 tasks to give them a new priority.

If Task B then becomes more important then A I would I would have

```<code>1 Task E
2 Task B
3 Task A
4 Task C
5 Task D
</code>```

I need to update Task B and A only.

What ways would go about structuring this in a DB? I imagine that you would have a differnt projects stored in the same table that would have there own weight.

Would it be better to point a Task that takes place after it (a bit like a link list).

This is just a brain dump really. Just was wondering how you would go about implementing something like this.

答:
I'm no database guru, so I solved this the most logical way I could in Access 2010.  I have a "Priority" field that is a numerical field.  Then I have an event for this field.

The event is an after update event for field "Priority" that triggers an Update Query "qryPriority" to add 1 to the priority number of all other records that have a priority greater than or equal to the priority number just entered.

Here is the event VB code and Update Query SQL:

"Priority" Event VB Code:

```<code>Private Sub Priority_AfterUpdate()
Me.Refresh
If Priority > 0 Then
DoCmd.OpenQuery ("qryPriority")
End If
Me.Refresh
Priority = Priority - 1
End Sub
</code>```

"qryPriority" Update Query SQL:

```<code>UPDATE YOURTABLENAME SET YOURTABLENAME.Priority = [Priority]+1
WHERE (((YOURTABLENAME.Priority)>=[Forms]![YOURFORMNAME]![Priority]));
</code>```

Body:
I'm no database guru, so I solved this the most logical way I could in Access 2010.  I have a "Priority" field that is a numerical field.  Then I have an event for this field.

The event is an after update event for field "Priority" that triggers an Update Query "qryPriority" to add 1 to the priority number of all other records that have a priority greater than or equal to the priority number just entered.

Here is the event VB code and Update Query SQL:

"Priority" Event VB Code:

Private Sub Priority_AfterUpdate()
Me.Refresh
If Priority > 0 Then
DoCmd.OpenQuery ("qryPriority")
End If
Me.Refresh
Priority = Priority - 1
End Sub

"qryPriority" Update Query SQL:

UPDATE YOURTABLENAME SET YOURTABLENAME.Priority = [Priority]+1
WHERE (((YOURTABLENAME.Priority)>=[Forms]![YOURFORMNAME]![Priority]));


问:
Python - 'if foo in dict' vs 'try: dict[foo]'
This is less a question about the nature of duck typing and more about staying pythonic, I suppose.

First of all - when dealing with dicts, in particular when the structure of the dict is fairly predictable and a given key is not typically present but sometimes is, I first think of two approaches:

```<code>if myKey in dict:
    do_some_work(dict[myKey])
else:
    pass
</code>```

And of course Ye Olde 'forgiveness vs permission' approach.

```<code>try:
    do_some_work(dict[myKey])
except KeyError:
    pass
</code>```

As a journeyman Python guy, I feel like I see the latter preferred a lot, which only feels odd I guess because in the Python docs try/excepts seem to be preferred when there is an actual mistake, as opposed to an, um… absence of success?

If the occasional dict does not have key in myDict, and it is known that it will not always have that key, is a try/except contextually misleading? This isn't a programming error, it's just a fact of the data - this dict just didn't have that particular key.

This seems particularly important when you look at the try/except/else syntax, which looks to be really useful when it comes to making sure that try isn't catching too many errors. You're able to do something like:

```<code>try:
    foo += bar
except TypeError:
    pass
else:
    return some_more_work(foo)
</code>```

Isn't that going to lead to swallowing all kinds of weird errors that are probably the result of some bad code? The above code might just be preventing you from seeing that you're trying to add 2 + {} and you may never realize that some part of your code has gone horribly wrong. I don't suggest that we should Check All The Types, that's why it's Python and not JavaScript - but again with the context of try/except, it seems like it's supposed to catch the program doing something it shouldn't be doing, instead of enabling it to carry on.

I realize the above example is something of a straw-man argument, and is in fact intentionally bad. But given the pythonic creed of better to ask forgiveness than permission I can't help but feel like it begs the question of where the line in the sand actually is between correct application of if/else vs try/except is, in particular when you know what to expect out of the data you're working with.

I'm not even talking about speed concerns or best practice here, I'm just sort of quietly confused by the perceived Venn diagram of cases where it looks like it could go either way, but people err on the side of a try/except because 'someone somewhere said it was Pythonic'. Have I drawn the wrong conclusions about the application of this syntax?

答:
Is missing key a rule or an exception?

From a pragmatic point of view, throwing/catching is much slower then checking if the key is in table. If missing key is a common occurrence - you should use condition.

Another thing in favor of condition is an else clause - it is much easier to understand when either block if executed, consider that even same exception class can be thrown from several statements in the try block.

Code in except clause should not be a part of the normal flaw (e.g. if key's not there, add it) - it should be handling the error.


问:
Best practice with respect to anonymous classes in UI applications
When working with user interface based Java programs, one way of attaching behaviour to a certain actions (e.g. to a button click) is through the use of anonymous classes. In the example below, the GUI framework is SWT, however I have the same issues with Swing or Android UI components. Namely the structuring of my programs.

MenuItem sampleMenuItem = new MenuItem(popupMenu, SWT.NONE);
sampleMenuItem.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent event) {
         doSomething();

         // handle all table entries
         for (int i=0; i<10; i++) {
             doSomething2();
         }

         doSomething3();
         doSomething4();
    }
});
```

Of course, some might argue that the amount of code in the sample above already warrants for the creation of a dedicated class that contains the logic. This is also suggested by Sonar's "Anonymous classes should not have too many lines" rule.

Interestingly, this rule also specifies that:

squid : S1188 - While waiting for support of closure in Java, anonymous classes is the most convenient way to inject a behavior without having to create a dedicated class. But those anonymous inner classes should be used only if the behavior can be accomplished in a few lines. With more complex code, a named class is called for.

However, since closures have not yet arrived in Java, my question is whether there are any more elegant solutions than:

writing a bunch of code within anonymous classes which has all sorts of drawbacks (limited reuse, slower navigating through the code, ...)

creating a huge number of dedicated classes which themselves all might have very limited functionality (i.e.: over-engineering, ...)

To extend my question: I would also like to know what are the best practices with respect to this aspect of Java based UI applications? Are there any well established patterns?

答:
The only pattern I've seen, that works is "When the code gets to hard to figure out what's going on, it's time to stop using an anonymous class.".

In your example, the method body is the anonymous class.  I might move the "new SelectionAdapter" onto it's own line, to make the opening paren a little more obvious, but otherwise it's fine.  Where you get into trouble is when a random person can no longer figure out where the anonymous class and method code are.

I've also create a private variable, or method to hold the anonymous class.  I put that kind of thing at the bottom of the class, out of the way.  It kinda sorta bridges the gap between a whole new class, and keeping it in the middle of the code.  Some people consider it bad style though, but my general rule of thumb is to code for readability first.


答:
Use the get method instead:

```<code>some_dict.get(the_key, default_value)
</code>```

...where default_value is the value returned if the_key is not in some_dict. If you omit default_value, None is returned if the key is missing.

In general, in Python, people tend to prefer try/except than checking something first - see the EAFP entry in the glossary. Note that many "test for membership" functions use exceptions behind the scenes.

Title: Python - 'if foo in dict' vs 'try: dict[foo]'

Body:
This is less a question about the nature of duck typing and more about staying pythonic, I suppose.

First of all - when dealing with dicts, in particular when the structure of the dict is fairly predictable and a given key is not typically present but sometimes is, I first think of two approaches:

```<code>if myKey in dict:
    do_some_work(dict[myKey])
else:
    pass
</code>```

And of course Ye Olde 'forgiveness vs permission' approach.

```<code>try:
    do_some_work(dict[myKey])
except KeyError:
    pass
</code>```

As a journeyman Python guy, I feel like I see the latter preferred a lot, which only feels odd I guess because in the Python docs try/excepts seem to be preferred when there is an actual mistake, as opposed to an, um… absence of success?

If the occasional dict does not have key in myDict, and it is known that it will not always have that key, is a try/except contextually misleading? This isn't a programming error, it's just a fact of the data - this dict just didn't have that particular key.

This seems particularly important when you look at the try/except/else syntax, which looks to be really useful when it comes to making sure that try isn't catching too many errors. You're able to do something like:

```<code>try:
    foo += bar
except TypeError:
    pass
else:
    return some_more_work(foo)
</code>```

Isn't that going to lead to swallowing all kinds of weird errors that are probably the result of some bad code? The above code might just be preventing you from seeing that you're trying to add 2 + {} and you may never realize that some part of your code has gone horribly wrong. I don't suggest that we should Check All The Types, that's why it's Python and not JavaScript - but again with the context of try/except, it seems like it's supposed to catch the program doing something it shouldn't be doing, instead of enabling it to carry on.

I realize the above example is something of a straw-man argument, and is in fact intentionally bad. But given the pythonic creed of better to ask forgiveness than permission I can't help but feel like it begs the question of where the line in the sand actually is between correct application of if/else vs try/except is, in particular when you know what to expect out of the data you're working with.

I'm not even talking about speed concerns or best practice here, I'm just sort of quietly confused by the perceived Venn diagram of cases where it looks like it could go either way, but people err on the side of a try/except because 'someone somewhere said it was Pythonic'. Have I drawn the wrong conclusions about the application of this syntax?

Body:
Use the get method instead:

some_dict.get(the_key, default_value)

...where default_value is the value returned if the_key is not in some_dict. If you omit default_value, None is returned if the key is missing.

In general, in Python, people tend to prefer try/except than checking something first - see the EAFP entry in the glossary. Note that many "test for membership" functions use exceptions behind the scenes.


问:
Is printing to console/stdout a good debugging strategy?
Let's say we have a function like this:

```<code>public void myStart()
{
    for (int i = 0; i<10; i++) myFunction(i);
}

private int myFunction(int a)
{

    a = foo(a);
    a = bar(a);
    return a;
}

private int foo(int a)
{
    //do something here

    //something gnarly here

    //etc
    return aValue;
}

private int bar(int a)
{
    // do something here
    //return aValue;
}
</code>```

Now for whatever reason, our code isn't working. Perhaps it's throwing an error, perhaps it's returning the wrong value, perhaps it's got stuck in an infinite loop.

The first thing any first year programmer, is print to console/std out, (having learned how to print Hello World before learning to use a debugger).

For example to debug this code they might do the following:

```<code>private int myFunction(int a)
{
    print("before foo: a=" + a);
    a = foo(a);
    print("before bar: a=" + a);
    a = bar(a);

    return a;
}

private int foo(int a)
{
    //do something here
    print ("foo step1: a=" + a);

    //something gnarly here
    print ("foo step2: a=" + a + " someOtherValue="+ someOtherValue + " array.length= " + someArray.length());
    //etc
    return aValue;
}

private int bar(int a)
{
    // do something here
    //return aValue;
}
</code>```

Now they run the code, they get a big console print out, which they can go through to trace where things are going wrong.

An alternative of course, is to set breakpoints and step through the code at each point.

One major advantage of printing to console, is that the developer can see the flow of the values in one go, without having to click through steps etc.

But the disadvantage is, your code is then riddled with all these print statements that then need to be removed.

(Is it possible perhaps to tell the debugger to print only certain values out to a log?, the breakpoints can then easily be added or removed without actually modifying the code.)

I do still use console printing as a primary debugging method, I'm wondering how common/effective this is in comparison to something else out there.

答:
Print statements and debugger are not mutually exclusive. They are just different tools available to you in order to locate/identify bugs.  There are those who will claim how they never touch a debugger and there are those who do not have a single logging/print statement anywhere in the code that they write.  My advice is that you do not want to be in either one of those groups.

Instead learn to use logging and learn to use a debugger. With experience you will (almost without having to think about it) pick the right tool and get the job done accurately and efficiently.  Without experience, sometimes you'll pick one over the other, and maybe it'll take you a bit longer poking around at the variables or sifting through log files, but that's all part of the learning process.

So, to answer your specific question. Yes. Using prints to trace execution is good and widely used debugging strategy. However...

Instead of using print statements, consider using a logging framework. Logging frameworks have a concept of logging levels so you can add a whole bunch of log messages but pick a level for each one.  When your application is running under normal conditions, your level would be ERROR or WARNING so that only important stuff gets reported.  However when you are tracing through the code and need to understand execution flow, you can change the logger to INFO or DEBUG and now all those "print" statements that you already have in the code will report additional info.

Using a logging framework...

you won't need to delete all the prints after you are done.

the prints you leave in the code, can help you or any other developer debug that same code in the future

you'll be able to debug this code in the field without having to rebuild it every time just to add the prints that you deleted.

you'll be able to redirect logging messages anywhere you want, not just a console. They could go to a file, syslog, DB, socket... etc

Update:
I just noticed at the end you were asking, "Is it possible perhaps to tell the debugger to print only certain values out to a log".  Depending on which debugger you use.  Many modern debuggers allow you to define an action to invoke when a breakpoint is hit. In some (I've done this in VS and WinDbg), it is possible to specify "print this and resume".  Visual Studio calls them "tracepoints" instead of "breakpoints"


问:
Factory method - when objects need information to get initalized
Lets look on a simple example: assume that I have three classes implemeting IPersonRepository: SQLPersonRepository, WebPersonRepository, InMemoryPersonRepository. I also have PersonRepositoryFactory class which is simple Factory method pattern implementation - contains GetPersonRepository methods which have enum/string as parameter. How could I create Factory pattern (or in other words centralize my object creation) when SQLPersonRepository needs dependency for: SQLConnection or string to database path, WebPersonRepository needs some http settings object and InMemoryPersonRepository has no dependencies? I could pass it in Factory constructor or as method parameter but it'd be ugly, unclean and unmaintable especially if I had more IPersonRepository implementations.

答: I suggest to implement PersonRepositoryFactory as an abstract factory, with subclasses SQLPersonRepositoryFactory, WebPersonRepositoryFactory and InMemoryPersonRepositoryFactory. Those subclasses can have different constructor parameters (like SQLConnection, HttpSetting or no parameters). Once you have initialized those three factory objects, you can use them through an ordinary factory method for producing of many IPersonRepository objects, all with the same SQL connection or http settings.


问:
What's the easiest (quickest) way to share one dataset in my app with someone else
I have some javascript that creates a canvas image that I want users to be able to share. I simply need to save the image somehow. Nothing else.

I've been contemplating using bits and pieces of ruby and activerecord, or perhaps sinatra but I feel like both would be over kill for this simple task.

Ideally I'd like to do it with JavaScript but I don't feel like including all of node. Any suggestions?

答:
If you just want to share something that lives clientside in your browser, you can always access querystring arguments with JavaScript and use that as the input, and have the javascript display a URL string that would recreate the live image.

The data required to recreate the image may be significant depending on the complexity and your approach (I would suggest some vector data as opposed to any actual scrape from the canvas, but you'd have to tell more about how you are drawing stuff on the canvas), and because of the size this may mean the querystring is horribly large. All the same this should work; post your webpage of HTML/JavaScript to a website and if people put the querystring url you give them, the webpage's JavaScript can parse that and recreate the canvas from the data in it.

This would get you away from doing any server side work if you really don't know anything about server side coding and don't want to kick up a server.


答:
To answer, let me first turn the question around on the need to upgrade.

If you never upgrade, over time you are stuck on an outdated version and will find bugs in your system that results from bugs in the library that have been fixed in later versions.

Assuming that you are continuing to develop your system, and the relevant library is of any size of complexity, sooner or later it will be worth upgrading. I.e. the cost of retesting justifies the benefit of the remaining on the latest version.

So, you may not need to upgrade if these assumptions fail.

I.e.:

You are not actively your application.

The library has minimal changes, perhaps only changes to specific problems that you know are not relevant to you.

It's more complex that this, as (2) is a moving target. With each library version that comes out, the accumulated change increases and hence the likely value (as well as risk and testing requirements).

Note that if you delay upgrade a long time "because so far none of the fixes matter to me", then when you do upgrade you may find it much harder due to accumulated impact.

Further, you may have multiple third party libraries that may require upgrade and retest from time to time. One approach is to review and consider upgrade of all third party libraries once per year (or whatever period), and execute the upgrade within a single project, allowing a single full system regression test. This might include upgrade to compiler or operating as well.

Finally, any risk in an upgrade will be inverse to the amount of automated testing in place. If you have very little (relevant to the library) and need to do a lot of manual testing you need more benefit to justify the upgrade cost.

So for example, upgrading a user interface library which requires extensive GUI retest is different to upgrading an XML lib which reads in a few files amenable an automated test.

Title: When would you choose *not* to update a third-party library to a newer version?

Body:
Using third party libraries for productivity gains in software development is common.  Unfortunately, along with the library's functionality we also import its bugs. Some of them get fixed in subsequent releases.  So, to upgrade or not to upgrade, this is the question.

I am interested in learning from experiences when upgrading to a newer version of the library was desirable, but after a cost/benefit analysis the conclusion was that upgrading was not a good solution "in the grand scheme of things". I am interested in finding out what forces influence the decision towards not upgrading.


答:
In the spirit of being "pythonic" and, specifically, duck typing - the try/except looks almost fragile to me.

All you really want is something with dict-like access, but __getitem__ can be overridden to do something not quite as you expect.  For example, using defaultdict from the standard library:

```<code>In [1]: from collections import defaultdict

In [2]: foo = defaultdict(int)

In [3]: foo['a'] = 1

In [4]: foo['b']  # Someone did access checking with a try/except exactly as you have in the question
Out[4]: 0

In [5]: 'a' in foo
Out[5]: True

In [6]: 'b' in foo  # We never set it, but now it exists!
Out[6]: True

In [7]: 'c' in foo
Out[7]: False
</code>```

Because the default return value is Falsy, access checking like that will work most of the time just fine..  It appears to keep the code simpler, too, which was why my co-workers and I had done it for months.

Unfortunately, a few months later, these extra keys actually ended up causing problems and hard-to-track-down bugs, because 0 became a valid value.  And sometimes we would use in to check if a key existed, making the code do different things when it should have been identical.

The reason I suggest it looks broken is because in Python's spirit of duck-typing, all you should want is something dict-like, and a defaultdict fits that requirement perfectly, as would any object you might create that inherits from dict.  You can't guarantee the caller isn't going to change its implementation later on down the line, so you should do the thing with the least side-effects.

Use the first version, if myKey in mydict.

Also, note that this is specifically about the example in the question.  The python creed of "Better to ask forgiveness than permission" is largely meant to ensure you actually act correctly when you don't get what you want.  For example, checking if a file exists and then trying to read from it - at least 3 things I can think of off the top of my head can go wrong:

A race condition is that the file might have been deleted/moved/etc

You don't have read permissions on the file

The file has been corrupted

The first one you can try to "ask for permission" on, but by nature of a race conditions it wouldn't necessarily always work; the second one is too easy to forget to check; and the third cannot be checked without trying to read the file.  In any case, what you do after failing will almost certainly be the same, so in this example, it is better to "ask forgiveness" by using a try/except.

Body:
In the spirit of being "pythonic" and, specifically, duck typing - the try/except looks almost fragile to me.

All you really want is something with dict-like access, but __getitem__ can be overridden to do something not quite as you expect.  For example, using defaultdict from the standard library:

In [1]: from collections import defaultdict

In [2]: foo = defaultdict(int)

In [3]: foo['a'] = 1

In [4]: foo['b']  # Someone did access checking with a try/except exactly as you have in the question
Out[4]: 0

In [5]: 'a' in foo
Out[5]: True

In [6]: 'b' in foo  # We never set it, but now it exists!
Out[6]: True

In [7]: 'c' in foo
Out[7]: False

Because the default return value is Falsy, access checking like that will work most of the time just fine..  It appears to keep the code simpler, too, which was why my co-workers and I had done it for months.

Unfortunately, a few months later, these extra keys actually ended up causing problems and hard-to-track-down bugs, because 0 became a valid value.  And sometimes we would use in to check if a key existed, making the code do different things when it should have been identical.

The reason I suggest it looks broken is because in Python's spirit of duck-typing, all you should want is something dict-like, and a defaultdict fits that requirement perfectly, as would any object you might create that inherits from dict.  You can't guarantee the caller isn't going to change its implementation later on down the line, so you should do the thing with the least side-effects.

Use the first version, if myKey in mydict.

Also, note that this is specifically about the example in the question.  The python creed of "Better to ask forgiveness than permission" is largely meant to ensure you actually act correctly when you don't get what you want.  For example, checking if a file exists and then trying to read from it - at least 3 things I can think of off the top of my head can go wrong:

A race condition is that the file might have been deleted/moved/etc

You don't have read permissions on the file

The file has been corrupted

The first one you can try to "ask for permission" on, but by nature of a race conditions it wouldn't necessarily always work; the second one is too easy to forget to check; and the third cannot be checked without trying to read the file.  In any case, what you do after failing will almost certainly be the same, so in this example, it is better to "ask forgiveness" by using a try/except.


答:
Printing to standard output in a way can be a good strategy to debug your code, for instance

i use a lot of print statements to see what is going on in different levels of my code especially if i don't fully understand the error

or maybe the error does not have any detailed information that might point me to what part of the code exactly is causing the problem.

However you need to get used to debugging tools, there are lots out there depending on what language or platform you use.

Also another method is logging, i log errors all the time when working on Android applications, also with exception handling, one can easily log a stack trace or error message of the exception being raised.

Title: Is printing to console/stdout a good debugging strategy?

Body:
Let's say we have a function like this:

```<code>public void myStart()
{
    for (int i = 0; i<10; i++) myFunction(i);
}

private int myFunction(int a)
{

    a = foo(a);
    a = bar(a);
    return a;
}

private int foo(int a)
{
    //do something here

    //something gnarly here

    //etc
    return aValue;
}

private int bar(int a)
{
    // do something here
    //return aValue;
}
</code>```

Now for whatever reason, our code isn't working. Perhaps it's throwing an error, perhaps it's returning the wrong value, perhaps it's got stuck in an infinite loop.

The first thing any first year programmer, is print to console/std out, (having learned how to print Hello World before learning to use a debugger).

For example to debug this code they might do the following:

```<code>private int myFunction(int a)
{
    print("before foo: a=" + a);
    a = foo(a);
    print("before bar: a=" + a);
    a = bar(a);

    return a;
}

private int foo(int a)
{
    //do something here
    print ("foo step1: a=" + a);

    //something gnarly here
    print ("foo step2: a=" + a + " someOtherValue="+ someOtherValue + " array.length= " + someArray.length());
    //etc
    return aValue;
}

private int bar(int a)
{
    // do something here
    //return aValue;
}
</code>```

Now they run the code, they get a big console print out, which they can go through to trace where things are going wrong.

An alternative of course, is to set breakpoints and step through the code at each point.

One major advantage of printing to console, is that the developer can see the flow of the values in one go, without having to click through steps etc.

But the disadvantage is, your code is then riddled with all these print statements that then need to be removed.

(Is it possible perhaps to tell the debugger to print only certain values out to a log?, the breakpoints can then easily be added or removed without actually modifying the code.)

I do still use console printing as a primary debugging method, I'm wondering how common/effective this is in comparison to something else out there.


问:
Building web apps in server-side vs client-side vs hybrid?
There are currently multiple approaches for building web applications:

1. Server-side only

This is a classical approach where you render pages on the server by a web framework like Ruby on Rails, Django, Express, Play! Framework and etc.

Typical workflow: Build all your business logic, models and view templates on the server in the framework of your choice.

2. Client-side + REST API

Relatively not too long ago, web community as a whole started to build client-side applications in Angular, Backbone, Ember, and a few dozen of other JavaScript MV* frameworks. And now we also have React.js join the party.

UPDATE: There is no misunderstanding. What I meant by client-side only is complete separation of concerns. Your have a REST API server and a client-side application that talks to that server. Depending on your use case, chances are, you will never have a true client-side only application that doesn't connect to a back-end either for authentication or data persistence.

Typical workflow: Spend hours deciding on Angular vs Backbone vs Ember vs X. Then you build your routes, models, views, controllers on the client. After you are done, now build models, controllers, routes on the server. In a way you are doing double amount of work.

3. Hybrid

I don't know much about using this approach, but if I were to take a guess, you render your views (View of the MVC framework) on the server. As a result you get SEO support plus faster page loads.

On the Hybrid front there is airbnb's rendr that supposedly combines backbone and express together.

Eric Florenzo has posted on his blog today: React: Finally, a great server/client web stack.

The amount of ways to build web applications is just overwhelming. And for someone who's learning web development this can become a problem. How does one decide on which approach to use in order to build their next application?

答:
I think you have totally misunderstood the "Client Side Only".

Firstly it should be labelled "Client Centric". This whole point of frameworks like Angular is that the "VC" parts of MVC are implemented entirely in the browser in Javascript. The "M" higher level logic of the "M" part -- the Model -- are implemented in the browser and the lower level "CRUD" logic is implemented on the server.

The business logic is developed once. The view logic is developed once. The control logic is developed once -- all in the Javascript framework of choice. The data access logic is also developed only once but this time on whatever RESTy or SOAPy framework you choose on the server side.

In extreme cases you can implement the Model entirely in the client, if it is acceptable to access the data from only one browser on one machine, and, have the data trashed every time the "Clear Cookies" option is selected.


答:
I think one of the key points of the newer approaches and frameworks is that there is less coupling between the front end technologies and the back end technologies.

The idea is that you can use whatever framework on the client and pull data and/or views from any number of sources regardless of the server side framework.

This lets us choose the best tools to get the job done and our choices can evolve independently.

Admittedly, I have not used Angular or Backbone so I can not make any experienced recommendations. My current base stack consists of the slimmest server side mvc or restful services I can find. Mostly delivering templates and data. The data is rendered and/or subsequent data retrieved client side using mostly just plain ol' javascript, jquery, and css.

I start here and build on it were I need to. The benefits of this approach are evident when you think about supporting multiple client platforms - browser, mobile, etc. If you need client specific rendering, you shouldn't need to make massive changes server side.

Title: Building web apps in server-side vs client-side vs hybrid?

Body:
There are currently multiple approaches for building web applications:

1. Server-side only

This is a classical approach where you render pages on the server by a web framework like Ruby on Rails, Django, Express, Play! Framework and etc.

Typical workflow: Build all your business logic, models and view templates on the server in the framework of your choice.

2. Client-side + REST API

Relatively not too long ago, web community as a whole started to build client-side applications in Angular, Backbone, Ember, and a few dozen of other JavaScript MV* frameworks. And now we also have React.js join the party.

UPDATE: There is no misunderstanding. What I meant by client-side only is complete separation of concerns. Your have a REST API server and a client-side application that talks to that server. Depending on your use case, chances are, you will never have a true client-side only application that doesn't connect to a back-end either for authentication or data persistence.

Typical workflow: Spend hours deciding on Angular vs Backbone vs Ember vs X. Then you build your routes, models, views, controllers on the client. After you are done, now build models, controllers, routes on the server. In a way you are doing double amount of work.

3. Hybrid

I don't know much about using this approach, but if I were to take a guess, you render your views (View of the MVC framework) on the server. As a result you get SEO support plus faster page loads.

On the Hybrid front there is airbnb's rendr that supposedly combines backbone and express together.

Eric Florenzo has posted on his blog today: React: Finally, a great server/client web stack.

The amount of ways to build web applications is just overwhelming. And for someone who's learning web development this can become a problem. How does one decide on which approach to use in order to build their next application?


问:
A Server sending data to be processed to clients
About a year ago I had an idea in mind which was using my friends computers to help me process my data, so I programmed a socket server application with boost::asio, and gave the client part of it to my friends.

When they connect they send the server (my machine) a message containing their computer specs (available cores, memory), based on that the server application decides how much data they can handle at a time and whenever they finish processing a batch they send a "ready for more messages" to my server, and the client applications keep sending data about the state of the process, and there is a lot of handling going in the background, whatever happens on the client machines its up to the server to take the right decision, if the connection with a client machine is lost and it has not been back in 5 minutes, the server keeps track of the data that has been sent to that machine and asks about it whenever that client reconnects.

I started this project and I only had some basic knowledge in network programming and I didn't read about any patterns that could be used and I just used my guts but I found it really useful, I would like to expand it but I want to know if there is a known pattern for doing the same thing using TCP sockets, if yes what's the name of that pattern?

I think of it as a super computer with its components spread around the world.

So I would appreciate some resources about this kind of thing.

答: The general concept you're referring to is distributed computing. More specifically, you seem to be doing some sort of volunteer computing. I'd suggest researching volunteer computing (on the magic googlebox) and looking into an existing project like BOINC.


答:
The answer to the question is that it depends on the requirements. An at least cursory look at the history of "web" development sort of indicates a cowboy culture where talking to stakeholders, customers, requirements gathering, is often overlooked.

I was lucky enough to attend a talk some years ago where I heard something that really stuck with me:  "you choose the design to meet the requirements, not the requirements to meet the design".  So when faced with a question like this, you need to go find out what is actually needed by the people who are asking you to build this software.

Your job is to explain the pros and cons behind each approach.


问:
Where can I find Turbo Pascal dialect description/reference?
Where can I find Turbo Pascal dialect description/reference? Is it still availiable in some place? I'm looking for the famous Turbo Pascal dialect description/reference(yes, the one from 80s/90s time) but I'm not having luck with google.</p>

答:
Since 2001, Borland has made it legal to download three vintage versions of Turbo Pascal for free: 1.0, 3.02 and 5.5.

You can get TP 5.5 here (you will have to fill out a short registration form if you haven't already visited the site).

You won't be able to run TP directly on any recent version of Windows.  I was able to install it and get it running in a DOS (command-line) box inside a Windows Virtual PC box (Windows XP Mode) under Windows 7.

You will be downloading a zip file (tp55.zip) containing images of two disks: Disk1 and Disk2.  All of the files need to be merged into one folder.  Open a DOS box, and using CD navigate to the folder containing all of the downloaded files.  Type install, and the program should start the installation.  Be sure to change the drive letter of the source disk from A to C when prompted.

By default, it will create a directory C:\TP where it puts all of the files.  For some reason, I got a message saying it couldn't run UNPACK.COM the first time I tried the install.  So I manually copied UNPACK.COM from the install source directory to C:\TP, and it ran fine the second time.

After you have successfully installed the program, edit your environment variables so C:\TP is added to your PATH.  That way you can run Turbo.exe from anywhere.

You can download a copy of the TP 5.5 manual here.

There is also a pretty good on-line tutorial for Turbo Pascal, with coverage of the object-oriented features introduced in TP 5.5 in Chapters 14 and 15.

For those that are interested in how the compiler works internally, there is a pretty neat website that discusses Turbo Pascal internals.


问:
Is input validation necessary?
This is a very naive question about input validation in general.

I'm a MATLAB user (1.5 years old) and I learned about input validation techniques such as "parse" and "validatestring". In fact, MATLAB built-in functions are full of those validations and parsers. So, I naturally thought this is the professional way of code development. With these techniques, you can be sure of data format of input variables. Otherwise your codes will reject the inputs and return an error.

However, some people argue that if there is a problem in input variable, codes will cause errors and stop. You'll notice the problem anyway, and then what's the point of those complicated validations?

Given that codes for validation itself take some efforts and time, often with quite complicated flow controls, I had to admit this opinion has got a point. With massive input validations, readability of codes may be compromised.

答:
The basic issue is how easy it is to understand and correct the input error.

If you have a short, simple sequence of "input x"... "number too large error, crashing" then the input validation is not really important. But when the user spends more than a few seconds entering information you either preserve it so they can resume where they left off, of they will get annoyed. Likewise, if they realise an earlier value was wrong they want to go back and edit it. Preserving input and jumping around in it means you now have to verify the saved values (did the user edit the saved values file?).

Or you skip the prompt-and-type cycle and go straight to a file. Matlab likes big files of input numbers. But very quickly you find yourself with a big "input" file that has to be verified. Having error messages that say "on line 8637 the 18th value is a float where it should be an integer between 0 and 400" is very handy. Albeit you shouldn't have 18 values on one line if you can avoid it. They're annoying to generate, but for the user "your 30,000 line file has an error, see if you can find it" is utterly unhelpful.

I once spent a month writing an "input file generator" for a scientist to use. He was feeding files into a big Fortran application that ran on a supercomputer, and it was very prone to the above type or message. It would run for an hour or two, then say "invalid profile". Not even "profile number 37 is invalid", just "something bad happened". So I wrote a GUI application that would load the file, parse it out and display it in an editable way, then save it as a valid input file for the big machine. Ugly as anything, lots of nested page controls and big grids, but usable. It was cheaper to pay me to do that than keep paying for supercomputer time that led to stupid error messages. And it dramatically sped up their work - instead of starting with a file they knew worked and modifying it one step at a time, feeding each one into their local slow computer and seeing if it ran overnight would an error, they could do a heap of edits in my program then verify it locally with great confidence that it would work.

Title: Is input validation necessary?


问:
Efficient way of evaluating an array of strings then add to an array in Ruby
I am looking for an efficient way of evaluating an array of strings against a series of rules and then adding them to another array.

For example I have an array of strings:

something

a

1234

#gohere

I want to iterate through all the items in the array and evaluate them based on a series of rules. For example:

Strings greater that 1 in length

Strings that don't start with the # character

I was thinking of either:

Nested loop of if statements evaluating the string for each rule and if they all pass then add to another array

Evaluating the string against rule 1 then adding to the array then performing another evaluation - I have discounted this since it requires lots of array read/write operations to evaluate the complete ruleset.

Please note that I have kept the number of rules to two for brevity however I could be needing up to 10 rules. Additionally, I do not control the original array since the function I am calling returns an array of strings.

I know I may have answered my own question with the nested loop however I wondered if anyone had any ideas for optimizing this type of situation.

Also, I know I asked this question in the reference of Ruby but any pseudo-code would suffice.

答:
I gave the answer below to a similar question at Stack Overflow:

```<code>module Checks
  def _invalid_permission() nil end
  def _check_another_error() "oops!" end
  def _and_another_one() nil end
end

class Doit
  @@checks = Checks.instance_methods(false)
  include Checks

  def doit
    @@checks.each { |m| rv = send(m); return rv if rv }

    "test"
  end
end

p Doit.new.doit # => "oops!"
</code>```

If you change

```<code>def _check_another_error() "oops!" end
</code>```

to

```<code>def _check_another_error() nil end
</code>```

then

```<code>p Doit.new.doit # => "test"
</code>```

Obviously, the check methods can be called with arguments.

This approach allows you to add, remove or rename a check method without having to remember to change references to it elsewhere.

Body:
I gave the answer below to a similar question at Stack Overflow:

module Checks
  def _invalid_permission() nil end
  def _check_another_error() "oops!" end
  def _and_another_one() nil end
end

class Doit
  @@checks = Checks.instance_methods(false)
  include Checks

  def doit
    @@checks.each { |m| rv = send(m); return rv if rv }

    "test"
  end
end

p Doit.new.doit # => "oops!"

If you change

def _check_another_error() "oops!" end

to

def _check_another_error() nil end

then

p Doit.new.doit # => "test"

Obviously, the check methods can be called with arguments.

This approach allows you to add, remove or rename a check method without having to remember to change references to it elsewhere.


问:
How to test a function that updates the password in database?
I have a test database with few user accounts. I don't want to break any tests.
If I am writing a function that updates password for user in db and one that reads the password.

Should I ideally reset the password to the previous one, once I am done testing update function ?

I have never written unit tests before, so I am little confused.

答:
An important rule when doing repeatable tests (automated or not) is to make sure that the test data is always in the same state before the tests start. This should be ideally assured for every single test of your test suite, so you can interchange the order of any tests at any time.

How you achieve this is up to you. For your scenario, it may make sense to reset the password to the original state after the test is finished (note that you have to do this indepently of the outcome of the test). A different approach is to have a complete db backup in place which is restored after each test (something which be feasible for small single-file databases like SQL lite or MS Access, but typically not for big C/S dbs like Oracle or MS SQL server). A third alternative is to have a script which initializes all relevant test data in your DB (including passwords) to a defined state, and to run this script automatically before any of your tests is executed.

Which of these alternatives is best depends on the kind of database you are using, the kind of tests you have, the dependencies among them, the total amount of test data, and some performance and safety considerations.


问:
Is it correct to require end-users to clear their cookies?
Is it any indications of poor programming if the support staff for a given product requires you to clear the cookies in order to troubleshoot issues with their web-site?

As a point of example, if you're trying to activate a new SIM on a tablet, and the carrier's activation web-site is giving you an error message that their web-site is down, even though there is no problem with actually accessing their web-server, which responds with the our-website-is-down page just fine.

Subsequently, the support staff instructs the user to try clearing the cookies (even though this activation web-site is not know to have been accessed prior to the error message taking place).

答:
It's just an example of tech support not knowing a lot about computers. I've had similar experiences with our tech support suggesting to customers that they turn of virus scanners, for instance. It's very much a cargo cult, driven by a business desire to keep expenses down.

As a customer, it's therefore a sign to avoid that company. They will be saving on QA too.


问:
Low level programming - what's in it for me?
For years I have considered digging into what I consider "low level" languages. For me this means C and assembly. However I had no time for this yet, nor has it EVER been neccessary.

Now because I don't see any neccessity arising, I feel like I should either just schedule some point in time when I will study the subject or drop the plan forever.

My Position

For the past 4 years I have focused on "web technologies", which may change, and I am an application developer, which is unlikely to change.

In application development, I think usability is the most important thing. You write applications to be "consumed" by users. The more usable those applications are, the more value you have produced.

In order to achieve good usability, I believe the following things are viable

Good design: Well-thought-out features accessible through a well-thought-out user interface.

Correctness: The best design isn't worth anything, if not implemented correctly.

Flexibility: An application A should constantly evolve, so that its users need not switch to a different application B, that has new features, that A could implement. Applications addressing the same problem should not differ in features but in philosophy.

Performance: Performance contributes to a good user experience. An application is ideally always responsive and performs its tasks reasonably fast (based on their frequency). The value of performance optimization beyond the point where it is noticeable by the user is questionable.

I think low level programming is not going to help me with that, except for performance. But writing a whole app in a low level language for the sake of performance is premature optimization to me.

My Question

What could low level programming teach me, what other languages wouldn't teach me? Am I missing something, or is it just a skill, that is of very little use for application development? Please understand, that I am not questioning the value of C and assembly. It's just that in my everyday life, I am quite happy that all the intricacies of that world are abstracted away and managed for me (mostly by layers written in C/C++ and assembly themselves). I just don't see any concepts, that could be new to me, only details I would have to stuff my head with. So what's in it for me?

My Conclusion

Thanks to everyone for their answers. I must say, nobody really surprised me, but at least now I am quite sure I will drop this area of interest until any need for it arises.

To my understanding, writing assembly these days for processors as they are in use in today's CPUs is not only unneccesarily complicated, but risks to result in poorer runtime performance than a C counterpart. Optimizing by hand is nearly impossible due to OOE, while you do not get all kinds of optimizations a compiler can do automatically. Also, the code is either portable, because it uses a small subset of available commands, or it is optimized, but then it probably works on one architecture only.

Writing C is not nearly as neccessary anymore, as it was in the past. If I were to write an application in C, I would just as much use tested and established libraries and frameworks, that would spare me implementing string copy routines, sorting algorithms and other kind of stuff serving as exercise at university. My own code would execute faster at the cost of type safety. I am neither keen on reeinventing the wheel in the course of normal app development, nor trying to debug by looking at core dumps :D

I am currently experimenting with languages and interpreters, so if there is anything I would like to publish, I suppose I'd port a working concept to C, although C++ might just as well do the trick.

Again, thanks to everyone for your answers and your insight.

答: If you don't do it just for fun, because geeks really love to have full control over their hardware, you might at least get a better feeling how much faster a program can become when written in C instead of, say, Java. You might also learn to really appreciate the features of higher-level languages, like garbage collection.</p>

ContentLicense: CC BY-SA 2.5


问:
What is an example of a computationally impossible business problem?
I have coworker who refuses to accept the reality that Turing machines (and Von Neuman machines by extension) cannot solve their own halting problem stating:

You can do anything with enough time and money.

He also dislikes theoretical problems arguing that:

In our field, we'll never run into those questions. We're application developers, not theoretical scientists.

Is there a good example of a business problem that is computationally impossible that I could use to help convince him of this?

答:
Others have commented on this, but I will try to write out an answer giving my point of view.

I like Robert Harvey answer, and the comments to his answer, and I would like to expand on those.

I think you have to present these undecidable problems (like termination) in a mundane way: for example, an IDE tool that "checks if this function always returns a value".

When teaching, my favourite example was refactoring (function equivalence, another undecidable problem). I asked:

how do you check if a function/program does the same after your nice refactoring? Sure, we have unit tests for that, but they do not cover all the cases. And they are boring to write... But we are programmers! We should write a program that checks if these two functions are producing always the same result!
  Why don't you try to write it?

or, as a variation maybe closer to your case:

We have this legacy code written in an ancient obscure COBOL dialect, for which no spec and/or compiler exist. We only have the program. Our whole business relies on it, so we have to be 100% sure the new Java code does exactly the same in every situation. Management wants a program that do that, checking all possible cases, and estimates it can be done in 6 to 8 weeks. Why don't you try to write it?

The point is not to write such a program. Or a good enough approximation of the requirements. The point is to realize that it can NOT be done in a direct way, do NOT waste countless ours trying to figure out how to do it (only to realize that it is not possible), but recognize it. "Ah! this is undecidable! It is not possible to do it directly. I need to figure out a different, more clever way to do it, with a good enough approximation".

You have to figure out a way to present the problem in a recognizable, and apparently simple, way. You wouldn't believe how many CS students will try to write such a program straight away... before taking a computability class :)


答:
Make each rule a lambda, such as this one that returns true if the string length is greater than 1:

```<code>->(s) {s.length > 1}
</code>```

Make an array of all of the rules that a string must pass for it to match.  Unless the list of rules changes, make it a constant:

```<code>RULES = [
  ->(s) {s.length > 1},
  ->(s) {s =~ /^#/},
]
</code>```

If any of the rules are complicated, give them their own constant, the name of the constant serving as a comment.  As with @sebastiangeiger's answer, order the rules by probability of failure.  You want to fail as early as possible, if speed is essential.

To see if a string matches, use the "any?" predicate:

```<code>RULES.all? do |rule|
  rule.call(s)
end
</code>```

Enumerable#all? short-curcuits, so the first rule that returns false will prevent the remaining rules from being evaluated for that string.

Now, to find all strings which match all rules:

```<code>matching_strings = strings.select do |string|
  RULES.all? do |rule|
    rule.call(string)
  end
end
</code>```

Title: Efficient way of evaluating an array of strings then add to an array in Ruby

Body:
I am looking for an efficient way of evaluating an array of strings against a series of rules and then adding them to another array.

For example I have an array of strings:

something

a

1234

#gohere

I want to iterate through all the items in the array and evaluate them based on a series of rules. For example:

Strings greater that 1 in length

Strings that don't start with the # character

I was thinking of either:

Nested loop of if statements evaluating the string for each rule and if they all pass then add to another array

Evaluating the string against rule 1 then adding to the array then performing another evaluation - I have discounted this since it requires lots of array read/write operations to evaluate the complete ruleset.

Please note that I have kept the number of rules to two for brevity however I could be needing up to 10 rules. Additionally, I do not control the original array since the function I am calling returns an array of strings.

I know I may have answered my own question with the nested loop however I wondered if anyone had any ideas for optimizing this type of situation.

Also, I know I asked this question in the reference of Ruby but any pseudo-code would suffice.

Body:
Make each rule a lambda, such as this one that returns true if the string length is greater than 1:

->(s) {s.length > 1}

Make an array of all of the rules that a string must pass for it to match.  Unless the list of rules changes, make it a constant:

RULES = [
  ->(s) {s.length > 1},
  ->(s) {s =~ /^#/},
]

If any of the rules are complicated, give them their own constant, the name of the constant serving as a comment.  As with @sebastiangeiger's answer, order the rules by probability of failure.  You want to fail as early as possible, if speed is essential.

To see if a string matches, use the "any?" predicate:

RULES.all? do |rule|
  rule.call(s)
end

Enumerable#all? short-curcuits, so the first rule that returns false will prevent the remaining rules from being evaluated for that string.

Now, to find all strings which match all rules:

matching_strings = strings.select do |string|
  RULES.all? do |rule|
    rule.call(string)
  end
end


答:
if there is a problem in input variable, codes will cause errors and stop.

A problem in inputs or code will cause errors and stop only if you're lucky. If you're unlucky, a problem in an input variable will cause an incorrect but plausible result.

Incorrect but plausible results are bad, because you think you've got the correct answer, and you think the problem is solved, so you move on to the next step of whatever it is you're doing, using an incorrect value. And the consequences of using an incorrect value that you think is correct can be huge - see did an Excel coding error destroy the economies of the Western world?.

Title: Is input validation necessary?

Body:
This is a very naive question about input validation in general.

I'm a MATLAB user (1.5 years old) and I learned about input validation techniques such as "parse" and "validatestring". In fact, MATLAB built-in functions are full of those validations and parsers. So, I naturally thought this is the professional way of code development. With these techniques, you can be sure of data format of input variables. Otherwise your codes will reject the inputs and return an error.

However, some people argue that if there is a problem in input variable, codes will cause errors and stop. You'll notice the problem anyway, and then what's the point of those complicated validations?

Given that codes for validation itself take some efforts and time, often with quite complicated flow controls, I had to admit this opinion has got a point. With massive input validations, readability of codes may be compromised.


问:
How do I stress the importance of unit tests to my manager
I've recently started a new job and I've been tasked with completing a feature that another developer didn't finish before he left the company.

The existing tests are out of date (i.e useless)... technical debt everywhere. I think it would be a very bad idea to implement features without tests, I've put this across to him a few times and he keeps saying that we'll complete this feature and then I can do tests.

But the previous developer didn't get around to updating the tests, so it seems that my manager just says that, but doesn't mean it and keeps pushing for more features.

This latest feature is a big one, and I think it would be a really bad idea to finish  it without writing tests for the whole application first. I understand that my manager has his own deadlines/pressures etc, but this feature needs to be done right, or it could come back to haunt both of us.

So how can I put this across to him in a way that will sink in how important this issue is?

I should also mention that I'm the sole developer, and the manager is non-technical.

答: If tests will help you deliver faster and more effectively, write them as you go (particularly possible in the form of asserts). He's hearing that you would like to waste time, because he has no basis for whether or not tests are a useful thing.</p>


答:
I know this problems from my company and after a nearly failed project the management decided to put more effort in testing. But that's of course not what you need.

I would try to explain him, that the later a bug / error is noticed, the more expensive (money & time) the correction will be. Show understanding for his requirements as he also needs to fulfill his own tasks but show up, that you can not guarantee the fulfillment of requirements in time. According to that, the "project success" is on risk.

As he is the project manager he would have need to explain to his bosses why he decided as he did. (This is implicit, I don't think you have to even mention it after your explanation)

What's really important is, that you communicate an a common knowledge level. Use language he understands and ask him for his sight on the topic. This way you get a discussion on the same level and hopefully he stops to block.
I hope this helps you out ;)

Title: How do I stress the importance of unit tests to my manager

Body:
I've recently started a new job and I've been tasked with completing a feature that another developer didn't finish before he left the company.

The existing tests are out of date (i.e useless)... technical debt everywhere. I think it would be a very bad idea to implement features without tests, I've put this across to him a few times and he keeps saying that we'll complete this feature and then I can do tests.

But the previous developer didn't get around to updating the tests, so it seems that my manager just says that, but doesn't mean it and keeps pushing for more features.

This latest feature is a big one, and I think it would be a really bad idea to finish  it without writing tests for the whole application first. I understand that my manager has his own deadlines/pressures etc, but this feature needs to be done right, or it could come back to haunt both of us.

So how can I put this across to him in a way that will sink in how important this issue is?

I should also mention that I'm the sole developer, and the manager is non-technical.


答:
I'm here assuming your project has more or less been used at this point.

Do not write tests for things that are already used. Such features are tested by the users themselves. Only write tests when a bug is encountered, to ensure that it doesn't happen again.

As for the new features, however, you should test them. You should maybe even test them before they exist (TDD). Do not work on another entity before the other one has been tested, and say that a feature is "not ready" if it hasn't been tested (which is true). Perhaps even include the testing time in the estimations for every task, when you feel it is indeed mandatory.


答:
I was just thinking this recently. I'd currently consider myself as a C# developer - which is perfectly fine for my career.

However, every so often I miss out on the really low level things (essentially 'getting my hands dirty' by doing assembler or device drivers in C). I just miss the programming. I don't expect that to help me in my career massively. If device drivers or embedded systems are your thing, then it could help a lot.

The more I program in the abstracted languages, the more I miss what got me into computers in the first place: poking around the computer and seeing what twitches. Assembler and C are very much suited for poking :)

By using the older languages, I think you're forced to do pretty much everything yourself. In C# I can do something like myArray.SortBy(x=>x.Name). No way I'd be able to do that in C. I'm accepting that the language will do the best sorting for me. If I was to do it in C, I'd be able to go back to the days of my university modules and revise my different sort and search algorithms.

So, I think the lower level languages would help you to revise any of the long forgotten bits that have all being abstracted away. More of a personal challenge than a career progressing one.

Title: Low level programming - what's in it for me?

Body:
For years I have considered digging into what I consider "low level" languages. For me this means C and assembly. However I had no time for this yet, nor has it EVER been neccessary.

Now because I don't see any neccessity arising, I feel like I should either just schedule some point in time when I will study the subject or drop the plan forever.

My Position

For the past 4 years I have focused on "web technologies", which may change, and I am an application developer, which is unlikely to change.

In application development, I think usability is the most important thing. You write applications to be "consumed" by users. The more usable those applications are, the more value you have produced.

In order to achieve good usability, I believe the following things are viable

Good design: Well-thought-out features accessible through a well-thought-out user interface.

Correctness: The best design isn't worth anything, if not implemented correctly.

Flexibility: An application A should constantly evolve, so that its users need not switch to a different application B, that has new features, that A could implement. Applications addressing the same problem should not differ in features but in philosophy.

Performance: Performance contributes to a good user experience. An application is ideally always responsive and performs its tasks reasonably fast (based on their frequency). The value of performance optimization beyond the point where it is noticeable by the user is questionable.

I think low level programming is not going to help me with that, except for performance. But writing a whole app in a low level language for the sake of performance is premature optimization to me.

My Question

What could low level programming teach me, what other languages wouldn't teach me? Am I missing something, or is it just a skill, that is of very little use for application development? Please understand, that I am not questioning the value of C and assembly. It's just that in my everyday life, I am quite happy that all the intricacies of that world are abstracted away and managed for me (mostly by layers written in C/C++ and assembly themselves). I just don't see any concepts, that could be new to me, only details I would have to stuff my head with. So what's in it for me?

My Conclusion

Thanks to everyone for their answers. I must say, nobody really surprised me, but at least now I am quite sure I will drop this area of interest until any need for it arises.

To my understanding, writing assembly these days for processors as they are in use in today's CPUs is not only unneccesarily complicated, but risks to result in poorer runtime performance than a C counterpart. Optimizing by hand is nearly impossible due to OOE, while you do not get all kinds of optimizations a compiler can do automatically. Also, the code is either portable, because it uses a small subset of available commands, or it is optimized, but then it probably works on one architecture only.

Writing C is not nearly as neccessary anymore, as it was in the past. If I were to write an application in C, I would just as much use tested and established libraries and frameworks, that would spare me implementing string copy routines, sorting algorithms and other kind of stuff serving as exercise at university. My own code would execute faster at the cost of type safety. I am neither keen on reeinventing the wheel in the course of normal app development, nor trying to debug by looking at core dumps :D

I am currently experimenting with languages and interpreters, so if there is anything I would like to publish, I suppose I'd port a working concept to C, although C++ might just as well do the trick.

Again, thanks to everyone for your answers and your insight.


问:
What changes can I make to my IDE to minimize the effect of my dyslexia?
I program and I am dyslexic. My vision is excellent. I do poorly processing symbols and am a visual thinker.

When I code, I'm slower than normal people because I am unpredictably unaware of the errors I make. I am learning python and the text only development environments cause me a lot of visual stress; I am using Wingware which is somewhat helpful, but cant complete assignments in the time given.

Can you suggest an accommodation that would help me?

What adaptations would be helpful to me?

Is there any way I can automatically find, highlight and fix these kinds of errors?

Proofreading, I see what I expect to see or something familiar. I don't notice typos, skip lines etc and the bugs turn up in testing. Even copy & pasting I can miss lines and cause errors.

Blocks of text from margin to margin give me headaches as do some color combinations

I do not process text as symbols, rather as objects that can be rotated, transposed so that the digits in a number move to different places, I may perceive "123" AS "132", THE LETTERS "pddq", look the same to me. I think of these as tricky - the same shape rotated and reflected.

答:
I do not know what language you are trying to develop in, but in any good IDE you should be able to change the default font to use Open Dyslexic which may help to some degree.

I personally use WebStorm/PHPStorm from JetBrains which does a great job of pointing out coding mistakes and syntax errors.

You may also want to focus a lot of your time practicing a good test-driven methodology so that any mistakes will be caught early. For JavaScript I use Mocha or Jasmine to do testing.

OwnerDisplayName: Dave Nelson


答:
I suffer from the same issues as you. Dyslexia has always made odd challenges but it isn't anything that can't be overcome!

I personally use Dreamweaver for all of my development - you can customise the code styling to the Nth degree. I have mine set up for a off white - off black background/text combination.

I know Dreamweaver isn't the cheapest, however it is good at picking up errors which has helped me extensively. You can also get it if you are a student for a significantly reduced amount; and it is worth every penny.

Title: What changes can I make to my IDE to minimize the effect of my dyslexia?

Body:
I program and I am dyslexic. My vision is excellent. I do poorly processing symbols and am a visual thinker.

When I code, I'm slower than normal people because I am unpredictably unaware of the errors I make. I am learning python and the text only development environments cause me a lot of visual stress; I am using Wingware which is somewhat helpful, but cant complete assignments in the time given.

Can you suggest an accommodation that would help me?

What adaptations would be helpful to me?

Is there any way I can automatically find, highlight and fix these kinds of errors?

Proofreading, I see what I expect to see or something familiar. I don't notice typos, skip lines etc and the bugs turn up in testing. Even copy & pasting I can miss lines and cause errors.

Blocks of text from margin to margin give me headaches as do some color combinations

I do not process text as symbols, rather as objects that can be rotated, transposed so that the digits in a number move to different places, I may perceive "123" AS "132", THE LETTERS "pddq", look the same to me. I think of these as tricky - the same shape rotated and reflected.


答:
If you are dyslexic, maybe you should start by leaning a statically typed language such as C, C++, C#, or Java.
Since you are forced to declare variables in these languages and there is type checking, the compiler and IDE will throw errors if by mistake you do something like:

```<code>var aux; //declaring a new variable
xau = 5; //mistake assignment. In python this will create a 2nd variable
</code>```

For dynamically typed languages such as Javascript, Python, PHP, you get get away with these mistakes, and you lose a lot of time trying to understand what's going on. That is why people often advise you to use test-driven methodologies, so that you can catch these errors more quickly.

If you really need to learn Python, then I probably you should try Visual Studio. It currently offers support for Python development.
Or try JetBrains PyCharm.

Body:
If you are dyslexic, maybe you should start by leaning a statically typed language such as C, C++, C#, or Java.
Since you are forced to declare variables in these languages and there is type checking, the compiler and IDE will throw errors if by mistake you do something like:

var aux; //declaring a new variable
xau = 5; //mistake assignment. In python this will create a 2nd variable

For dynamically typed languages such as Javascript, Python, PHP, you get get away with these mistakes, and you lose a lot of time trying to understand what's going on. That is why people often advise you to use test-driven methodologies, so that you can catch these errors more quickly.

If you really need to learn Python, then I probably you should try Visual Studio. It currently offers support for Python development.
Or try JetBrains PyCharm.

OwnerDisplayName: jff