问:
Why use other number bases when programming
My coworkers and I have been bending our minds to figuring out why anyone would go out of their way to program numbers in a base other than base 10.

I suggested that perhaps you could optimize longer equations by putting the variables in the correct base you are working with (for instance, if you have only sets of 5 of something with no remainders you could use base 5), but I'm not sure if that's true.

Any thoughts?

答:
It's honestly preference, if for some reason you've got polydactyly and have 11 fingers or like counting with your toes so you like working in base 20 it's honestly up to you.  But realize that on a universality topic that most of us that have to deal with bits and bytes on a daily basis will be really ticked if we get something that's doing bit manipulation in base 19.

REASONS FOR BASE x

Base 10 - Model of all of our stuff because we've got 10 counting digits (feet are weird and smelly so we don't use those).

Base 2 - Computers use this for bits (on/off) this is related to readable voltage levels being propagated by gates/transistors/capacitors.

Base 8 - Old, back when computers weren't super huge (or back when they were space wise) this was good for something or other (i don't like it one bit)

Base 16 - Good for showing upper and lower nibbles of a byte for bit manipulation.  This is super useful in the embedded/fpga/hardware world.

NORMAL BASES IN COMPUTERS

To go with preference, I could tell you exactly how "on" a color is in a hex RGB value that's given to me is, this consequently can be represented in a single int in hardware and then with some shifts can be given back to me easy-peasy, 1 complex color = 1 data point that's nice for large image processing with limited memory.  Compare that to a base 10 representation, you could add them all and store them in a number, but which number is which, or maybe R is time 10000, G is 100, and B is its own space, that's a lot of math operations, usually multiplications cost more cycles than a shift, so your next data piece is already in queue before your done with your last piece being processed, whoops, that's gone now.

Sometimes it's just better to work in base 2, 8 or 16.  With most machines a multiply by 2 is just a bit shift, those are super speedy, same with a divide by 2.

To expound even further on the idea of bit twiddling.  There are a large number of times when working in an embedded environment that I've needed to access some array of lights, switches, or some other register mapped items.

In this case assigning an entire char, byte, or int to each switch would be both inefficient and silly, a switch or light has 2 positions - on and off - why would I assign something that has up to 256 positions, or 2^16 positions etc.  Each light in an array could be 1 bit fitting 8 or 16 or 32 or 64 or 128 (width of your datatype) on a single word/register.  The space efficiency is needed and rather welcome.

Using anything that's base 2^n in programming for things like handling RGB data, lots of signal data - GPS's, audio, ascii, etc - is much simpler in hex, binary, and octal since that's how it's represented in the machine and one can more easily discern what's being presented and how to manipulate it.

USING STRANGE BASES

There is no efficiency unless you code for it.  You want base 11, you've gotta set up a data-type for it and overload any operators to handle its representation to the user.  I see no reason why a system holding 5 items, and only ever holding multiples of 5 items would need to be converted to the five item math.  And further, you'd better pray that whomever decided to write their code for base 271 documented it well or you could spend more time understanding it than is worth in creating base 271 because all of the items are a multiple of 271.


问:
Is it correct to add booleans in order to count the number of true values in a vector?
Is it conceptually correct to sum a vector of booleans? From a mathematical point of view, I would argue it's not: True + True != 2. But it's quite practical to do so still! Example using the vectorised Python library numpy:

```<code>In [1]: X = rand(10)

In [2]: large = X>0.6

In [3]: large.dtype
Out[3]: dtype('bool')

In [4]: large.sum()
Out[4]: 7
</code>```

I don't like it, but it's very practical. Is this a good practice?

Update: the aim is to count the number of true values in a vector.\

Update 2013-02-18: I just discovered the numpy function count_nonzero does exactly what I need in a proper way. That means that as far as Python is concerned, there is no need to use the "dirty" way.

答:
I would say it is not semantically proper to add True and True to get two.  It may work, but it seems to rely on an implementation detail.

Python defines a few things as False, such as:

```<code>""
0
0.00
None,
[],
(),
.__bool__() evaluates to False,
etc...
</code>```

and everything else is True.

The + operator in python, when used on a bool will first convert it to int.

```<code>>>> int(True)
1
>>> int(False)
0
>>> True + True
2
</code>```

If you choose to do so in Python, make sure you comment your code accordingly.

ContentLicense: CC BY-SA 3.0

Body:
I would say it is not semantically proper to add True and True to get two.  It may work, but it seems to rely on an implementation detail.

Python defines a few things as False, such as:

""
0
0.00
None,
[],
(),
.__bool__() evaluates to False,
etc...

and everything else is True.

The + operator in python, when used on a bool will first convert it to int.

>>> int(True)
1
>>> int(False)
0
>>> True + True
2

If you choose to do so in Python, make sure you comment your code accordingly.


问:
How to implement string matching based on a pattern
I was asked to build a tool that can identify if a string match a pattern.

Example:

{1:20} stuff t(x) {a,b,c}

would match:

1 stuff tx a

20 stuff t c

It is a sort of regex but with a different syntax

Parentheses indicate an optional value

{1:20} is a interval; I will have to check if the token is a number and if it is between 1 and 20

{a,b,c} is just an enumeration; it can be either a or b or c

Right now I implemented this with a regex, and the interval stuff was a pain to do.

On my own time I tried implementing some kind of matcher by hand, but it turns out it's not that easy to do.

By experimenting I ended up with a function that generates a state table from the pattern and a state machine. It worked well until I tried to implement the optional value, and I got stuck and how to generate the state table.

After that I searched how I could do this, and that led me to stuff like LL parser, LALR parser, recursive-descent parser, context-free grammars, etc. I never studied any of this so it's hard to know what is relevant here, but I think this is what I need:

A grammar

A parser which generates states from the grammar and a pattern

A state machine to see if a string match the states

So my first question is: Is this right ? And second question, what do you recommend I read/study to be able to implement this ?

答:
If the requirements are as described (just matching static text, integers in a set range, optional values and alternation), then your patterns do describe regular languages, so a regular expression is probably the right way to go -- full context-free grammars give you more power than you need here.

If you want to implement a matcher from scratch, you should read up on DFAs, and NFAs. I would also recommend you read Regular Expression Matching Can Be Simple And Fast, which describes how to implement efficient (linear in the length of the text being searched) matching using NFAs and DFAs.

Alternatively, you could just hack something together to turn your patterns into a more common regular expression syntax and use an existing regex engine (I would recommend re2, which was created by the same person who wrote the above description).

