问:
Is there a correlation between the scale of the project and the strictness of the language?
Explaining the difference between strictness of languages and paradigms to a colleague of mine, I ended up asserting that:

Tolerant languages, such as dynamic and interpreted languages, are used best for prototypes and small projects or medium-size web applications. When choosing elegant dynamic languages such as Python or JavaScript with Node.js, the benefits are:

Fast development,

Reduced boilerplate code,

Ability to attract young, creative programmers who flee “corporate languages”  like Java.

Statically typed/compiled languages are best for applications which require higher strictness such as business-critical apps or apps for medium to large-size apps.

Well-known paradigms and patterns developed for decades,

Ease of static checking,

Ability to find many professional developers with decades of experience.

Strict languages such as Haskell, Ada or techniques such as Code contracts in C# are better for systems which favor safety over flexibility (even if Haskell can be extremely flexible), such as life critical systems and systems which are expected to be extremely stable. The benefits are:

Ability to catch as many bugs as possible at compile time,

Ease of static checking,

Ease of formal proofs.

However, by looking at the languages and technologies used for large-scale projects by large corporations, it seems that my assertion is wrong. For example, Python is successfully used for large systems such as YouTube or other Google applications which require an important amount of strictness.

Is there still a correlation between the scale of the project and the strictness of the language/paradigm which should be used?

Is there a third factor that I've forgotten to take in account?

Where am I wrong?

答:
Your assertion is not wrong. You just need to dig little deeper.

Simply said, big systems use multiple languages, not just one language. There might be parts that are built using "strict" languages, and there may be parts that are built using dynamic languages.

As for your Google and YouTube example, I heard that they use Python primarily as "glue" between various systems. Only Google knows what those systems are built with, but I bet that many of Google's critical systems are built using strict and "corporate" languages like C++ or Java, or maybe something they themselves created like Go.

It is not that you can't use tolerant languages for large-scale systems. Many people say Facebook uses PHP, but they forget to mention that Facebook had to create extremely strict programming guidelines to use it efficiently on this scale.

So yes, some level of strictness is required for large-scale projects. This can come either from strictness of language or framework, or from programming guidelines and code conventions. You can't just grab few college graduates, give them Python/Ruby/JavaScript and expect them to write software that scales across millions of users.


问:
From a high level programming perspective, where does the 'different-paradigm' barrier between C# and F# really kick in?
I'm aware that they both use different programming paradigms, but from a high level perspective apart from differing syntax it seems most basic tasks can be achieved in similar fashion.

I only say this because when I've previously touched functional programming languages such as Haskell, writing code for basics tasks was (at first) difficult, frustrating, and required a completely different mindset.

For example the following took some time to get to grips with using recursive syntax:

```<code>loop :: Int -> IO ()
loop n = if 0 == n then return () else loop (n-1)
</code>```

Where as an F# loop is recognisable and understandable almost immediately:

```<code>let list1 = [ 1; 5; 100; 450; 788 ]
for i in list1 do
   printfn "%d" i
</code>```

When C# programmers start learning F# they are advised to completely re-think their thought pattern (which was definitely required for Haskell), but I've now written several F# programs dealing with conditions, loops, data sets etc to perform practical tasks, and I'm wondering where the 'different-paradigm' barrier really kicks in?