To avoid the difficulties of matching integer intervals textually, I would suggest you turn intervals into general integer matching (i.e., match any sequence of digits) and use a separate pass to check whether the value is in the specified interval. If you end up writing your own matcher, you could build this functionality into the core. Note that matching integer intervals textually is entirely possible (they're still regular), but pulling out arbitrary integers and performing a separate range check may be simpler.


问:
Is using dirname(__FILE__) a good practice?
Looking at the code of Joomla I see that in the first line of the index, it defines the base path of installation with dirname(__FILE__).

Is this a possible risk for the site? If a non controlled error message show the internal path of the Joomla directory, because of, for example a failed include, can it be used to perform some kind of attack to the site? If yes, is it convenient to use this function?

答:
You shouldn't show the PHP error messages to users in the first place. So no, it's not a risk.

Also, if the only safety measure on the server is to hide the path where the source code is located, then... well... you should be more concerned by other risks then showing the path to the users.

Finally, by using relative paths, you're potentially introducing more security holes. See for example Preventing Directory Traversal in PHP but allowing paths.


问:
Why do Git users say that Subversion does not have all the source code locally?
I'm only going on what I've read on SO, so forgive me, but all I read says that one major advantage of Git over Subversion is that Git gives all the source code to the developer locally, not having to do anything on the server.

With my limited using of SVN and TortoiseSVN, I had all the source code, or at least I thought I did.  For example, I have a website.  I upload it to SVN.  I am still running my website locally, aren't I?  If someone submits a change and I'm not connected, it wouldn't matter if I had Git or not, until I reconnect to the server.

I do not understand.  I'm not asking for a rehash of one vs. the other except this one point.

答:
The short answer is this: with git you have all of your source code, with subversion you have all of the most recent version of your source code.

Git keeps a copy of the entire history of your repository locally. With subversion the entire history is on a server.


答:
__FILE__ is a native global variable that holds the path of the script that's being executed, and dirname(__FILE__) will return the directory part of that path. There's absolutely no way this will fail, if the path in __FILE__ doesn't exist or is invalid, you couldn't have called the script in the first place anyway.

Generally speaking you shouldn't let any PHP errors (including warnings and notices) reach the user, read up on error_reporting and display_errors.

Title: Is using dirname(__FILE__) a good practice?

Body:
Looking at the code of Joomla I see that in the first line of the index, it defines the base path of installation with dirname(__FILE__).

Is this a possible risk for the site? If a non controlled error message show the internal path of the Joomla directory, because of, for example a failed include, can it be used to perform some kind of attack to the site? If yes, is it convenient to use this function?


答:
Back in the ancient days of computers, we had a number of displays that could show the digits 0-9, but we didn't have A-F yet.

http://ad7zj.net/kd7lmo/images/ground_nixie_front.jpg is one such example...

Octal fit real nicely on these displays and was easier than binary or decimal.

Title: Why use other number bases when programming

Body:
My coworkers and I have been bending our minds to figuring out why anyone would go out of their way to program numbers in a base other than base 10.

I suggested that perhaps you could optimize longer equations by putting the variables in the correct base you are working with (for instance, if you have only sets of 5 of something with no remainders you could use base 5), but I'm not sure if that's true.

Any thoughts?


问:
Is C# development effectively inseparable from the IDE you use?
I'm a Python programmer learning C# who is trying to stop worrying and just love C# for what it is, rather than constantly comparing it back to Python.

I'm caught up on one point: the lack of explicitness about where things are defined, as detailed in this Stack Overflow question. In short: in C#, using foo doesn't tell you what names from foo are being made available, which is analogous to from foo import * in Python -- a form that is discouraged within Python coding culture for being implicit rather than the more explicit approach of from foo import bar.

I was rather struck by the Stack Overflow answers to this point from C# programmers, which was that in practice this lack of explicitness doesn't really matter because in your IDE (presumably Visual Studio) you can just hover over a name and be told by the system where the name is coming from. E.g.:

Now, in theory I realise this means when you're looking with a text editor, you can't tell where the types come from in C#... but in practice, I don't find that to be a problem. How often are you actually looking at code and can't use Visual Studio?

This is revelatory to me. Many Python programmers prefer a text editor approach to coding, using something like Sublime Text 2 or vim, where it's all about the code, plus command line tools and direct access and manipulation of folders and files. The idea of being dependent on an IDE to understand code at such a basic level seems anathema. It seems C# culture is radically different on this point. And I wonder if I just need to accept and embrace that as part of my learning of C#.

Which leads me to my question here: is C# development effectively inseparable from the IDE you use?

答:
Anyone bother to read way down here??

I summarize by saying the massively complex IDE functionality is indispensable and it will (should) evolve to the Zen of Sublime VimNess some day....

Our software is 129 projects of about 2M LOC. Add in the massiveness of the .NET framework and given this all I can say is the IDE is vital, transcending the motivations of this thread's question.

Insight into the Code Base

Period. You know the kinds of features we're talking about; except that its convenience becomes indispensable and essential with the kind of code base I deal with.

I write better code because of the IDE. I always add custom messages to my Nunit tests because it's easy, fast and accurate. I favor enumerations over strings due in large part to intellisense. I do not hesitate to use descriptive/long naming - a multi-line statement is composed fast and clean.

But even this smartness is too much at times. I often use good-old "find in files" text searching.

Coding help

Here is where I oft cry "enough!". Imagine a screen-full with a dozen colors of mostly obscureatta, some particular variable highlighted everywhere, brace highlighting obscuring what the brace actually is, squiggly underlining everywhere because "it" wants me to write literature not code, icons for Resharper context menus (you just gotta click it! then ignore it most of the time), a signature help popup spanning 2/3 of the screen horizontally, vertically displaying several overloads, a popup because of where you just happened to leave the mouse cursor....  I cant even seen the &^!% line*s* of code I'm working on!

Vis.Stud. needs to embrace minimalism so I can focus on coding and not go through hundreds (thousands if you count every color coding setting and all those plugins) of settings in a losing battle to reclaim sanity. A "Pareto" key would be great.


问:
Torvalds' quote about good programmer
Accidentally I've stumbled upon the following quote by Linus Torvalds:

"Bad programmers worry about the code. Good programmers worry about
  data structures and their relationships."

I've thought about it for the last few days and I'm still confused (which is probably not a good sign), hence I wanted to discuss the following:

What interpretation of this possible/makes sense?

What can be applied/learned from it?

答:
What can be applied/learned from it?

If I may, my experience in the last few weeks. The preceding discussions clarified the answer to my question: "what did I learn?"

I rewrote some code and reflecting upon the results I kept seeing & saying "structure, structure..." is why there was such dramatic difference. Now I see that it was Data structure that made all the difference. And I do mean all.

Upon testing my original delivery, the business analyst told me it was not working. We said "add 30 days" but what we meant was "add a month" (the day in the resulting date doesn't change). Add discrete years, months, days; not 540 days for 18 months for example.

The fix: in the data structure replace a single integer with a class containing multiple integers, change to it's construction was limited to one method. Change the actual date arithmetic statements - all 2 of them.

The Payoff

The new implementation had more functionality but the algorithm code was shorter and clearly simpler.

In Fixing the code behavior/results:

I changed data structure, not algorithm.

NO control logic was touched anywhere in code.

No API was changed.

The data structure factory class did not change at all.

Title: Torvalds' quote about good programmer


问:
Pair programming business logic with a non-IT person
Have you had any experience in which a non-IT person works with a programmer during the coding process?

It's like pair programming, but one person is a non-IT person that knows a lot about the business, maybe a process engineer with math background who knows how things are calculated and can understand non-idiomatic, procedural code.

I've found that some procedural, domain-specific languages like PL/SQL are quite understandable by non-IT engineers. These persons end up being co-authors of the code and guarantee the correctness of formulas, factors, etc.

I've found this kind of pair programming quite productive, this kind of engineering-type users feel they are also "owners" and "authors" of the code and help minimize misunderstandings in the communication process. They even help design test cases.

Is this practice common?

Does it have a name?

Have you had any similar experiences?

答:
Though you are describing this as a shared coding session (I can't call it pair programming, as only one person is "driving" - in pair programming, both parties take the keyboard and write code), I would call it gathering acceptance criteria.

That is, you are validating business rules (correct calculations and processes) with the business user (though one with a very technical role, an engineer).

In this case, it translates immediately to written code (SQL), but for many other activities is will not, though there are automated acceptance test tooling for different languages and platforms (I am specifically thinking about the gherkin language and related tooling).

This practice is not as common as it should be, but is gaining more and more followers and those who follow it (getting acceptance criteria in a form that can be executed) find it invaluable as both a tool to communicate with the business and to drive development.


问:
How to wrap console utils in webserver
I have a big dataset (100Mbs/day) and a bunch of console a TCL/TK tools to view it - I want to turn it into a web app that I can build, and others can maintain.

In long:

my group runs simulations yielding 100s of Mbs of data daily, in multiple (mostly but not only) text forms.

We have a bunch of scripts and tools, mostly old school 1990's style stuff requiring a 5-button mouse, as well as lots of ad-hoc scripts that engineers build out of frustration every month or so. These produces UIs, graphs, spreadsheets (various sizes), logs, event histories etc.

I want to replace (or at least supplement) the xwindows / console style UI with a web-based one, so I need the following properties:

pleasant to program

can wrap existing command-line tools in separate views (I don't need to scrape GUIs or anything)

as I port logic from the existing scripts I can create a modularised and pleasant codebase to replace it

I can attach a web-ui to navigate between views - each view is likely to contain keys which might make sense to view in another

I am new to building systems that have logic on the back-end and front-end of a web-server. from that point of view, they do this:

backend wraps old-school executables, constructs calls into them and them takes the output and wraps it up, niceifies it and delivers it to the web client. For instance the tool might generate a number of indexed images (per invocation) which I might deliver all at once or on-demand. May (probably) need to to heavy stats on some sources.

frontend provides navigation connecting multiple views, performs requests from one view for data from another (or self to self), etc. Probably will have some views with a lot of interactivity.

Can people please point me towards viable solutions for this? I know it's a bit of an open question so as answers come in I hope to refine the spec until we have a good match.

I guess I expect to see answers like "RoR!" "beans!" "Scala!" but please give an indication of why those are a good fit; I know nothing!  I'm not asking for _which is best, Scala or RoR*, but rather which have been a good fit for people doing what I'm trying to do?

I got bumped off SO for asking an open-ended question, so sorry if its OT here too (let me know).  I take the policy that I use the best/closest matched language for a project but most of my team are extremely low level (ie pipeline stages and CDyn) so I don't have the peer group to know where to start.

答:
If you're willing to be a little self-service (which it sounds as if you are) you may be interested in using AOLServer (http://www.aolserver.com).  It's the basis for OpenACS (http://openacs.org) and is one of the oldest application servers.

It's built and extended with TCL, so you may be able to use your existing functional scripts without having to port them to another language or environment.  At the very least, you should be able to use parts of your existing code.

Title: How to wrap console utils in webserver


问:
Why are there no package management systems for C and C++?
There are some programming languages for which exist a package management system:

CTAN for TeX

CPAN for Perl

Pip & Eggs for Python

Maven for Java

cabal for Haskell

Gems for Ruby

npm for NodeJS

bower for frontend Javascript & CSS

nuget for C#

composer for PHP

Is there any other languages with such systems? What about C and C++? (that's the main question!) Why there are no such systems for them? And isn't creating packages for yum, apt-get or other general package management systems better?

答:
There is a little confusion in this question. The above mentioned software manage extensions for specific programming languages. They provide libraries and source code that afterwards can be used in you program with your programming language of choice.

While general system level package mangers usually provide binary packages that can be used regardless of the application. They are more oriented at the system and user. Of course, system level package management systems like Aptitude, rpm, Entropy can provide any package, being it binary or source code. That's why you will find in them most of the extensions you would install with ... Gem for example.

Than, what you mentioned as Yum and Apt-get or Rigo are just user interfaces for the package management systems below them.

One more for the list o programming languages:

Composer and Pear for PHP


问:
Is there anything in .NET that allows me to define a grammar and generate a programming language?
I have a course in which the proffesor has asked us to create a DSL for a our final project.  He presented us in the first courses xText with Eclipse.  This being a new course, I am still a bit fuzzy on what Domain Specific Languages means.

This is my current understanding:  a domain specific language is a language that is created for specific problems in software development.  Examples of DSL's are PHP, SQL, JavaScript and on the opposite are languages like Java , C# , C++ , Ruby etc.

Please feel free to correct me if I am wrong.

What I would like to know: is there is any tool for .NET/Visual Studio that is similar to Xtext, that allows me to define a grammar and be allowed to generate a programming language based on that with an activity diagram?

答: This site may be interesting for you: http://nemerle.org . It's language for .net platform with rich metaprogramming features. More recently, the project is under the wing of the JetBrains: http://blogs.jetbrains.com/dotnet/2012/06/jetbrains-and-nemerle/ .</p>


问:
Switch or a Dictionary when assigning to new object
Recently, I've come to prefer mapping 1-1 relationships using Dictionaries instead of Switch statements. I find it to be a little faster to write and easier to mentally process. Unfortunately, when mapping to a new instance of an object, I don't want to define it like this:

```<code>var fooDict = new Dictionary<int, IBigObject>()
{
    { 0, new Foo() }, // Creates an instance of Foo
    { 1, new Bar() }, // Creates an instance of Bar
    { 2, new Baz() }  // Creates an instance of Baz
}

var quux = fooDict[0]; // quux references Foo
</code>```

Given that construct, I've wasted CPU cycles and memory creating 3 objects, doing whatever their constructors might contain, and only ended up using one of them. I also believe that mapping other objects to fooDict[0] in this case will cause them to reference the same thing, rather than creating a new instance of Foo as intended. A solution would be to use a lambda instead:

```<code>var fooDict = new Dictionary<int, Func<IBigObject>>()
{
    { 0, () => new Foo() }, // Returns a new instance of Foo when invoked
    { 1, () => new Bar() }, // Ditto Bar
    { 2, () => new Baz() }  // Ditto Baz
}

var quux = fooDict[0](); // equivalent to saying 'var quux = new Foo();'
</code>```

Is this getting to a point where it's too confusing? It's easy to miss that () on the end. Or is mapping to a function/expression a fairly common practice? The alternative would be to use a switch:

```<code>IBigObject quux;
switch(someInt)
{
    case 0: quux = new Foo(); break;
    case 1: quux = new Bar(); break;
    case 2: quux = new Baz(); break;
}
</code>```

Which invocation is more acceptable?

Dictionary, for faster lookups and fewer keywords (case and break)

Switch: More commonly found in code, doesn't require the use of a
Func<> object for indirection.

答:
C# 4.0 gives you the Lazy<T> class, which is similar to your own second solution, but shouts out "Lazy initialization" more explicitly.

```<code>var fooDict = new Dictionary<int, Lazy<IBigObject>>()
{
    { 0, new Lazy(() => new Foo()) }, // Returns a new instance of Foo when invoked
    { 1, new Lazy(() => new Bar()) }, // Ditto Bar
    { 2, new Lazy(() => new Baz()) }  // Ditto Baz
}
</code>```

Body:
C# 4.0 gives you the Lazy<T> class, which is similar to your own second solution, but shouts out "Lazy initialization" more explicitly.

var fooDict = new Dictionary<int, Lazy<IBigObject>>()
{
    { 0, new Lazy(() => new Foo()) }, // Returns a new instance of Foo when invoked
    { 1, new Lazy(() => new Bar()) }, // Ditto Bar
    { 2, new Lazy(() => new Baz()) }  // Ditto Baz
}


问:
Do non-manager coders in their forties or older out there sometimes regret about not being managers?
And why do most programmers quit coding and become managers so early compared to other areas? You can work as a construction worker, a lawyer, researcher, writer, architect, movie director for decades if not your whole life, without quitting the favorite thing you are doing. And yet most programmers think being a manager, or better, a non-coding manager is a cool thing and the ultimate goal of the software career. It's so rare to see an ordinary coder in his 40s or 50s (or 60s!) in a typical software company. Why?

(And I am for being a coder for as long as you love doing it.)

答:
In my class it's sort of the other way around.

We have mixed-classes, programmers and managers. Alot of the managers switched to programming in the 2th year.

I'm actually chocked to hear (assuming it's true) that most of the programmers want to switch to management.

ContentLicense: CC BY-SA 2.5


问:
How is the Linux repository administrated?
I am amazed by the Linux project and I would like to learn how they administrate the code, given the huge number of developers. I found the Linux repository on GitHub, but I do not understand how it is administrated. For example the following commit: https://github.com/torvalds/linux/commit/31fd84b95eb211d5db460a1dda85e004800a7b52

Notice the following part:

So one authored and Torvalds committed. How is this possible. I thought that it was only possible to have either pull or pushing rights, but here it seems like there is an approval stage.

I should mention that the specific problem I am trying to solve is that we use pull requests to our repo. The problem we are facing is that while a pull request is waiting to get merged, it is often broken by a commit. This leads to a seemingly never ending work to adapt the fork in order to make the pull request merge smoothly. Do Linux solve this by giving lots of people pushing rights (at least there are currently just three pull requests but hundreds of commits per day).

答:
Every git commit has separate "author" and "committer" metadata fields, which can be set manually when doing a commit, or automatically through mechanisms like pull requests in github.

This allows workflows that include sending patches via email, which is apparently still the main mechanism used for the Linux kernel - the github repository is just a mirror, and Linus does not like the implementation of github pull requests, so he will not accept them.


问:
Aggregate root & Repository dilemma
I am in a big dilemma here.

I have a League, Team and Player entities. I have created a repo for the league only as a Team cannot exists without a League. At first I had bounded the players only with the team but then I realised I would have a problem with free agents so I also bounded the players to the league. Then I was wondering if a player could exists without a League or a Team and I am totally confused to that question.

So would you make a player repository or include them in the league repo?

Thanks

答: Aggregate doesn't mean "cannot exists without". It means the two are logically tied together, and root manages access to entities inside the aggregate. In your case, I don't think League and Team are aggregate. Same with League and Player.</p>

Title: Aggregate root & Repository dilemma


问:
What is the need for 'discoverability' in a REST API when the clients are not advanced enough to make use of it anyway?
The various talks I have watched and tutorials I scanned on REST seem to stress something called 'discoverability'. To my limited understanding, the term seems to mean that a client should be able to go to http://URL - and automatically get a list of things it can do.

What I am having trouble understanding - is that 'software clients' are not human beings. They are just programs that do not have the intuitive knowledge to understand what exactly to do with the links provided. Only people can go to a website and make sense of the text and links presented and act on it.

So what is the point of discoverability, when the client code that accesses such discoverable URLs cannot actually do anything with  it, unless the human developer of the client actually experiments with the resources presented? This looks like the exact same thing as defining the set of available functions in a Documentation manual, just from a different direction and actually involving more work for the developer. Why is this second approach of pre-defining what can be done in a document external to the actual REST resources, considered inferior?

答: The need for discoverability may not be relevant, but the links that allow discoverability serve more purposes. The most important of these, to my mind, is that providing full URI's in the responses to the client, means that no client will ever need to "compose" an URI. That means that no client will ever need knowledge about how the URI's are structured. And that in turn allows the server developers to change the URI scheme whenever it suits them as they do not need to consider older clients still relying on an old way of structuring URI's.</p>


答:
I think you are thinking to complex. What you have here are all related entities. These are all in the same layer and have all the same intention: handling of data.

Think about the usage of the Layer Supertype Pattern from Martin Fowler. It says:

It's not uncommon for all the objects in a layer to have methods you don't want to have duplicated throughout the system. You can move all of this behavior into a common Layer Supertype.

There you should have for example a EntityBase class. A abstract class that handles all the common things like ID, Validation, comparision.

Each of your items are entities and should have a own repository. If you do not want that a specified repository has posibility for write actions, you could split your IRepository interface into two parts: IReadOnlyRepository and IRepository.

For your example:
You can have multiple leagues, a league has multiple teams and a team can have only 1 league?!?. Each team has multiple players, and they can only be part of one team. Nevertheless. It all depends on the informations you want to reuse. But for a good DB Design you should have each of this entities as own aggregates.

Title: Aggregate root & Repository dilemma

Body:
I am in a big dilemma here.

I have a League, Team and Player entities. I have created a repo for the league only as a Team cannot exists without a League. At first I had bounded the players only with the team but then I realised I would have a problem with free agents so I also bounded the players to the league. Then I was wondering if a player could exists without a League or a Team and I am totally confused to that question.

So would you make a player repository or include them in the league repo?

Thanks


问:
What is the difference between "good" designers and "great" designers?
While reading this wikipedia article, Brookes has told that there is a difference between "good" designers and "great" designers.  What is the difference between them? How can I decide if a designer is good or great?</p>

答:
I'm going to assume you're talking about Software Design as opposed to the narrower Ux design.

I'll quote a semi-famous passage from Alan Perlis:

"Fools ignore complexity. Pragmatists suffer it. Some can avoid it. Geniuses remove it."

One aspect of a Great designer is that they reduce complexity.


问:
Does Dropbox use a cronjob to sync up?
I was looking into lipsync on a Dropbox clone. I was looking at the diagram on how it works here.

It shows that a cronjob is used to keep files in sync between client and server. Does that mean that every sec/min/hour, a cronjob runs and checks to see if there is a difference between client and server? Is that how Dropbox does it?

If it does use a cronjob, what happens when you are in the middle of syncing and another cronjob runs? Does rsync (or additional libs) know how to handle this?

答:
No, Dropbox and any decent synchronization tool relies on file system events. All operating systems offer such events and programs like Dropbox are just simply listening for changes on files they are watching. When a change happens, or file is added / deleted, Dropbox decides what it has to do.

If several events happen while others are in progress, they a queued and executed sequentially, or parallel where possible.

EDIT: for Linux see the inofity file system event system.

Title: Does Dropbox use a cronjob to sync up?


问:
Why is naming a table's Primary Key column "Id" considered bad practice?
My t-sql teacher told us that naming our PK column "Id" is considered bad practice without any further explanations.

Why is naming a table PK column "Id" is considered bad practice?

答:
The practice of using Id as primary key field leads to the practice where id gets added to every table. A lot of tables already have unique information that uniquely identifies a record. Use THAT as primary key and not an id field you add to each and every table. That's one of the foundations of relational databases.

And that's why using id is bad practice: id is often not information just an autoincrease.

consider the following tables:

```<code>PK id | Countryid   | Countryname
    1 |         840 | United States
    2 |         528 | the Netherlands
</code>```

What's wrong with this table is that it enables the user to add another line: United States, with countrycode 840. It just broke relational integrity.
Ofcourse you can enforce uniqueness on individual columns, or you could just use a primary key that's already available:

```<code>PK Countryid   | Countryname
           840 | United States
           528 | the Netherlands
</code>```

That way you use the information you already have as primary key, which is at the heart of relational database design.

Body:
The practice of using Id as primary key field leads to the practice where id gets added to every table. A lot of tables already have unique information that uniquely identifies a record. Use THAT as primary key and not an id field you add to each and every table. That's one of the foundations of relational databases.

And that's why using id is bad practice: id is often not information just an autoincrease.

consider the following tables:

PK id | Countryid   | Countryname
    1 |         840 | United States
    2 |         528 | the Netherlands

What's wrong with this table is that it enables the user to add another line: United States, with countrycode 840. It just broke relational integrity.
Ofcourse you can enforce uniqueness on individual columns, or you could just use a primary key that's already available:

PK Countryid   | Countryname
           840 | United States
           528 | the Netherlands

That way you use the information you already have as primary key, which is at the heart of relational database design.


问:
Why learn more programming languages?

Possible Duplicate:

  (Why) Should I learn a new programming language?

I came across a line in this article which is,

Learn one programming language every year

Why do good programmers suggest to learn more programming languages . We can be a jack of all and master of none too in this case.

答:
I have not read the article, but I have seen this specific piece of advice many times over, it is common knowledge.

The original piece of advice, does not refer to mastery that comes after years of experience, but to exposure on different paradigms that will provide the individual with different approaches on solving problems. So there is a footnote somewhere missing that would say: "Different programming paradigms".

A good but not so relevant post on how different approaches to programming affect problem solving is this post by Steve Yegge Notes from the Mystery Machine Bus.

Title: Why learn more programming languages?


答:
It helps to know more than language, you can more easily talk to more people. It is true with foreign languages, it is also true with programming languages.

First of all it's a good training for your brain. You learn new ways of doing the stuff you usually do. Sometimes you'll find that your common tasks are more easily done in a different programming language.

Second of all when your main programming language gets worn off, you will be able to switch to another one easily.

You will also be able to get along with 3rd party software developers. Knowing limitations and strengths of various different languages you will be able to predict what will be difficult to implement in a given language.

Also remember that programming skill is independent of a programming language. It's like knowing how to speak. If you know how to speak in one language, you just have to learn new vocabulary and new grammar to properly speak in another language. No need to learn how to use your tongue, vocal chords, teeth, etc.

Title: Why learn more programming languages?

Body:
Possible Duplicate:

  (Why) Should I learn a new programming language?

I came across a line in this article which is,

Learn one programming language every year

Why do good programmers suggest to learn more programming languages . We can be a jack of all and master of none too in this case.


问:
Why error codes are negated?
Very often I see in C code negation of returned error codes, e.g. return -EINVAL instead of return EINVAL. Why used negation?

答:
On many UNIXen, convention for syscalls is that they return the error code negated in case of an error, and the actual value in case of success.

This is translated on the user space side into -1 for errors with the positive error code in errno, or the actual value in case of success.

The need for this dual-purposing of the return value is because multiple-returns in this kind of language is bothersome, as you'd have to resort to passing in out-parameters to hold an eventual error.

Title: Why error codes are negated?


答:
Why do good programmers suggest to learn more programming languages

There are a couple of different ways I could see this being quite useful:

Getting different perspectives.  If you've looked through a lot of procedural, OO, and functional code you can see very different ways to approach a problem and this can be useful to have many different tools in one's toolbox.  The breadth can be useful since more often someone will want something fixed and doesn't care at all about what language is used.  "Just get it done!" will be what the client or customer's focus yet there are likely multiple ways to implement a solution.  How many do you naturally consider and how many others are out there?  This is more about how to be open to what choices are available which can be more than a bit mind numbing to consider all of them.  Thus, trying to make this bite size and just do one at a time can be quite useful.

Preventing lock-in.  By adding another language, there is a chance that there will be some new pieces that may require some adaptation.  How do you handle things changing?  By taking on a new language regularly, it can help prevent the perspective of thinking everything can be done in one language or with one framework.  Technology changes often enough that the skill of how to pick something up from scratch is well worth having honed, and that is part of the benefit that comes from this practice.  If someone just coded in C for 20 years and didn't touch other languages, it may be challenging to see how well this person would adjust to a language with a very different syntax and overall structure.

Title: Why learn more programming languages?


答: It is a convention; a lot of functions return a stricly positive result on success and a negative result on failure. Initially, it was related to the return code of Unix process. A success was indicated by 0.</p>

Title: Why error codes are negated?

Body: Very often I see in C code negation of returned error codes, e.g. return -EINVAL instead of return EINVAL. Why used negation?


答:
Because life rarely lets you get by with a strategy as simple as "I will become an expert in X and ignore all other fields." It more difficult and more subtle than that. Developing an area of deep expertise is essential but you also have to keep your eye on developments outside your specialty. Over decades the industry inevitably changes. If you don't keep up with developments outside your specialty you can miss the appearance of superior tools, miss the rise of new markets, and end up stuck in a niche market. How you balance the time you spend on deepening your primary expertise vs. expanding your knowledge is a judgement call. In your first few years almost all of your time will be spent going deep, but as you mature you'll want to spend more time branching out.

Not all languages are equally effective for all tasks. CGI is a pain to do in C, and you aren't going to be writing device drivers in JavaScript. The folk wisdom is "If all you have is a hammer, then all the world looks like a nail". Knowing multiple languages helps you make judgments about what the right tool for a job is.

Learning other languages will help you understand your primary language. If you only know one language you'll have a host of unconscious assumptions that are actually design decisions. Learning multiple languages will help make you aware of you assumptions.

Once you've learned three or four languages learning another one becomes pretty easy.

Title: Why learn more programming languages?


问:
Should I be paid for time spent learning a framework?
To give light to the situation: I am currently one of two programmers working in a small startup software company. Part of my job requires me to learn a Web development framework that I am not currently familiar with. I get paid by the hour.

So the question is: Is it wholly ethical to spend multiple hours of the day reading through documentation and tutorials and be paid for this time where I am not actively developing for our product? Or should the bulk of this learning be done at home, or otherwise off hours, to allow for more full-on development of our application during the work day?

答:
Of course it's ethical to study and learn a new framework when you're on the clock. You might spend some of your own time on it, but your employer must expect that you need some time to research things at work. I run a web development team and I give all members 5 hours a week - an hour a day - for independent research and self learning. I know what they gain in that time will help them grow as programmers, and I know it's not fair to ask people to use any new technology we don't provide training for.

Any solid employer should want their people doing some learning and research on the clock.

As an example, I bring in new hires who are smart and can code OOP PHP5 but maybe don't know MVC well enough or don't have experience with Zend or CodeIgniter. But I know they can pick it up, so giving them research time with a mentor helps the company keep a good base of programmers.


问:
DDD Model Design and Repository Persistence Performance Considerations
So I have been reading about DDD for some time and trying to figure out the best approach on several issues.

I tend to agree that I should design my model in a persistent agnostic manner. And that repositories should load and persist my models in valid states.

But are these approaches realistic practically? I mean its normal for a model to hold a reference to a collection of another type. Persisting that model should mean persist the entire collection. Fine. But do I really need to load the entire collection every time I load the model? Probably not.

So I can have specialized repositories. Some that load maybe a subset of the object graph via DTOs and others that load the entire object graph. But when do I use which? If I have DTOs, what's stopping client code from directly calling them and completely bypassing the model?

I can have mappers and factories to create my models from DTOs maybe? But depending on the design of my models that might not always work. Or it might not allow my models to be created in a valid state.

EDIT 1:
Aside from lazy/eager loading and using a DI framework to inject repositories in my models, what is another approach?

What's the correct approach here?

答:
First is that, it is hard to have both complex model and good performance. This is compromise you need to make. To have both, you would need much bigger investment than sum of both. If you really need performance, DDD is not good alternative.

Second is, that you are worrying about performance before actually writing code and profiling it. Maybe the performance implications are not that bad as you think and you can easily use object-access/ORM/lazy approach without troubles.

But if you find out, through profiling, that performance is bad, maybe because you are hitting DB too often. Solution is probably just like you said: specialized methods on repositories. Those can either return entity along with some related entities already required (eager loading through ORM) or by doing a queries, that return specific aggregate or filtered data. Also, there seems to be some confusion, those repository methods and objects they return are part of the model, just like repositories they belong to. So "bypassing model" doesn't make sense here. You just need to continuously keep eye on performance and make sure developers use the correct methods to reduce code duplication and leverage the more efficient methods.


答:
Actually some people (of noticeable boost fame) are working hard to create and establish such a system called Ryppl.
It is hard to establish such a System for C++, because it has no single player which can dictate it. --UPDATE: Unfortunately it is abandonned.

On your second question, a normal package manager (besides not being cross platform) does not handle the specific needs of developers.

Title: Why are there no package management systems for C and C++?

Body:
There are some programming languages for which exist a package management system:

CTAN for TeX

CPAN for Perl

Pip & Eggs for Python

Maven for Java

cabal for Haskell

Gems for Ruby

npm for NodeJS

bower for frontend Javascript & CSS

nuget for C#

composer for PHP

Is there any other languages with such systems? What about C and C++? (that's the main question!) Why there are no such systems for them? And isn't creating packages for yum, apt-get or other general package management systems better?


问:
ASP.NET MVC Portable Areas - Can they communicate and be used as a plugin-like architecture?
I'll get straight to the point:
I was wondering if there is a common pattern to use portable areas as a components of a plugin-like architecture.

Example:
We've got 3 plugins (portable areas) packaged and distributed via NuGet feed.
Each of them is following the standard MVC structure (has it own Models, Views and Controllers). Lets say login form, header and footer.

What I was wondering if there is a way to make them communicate.
For example: when user logs on, login plugin executes it own logic, logs the user and then it updates the state of the header plugin with changes it state accordingly.

Edit: Dealing with client side calls
Another thing that I did not mention in the original post is that I wanted to expose the plugin features via controllers to be consumed via JavaScript as well.
Lets say I have all architecture in place and all plugins registered themselves with the system properly (routes, dependencies ...etc)
For example if I click the "Change color" feature of one "Colors picker" plugin it calls action method of another plugin (Image plugin lets say) and loads image of requested color. Of course everything should be done via Ajax without resubmitting the entire page that hosts the components.

You think it is a doable scenario in the solutions you've proposed here?

Thanks in advance for all the answers.

答:
I would not use a shared database where all plugins has write access since that makes debugging extremely difficult. There is no way to tell which plugin screwed up.

The best solution today is to take advantage of an inversion of control container.

Let each plugin have a separate assembly (separated interface pattern) where it declares it's integration interfaces (that other plugins uses)

Allow each plugin to have a composition root where it registers it's services

Then simply let every plugin use dependency injection to use the services which was specified by other plugins.

Another way is to use commands and domain events as I describe here: http://blog.gauffin.org/2012/10/writing-decoupled-and-scalable-applications-2/

Do note that it's not really portable areas specific.

If you're interested in a MVC3 plugin architecture I've made one using my Griffin.MVcContrib project: http://blog.gauffin.org/2012/05/griffin-mvccontrib-the-plugin-system/

OwnerDisplayName: Beton


答: Our trade is programming.  Programming languages are tools of that trade.  Learning multiple languages isn't being a "jack of all trades," it's being a master of the tools of one trade.</p>

Title: Why learn more programming languages?


问:
Why is the use of abstractions (such as LINQ) so taboo?
I am an independent contractor and, as such, I interview 3-4 times a year for new gigs.  I am in the midst of that cycle now and got turned down for an opportunity even though I felt like the interview went well.  The same thing has happened to me a couple of times this year.

Now, I am not a perfect guy and I don't expect to be a good fit for every organization.  That said, my batting average is lower than usual so I politely asked my last interviewer for some constructive feedback, and he delivered!

The main thing, according to the interviewer, was that I seemed to lean too much towards the use of abstractions (such as LINQ) rather than towards lower-level, organically grown algorithms.

On the surface, this makes sense--in fact, it made the other rejections make sense too because I blabbed about LINQ in those interviews as well and it didn't seem that the interviewers knew much about LINQ (even though they were .NET guys).

So now I am left with this question: If we are supposed to be "standing on the shoulders of giants" and using abstractions that are available to us (like LINQ), then why do some folks consider it so taboo?  Doesn't it make sense to pull code "off the shelf" if it accomplishes the same goals without extra cost?

It would seem to me that LINQ, even if it is an abstraction, is simply an abstraction of all the same algorithms one would write to accomplish exactly the same end.  Only a performance test could tell you if your custom approach was better, but if something like LINQ met the requirements, why bother writing your own classes in the first place?

I don't mean to focus on LINQ here.  I am sure that the JAVA world has something comparable, I just would like to know why some folks get so uncomfortable with the idea of using an abstraction that they themselves did not write.

UPDATE

As Euphoric pointed out, there isn't anything comparable to LINQ in the Java world.  So, if you are developing on the .NET stack, why not always try and make use of it?  Is it possible that people just don't fully understand what it does?

答:
Something else you should consider is that your enthusiasm for a cool new technology can simply make people feel uncomfortable and not want you around. You're not "empowering" them, because it's you who knows this technology, not them. Even if they themselves don't realize it, they may be seeking candidates who reinforce what they've already invested so much time into.

You want to present an attitude that says, "Whatever you're doing, I want to help you achieve it", rather than giving a subtext that says, "You might be doing things in a bad way, and having me around will prove it."


答:
From another answer, I've always thought "learn one programming language every year" was terrible advice for novice programmers for exactly the reason you state.

A novice programmer needs to learn far more than one language in short order:

A general purpose scripting language such as python or perl

A faster language, typically a compiled language, because python and perl are too slow

Some familiarity with the shell

Some familiarity with make

That's a minimum. Add Matlab or Mathematica for someone working in scientific programming. The simulation environment often is a language if you're working on simulations. For someone working on databases or games, that database or physics engine are in a sense languages of their own. A GUI adds yet another piece of complexity.

It's the novice programmer who faces the steepest learning curve. Learning a language a year is a piece of cake after having accomplished that initial step.

Title: Why learn more programming languages?


问:
Should we test all our methods?
So today I had a talk with my teammate about unit testing. The whole thing started when he asked me "hey, where are the tests for that class, I see only one?". The whole class was a manager (or a service if you prefer to call it like that) and almost all the methods were simply delegating stuff to a DAO so it was similar to:

```<code>SomeClass getSomething(parameters) {
    return myDao.findSomethingBySomething(parameters);
}
</code>```

A kind of boilerplate with no logic (or at least I do not consider such simple delegation as logic) but a useful boilerplate in most cases (layer separation etc.). And we had a rather lengthy discussion whether or not I should unit test it (I think that it is worth mentioning that I did fully unit test the DAO). His main arguments being that it was not TDD (obviously) and that someone might want to see the test to check what this method does (I do not know how it could be more obvious) or that in the future someone might want to change the implementation and add new (or more like "any") logic to it (in which case I guess someone should simply test that logic).

This made me think, though. Should we strive for the highest test coverage %? Or is it simply an art for art's sake then? I simply do not see any reason behind testing things like:

getters and setters (unless they actually have some logic in them)

"boilerplate" code

Obviously a test for such a method (with mocks) would take me less than a minute but I guess that is still time wasted and a millisecond longer for every CI.

Are there any rational/not "flammable" reasons to why one should test every single (or as many as he can) line of code?

答: In my opinion cyclomatic complexity is a parameter. If a method is not complex enough (like getters and setters). No unit testing is needed. McCabe's Cyclomatic Complexity level should be more than 1. Another word there should be minimum 1 block statement.</p>

Title: Should we test all our methods?


答:
You have to setup rules by yourself before modeling. Here are some suggestions

A team can exist without a League. How else would they be able to play matches outside the league?

Players can switch teams.

Players do not suddenly disappear if a team is shut down.

It all depends on how your application works. If you need to reference an aggregate outside the root (without the root) it usually means that that aggregate should be a root to.

Title: Aggregate root & Repository dilemma


答: Depends on what kind of design. For web page designers a good designer can make something that looks good but a great designer can make something that looks good and works well (ie intuitive and easy to use).</p>

Title: What is the difference between "good" designers and "great" designers?

Body: While reading this wikipedia article, Brookes has told that there is a difference between "good" designers and "great" designers.  What is the difference between them? How can I decide if a designer is good or great?</p>


答: While I have yet to truly master any language, I've learned a few well, and I've used/dabbled in many. With each new language I pick up I get better at the others I know. Learning each new language teaches me to focus on core disciplines that work across them all. Thus learning new languages makes me better at software architecture, better at choosing and using data structures, I learn new things about my text editor/IDE, and I get better at communicating ideas in a less language-specific manner (to name only a few benefits.)</p>

Title: Why learn more programming languages?


问:
Is perfectionism a newbie's friend or enemy?

Possible Duplicate:

  Where do you draw the line for your perfectionism?

I see that the development community is very focused on doing things the right way and personally I would like to do the same too, however, is it a good or bad idea for a newbie to focus on design principles, design patterns, and commenting code when getting started, or is it better to let creativity run wild and potentially write sloppy code. Where should a newbie draw the line?

答:
Write a prototype any way you want. If it's working - it's ok, leave it that way. If you want to show the code to anyone else - think what can be done better and refactor.

After some time you'll write code the right way without even noticing it. Of course "the right way" depends on the company's policies, language common code onvention, regulations, etc.

If you try to be perfect from the start, you'll be progressing very slowly. You'll ask yourself questions like:

Maybe I could use a design pattern here?

Are my functions too short or too long? Or maybe they are named the wrong way?

Some other language specific silly question :)

It takes time (lines of code) to become proficient in any discipline. To be proficient in programming you have to solve problems. Writing 100 CRUD applications will teach you less than a few different complex applications.

Don't forget that getting things done on time is more important than getting things done properly but late, or not accomplishing them at all but having all the code perfectly polished but unfinished.


问:
What is the usage of Splay Trees in the real world?
I decided to learn about balanced search trees, so I picked 2-3-4 and splay trees.
What are the examples of splay trees usage in the real world?

In this Cornell: http://www.cs.cornell.edu/courses/cs3110/2009fa/recitations/rec-splay.html I read that splay trees are 'A good example is a network router'.
But from rest of the explanation seams like network routers use hash tables and not splay trees since the lookup time is constant instead of O(log n).

答:
It is important to note that hash tables only have average access time of O(1). This means a particular operation could be much worse. Additionally, there are several requirements for properly formed hash trees:

Mostly empty - few hash algorithms perform well beyond 70% usage, and most recommend 50% usage.

Collision handling is complex - either having to use a list as the "stored value" or accepting a worst case linear search time

Hashing cost - you have to perform a hashing operation, which may or may not involve a lot of work

It sounds like the course mentions that in many routers these issues have been solved so they use a hash table for storage. However there are several advantages to splay trees

No overhead - if you allocate 10 MB to storage you get 10 MB worth of data without adjusting your run-times

Recent access preference - recent data is more easily accessed, and routers access more recent data frequently (new network nodes are likely to talk, and most networks are not used evenly)

Dups are fine - can be useful depending on what you are storing

Simple implementation - routers are typically run on fairly weak processors and are incredibly difficult to update, so simplicity is nice

Unfortunately this doesn't answer your question directly, but hopefully it sheds some light on why that is the case.

BTW, here are some notes on why routers may have moved away (these line up with advantages):

Storage sizes have gone up, due to the cost of RAM going down, ability to keep things in memory is easier

Hash tables when properly maintained have constant access to all elements

Hash tables can handle dupes if you need them to

Router manufacturers are typically long lived and can overcome complexity issues with time


答:
Constantly improving the quality of the code you write is simply a given. You need to do it.

But keep it in context - you learn and apply new things in order to get a return on your investment, which may be raw productivity, reliability, future maintainability, or ANY other criteria you feel carries weight.

When I hear the word perfectionist, I generally think of someone whos main motivation is be perfect, not productive. Don't be that person. You want utility from increasing your production. Let your efforts be driven by tangible and realistic payoff. Don't get caught up in the "everything is worth learning" trap.

Title: Is perfectionism a newbie's friend or enemy?

Body:
Possible Duplicate:

  Where do you draw the line for your perfectionism?

I see that the development community is very focused on doing things the right way and personally I would like to do the same too, however, is it a good or bad idea for a newbie to focus on design principles, design patterns, and commenting code when getting started, or is it better to let creativity run wild and potentially write sloppy code. Where should a newbie draw the line?


问:
Is functional intellisense and code browsing more beneficial than the use of dependency injection containers
This question is really based on PHP, but could be valid for other dynamically typed, interpreted languages and specifically the methods of generating code insight and object browsing in development environments.

We use PHPStorm, and find intellisense invaluable, but it is provided by some limited static analysis and parsing of doc comments.

Obviously this does not lend well to obtaining dependencies through a container, as the IDE has no idea of the type returned, so the developer loses out on a plethora of (in the case of our framework anyway) rich documentation provided through the doc comments.

So we start to see stuff like this:

```<code>$widget = $dic->YieldInstance('WidgetA', $arg1, $arg2, $arg3, $arg4...));
/**
 * @var $widget WidgetA
 */
</code>```

So that code insight works.

In effect the comments are tightly bound, but worse they come out of sync when code is modified but not the comments:

```<code>$widget = $dic->YieldInstance('WidgetB', $arg1, $arg2, $arg3, $arg4...));
/**
 * @var $widget WidgetA
 */
</code>```

Obviously the comment could be improved by referencing a Widget interface, but then we might as well use a factory and avoid the requirement for the extra typing hints in the comments, and dic complexity / boiler plating.

Which is more important to the average developer, code insight / intellisense or 'nirvana' decouplement?

答:
First of all, complete decoupling is not necessarily an ideal condition.  There will always be some coupling between classes, methods and properties, otherwise it would be impossible to communicate any meaningful information.  Taken to its logical extreme, complete decoupling resolves to passing a pure object (i.e. a pointer/reference) with no shape whatsoever, which must be cast to the correct type before any meaningful information transfer can take place, and the only way that can occur is by transferring information about the type to cast to.

The same tradeoff occurs with statically typed and dynamically typed languages.  Consider the dynamic keyword in C#.  The dynamic keyword allows late binding of method calls, deferring resolution of those calls from compile time to runtime.  Intellisense stops working.  Why?  Because there's no way to predict what method signatures are going to be available on the dynamic object until runtime.  But lack of Intellisense doesn't mean that the dynamic keyword is useless; it just means that you have to accept the absence of Intellisense as a tradeoff for the benefits of using dynamic.

In the C# world, the way one would solve this problem is to inject an object that conforms to a specific interface.  This allows enough shape to draw meaningful information from the object, while still allowing different implementations of that interface to have different underlying behavior.  The interface still benefits from intellisense, while providing the flexibility to change the behavior by swapping the implementation.


答:
This is exactly what PHP interfaces are for: presumably there is some functionality (methods) that are shared by both WidgetA and WidgetB, otherwise you could not substitute them. So those methods go into an interface and are documented there, and you can declare the $widget variable to have that interface as its type.

Of course this basically means that you're doing the same work as you'd do with a statically typed language like Java, so you might as well use one since you've already found that you're missing the benefits of static typing...

Title: Is functional intellisense and code browsing more beneficial than the use of dependency injection containers

Body:
This question is really based on PHP, but could be valid for other dynamically typed, interpreted languages and specifically the methods of generating code insight and object browsing in development environments.

We use PHPStorm, and find intellisense invaluable, but it is provided by some limited static analysis and parsing of doc comments.

Obviously this does not lend well to obtaining dependencies through a container, as the IDE has no idea of the type returned, so the developer loses out on a plethora of (in the case of our framework anyway) rich documentation provided through the doc comments.

So we start to see stuff like this:

```<code>$widget = $dic->YieldInstance('WidgetA', $arg1, $arg2, $arg3, $arg4...));
/**
 * @var $widget WidgetA
 */
</code>```

So that code insight works.

In effect the comments are tightly bound, but worse they come out of sync when code is modified but not the comments:

```<code>$widget = $dic->YieldInstance('WidgetB', $arg1, $arg2, $arg3, $arg4...));
/**
 * @var $widget WidgetA
 */
</code>```

Obviously the comment could be improved by referencing a Widget interface, but then we might as well use a factory and avoid the requirement for the extra typing hints in the comments, and dic complexity / boiler plating.

Which is more important to the average developer, code insight / intellisense or 'nirvana' decouplement?


答: Think about this: temporary fixes / lines-of-code lasts often longer than expected if not forever ...</p>


问:
Do unit tests sometimes break encapsulation?
I very often hear the following: "If you want to test private methods, you'd better put that in another class and expose it."

While sometimes that's the case and we have a hiding concept inside our class, other times you end up with classes that have the same attributes (or, worst, every attribute of one class become a argument on a method in the other class) and exposes functionality that is, in fact, implementation detail.

Specially on TDD, when you refactor a class with public methods out of a previous tested class, that class is now part of your interface, but has no tests to it (since you refactored it, and is a implementation detail).

Now, I may be not finding an obvious better answer, but if my answer is the "correct", that means that sometimes writting unit tests can break encapsulation, and divide the same responsibility into different classes.

A simple example would be testing a setter method when a getter is not actually needed for anything in the real code.

Please when aswering don't provide simple answers to specific cases I may have written. Rather, try to explain more of the generic case and theoretical approach. And this is neither language specific.

Thanks in advance.

EDIT: The answer given by Matthew Flynn was really insightful, but didn't quite answer the question. Although he made the fair point that you either don't test private methods or extract them because they really are other concern and responsibility (or at least that was what I could understand from his answer), I think there are situations where unit testing private methods is useful. My primary example is when you have a class that has one responsibility but the output (or input) that it gives (takes) is just too complex. For example, a hashing function. There's no good way to break a hashing function apart and maintain cohesion and encapsulation. However, testing a hashing function can be really tough, since you would need to calculate by hand (you can't use code calculation to test code calculation!) the hashing, and test multiple cases where the hash changes. In that way (and this may be a question worth of its own topic) I think private method testing is the best way to handle it. Now, I'm not sure if I should ask another question, or ask it here, but are there any better way to test such complex output (input)?

OBS: Please, if you think I should ask another question on that topic, leave a comment. :)

EDIT2: I accepted an answer as my correct because it made me think and decide my course of action, although it didn't answered my question completely. But for those who face the same problem as I do (one cohesive class that will change together, but is still too hard to test by itself), I'll tell what I did and why. I decided that the output of that class is simply too hard to a computer to test correctly, so I didn't test it. I could have used a framework to test it's private methods (which would be the best idea, I think), but I didn't want to get to that point. If you are wondering what it is that is cohesive and respects SRP, and still is too hard to a computer to test, I'll give some examples: heightmap generation, hashing functions, procedural music generation (you can test some units, but the highest level unit is simply too subjective).

答:
When I was younger and raised this question, I was told that I really don't need to write unit tests for private methods.  Surprisingly, this turned out to be true.

If you take a behavioral driven approach to unit tests, this makes perfect sense--your public methods are what are being asked to do stuff.  The fact that they call internal private methods is orthogonal to their outward behavior.  Because the other method is private/encapsulated, it really is part of the unit being tested.

You may ask that if multiple methods in your class all call a single private method, so shouldn't you be testing that that one method works? The answer here is yes, but it is not made evident by a unit test of the private method, but rather the unit tests of the public methods calling it.  If the public methods work, and they call a private method, then the private method must also work.

ContentLicense: CC BY-SA 4.0


答:
Perfectionism is a poor developer's excuse for not getting the work done.

Larry Wall, in the glossary of the first edition of Programming Perl, famously notes:

We will encourage you to develop the three great virtues of a programmer: laziness, impatience, and hubris.

In the second edition of the book the terms are further defined:

Laziness: The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful, and document what you wrote so you don't have to answer so many questions about it. Hence, the first great virtue of a programmer. Also hence, this book. See also impatience and hubris. (p.609)

Impatience: The anger you feel when the computer is being lazy. This makes you write programs that don't just react to your needs, but actually anticipate them. Or at least pretend to. Hence, the second great virtue of a programmer. See also laziness and hubris. (p.608)

Hubris: Excessive pride, the sort of thing Zeus zaps you for. Also the quality that makes you write (and maintain) programs that other people won't want to say bad things about. Hence, the third great virtue of a programmer. See also laziness and impatience. (p.607)

While Perl is not everyone's cup of tea, the ideas expressed in the above quote apply to programming in general. Very recently I assigned what I thought was an easy task to a relatively new developer, and gave him explicit guidelines to skip certain "best practices". The task was performance sensitive, a background process that would receive a huge lump of XML from a webservice (that we didn't control), transform the data, do a couple of simple checks and then store them in our database. The size of the XML data was huge and we expected it to get gigantic in the very near future, this thing needed to be fast. Really fast.

What he came up with, a week later, can only be described as an over-engineered piece of crap (honest assessment). It worked, flawlessly, for some smallish XML files I've given him to test the data transformations on, but when hooked up to the actual webservice it just couldn't cope, stuff started crashing at random, as they typically do when a background process faces performance issues. When I reviewed his code I found out, to my horror, that he had completely ignored me, the code was full of... design patterns! Poor noob had beautifully scribed an almost academic example of the strategy pattern for what was essentially a smallish switch statement, amongst other things.

Now, don't get me wrong, he applying patterns wasn't the root cause of the performance issues we were facing, however he had spent all week trying to write the "best" code possible when he should have quickly hacked the code in a day or two, and then spend the rest of the time stress testing the damn thing and identifying bottlenecks. And now I had to dig through thousands of uneccessary lines of code to even start getting an idea what was going on. No chance of me wasting my time like that, just scrapped the whole thing and wrote it from scratch in a few hours.

I discussed his code with him, and my conclusions are:

He had just discovered some of the concepts he applied, and was too eager to see them in action, and

He, unknowingly, wanted to impress (not me, but the team in general).

Enthusiasm is great, rushing to apply concepts you might not yet fully understand in your code is not. Even if you do fully understand them, more often than not you don't actually need them. One of the guiding principles of Extreme Programming is "You ain't gonna need it" (YAGNI), and it's a principle that I always try to pass to newer developers. Ron Jeffries, one of the founders of XP, explains:

Often you will be building some class and you’ll hear yourself saying "We’re going to need...".

Resist that impulse, every time. Always implement things when you actually need them, never when you just foresee that you need them. Here’s why:

Your thoughts have gone off track. You’re thinking about what the class might be, rather than what it must be. You were on a mission when you started building that class. Keep on that mission rather than let yourself be distracted for even a moment.

Your time is precious. Hone your sense of progress to focus on the real task, not just on banging out code.

You might not need it after all. If that happens, the time you spend implementing the method will be wasted; the time everyone else spends reading it will be wasted; the space it takes up will be wasted.

You find that you need a getter for some instance variable. Fine, write it. Don’t write the setter because "we’re going to need it". Don’t write getters for other instance variables because "we’re going to need them".

The best way to implement code quickly is to implement less of it. The best way to have fewer bugs is to implement less code.

You’re not gonna need it!

Several of my answers on Programmers advocate for best practices, however I hope I haven't mislead anyone into thinking that applying those best practices is a goal in itself. The goal is to get things done, done is better than perfect. Don't just blindly follow dogma, without a deep understanding of the concepts and practices, and an itch to scratch you are just setting yourself for a world of trouble.

Keep it simple, stupid!

Further reading:

Where do you draw the line for your perfectionism?

The quest for perfection

Why can’t perfectionists break the habit?

The Done Manifesto

Programming, Motherfucker


答:
I'm still a newbie, but I'll give my 2 cents:

I'm the kind of programmer that is perfectionist. I sometimes struggle days to find an elegant answer, and sometimes I don't even find it. But that is because learning that kind of stuff is my focus. If it yours too, you may consider being a little perfectionist (but see below).

If your focus is completing something and then never use it again, don't try to be fancy. Writing fancy code will help you if you need to use that code again. If you don't, just get it to work.

Now, some tips I can give you:

-If you write the same functionality a lot of times, consider refactoring that functionality in a well structured, library for your own use. That way you can learn how to mantain something and will never need to rewrite that again.

-Be pragmatic to your objective. You want to learn? Good, write fancy code. You want to ship and mantain? Find a midterm.

-Have ONE focus at a time. Don't try to learn, ship and teach, for instance, at the same time. One can do only one thing at a time.

-If you got the time, read a lot. Sometimes that help you have an insight in some particular problem.

Hope I helped in something :)


答:
If learning a new language strikes you more as a task than a joy, you may have picked the wrong profession.

It's like a musician not wanting to learn a new instrument--they may prefer one and be better at it, but one who loves music should always be interested in exploring new options that might be provided by different instruments or styles.

Also, learning a new language may provide you insights into programming styles that you can apply to other languages.  A language could teach you to write your code to be more readable or take advantage of various patterns...  It's just part of being a programmer to be constantly learning.

Title: Why learn more programming languages?


答: I agree with dimitris mistriotis, but I can also mention that if you read a lot on the theoretical topic (such as OOP, functional programming, agile practices and many other...) you don't really need to know more languages than those you use. But it is a matter of personal opinion, I guess.</p>

Title: Why learn more programming languages?


答:
There is sometimes value in testing having access to protected/private members.

Suppose you have an initialisation function - you want to test that certain internal variables have been set. The easiest way to do this is for your testing framework to have access to those variables, generally either the testclass derives from the class or there is some trick to convert protected->public during test.

You could add public() functions to return the value of all the protected variables - but that would break encapsulation rather more.

Title: Do unit tests sometimes break encapsulation?

Body:
I very often hear the following: "If you want to test private methods, you'd better put that in another class and expose it."

While sometimes that's the case and we have a hiding concept inside our class, other times you end up with classes that have the same attributes (or, worst, every attribute of one class become a argument on a method in the other class) and exposes functionality that is, in fact, implementation detail.

Specially on TDD, when you refactor a class with public methods out of a previous tested class, that class is now part of your interface, but has no tests to it (since you refactored it, and is a implementation detail).

Now, I may be not finding an obvious better answer, but if my answer is the "correct", that means that sometimes writting unit tests can break encapsulation, and divide the same responsibility into different classes.

A simple example would be testing a setter method when a getter is not actually needed for anything in the real code.

Please when aswering don't provide simple answers to specific cases I may have written. Rather, try to explain more of the generic case and theoretical approach. And this is neither language specific.

Thanks in advance.

EDIT: The answer given by Matthew Flynn was really insightful, but didn't quite answer the question. Although he made the fair point that you either don't test private methods or extract them because they really are other concern and responsibility (or at least that was what I could understand from his answer), I think there are situations where unit testing private methods is useful. My primary example is when you have a class that has one responsibility but the output (or input) that it gives (takes) is just too complex. For example, a hashing function. There's no good way to break a hashing function apart and maintain cohesion and encapsulation. However, testing a hashing function can be really tough, since you would need to calculate by hand (you can't use code calculation to test code calculation!) the hashing, and test multiple cases where the hash changes. In that way (and this may be a question worth of its own topic) I think private method testing is the best way to handle it. Now, I'm not sure if I should ask another question, or ask it here, but are there any better way to test such complex output (input)?

OBS: Please, if you think I should ask another question on that topic, leave a comment. :)

EDIT2: I accepted an answer as my correct because it made me think and decide my course of action, although it didn't answered my question completely. But for those who face the same problem as I do (one cohesive class that will change together, but is still too hard to test by itself), I'll tell what I did and why. I decided that the output of that class is simply too hard to a computer to test correctly, so I didn't test it. I could have used a framework to test it's private methods (which would be the best idea, I think), but I didn't want to get to that point. If you are wondering what it is that is cohesive and respects SRP, and still is too hard to a computer to test, I'll give some examples: heightmap generation, hashing functions, procedural music generation (you can test some units, but the highest level unit is simply too subjective).


答:
Think like a chef. If you learn a new cooking technique, if you learn about a nice spice to add to your dish, or if you learn a new preparation for a given ingredient set, you expand your abilities. You can add some flare to your cooking abilities. </p>

<p>The same is true with programming. Some tools are better for some tasks than other, and different programming languages can help differentiate between how to solve problems in different ways. It helps to have diversity in how to solve problems. </p>

Title: Why learn more programming languages?

Body:
Think like a chef. If you learn a new cooking technique, if you learn about a nice spice to add to your dish, or if you learn a new preparation for a given ingredient set, you expand your abilities. You can add some flare to your cooking abilities.