答:
I will comment from experience of using both languages (C# and F#) and the 'bumps' I have found. (I would agree that there are no barriers. There are definitely 'bumps' in the road though).

I first used F# for scripting through fsi because you can't do that with C# and I had been learning some functional paradigm stuff. F# did a really good, concise job because the task at hand was suited to functional programming (it was essentially map/reduce).

The biggest bump was in 'forgetting' objects, and realising that I don't have to use loops and conditionals. I spent a lot of time in this 'scripting' space. (I looked back at some old F# and saw how I was trying to 'force it' in the past).

I am now doing my first big piece of work in F# - a DSL. It is a better suited language for this task. I still use C# - this is my 'systems' language. Objects moving around and mutability suits the mental model I have of how that works.

I would say that it is about best fit for the job rather than making a total switch. The massive benefit is that it makes you think differently about how to solve various problems. Since I have learnt F# my C# has massively improved.

ContentLicense: CC BY-SA 3.0


答:
Another consideration is the who behind writing large-scale applications. I have worked at plenty of places who want to use Ruby or Python on some big enterprise-style projects, but are consistently "shot down" by IT managers and corporate security teams precisely because of the open source nature of the projects.

I have been told, "We can't use Ruby on Rails because it is open source and someone could put hacks in there that steal critical or protected information." I'm sorry, but once someone has that mindset that open source == evil, it is nearly impossible to change it. That line of thinking is a corporate disease.

C# and Java are trusted languages with trusted platforms. Ruby and Python are not trusted languages.

Title: Is there a correlation between the scale of the project and the strictness of the language?

Body:
Explaining the difference between strictness of languages and paradigms to a colleague of mine, I ended up asserting that:

Tolerant languages, such as dynamic and interpreted languages, are used best for prototypes and small projects or medium-size web applications. When choosing elegant dynamic languages such as Python or JavaScript with Node.js, the benefits are:

Fast development,

Reduced boilerplate code,

Ability to attract young, creative programmers who flee “corporate languages”  like Java.

Statically typed/compiled languages are best for applications which require higher strictness such as business-critical apps or apps for medium to large-size apps.

Well-known paradigms and patterns developed for decades,

Ease of static checking,

Ability to find many professional developers with decades of experience.

Strict languages such as Haskell, Ada or techniques such as Code contracts in C# are better for systems which favor safety over flexibility (even if Haskell can be extremely flexible), such as life critical systems and systems which are expected to be extremely stable. The benefits are:

Ability to catch as many bugs as possible at compile time,

Ease of static checking,

Ease of formal proofs.

However, by looking at the languages and technologies used for large-scale projects by large corporations, it seems that my assertion is wrong. For example, Python is successfully used for large systems such as YouTube or other Google applications which require an important amount of strictness.

Is there still a correlation between the scale of the project and the strictness of the language/paradigm which should be used?

Is there a third factor that I've forgotten to take in account?

Where am I wrong?


问:
Why is float the default in the majority of languages?
In programming languages, for represent numbers you have (mainly) two types: Int(s) and floats.

The us of Int is very easy. However floats cause a lot of unexpected surprises:

http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/float.html

I wonder why is not used a decimal-based type make more sense as the default for literals and normal math?

Where normal math is more precise?

答:
Floating point numbers are a tradeoff between precision and accuracy.  They are notable for their ability to handle very wide numeric ranges, with reasonable accuracy.  They are therefore considered a "one size fits all" type.

If you take a floating point number, and constrain its range to those numbers that can be represented by the mantissa only, you can treat it like an integer for accuracy purposes (in other words, you won't get the weirdness you would normally get from floats; you can compare them exactly in an if statement, for example).

This is why Lua chose a floating point as its default data type; in a sense, you can get the best of both worlds.

See Also

How Lua handles both integer and float numbers?


答:
Languages which are using a single representation of numbers are relatively rare.  As statically typed I can think only of some basic variants, and even in the dynamically typed realm I know more which are using at least integers and float than a unique format.  Those who are came relatively late in the game and the choice of binary floating point is probably the result of the fact that binary floating point was already available in hardware and as type in the implementation language of their interpreter.

Now, why binary floating point has become the method of choice for type modelling real numbers?

If you want a type to modelize real numbers while using a constant size of a few words, you have the choice between fixed point and floating point numbers.  Other kind of representation for rational numbers (fixed point and floating point are able to represent only rational number and a few other value like infinities -- which aren't real numbers BTW) exist but they are less widely useful.

Fixed point representations have some advantages, but they have one big issue: there is no good default for the number of digits after the point, so all languages and libraries which provide them ask the programmer to choose in the context of their application.

Floating point representations don't have that problem: once the size is fixed, you can come up with a repartition between the significand (often improperly called the mantissa) and the exponent good enough that allowing to customize it brings more problems than it would solve.

You may wonder why one has chosen a binary floating point format (BFP in the following of the discussion) instead of a decimal one.  Decimal floating point (DFP) has one (and none more) advantage over binary: it can represent exactly real constant as we usually write them, in decimal.  All other problems of BFP are also problems of DFP, but they may be hidden for simple enough computations by the advantage above (you get the exact result because the computation is so simple that all results -- final and intermediary -- are exactly representable).

DFP has some disadvantages of his own.  Some properties of real numbers are also properties of BFP, but not of DFP (the most obvious is that (a+b)/2 may be outside the closed interval [a, b] with DFP) and because of that and for some other reasons, analysis of numerical properties of algorithms is more difficult for DFP than for BFP. Worse, error bound achievable with DFP are worse than one achievable with BFP for a given representation size.  Implementing DFP is more difficult than implementing BFP (not so much that it has any importance nowadays, but it was a factor -- both of complexity and achievable performance -- when the trend was set).  Finally for scientific computing -- historically the major consumer of FP -- the advantage of DFP is not pertinent, while all its disadvantages are.

So you got BFP in the hardware because it was what people needing FP wanted, and although some language definitions allow for DFP, implementations rarely use the possibility and prefer to use what the hardware provides.

Title: Why is float the default in the majority of languages?

Body:
In programming languages, for represent numbers you have (mainly) two types: Int(s) and floats.

The us of Int is very easy. However floats cause a lot of unexpected surprises:

http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/float.html

I wonder why is not used a decimal-based type make more sense as the default for literals and normal math?

Where normal math is more precise?


答:
An interesting case study on the matters of scaling projects that use dynamic and interpreted language can be found in Beginning Scala by David Pollak.

I started searching for a way to express the code in my brain in a simpler, more direct way. I found Ruby and Rails. I felt liberated. Ruby allowed me to express concepts in far fewer lines of code. Rails was so much easier to use than Spring MVC, Hibernate, and the other “streamlined” Java web frameworks. With Ruby and Rails, I got to express a lot more of what was in my head in a shorter period of time. It was similar to the liberation I felt when I moved from C++ to Java...

As my Ruby and Rails projects grew beyond a few thousand lines of code and as I added team members to my projects, the challenges of dynamic languages became apparent.

We were spending more than half our coding time writing tests, and much of the productivity gains we saw were lost in test writing. Most of the tests would have been unnecessary in Java because most of them were geared toward making sure that we’d updated the callers when we refactored code by changing method names or parameter counts. Also, I found that working on teams where there were mind melds between two to four team members, things went well in Ruby, but as we tried to bring new members onto the team, the mental connections were hard to transmit to new team members.

I went looking for a new language and development environment. I was looking for a language that was as expressive as Ruby but as safe and high-performance as Java...

As you can see, major challenges in project scaling for author turned out to be in test development and knowledge transfer.

In particular, author goes into more details in explaining the differences in test writing between dynamically and statically typed languages in Chapter 7. In section "Poignantly Killing Bunnies: Dwemthy’s Stairs" author discusses Scala port of a particular Ruby example:

Why the Lucky Stiff... introduces some of Ruby’s metaprogramming concepts in Dwemthy’s Array in which a rabbit battles an array of creatures. N8han14 updated the example to work in Scala...

Compared to the Ruby code, the library parts of the Scala code were more complex. We had to do a lot of work to make sure our types were correct. We had to manually rewrite Creature’s properties in the DupMonster and the CreatureCons classes. This is more work than method_missing. We also had to do a fair amount of work to support immutability in our Creatures and Weapons.

On the other hand, the result was much more powerful than the Ruby version. If we had to write tests for our Ruby code to test what the Scala compiler assures us of, we’d need a lot more lines of code. For example, we can be sure that our Rabbit could not wield an Axe. To get this assurance in Ruby, we’d have to write a test that makes sure that invoking |^ on a Rabbit fails. Our Scala version ensures that only the Weapons defined for a given Creature can be used by that Creature, something that would require a lot of runtime reflection in Ruby...

Reading above can make one think that as projects grow even larger, test writing might become prohibitively cumbersome. This reasoning would be wrong, as evidenced by examples of successful very large projects mentioned in this very question ("Python is successfully used for... YouTube").

Thing is, scaling of the projects isn't really straightforward. Very large, long-living projects can "afford" different test development process, with production quality test suites, professional test dev teams and other heavyweight stuff.

Youtube test suites or Java Compatibility Kit sure live a different life than tests in a small tutorial project like Dwemthy’s Array.


问:
What is a "task pool"?
I have searched for many websites for a definition of "task pool", but most descriptions are very vague. Anywhere I can find a precise definition of it?

More details.

Are dependencies allowed in task pool?

Can a running task exchange data with other running tasks?

To phrase conversely, are tasks permitted to accept data only prior to start and permitted to publish results only after the task has finished?

What keeps track of the temporary resources (memory, CPU etc) that are used by tasks?

How to define weights that will encourage efficient task assignment?

For example, if one task needs to pass a lot of data to the next task, it may make sense to run the next task immediately following the first task, and as close to the first thread / CPU / machine / cluster (locality) as possible

What about tasks that are not known (do not exist) in the beginning, but were "created" later?

答:
There's some terminology trouble here, which is why your internet searches haven't yielded the answer yet.

A pool is the name given to a collection of 'expensive', re-usable resources such as threads, completion ports, database connections. The operating system, library or framework will manage the number of items in the pool according to some heuristics based on current load or availability of resource.

Tasks are usually units of execution, such as a Deferred Procedure Call, Delegate Call or Objective-C's NSTask. The simplest case is that there's a queue of these waiting to happen built up by code that needs things done 'later', at lower/higher priority than other tasks, asynchronously, concurrently, on another thread (e.g. UI thread) or some combination of all these. Some frameworks allow for inter-dependencies of tasks to be constructed, so you end up with fairly complex decisions being made to determine which task to execute next, but that's all down to the framework/library/O/S.

As already mentioned, the Task Parallel library is one example of breaking stuff up to be executed. Another is the NSOperationQueue on Mac OS X, which has been leveraged to greatly reduce the number of threads (expensive) required to be running at any one time.

To answer your questions specifically:

Dependencies depend on the framework/library you use, but its' a first-class concept.

Ownership of data is generally de-coupled from the creator of the task and passed to the task itself, as the actual thread/CPU it runs on is unclear. One task handing its' data to another isn't a particular problem conceptually - it depends on the framework for constraints. Use execution dependencies if one task needs the output of another.

As the task owns the data, it should take responsibility for cleaning up afterwards. Clearly, if you're handing data to another task, you need reference counting or garbage collection on top of a data ownership policy.

Some frameworks will allow tuning of which tasks run, how much CPU, at what O/S scheduling level, etc. If a task starts using all available memory, it's likely you'll have to deal with that in your own code. Even if you didn't use a 'task pool' strategy, that'd be a problem.

Tasks created 'later' can be enqueued in the existing task pool for execution.

ContentLicense: CC BY-SA 2.5

Title: What is a "task pool"?


答: Languages use binary floating point numbers because that's what the hardware usually provides.  Very few CPUs have instructions for handling decimal floating point numbers, and the adoption of the IEEE 754 appears to have fixed the decision for the future.</p>


问:
Pair Programming/Collaboration in a small company
I work at a small development company as the lead developer. We have two other developers, as well as my boss who is a developer, but doesn't really do much of the actual coding anymore.

The problem I am trying to overcome is multifaceted. We have a tendency all to work on our own projects without much collaboration between us. As a matter of fact, I (as the most advanced developer) ask for the others' opinion/help more than they do mine, because I value the input of an outside eye.

I want to increase our collaboration, and have expressed that to them. In large part because I'd like to show them some things about how to become better developers and follow better practices. But given our other developers' personality types, I think they are more comfortable working alone.

I've been reading about pair programming, and I have read (in some forums) that it doesn't work well when you have one developer being more advanced than the others (which I am). And yet, I feel it is imperative that we start to collaborate so that our work is not so disparate.

My question is whether anyone has ever been in a similar situation, and what worked for them?

I realize this is not a one-size-fits-all situation, but I'm willing to give multiple approaches a shot.

We all work in a common area, developers don't have have individual offices / cubicles.

答:
In my opinion, pair programming is not the solution to the issue you raise.

There are two distinct roles in a pair programming. The observer is there to review and feedback on the code written by the driver. If you are trying to convey ideas to improve the decisions your junior programmers are making, I question how effective you may find their ability to critically review the code you are writing when you are performing the role of the driver.

Without this dynamic the benefit of pair programming is lost.

As the senior programmer I would suggest you consider a stronger program of employee training and development with your boss. Your junior programmers should be given a framework to improve their skills. Typically you can use methods such as enlightenments, writing a coding standards document, splitting off self-contained tasks from your own work and ensuring proper code review processes are in place.


答:
I don't think that pair programming is something that would help you in your environment. It's not that it wouldn't help bring the less experienced developers up in skill - there's even a Programmers question about pair programming with engineers of varying skill levels. Even though there are benefits such as knowledge sharing and fewer errors, pair programming requires a greater time investment. With a team of three developers and only four people who have development backgrounds/experiences, maintaining a pair programming routine seems like it would be difficulty.

I think that a better alternative in your situation is code reviews, especially if you tailor them appropriately. A code review could consist of anything from one person looking over a small bit of code and providing feedback to multiple people (even the whole team) in a room for an hour or two to look through an entire component's design and implementation. These can be varied as appropriate for the work being done, especially based on the knowledge, experiences, and needs of the team. You can still get the knowledge sharing aspect by having multiple people partake in the review for the purposes of finding problems, providing suggestions, and gaining knowledge by reading the outputs of the review to incorporate the comments into their own work, before they have it reviewed. This also has the advantage of letting the other developers work individually until they consider their work to be done, but still provides a venue for achieving your desired goals while utilizing the entire team's knowledge and skills.

Title: Pair Programming/Collaboration in a small company

Body:
I work at a small development company as the lead developer. We have two other developers, as well as my boss who is a developer, but doesn't really do much of the actual coding anymore.

The problem I am trying to overcome is multifaceted. We have a tendency all to work on our own projects without much collaboration between us. As a matter of fact, I (as the most advanced developer) ask for the others' opinion/help more than they do mine, because I value the input of an outside eye.

I want to increase our collaboration, and have expressed that to them. In large part because I'd like to show them some things about how to become better developers and follow better practices. But given our other developers' personality types, I think they are more comfortable working alone.

I've been reading about pair programming, and I have read (in some forums) that it doesn't work well when you have one developer being more advanced than the others (which I am). And yet, I feel it is imperative that we start to collaborate so that our work is not so disparate.

My question is whether anyone has ever been in a similar situation, and what worked for them?

I realize this is not a one-size-fits-all situation, but I'm willing to give multiple approaches a shot.

We all work in a common area, developers don't have have individual offices / cubicles.


答:
My question is whether anyone has ever been in a similar situation, and what worked for them.

Since you're inviting experience here's what I did. I chose the low risk approach and asked someone decades younger than me to spend some time working together. We did not label the activity. Nobody, except for me, knew we were trying a new technique.

I don't know exactly what details to relate, but the process worked very well. He wanted to be mentored, which was something I had no hint of in advance. So it opened communication in both directions in a very positive way.

As a matter of fact, I (as the most advanced developer) ask for the others' opinion/help more than they do mine, because I value the input of an outside eye.

It sounds like you could frame this as logical progression of what you're currently doing.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
They asked me to search a Commercial Product that could find and fix source code bugs automagically.

Still searching..since 2001 :).


问:
How to manage with less technical knowledge?
I've become a project manager in my company and here is what I've experienced till now:

At first, I was trying to keep in shape technically with other developers of the team (about 15 developers) and read as much as I could so that I would know almost everything going on in the project, from architecture, up to syntax consistency.

However, soon I realized that it's almost impossible for you to know everything. Therefore it's natural that you fall back in the technical race. Imagine how much work it requires for you to learn Ext JS, Angular JS, BRE, WCF, Enterprise Library for logging, Asterisk, etc. etc. all at the same time. Thus it seems to me that this is not the correct path.

I think the formula is: The more people you have to manage, the less technical knowledge you can possess.

However, there are problems in not knowing what's going on inside your team technically:

You might not understand and detect bottlenecks just the way you would do when you were developing

You might not decide which technology is better at performance and productivity

In case of a technical dispute in team, you might not be able to help

The more distance you get from code, the less you might understand developer's stress, pressures, and feelings (this is a big concern for me)

You might not be able to forecast and predict the time necessary to get a task done

You loose your passion when a developer talks with enthusiasm about a problem that has been solved, because you don't understand like 40 percent of what he talks about, and the less you know about something, the more boring it might become for you

Developers would find it harder to explain something to you and they need to speak less technically

Bad developers (rare but existing) might misuse your lesser technical knowledge and cause all sort of problems

...

This phenomenon probably occurs in any career and profession. However, since the world of development and computer in general is moving forward with more speed (comparing to say, car industry), thus in a short period of time like 6 months you feel that you've fallen back. Version after version, feature after feature, library after library, you got the idea.

I saw these questions, and they contain good suggestions.

How can I maintain my technical skills after becoming a project manager?

How much should my project manager know?

How much should my project manager know?

Should a manager (or CEO)  in an IT company have an IT background to perform in the organization?

How can I convince management to deal with technical debt?

However, they're based more on personal experience and advises, which is of course good, but might not help that much.

Do we have a book, or a well-thought and researched essay on this subject, on how to manage a team of software developers, with lesser technical knowledge than team members? What points should I take into account to lead effectively and make the whole team achieve success?

答:
Some quick thoughts.

Be a leader, not a boss. Dont tell people what to do, and how to do it, instead give your team members problems to solve, challenges to own, and most importantly responsibility.

Dont hide behind a schedule. Talk to your team, sit down with them and ask them how they're going and what frustrations / issues they have. Understand what it is your team is doing.

Trust your team, ask them for information before making decisions that effect them.

Before "saber rattling" and changing how the team's working to "your" way, as often newly promoted people do. Take time to observe what works and what doesn't, and slowly fix the actual problems rather than imposing "your way".

Be steady, dont lose your cool, or your temper. There's always a solution, often one you never considered but someone on your team has. You succeed and fail as a team, not individuals.

Never take credit for things your team does, its not about you. Your job is to make them look good, and by proxy, their success will influence how people see you as a manager.

and finally

The temptation is often there for newly promoted people to do all the work for the team. You have a team for a reason, they want to help you. Use them, let them help you, let them take responsibility for things. delegate. Accept that you will not actually get any "work" done, but the things you will do instead are far more valuable to the team overall.


问:
Efficiently "moving" data upward through a communication stack
I have implemented an application protocol stack that moves an incoming stream of data upward through several layers, as follows:

copies a TCP segment from an OS buffer to my_buffer.

after identifying a record boundary, splits the record in my_buffer into tab-separated strings which are copied into deque<string> my_deque (rather than into a vector because I then have to immediately pop a couple of fields from the front)

copies my_deque to vector<string> my_records[n] where it is presented without further copying to the application.

I'm wondering whether it's best to stick to a clean architecture (layering) and pay the price (whatever that is) of copying payload from layer to layer, or if there are some simple optimizations that people use.

Is it customary to use separate buffers for separate layers, or is this something which can easily be optimized away without dangerously compromising the independence of the layers?

答: Rather than solve this problem again, I would highly recommend trying out http://kentonv.github.io/capnproto/.  It is being developed by the person who was maintaining https://developers.google.com/protocol-buffers/ internally at Google, and is specifically designed to take advantage of all of the good ideas that he had while doing that about how to make things faster for network communication.  (Protocol buffers themselves are already far more efficient than what most people do over the wire, and are extensively used internally at Google for exactly that reason.)</p>


问:
Git for a solo developer
I'm a developer working on a Wordpress project. I work on this alone and I want to improve the way I use Git but I don't know where to start.

Currently, I'm using git to commit all of the work that I've done for the day as long as that specific work is done. Here are some instances where I commit a specific work:

A specific feature whose code can be written within a day

A bugfix

For bigger features that can take weeks to finish I create a branch for it, then commit the sub-features once they're done.

But often times I feel like I'm committing way too much; for example, when I'm trying to solve lots of bugs I do not commit each and every bug that I resolve.

Sometimes I also end up working with 2 or more things that should be in there own commits. Then I'll find it hard to just target the specific files within a specific change so I end up putting them all in one commit and end up with a commit message like add search feature and add caching feature.

What I want to know are the best practices for solo developers working with Git. For solo developers out there you're welcome to answer with your own workflow as well.

答:
Solo or multiple is the same.  Commit early, commit often.  As soon as you go from non-broken to non-broken and changed, commit.  If you feel that you're committing a lot, it is only because you're not used to it.

Here is a benchmark for you.  When I was at Google, the average commit was under 20 lines.  That will feel crazy when you first do it, but really, it is not too much.

Title: Git for a solo developer


答:
I've had some experience in optimizing network code, both native and .NET.  Things that I've fond that are important include:

How many messages/second are being transferred?

How many megabytes/second are being transferred?

Is this a garbage-collected language? (In your case, no)

What are your app requirements?

If 1 is "small" (50 per second or less?), then your network code frankly isn't what anyone will notice.  You should instead optimize for touch-friendliness, or improve your customer's workflows of something; you'll get more bang for the buck.   For server scale, you'll need to worry more about thread affinity than about memory copies.  If it's large, a number of OSes now include special network APIs to handle the shear number of calls -- Windows, for example, has the RIO APIs in Winsock for just this.

If 2 is "big" (> 100 megabytes/second), then you need to worry about extra copying on servers but only because of the memory pressure.  For a VM environment especially, that memory pressure will often be what keeps your VM from handling more clients, which instantly leads to having to run more VMs.

If 3 is true and #1 is "big" and you're on a server, you have to worry about memory pinning and object lifetime.  But don't let that drive you to avoid GC languages; there are lots of big programs that do networking in GC languages.

And #4 is truly important.  Do you have extreme latency requirements like high-speed stock traders?  Have you measured your performance?

I rarely meet up with client-side programs where optimizing the number of buffers copied made any difference that users could see.  For servers, I generally first see that there's an unexpected bottleneck that hits long before anything else.  There's a bunch of techniques to help -- receive-side scaling, various async techniques, and special buffer-management calls.

TL;DR: if you're not a server, keep your code clean. If you are, measure first, optimize second.  And "optimize" includes lots of techniques, of which "copy less memory" is one.

Title: Efficiently "moving" data upward through a communication stack

Body:
I have implemented an application protocol stack that moves an incoming stream of data upward through several layers, as follows:

copies a TCP segment from an OS buffer to my_buffer.

after identifying a record boundary, splits the record in my_buffer into tab-separated strings which are copied into deque<string> my_deque (rather than into a vector because I then have to immediately pop a couple of fields from the front)

copies my_deque to vector<string> my_records[n] where it is presented without further copying to the application.

I'm wondering whether it's best to stick to a clean architecture (layering) and pay the price (whatever that is) of copying payload from layer to layer, or if there are some simple optimizations that people use.

Is it customary to use separate buffers for separate layers, or is this something which can easily be optimized away without dangerously compromising the independence of the layers?


答:
Since it has already been discussed in other answers why pair programming isn't a solution for you, I will discuss what we have currently experimented with, and are satisfied with the results.

In my view what you can do to increase collaboration is to have two people together on each project. Each of them works on a different part of the project, but because these parts have to be integrated the two developers have to collaborate. This also requires that the two programmers discuss the architecture (layering and interfaces) of the project, and then decide to take on different roles.

And, if this approach, limits the number of projects your company can handle at a time, you can assign this collaborating pair two projects simultaneously.

We recently experimented with this approach, having one of them develop models + integration with apis and the other programmer handling views and controllers. We have found following advantages of this setting:

The code structure results out in a much better way than if only one is working on all aspects of the project.

We don't have to remind them about committing code to repository etc.

They have to put some effort in testing each others code, instead of relying solely on our dedicated QA for it.


问:
What is the definition of pointer?
Conceptually a "pointer" is just something that "points" to something else;Is this definition is sufficient to tell exactly what a pointer is in programing languages?
Does it need to have any other features?

Programmers who come from specific language may have  pre-conceived  ideas of what constitutes a 'pointer' based on how it is used in the language So let say if he is from c/c++ language, he say's pointers supports pointer arithmetic.Is pointer arithmetic an essential feature of a pointer?

Go has pointers and does not support pointer arithmetic. Is the ability to "dereference" the pointer essential to the concept of a pointer?

So what is the precise definition of a pointer that I can give as an answer, irrespective of any specific programming language?

答:
What a pointer "is" is typically dependent on both the language, and the implementation of that language. e.g: Pointers in C/C++ are typically int's which hold the memory address of the thing pointed at, however they dont necessarily have to be. Thats just how they're usually implemented.

So, thinking about operations that can be performed on a pointer, anything other than a "deference" is really implementation dependent. Being able to do pointer arithmetic is often useful, but depends entirely on the underlying implementation.

Pointers also have a secondary role in c/c++ in that they often point at items allocated on the heap rather than the stack. This is differentiation is often not captured in other languages. Other languages tend to avoid the term "pointer" and use "reference" or "alias" instead.

Personally, I like to think, in a general sense, of pointers as a special type of alias. But when it comes to C/C++ I tend to envisage the entire language as being about memory, and pointers become just one subset of managing memory.

Title: What is the definition of pointer?


答:
What is the definition of pointer?

That completely, entirely depends on the language.

Both C and C++ (there's no such language as "C/C++"!) have a solid, precise definition of pointers. For example, C99 says (§6.2.5.20):

A pointer type may be derived from a function type, an object type, or an incomplete type, called the referenced type. A pointer type describes an object whose value provides a reference to an entity of the referenced type. A pointer type derived from the referenced type T is sometimes called ‘‘pointer to T’’. The construction of a pointer type from a referenced type is called ‘‘pointer type derivation’’.

(emphasis mine)

later, when describing the & (address-of) operator (§6.5.3.2.3):

The unary & operator yields the address of its operand. If the operand
  has type ‘‘type’’, the result has type ‘‘pointer to type’’.

This interpretation again suggests that a "pointer" is simply an address. (Well, not simply, but an address nevertheless.)

Is the ability to "dereference" the pointer essential to the concept of a pointer?

Again, that depends. Conceptually, Java has pointers, but you can't dereference them. Objective-C objects are pointers too, but the compiler whines if you are trying to dereference such a pointer. (I suspect that these phenomena have a common origin - pointers are used in both languages to represent references to objects, and at an implementation level, they are also used for different clever things like polymorphism.)

So what is the precise definition of pointer i can answer irrespective of specific programming language?

Unfortunately, there's no such thing. (Shameless self-promotion: but you can provide a link to this answer if you think it's good enough :P)

Title: What is the definition of pointer?

Body:
Conceptually a "pointer" is just something that "points" to something else;Is this definition is sufficient to tell exactly what a pointer is in programing languages?
Does it need to have any other features?

Programmers who come from specific language may have  pre-conceived  ideas of what constitutes a 'pointer' based on how it is used in the language So let say if he is from c/c++ language, he say's pointers supports pointer arithmetic.Is pointer arithmetic an essential feature of a pointer?

Go has pointers and does not support pointer arithmetic. Is the ability to "dereference" the pointer essential to the concept of a pointer?

So what is the precise definition of a pointer that I can give as an answer, irrespective of any specific programming language?


答:
I do not know of any general definition for "pointers", or another related term, "references". It's fairly safe, however, to say that pointers and programming languages supporting pointers usually have several of the following characteristics:

At the very least, a pointer is a reference to other objects/values.

A pointer type may or may not be typed, i.e. pointers of that type may reference only a certain type of objects/values (e.g. int* vs. void* in C). Whether this characteristic is present or not may depend mostly on the nature of the supporting programming language's type system.

A programming language that supports pointers may or may not have a pointer dereference operator, which resolves a pointer to the referenced object/value (e.g. unary * in C).

Such a programming language may or may not have an operator that creates a pointer for an object/value (e.g. unary & in C).

A pointer may or may not contain a null reference, i.e. not point at anything. (This feature was invented by Tony Hoare, which he now calls his Billion Dollar Mistake.) Such pointers may not be dereferenced, and cannot be the result of the pointer creation operator.

A pointer type may or may not support a limited form of arithmetic, e.g. incrementation/decrementation, adding/subtracting an integral value to a pointer value, subtracting two pointers of the same pointer type, etc.

A pointer, i.e. a reference to another object, may be implemented using memory addresses (linear, segmented, or otherwise).

Title: What is the definition of pointer?


问:
What would be negative test case for this scenario?
Let's say we have some requirements

Req1: User name will accept 6-10 character alpha value.

Req2: On click of Submit button, application will show error message "Please enter value or character between 6 to 10 including" for invalid boundary value.

In this case if we are designing test cases for invalid boundary values of 5 and 11, those would be positive test cases, since we are also verifying the error message, which is mentioned in requirement.

What would be negative test case for this scenario?

答:
If negative testing is testing things outside the specifications or testing things outside the normal usage is just a question of definition (and then you may also hold the view that some operator errors are so common that they are part of the normal usage).

For about every concept, there are limit conditions which can be chosen either to be part or not of the concept, the important is to ensure that you have a consistent definition in your team, and to be aware when communication outside of your team that others may have chosen something else.


答:
A "Negative Test" is testing that something that shouldn't happen, doesn't happen.

In this example, a negative test would be to enter an 8 characters password, and checking that said error message is not shown.

In automated testing context, negative tests are usually harder to write and provide less value than other positive tests - for instance, a test that an 8 characters password is accepted.
Some strange cases that may pass the negative test here are:

A different error message

The system crashes and the forms go away, not displaying a message but not doing anything else either.

Alternatively, such a test will have to be re-written if the password requirements are hardened, like if the new rules require a special symbol - instead of only re-writing the "system accepts valid password", you also need to fix this case.

Body:
Let's say we have some requirements

Req1: User name will accept 6-10 character alpha value.

Req2: On click of Submit button, application will show error message "Please enter value or character between 6 to 10 including" for invalid boundary value.

In this case if we are designing test cases for invalid boundary values of 5 and 11, those would be positive test cases, since we are also verifying the error message, which is mentioned in requirement.

What would be negative test case for this scenario?


问:
Best practice to store DateTime based on TimeZone
Developing a web application which should allow User to schedule appointment based on their TimeZone. And I am storing the User scheduled datetime as server datetime into database field.  While showing schedule information retrieved the value from Database and converted into user timzone. processing in Code base I am converting the DateTime based on the user timezone.
Please suggest is this best practice or any easy way is exist?</p>

答:
The easiest way to deal with date/time information depends on the requirements of your application.

If the date and time are entered by the user and the server does no processing with that date/time information except to store it in a database and there is no expectation that the entered time gets adapted to the location where it is viewed (for example, the user entered "8:00 PM" and it should be displayed as "8:00 PM" regardless of where on the world it is viewed), then the easiest way is to store the DateTime as local time without any timezone information.

On the other hand, if the server must use the entered DateTime as a trigger to do something, or if the time should be correctly adjusted to the current timezone, then your best option is to store the DateTime as UTC time and adjust it to local time (for the user's current location) each time you read it from the database.


答:
Here's what I learned in CS:

A variable is a named location of a value.

A pointer is a variable whose value is the address of the location of a variable.

And yes, in my opinion pointers in general are dereferencable.

Title: What is the definition of pointer?


答:
Commit early, commit often

You will find that if your code is based on good design principles (KISS, DRY, SOLID, design patterns etc) that most of the time you will be making a small change here and an adjustment there. Each time you do this (and support it with a matching unit test to verify the change) then you should commit. Once those commits cover a user story or complete a task then you should push to share your work with others.

You may find that the "master-develop" branching strategy to be helpful. I've seen this in use in many open source projects and I have yet to find a significant flaw with it.

Title: Git for a solo developer

Body:
I'm a developer working on a Wordpress project. I work on this alone and I want to improve the way I use Git but I don't know where to start.

Currently, I'm using git to commit all of the work that I've done for the day as long as that specific work is done. Here are some instances where I commit a specific work:

A specific feature whose code can be written within a day

A bugfix

For bigger features that can take weeks to finish I create a branch for it, then commit the sub-features once they're done.

But often times I feel like I'm committing way too much; for example, when I'm trying to solve lots of bugs I do not commit each and every bug that I resolve.

Sometimes I also end up working with 2 or more things that should be in there own commits. Then I'll find it hard to just target the specific files within a specific change so I end up putting them all in one commit and end up with a commit message like add search feature and add caching feature.

What I want to know are the best practices for solo developers working with Git. For solo developers out there you're welcome to answer with your own workflow as well.


答:
A pointer is a kind of variable whose value is a reference to a
  point in the memory of the machine where the program is running.

Being variables they need to support operations (they would be useless otherwise), the operations supported may vary depending on the programming language.

Many new programming languages (such as Java) even go all the way to hiding pointers to the users (which we could probably say that in these languages pointers are variables supporting no operations).

I would say that any operation on pointers needs to be supported or not depending on the structure of the language. In some way al programming languages use pointers, but, the fact that not all languages give you access to them, is indicative that operations may be necessary or not depending on the structure of the language.

Title: What is the definition of pointer?


问:
Should SCRUM be used for a project with only one person working on it?
At our company we have a team working on 3 different projects at the same time, where typically only one or two people are involved in each project. Project work often involves mastering new technologies and or solving bugs, both leading to tasks which are very hard to estimate. In this situation, the management still insists on using SCRUM and does not allow allocating a safety buffer at the end of the sprint for unexpected situations. The stand-up meeting happens for the whole team, although pretty much everyone works on unrelated software components or different software projects all together.

I was wondering if someone have seen SCRUM working well for a project with a single developer and fuzzy tasks, and how you made the process work well?

How to estimate tasks which involved research/mastering new technologies (this involves learning new programming languages, platforms, and development tools)?

Has anyone succeeded in convincing management not to use SCRUM for particular projects, and if yes, which arguments were most successful?

Thanks!

答:
I am working in a similar shop. As others here noted, what you describe may be agile but not scrum. I would also add that whether or not back logs and sprints makes sense depends on if it is new work or maintenance and on-going support. If the former, then a waterfall approach would make more sense for a one-person team. If not, from a PM perspective, what they are doing seems like a good approach if they have multiple projects in their portfolio.

To Agile enthusiasts, the mere mention of using waterfall is sacrilege. But people need to use common sense.

Let me give an example from a recent project of mine. I was leading a team of 3 developers on an aggressive 5-month timeline to redesign two major websites. We had daily stand-up meetings. But it was a waterfall project because it was a small team, limited life cycle, and the developers were all short-term contractors committed to the project only until launch. The project followed a very traditional waterfall life cycle. Absolutely nothing wrong with that. Except we did work in an "agile" way, we kept the stand-up meetings and we kept agile development best practices. Our small team was exempted from the larger team's weekly sprint planning meetings. Why? Because we didn't have weekly deployments. And our team didn't depend on or influence the work being done by any other team. In fact, we worked almost autonomously. After the websites launched, we then transitioned over to an agile process for on-going maintenance and support. The other developers are now working elsewhere. All enhancements are planned according to periodic deployments.

The point is, it is better to use the processes that makes the most sense for the size, complexity, and the maturity of each project. If you're doing a lot of research, then it's hard to make an estimate for the next five months, so agile is probably a better approach than waterfall.

Part of the problem is that some people seem to think you be able to plan the next five sprints out in advance. That's been the case with me before. You should not be planning more than two sprints out because if you are then you are defeating the whole purpose of having sprints. A sprint is supposed to be a commitment to deliver a realistic quantity of enhancements within a set amount of time. You should not commit to something you're not sure of. Sprint planning is by its nature short-term planning, but that's kind of the point. If you have a long-term schedule, then think about breaking things down into smaller deliverables. Or setting up checkpoint meetings based on where you are in the SDLC.

Sprint planning is supposed to be a realistic commitment about what is guaranteed to be completed within a certain time frame. If you find that the planning is not accounting for unknown variables, perhaps you should start giving ranges or pessimistic estimates. Or as other suggested, use story points. Sprints also should not be booked completely to allow for slippage and other important tasks that come up.

OwnerDisplayName: Serge


问:
How can I keep current with Python coding style?
I've been using Python since version 2.2. I do pick up new language constructs like for example with statement or dictionary/set comprehensions. However, I've realized that even though I'm being consistent with PEP-8, for existing constructs I'm using old style, rather than new style (for example except Exception, e instead of except Exception as e).

Is there a resource which would have either most current style guide, or even better a list of changes in Python's coding style?

答: If you are ready to move to Python 3.x, read Python Cookbook, 3rd Edition, by David Beazley and Brian K. Jones. By solving many practical problems in different areas it showcases a modern style of programming in which takes advantage of the newest language features.</p>


问:
Best practice for handling variable values outside of source code?
I am trying to get my head wrapped around OOP after programming in more procedural languages for a number of years.

My question: What is the best practice for handling variable values outside of source code?

For example, I have file directory values and regex patterns that may need to be manually changed from time to time. I would like to avoid changing these values directly in the source code. I am thinking of creating a text file that will hold key/value pairs. I would then create an object to set these values so that they can be referenced by any methods in my code.

Is this the right approach or am I violating any OOP principles?

Thanks

答:
Your approach does not violate any OOP principles.

If it is the right approach is unanswerable, because there is no the right approach. I can tell you that it is a right approach, but there are always other approaches possible. That said, if it works for you, stick with it.


问:
Can a method that must be overridden be considered private?
Suppose I have a class C with a method f() which is meant to be used only within C's implementation, but which should be overridden by C's subclasses.

Is it reasonable, or "pythonic", to consider it private, i.e. to name it _f() rather than f()?

In other words would you distinguish the interface provided to subclasses from the interface provided to code outside the inheritance hierarchy?

答:
Your question isn't really specific to python but could be applied to many OO languages like C++ or C#.  I haven't yet come across a hard rule but same thought did occur to me from time to time.

So what follows is my opinion:

Private method - what only class C should know about and/or use.  No one else

Protected methods - what deriving classes should know about and/or use.

Public methods - what external code should know about and/or use.

So in your example, I would make the function protected but in documentation of class C make it very explicit that deriving classes are not intended to call this function directly. Rather they should implement it and let the base class decide when it is appropriate to call it.

In other words, you expect deriving class to provide implementation. So at this point, nothing is stopping the person coding that class from calling that code. Even if you manage  to somehow "mark it private", since that person wrote that code once, he'll write it again, or find another way to run it if that's what he/she really wants to do.

As far as what's pythonic. I'm not a python expert, but I believe this is the language convention:

no underscore prefix (i.e. f() ) = public function

double underscore (i.e. __f() ) = private function

single underscore (i.e. _f() ) = internal use function

Python relies heavily on convention rather than language to keep people from accessing private date.  Nothing is really hidden, but when you prefix function name with __, the interpreter will "mangle" that function name.  The reason it does that is to discourage (not prevent) people from writing client code that calls private functions:

```<code>c = C()
c.__foo()
</code>```

... will result in interpreter telling you that the function doesn't exist.  But if someone really wants to call your private function, they'll just write:

```<code>c._C__foo()  # mangled name
</code>```

I wouldn't recommend using private functions in python for protected ones. It seems the language really intended __ to signal to the outside world, including deriving classes: "don't touch".

In your case, I would use a single _ to signal that the function is not for public/external consumption but rather should only be used, or overridden by someone who has enough knowledge about the class (i.e. presumably implementer of the deriving class is more knowledgeable about some internal details than someone writing client code).

Few sources that mention the use of __ (double-underscore) for private symbols:

Section 5.9 of Dive Into Python Book

https://stackoverflow.com/questions/3385317/private-variables-and-methods-in-python

https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private

https://stackoverflow.com/questions/2064202/private-members-in-python

Body:
Your question isn't really specific to python but could be applied to many OO languages like C++ or C#.  I haven't yet come across a hard rule but same thought did occur to me from time to time.

So what follows is my opinion:

Private method - what only class C should know about and/or use.  No one else

Protected methods - what deriving classes should know about and/or use.

Public methods - what external code should know about and/or use.

So in your example, I would make the function protected but in documentation of class C make it very explicit that deriving classes are not intended to call this function directly. Rather they should implement it and let the base class decide when it is appropriate to call it.

In other words, you expect deriving class to provide implementation. So at this point, nothing is stopping the person coding that class from calling that code. Even if you manage  to somehow "mark it private", since that person wrote that code once, he'll write it again, or find another way to run it if that's what he/she really wants to do.

As far as what's pythonic. I'm not a python expert, but I believe this is the language convention:

no underscore prefix (i.e. f() ) = public function

double underscore (i.e. __f() ) = private function

single underscore (i.e. _f() ) = internal use function

Python relies heavily on convention rather than language to keep people from accessing private date.  Nothing is really hidden, but when you prefix function name with __, the interpreter will "mangle" that function name.  The reason it does that is to discourage (not prevent) people from writing client code that calls private functions:

c = C()
c.__foo()

... will result in interpreter telling you that the function doesn't exist.  But if someone really wants to call your private function, they'll just write:

c._C__foo()  # mangled name

I wouldn't recommend using private functions in python for protected ones. It seems the language really intended __ to signal to the outside world, including deriving classes: "don't touch".

In your case, I would use a single _ to signal that the function is not for public/external consumption but rather should only be used, or overridden by someone who has enough knowledge about the class (i.e. presumably implementer of the deriving class is more knowledgeable about some internal details than someone writing client code).

Few sources that mention the use of __ (double-underscore) for private symbols:

Section 5.9 of Dive Into Python Book

https://stackoverflow.com/questions/3385317/private-variables-and-methods-in-python

https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private

https://stackoverflow.com/questions/2064202/private-members-in-python

ContentLicense: CC BY-SA 4.0


答:
I can't speak for the "pythonic" way, as I am not familiar with Python.

In languages like C++, C# and Java, there is an explicit provision to distinguish three kinds of members:

private for the members that are only accessible to the class itself

public for the members that are accessible to the world

protected for the members that are accessible to the descendants

In C++, there is even an idiom to use private virtual functions (and override them in a derived class). See this question on SO for more details.

Title: Can a method that must be overridden be considered private?

Body:
Suppose I have a class C with a method f() which is meant to be used only within C's implementation, but which should be overridden by C's subclasses.

Is it reasonable, or "pythonic", to consider it private, i.e. to name it _f() rather than f()?

In other words would you distinguish the interface provided to subclasses from the interface provided to code outside the inheritance hierarchy?


问:
Strategy for normalising and interpreting location data
I'm a bit stuck with a problem involving the normalisation of location input data from the user (which comes from a third party).

Aim

To logically breakdown and interpret the user location input field and understand if it is listing single or multiple locations, from one or more countries.

The Problem

The type of data that I am receiving from the user input is messy and has no logical structure or consistency as show below. Daily geocodes are limited from google, so I have to use them sparingly. I want to efficiently process the location input from the user and send the correct geocoding query to google to get the right result.

Data Sources

Data is irrational and irregular and could be supplied in some of the following formats:

```<code>London, UK                              Alternative format
England, London                         Reversed order
London                                  Generic location
London Sheffield, Newcastle             Three separate locations in the same country without consistent commas
London, Sales, Sales Assistant          Non location content inserted
London [NOT SPECIFIED]                  Other non location content inserted with non alphabet chars not separate with commas
London, Washington, Brazil, England     Mix of unrelated locations, including cities and countries
Washington, London, Kent                Mix of places within a single country
</code>```

Proposed Solution

Step 1: Breakdown data

Put each separated word in an array

Step 2: Sanitize data

Strip out invalid chars, commas, additional spaces etc

Strip out any words against a stoplist.txt (like job, sales, in, at, etc)

Step 3: Deterimine if valid location

See if each individual array item has been geocoded before, if not, geocode and store

Log any words which have been geocoded with no result – add these into the stoplist file to avoid pointless geocodes

Step 4: Interlink values

Compare if a places coordinate value falls within the range of another array item. If it does, we know they are parents and we treat them as a single item

London + England -> London coordinates falls within the co-ordinate range of England so we know it is a single location, not two separate ones.

Issues

Issue 1: Kent, London, Sussex
Technically, there is a Kent in the USA, and it is the first one that comes up when you type it into google maps. However since all the results are in England it is extremely unlikely that the result we want is the USA one

Issue 2: England, Washington, New York
There is a Washington in England, but this doesnt seem likely to be the one in England

Question

Is my proposed solution of breaking the words down into separate entities and relinking them the most logical solution? Any help or advice would be much appreciated, I know it's not any easy problem.

答:
I will make an attempt to answer the question. :)

I think you need a system that can:

Learn about locations as it grows.

Improve itself overtime.

Assumptions: Assuming that you don't need any real time geo code analyses. The below solution will work in back ground and will continue to improve automatically as it grows older.

You should be having a giant repository of countries states cities etc. in your database. This is the only way you can track whether some address is related

Some pseudo algorithm which might help:

You need to group that array by some groupId

Check whether the individual item in the array is already a known country, state, city or even already geo coded.

If the above step yields nothing then Google it, there might be some websites that provide such kind of stuff. You can do Web crawling to get there.

From the above step you will get further stop words to add in Your stop list.

You are ready to geocode as it is easy now to know country, state, city.

You should save the geocoding results so that it may be of use later.

Note: You might also consider having a revalute policy of the stop list. Some time after which you may reconsider the words as allowed words. The world is growing who know they might have a new location with a name that is in Your stop list :)

Disclaimer: I have never worked on geocodes and have not researched much about it. I am giving the solution as a conceptual answer.

Hope it helps


答:
This has nothing to do with OOP and everything to do with requirements.

For instance, would it be OK to recompile all or part of the program when the values or patterns change? Then you might chuck them away into a header file or a class (or whatever your language provides) so you wouldn't have to hardcode them into the actual program logic (a good practice anyway).

If not, you probably mean to make the values changeable at runtime. You'd need to read them out of some kind of file format or database and make your program data-driven.

Ultimately, this is something you (or whoever is in charge) need to decide before starting the design because it has direct bearing on what you design. Many procedural, functional or object-oriented approaches tackle both problems, but you need to decide which one you're facing first.

Title: Best practice for handling variable values outside of source code?

Body:
I am trying to get my head wrapped around OOP after programming in more procedural languages for a number of years.

My question: What is the best practice for handling variable values outside of source code?

For example, I have file directory values and regex patterns that may need to be manually changed from time to time. I would like to avoid changing these values directly in the source code. I am thinking of creating a text file that will hold key/value pairs. I would then create an object to set these values so that they can be referenced by any methods in my code.

Is this the right approach or am I violating any OOP principles?

Thanks


答:
Pythonically speaking, you should utilize the Abstract Base Class module to implement this functionality.

Example:

```<code>from abc import ABCMeta, abstractmethod

class MyBaseClass(object):

    __metaclass__ = ABCMeta

    @abstractmethod
    def f(self, *args):
        #"Public" method (accessible from outside of class instance)
        pass

    @abstractmethod
    def _f(self, *args):
        #"Private" method (should only be accessed from with instance)
        pass
</code>```

Then this is what happens when you attempt to instantiate a subclass of MyBaseClass without overriding _f():

```<code>>>> my_base_class = MyBaseClass()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyBaseClass with abstract methods _f
>>> class B(MyBaseClass):
...     pass
...
>>> b = B()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class B with abstract methods _f
>>> class B(MyBaseClass):
...     def _f(self):
...             print "foo"
...
>>> b=B()
>>> b._f()
foo
>>>
</code>```

Note that there are no programmatically "private" methods in Python. That being said, a single underscore before the name (_f()) is used to signify that the method should only be accessed internally.

Body:
Pythonically speaking, you should utilize the Abstract Base Class module to implement this functionality.

Example:

from abc import ABCMeta, abstractmethod

class MyBaseClass(object):

    __metaclass__ = ABCMeta

    @abstractmethod
    def f(self, *args):
        #"Public" method (accessible from outside of class instance)
        pass

    @abstractmethod
    def _f(self, *args):
        #"Private" method (should only be accessed from with instance)
        pass

Then this is what happens when you attempt to instantiate a subclass of MyBaseClass without overriding _f():

>>> my_base_class = MyBaseClass()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyBaseClass with abstract methods _f
>>> class B(MyBaseClass):
...     pass
...
>>> b = B()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class B with abstract methods _f
>>> class B(MyBaseClass):
...     def _f(self):
...             print "foo"
...
>>> b=B()
>>> b._f()
foo
>>>

Note that there are no programmatically "private" methods in Python. That being said, a single underscore before the name (_f()) is used to signify that the method should only be accessed internally.


问:
Is it required to differentiate between js framework and js library?
While searching through many javascript libraries/frameworks, I observed that the terms are sometimes used interchangeably.

So, conceptually is it important to distinguish between framework and library?

Do people seriously make their decisions based on whether it is a library or framework?

Would a user like to browse two separate areas - libraries and frameworks while looking for a solution?

答:
So, conceptually is it important to distinguish between framework and library?

Yes, it is. A framework and a library are fundamentally different. The defining characteristic of a framework is inversion of control: when you use a library, you call the library; when you use a framework, the framework calls you.

So, they are not just "different", they are in fact exact opposites in some sense.

Do people seriously make their decisions based on whether it is a library or framework?

Yes, of course. Building a solution with a library vs. a framework yields completely different (again, in some sense opposite) design. With a framework, the entire structure of your code will be "inside-out" compared to with a library.

Would a user like to browse two separate areas - libraries and frameworks while looking for a solution?

Highly likely. I know I would.


问:
Generic term for "objects" vs "fundamental types"?
What are the exact terms to call data types with a logic structure (like C structures, C++ or Java objects) versus fundamental data types (like numeric types, characters, booleans...) independently of any language or paradigm. (I am searching for abstract/academic computer science words).

答:
I don't think there are any.

It depends entirely on the language: in Lambda Calculus, functions (and only functions) are primitive, booleans, numbers, strings, lists are not. In Smalltalk, objects are primitive, integers are not. In C, integers are primitive, objects are not. Pairs are not primitive in Java, but they are in Scheme. Java makes a difference between primitives and objects, C# doesn't.


答: In Object-Oriented systems they are almost universally called "Objects" and "Primitive Types" respectively.  Before we had OO, there were "Data Structures" and "Primitive Types".</p>

Title: Generic term for "objects" vs "fundamental types"?

Body: What are the exact terms to call data types with a logic structure (like C structures, C++ or Java objects) versus fundamental data types (like numeric types, characters, booleans...) independently of any language or paradigm. (I am searching for abstract/academic computer science words).


答:
Welcome to one of the hardest problems in non-computational programming - properly representing dates and times to end users.

Realistically, timestamps should be stored in a fixed single representation regardless of how they will be interpreted, because no matter how hard you try, you will always have ambiguous cases, and you can't resolve them without a fixed representation.  And you've picked one of the worst of the use cases - scheduling an appointment.  The only worse common use case is air travel, where a trip might start in one time zone and end in another, possible at an earlier local time.

Always, always, ALWAYS store in UTC and display in the user's preferred or explicitly specified timezone.  If at all possible, make the user tell you what timezone they believe the timestamp to be in when they input it (e.g., have an explicit timezone field and pre-populate it with their preferred zone).

Title: Best practice to store DateTime based on TimeZone

Body:
Developing a web application which should allow User to schedule appointment based on their TimeZone. And I am storing the User scheduled datetime as server datetime into database field.  While showing schedule information retrieved the value from Database and converted into user timzone. processing in Code base I am converting the DateTime based on the user timezone.
Please suggest is this best practice or any easy way is exist?</p>


答: Avoid copying at all costs. If you look into the history of network protocol implementations, you'll find that, time and again, the real high-bandwidth optimizations come from building "zero copy" protocols and algorithms.  Modern OSes work very hard to pass packets upstream from the interrupt handler through to the IP and sometimes higher layers without copying the data, for very good reasons.


问:
Pre-Interview Screening Questions
I need to hire a senior software developer.  I've switched to a new recruiter and he's asked for about 3 questions to ask each candidate on the phone that he'll send the answers to when I see the CV to help me screen out the obvious bad ones.  I quite like the idea of not having to phone screen people who just cannot code but I'm struggling to be honest.

The notion of quickfire hire/no hire questions intrigues and worries me in equal measure.  I reckon it's possible to come up with some useful ones but most of the questions I ask in an interview are open ended, language agnostic and based on cultural fit.

Now, the recruiter has told me that the candidate wont be able to google the answers since they'll be asked immediately before he sends the CV but I clearly don't want to ask questions that are 'googleable',..I don't care if they routinely google those sorts of questions.  In fact, I'd rather they did!

So, if you were in my position what questions would you ask?

For what it's worth, the primary platform is .Net, C#, Sql Server et al along with the normal slew of legacy technologies.

Edit
Just to be super clear... knowing whether the candidate knows what the volatile keyword does in C# or how they would create a regex that validates UK postcodes would be pointless information.  That's classic google fodder.  I want something that demonstrates a deeper understanding than that.

I considered simple 'what is polymorhism' type questions or 'explain the difference between an 'HTTP PUT vs POST' but these seem pretty straight forward for a senior.  I'm looking for something to help support the decision to interview a senior.

答:
To be honest, I've yet to meet a recruiter that I'd trust to be qualified to interpret a candidate's response to anything other than factual data (e.g., last place of employment, education).

I would not ask anyone else to ask FizzBuzz.  It's a great question, but the value comes in seeing the answers first hand.

Interviewing is a 2 way street.  While you're trying to decide if a candidate is a good fit for your company, the candidate is trying to decide if the company is a good fit for them.  For a position to be offered and accepted, both have to agree that it's going to work.

Possible questions:

Tutoring/mentoring junior developers is a job requirement.  Will you do that?

Fixing bugs takes priority over new code, especially on a Friday afternoon right before quitting time.  Do you agree?

We take the team approach to development - code is owned by the team, and all code is reviewed.  Are you OK with that?

All the recruiter need do is record 'yes' or 'no'.  The candidate gets some signals about what kind of shop you're running, and may elect to decline an interview.

Title: Pre-Interview Screening Questions


答:
#Abstract Data Types

from wikipedia:

In computer science, an abstract data type (ADT) is a mathematical
  model for a certain class of data structures that have similar
  behavior; or for certain data types of one or more programming
  languages that have similar semantics. An abstract data type is
  defined indirectly, only by the operations that may be performed on it
  and by mathematical constraints on the effects (and possibly cost) of
  those operations.

(or just say "data structure", most people will know what you mean)

Exact academic terms are arguable (see comments); I say 'data structure' or even 'abstract data type' and have no trouble being understood. 'Object' is more specific than what you asked for.

If you want total precision, say 'primitive' and 'non-primitive' (or 'secondary').

I'm wondering why this matters? What's the purpose?


答:
I would say compound data-types. As an example, see those documentations for different languages: C++, guile and C (beware, audio speech).

Also, check Rosetta Code, where the term is defined as:

```<code>[a type] that holds multiple independent values.
</code>```

This definition encompasses arrays, structures, classes, and so on.
Here, "value" means either a primitive type or another compound type, I guess.

Body:
I would say compound data-types. As an example, see those documentations for different languages: C++, guile and C (beware, audio speech).

Also, check Rosetta Code, where the term is defined as:

[a type] that holds multiple independent values.

This definition encompasses arrays, structures, classes, and so on.
Here, "value" means either a primitive type or another compound type, I guess.


问:
Is there too much abstraction in the Ruby on Rails community?
Rails, to me, seems like a perfect level of abstraction for most types of web development. However, having watched some seasoned Rails consultants build an application, I'm finding that they use Gems to an extent that it's often pretty difficult to figure out what's going on in the code. As an intermediate-level Rails developer, I've had a pretty hard time digging through their code to figure out how things work, and I'm really struggling to see the payoff of this approach.

So is it me, or does Rails, by dint of the fact that it has such a vibrant community of contributors, kind of encourage over-abstraction?

答: Ruby in general encourages programming at a high level, and Rails specifically encourages a somewhat declarative style of programming (one might even think of Rails as a declarative DSL for defining webpages, to an extent). As a result, Rails apps can be difficult to grok if you don't have a lot of experience with the app itself, and all the gems it utilizes. But like most things programming, to an experienced Rails programmer (and someone experienced with the specific app itself) it probably makes sense.</p>


问:
Method vs Function vs Procedure
Simple question, but I often hear these three terms defined with such ferocity, but which have been known to me to mean different things over the years.

What are the "correct" definitions of "Procedures", "Methods", "Function", "Subroutines", etc?

答:
I'm going with a different answer here: practically speaking, there's really no difference, with the slight exception that "method" usually refers to a subroutine associated with an object in OO languages.

The terms "procedure, function, subroutine, subprogram, and method" all really mean the same thing: a callable sub-program within a larger program.  But it's difficult to come up with a definition that captures all variant usages of these terms, because they are not used consistently across programming languages or paradigms.

You might say a function returns a value.  Well, the following C function doesn't return a value:

```<code>void f() { return; }
</code>```

...but I doubt you'd find anyone who would call it a procedure.

Sure, in Pascal, procedures don't return values and functions return values, but that's merely a reflection of how Pascal was designed.  In Fortran, a function returns a value, and a subroutine returns multiple values.  Yet none of this really allows us to come up with a "universal" definition for these terms.

In fact, the term "procedural programming" refers to a whole class of languages, including C, Fortran and Pascal, only one of which actually uses the term "procedure" to mean anything.

So none of this is really consistent.  The only exception is probably "method", which seems to be used almost entirely with OO languages, referring to a function that is associated with an object.  Although, even this is not always consistent.  C++, for example, usually uses the term "member function" rather than method, (even though the term "method" has crept into the C++ vernacular among programmers.)

The point is, none of this is really consistent.  It simply reflects the terminology employed by whatever languages are en vogue at the time.

Title: Method vs Function vs Procedure

Body:
I'm going with a different answer here: practically speaking, there's really no difference, with the slight exception that "method" usually refers to a subroutine associated with an object in OO languages.

The terms "procedure, function, subroutine, subprogram, and method" all really mean the same thing: a callable sub-program within a larger program.  But it's difficult to come up with a definition that captures all variant usages of these terms, because they are not used consistently across programming languages or paradigms.

You might say a function returns a value.  Well, the following C function doesn't return a value:

void f() { return; }

...but I doubt you'd find anyone who would call it a procedure.

Sure, in Pascal, procedures don't return values and functions return values, but that's merely a reflection of how Pascal was designed.  In Fortran, a function returns a value, and a subroutine returns multiple values.  Yet none of this really allows us to come up with a "universal" definition for these terms.

In fact, the term "procedural programming" refers to a whole class of languages, including C, Fortran and Pascal, only one of which actually uses the term "procedure" to mean anything.

So none of this is really consistent.  The only exception is probably "method", which seems to be used almost entirely with OO languages, referring to a function that is associated with an object.  Although, even this is not always consistent.  C++, for example, usually uses the term "member function" rather than method, (even though the term "method" has crept into the C++ vernacular among programmers.)

The point is, none of this is really consistent.  It simply reflects the terminology employed by whatever languages are en vogue at the time.


答:
Since your question is about what is the "pythonic" way, see the naming section of Code Like a Pythonista in which the author says "But try to avoid the __private form. I never use it." and more importantly:

It's better to use the single-leading-underscore convention, _internal. 　This isn't name mangled at all; it just indicates to others to "be careful with this, it's an internal implementation detail; don't touch it if you don't fully understand it". It's only a convention though.

In other words, the very concept of "private" is not pythonic.  In addition, the single underscore _internal notation is explicitly there to special purpose internal structure you describe.


问:
What is the identification procedure that registers a mobile device on a subscriber account and installs purchased content?
We know there are several moving parts to a system like the apple store or google play. At the very least;

The device has a unique hardware id or sim card

The user has a login/pass

The "store" site has some crypto

In what order and format (cypher/plaintext) is this data exchanged between the device and store software before content is installed?

答:
This is a very general question, and the answer will differ depending on the application interface you're using.

Generally:

Content is encrypted. You need a "key" to unlock it.

The "key" is attained by synchronizing the local profile with a master server.

Typical authentication methods are used to login to the master server.

All communication to the master server is typically over SSL/encrypted channels.

Your profile on the master server will contain all the purchases you have performed, and this is used to generate keys to unlock encrypted content.

Keys can be revoked by the master server if necessary.

Its also likely that all content, including free content, is encrypted, and requires a key from the master server to unlock and use/execute. This is all pretty standard authentication/DRM type mechanics.


问:
Code execution within delimiters
Is there any way I can execute a block of code in a loop, like so:

```<code>[ some code goes here ]
</code>```

Where the delimiters are "[" and "]", and also allowing for nested blocks, i.e.:

```<code>[the user can create another loop[]]
</code>```

I am creating a parser for a language that implements such semantics, and it reads the code one byte/character at a time since the commands are all single characters and because the syntax is supposed to be very minimal (which is fairly important), and I am currently stuck in this loop thing.

I have tried matching the byte (since I am only reading 1 character at a time) with a "[" character and then setting a global variable across the instance, but this seems to break when the statements are nested, and doesn't seem to work.

Any help (in Python, possibly) is appreciated!

EDIT: Conforming to what @mattnz commented, the question & post has been further clarified.

答:
Indeed, you can use a variable which stores the current state or the current context. If you have an issue with nested blocks, it's because you are storing only one state at a time. Using a stack can help.

For more information, look at "parenthesis matching algorithm" in Google. You'll find plenty of information about how to match nested brackets.

Also, Kilian Foth's comment to your question is particularly valuable: if you're already stuck at the very beginning with a problem such as parenthesis matching, it is a good sign that you may want to learn a bit more about parsing before you venture into building a parser yourself.

Title: Code execution within delimiters


问:
Why does Java compiler decide whether you can call a method based on the "reference" type and not on actual "object" type?
I was just wondering why does Java compiler decide whether you can call a method based on the "reference" type and not on actual "object" type? To explain I would like to quote an example:

```<code>class A {
    void methA() {
        System.out.println("Method of Class A.");
    }
}

class B extends A {
    void methB() {
        System.out.println("Method of Class B.");
    }
    public static void main(String arg[]) {
        A ob = new B();
        ob.methB();       // Compile Time Error
    }
}
</code>```

This will produce a Compile Time Error that method methB() not found in class A, although Object Reference "ob" contains an object of class B which consists of method methB(). Reason for this is that Java Compiler checks for the method in Class A (the reference type) not in Class B (the actual object type). So, I want to know whats the reason behind this. Why does Java Compiler looks for the method in Class A why not in Class B(the actual object type)?

答:
My favorite analogy for polymorphism is to use teachers. This will provide more clarity rather than the abstract MethodA() and MethodB(). Say you have a Teacher and a Math teacher. The latter is a more specific version and represents an IS-A relationsihp. A Math Teacher IS a teacher, so it can do anything a teacher can do, but the opposite is not true. Not all teachers can teach math. If I have a teacher reference,

```<code>Teacher teacher = GetTeacher();
teacher.Teach();
</code>```

It would not be safe to assume the teacher knows math, it could be a lanuage or science teacher. We do know that all teachers have the Teach() method, so this is safe to call. The reference defines the interface or contract. This separation of interface from the implementation is a very powerful OOP principal. For this reason it is often encouraged to decouple your implementation entirely. I don't need to know what kind of teacher the reference holds, because I know it can teach regardless.

This can continue even further as you get more specific, you can have a Calculus teacher which IS a math teacher. Both math teacher and calculus teacher have the method DoEquation() and Teach(), but only the calculus teacher can call DoAdvancedEqation().

Thinking about inheritance as an IS-A relationship should help you understand why it is not safe to make assumptions such as proposed in the question.

Body:
My favorite analogy for polymorphism is to use teachers. This will provide more clarity rather than the abstract MethodA() and MethodB(). Say you have a Teacher and a Math teacher. The latter is a more specific version and represents an IS-A relationsihp. A Math Teacher IS a teacher, so it can do anything a teacher can do, but the opposite is not true. Not all teachers can teach math. If I have a teacher reference,

Teacher teacher = GetTeacher();
teacher.Teach();

It would not be safe to assume the teacher knows math, it could be a lanuage or science teacher. We do know that all teachers have the Teach() method, so this is safe to call. The reference defines the interface or contract. This separation of interface from the implementation is a very powerful OOP principal. For this reason it is often encouraged to decouple your implementation entirely. I don't need to know what kind of teacher the reference holds, because I know it can teach regardless.

This can continue even further as you get more specific, you can have a Calculus teacher which IS a math teacher. Both math teacher and calculus teacher have the method DoEquation() and Teach(), but only the calculus teacher can call DoAdvancedEqation().

Thinking about inheritance as an IS-A relationship should help you understand why it is not safe to make assumptions such as proposed in the question.


问:
My github pull request was merged, what's the convention at this stage?
I forked a project on Github, made a small change and sent a pull request to the original maintainer, who has pulled it in. Now the last commit there is Merged pull request #11 from my_username/master.

This is the first time I'm doing this, so I'm not sure what the etiquette now is: I did a git pull upstream master and then git push origin master, and now the last commit on my own repository reads Merged pull request #11 from my_username/master which feels pretty weird to me. Is this the way people usually do it, is there anything I need to do to "clean up the history" or something?

Note: since this was a tiny documentation change, I hadn't created any branches, I just made the change in my master branch and sent the pull req. So there's no cleanup to be done in that part.

答:
Yes, this is what people usually do, because it is what git does.

The merge tests often don't make sense. It is the result of the "fast forward" logic, i.e. merging does not create new commit if it is not necessary. Most of the time last commit on master says "merged master", because the developer merged master to their branch and pushed to merge, which didn't need any more merges. Nobody cares about merge commits in git anyway.


问:
Web app outgrowing current framework
I have quite a bit of experience with using Django for websites and so when I started a new project I naturally chose to use Django for it. Everything went well for a time but now the application is really starting to rub up against what Django can comfortably cope with and I fighting all the time to ensure that things work as intended.

I've been considering moving the site over to Java EE 7 now that it has been released. It certainly seems to provide the features I require as well as also being less forceful in the way that a project is laid out and maintained. I guess now that I have a good idea of how the application should be structured, development should be much faster.

Have you felt the need to change the web framework you are using simply because it doesn't lend itself well to the type of project you are trying to produce?

答:
You say:

The problem I'm currently facing is mixing a website frontend with a
  distributed backend written in differnet languages (there is some C++,
  Erlang and Haskell stuff to consider). Tasks need to be dispatched
  from the web frontend to the many backends asynchronously and reliably
  as well as also having certain tasks run regularly like a cron script
  but spread amongst these different systems. I'm striggling to find a
  clean and elegant solution for all these requirements in Django.

Reading this I am not sure that this is a Django problem, or even a web framework problem, but more that you should be looking at using some kind of message queue to send messages back and forth.

Something like RabbitMQ and Celery might be what you are looking for.  These will let you dispatch tasks to the backends and also schedule tasks as you need them.

Title: Web app outgrowing current framework


问:
Should I help anonymity related projects?
Projects that increase online anonymity, such as Tor and bitcoin, allow personal freedom from government oppression but also allow crimes to go unpunished.

As a developer, should I contribute to such projects?
Is there a way to enforce that those technologies will not be used for money laundering and child pornography?

答: Your question is similar to those the founding fathers of the United States faced when they decided on the basic constitutional rights to grant the people.  Undoubtedly many criminals benefit from such rights as freedom from self-incrimination, the principal of "innocent until proven guilty", the need for probable cause before their property is searched, etc.  The founders reasoned that these rights did more good than harm.   If you take a similar view regarding tools to protect privacy online, you would be in good company.</p>