The same is true with programming. Some tools are better for some tasks than other, and different programming languages can help differentiate between how to solve problems in different ways. It helps to have diversity in how to solve problems.


答:
If we made a pattern out of this problem of learning to code, it would be affected by many forces including:

Practice makes permanent.

To do is to understand.

People have uni-tasking brains.

You do not want to do something in the wrong way repeatedly, because that will become your habit for the future.  However, you do want to do something and if perfectionism leaves you paralyzed, you may want to risk some mistakes.

There are probably some parallels to the way kids are being taught to write these days.  They are encouraged to write, ignoring spelling but putting great emphasis on letting their creativity flow.  I cringe when I see this kind of work product on elementary school bulletin boards, but I think that the method has merit if there is a follow up step (probably the same day or at least week), where with a dictionary or advice from a teacher, they look up spelling and perhaps drill on a rule like i after e except after C so they have a way to avoid typing "recieved".

Because programming is so complex, new programmers have a hard time keeping all the rules for programming in their heads at the same time.  There is not much to be done about it except perhaps better tools and better tutorials.  Balanced and great training is a complex undertaking.  Just as someone doing weight training or other kinds of sport training would not think of training for strength of one body part alone or training for strength only without some work on flexibility, speed, endurance, or balance.

Your training should include short programs, medium programs, long programs, programs where you retype someone else's program (kinematic learning), something where you start with some code and change it to do something new, or a program where you create code from a word problem (this happens a lot in teaching math).  Something where you see things represented as text and as figures, something that focuses on a few statements, somethings with a broad mix of statement types.  You should see something that does all the work directly and something that does almost all the work through APIs.


问:
Under what conditions is the use of MVVM appropriate?
Model View View-Model was developed by Microsoft to target UI development platforms which support event-driven programming, specifically Windows Presentation Foundation (WPF) and Silverlight on the .NET platforms using XAML and .NET languages.  In the years since, many Javascript frameworks such as Angular, Knockout and ExtJS have adopted the pattern.

Like most software patterns, MVVM has its appropriate uses, and its abuses.  Under what conditions is the use of MVVM appropriate?  When is it ill-advised?

答:
You may enjoy checking out this alternative. This option sidesteps the WPF way of databinding, datatemplates, and MVVM. This option is more like the old, simple, dependable WinForms designer.cs approach.

WPF Composites

http://wpfcomposites.codeplex.com/

Here, concise C# code-behind for WPF is produced by overlaying a simple matrix on top of the UI via grid-based composites. If a modern XAML UI only contains a few text labels and a listbox of photos, why can't this be defined by the simple line of code: grid.AddText( guid, x coordinate, y coordinate) ? Note, this isn't on a canvas, but still within the WPF containers: grid, dockpanel, etc. WPF is hugely powerful. This approach merely leverages this.

Developers don't typically mind matrices and indices. Start with a coarse-grained container level defined by the GUID's of data transfer objects (DTOs) or POCO's, then compliment these keyed containers by a finer-grained matrix of potential rows and columns within?

The above codeplex project introduces this approach by starting with the ListBox control but is expanding to cover all WPF composite controls. For instance, each listboxitem is a composite added with a GUID (a composite ties one-to-one to a class), then inside of this item there is a Grid on which child UI elements (children tie one-to-one to properties in a class) may be added at will via code-behind. Children might be textblocks or images.

The idea is to leverage indices and a well-defined UI Element structure (it forces a PresentationFramework.Aero themed ListBox as the base to start from) instead of datatemplates. This new approach purposely limits what can be done but by so doing yields concise, robust C# code-behind that is intuitive. No need to hunt for control template solutions for styling a scrollbar or to clutter a solution with multiple data templates for simple tasks.


问:
Best approach for saving highlighted areas on geographical map
I am designing an application that allow users to highlight areas of a geographical map using a tool that is like brush or a pen. The tool basically draw a circle with a single click and continue drawing those circles with mouse move.

Here is an example of drawing made by moving the tool. It is pretty much same as Microsoft Paint.

Regardless of programming language what is best approach (most inexpensive approach) for saving this kind of data?

答:
I am not aware of any mapping libraries that support highlights outright but if you want to do this with Google Maps or Yahoo GeoService then you can simply record the latitude and longitude of the bounds of the highlight area in a database.

On loading the map again, you can restore the highlight area from those bounds by rendering points using the lat/long. The approach will also work with resizable and transformable maps.

Obviously, the more complicated shapes you support the messier the implementation would get. Simplest would be to support shapes that follow a simple 2 variable equation (e.g., circles or rectangles).


问:
Silverlight, one database per user
I have a Silverlight application with WCF and entity framework.

Is it possible to have one database per user. So when the the user log in, the user will use his own database?

答:
Yes, it's certainly possible.

What you will need is a central database that just holds all the user login details (you could use the standard ASP.NET membership database for this). This would allow the user to gain access to the system.

Then you would need another table to hold the connection details for each user. This will allow them to access their database and no one else's. You create the database connection from this data. This is separate to the login database connection, so use a new connection rather than reusing the existing one.

Title: Silverlight, one database per user


答:
There is an implementation of MVC objects in Google Maps JavaScript API V3. It allows map objects to store state and update their presentation automatically.
There is a DEMO of moving and resizing a circle which may provide what you require. The full tutorial can be seen HERE</p>

Title: Best approach for saving highlighted areas on geographical map

Body:
I am designing an application that allow users to highlight areas of a geographical map using a tool that is like brush or a pen. The tool basically draw a circle with a single click and continue drawing those circles with mouse move.

Here is an example of drawing made by moving the tool. It is pretty much same as Microsoft Paint.

Regardless of programming language what is best approach (most inexpensive approach) for saving this kind of data?


答:
When you feel the urge to test private methods, you're simply doing it wrong. It might be okay to factor out a complicated algorithm of a private method to a separate, "more public" class, and use this class in the original private method. But the point is this still doesn't break encapsulation.

If you make something private, it is not part of the API of the class, it just doesn't exist for the outside world. If something happens there which is really important, and should be tested in your opinion, but can't be properly detected through the API, then something in your  API design is broken. You have to decide if something matters, or if it is an implementation detail. It can't be both.


答: The most important thing is to really grok the fundamental design principles like KISS, DRY, SRP, LSP. You need to get the ability to see where these rules are broken, and why it matters. Once you can really recognize "rule violations", it's okay to write sloppy code in certain situations (e.g. throw away code for migrations), because then you know the pitfalls, and how to clean up the mess when you must.


答:
Enemy

Perfectionism is everyone's enemy, by definition. It's (according to Wikipedia)

a personality disposition characterized by an individual striving for
  flawlessness and setting excessively high performance standards

Nearly every decision you make is a tradeoff.

Execution time vs development time: "do I write this in C or Ruby?"

Simplicity vs flexibility: "Do I write a query for MySQL, or an abstract querying tool that can support multiple databases?"

Ease of creation vs ease of maintenance: "Do I write a throwaway script with no comments or a well-documented library?"

All of the above vs. finishing the task quickly

If your standards are too high in one area, you're probably neglecting another.

If you write a fast, readable, flexible, easy-to-maintain, well-documented, well-tested piece of code, but it takes you 3 times longer than it should based on the importance of the task, that's not perfect, is it?


问:
Dropbox as a Version Control tool
I have some friends telling me that Dropbox can be used as a  version control tool. I have always used SVN or Git. I was looking around Dropbox and couldn't find anything that tells me about is characteristics as Merging, Fork and other characteristics for a complete VCS.

Can someone point me what I'm missing.

答:
Dropbox is not a suitable replacement for something like Subversion or Git for controlling changes to source code. There is some functionality to revert to old versions of files, but (to the best of my knowledge and consulting with the documentation) there is no support for performing merging, or branching. There are some APIs that expose diffs, but you would need to find a way to integrate these APIs into your tool.

However, for personal projects with few (if any) other developers, it's not unreasonable to use Dropbox to store your repositories and make them more readily available. The backup and global access to your files could help make it easier for you to do your development work. This model breaks down with larger teams working on the project.

Title: Dropbox as a Version Control tool