答:
I've been pushing for making these tasks into official user stories, but no one else seems to like this.

An important question to ask / answer here is - do these tasks need to be user stories, or do they just need to be in the backlog, given the same consideration as user stories? I'm not a fan of writing a task as a story just for consistency, as (imo) the purpose of a user story is focus on  delivering value to the customer by developing to a customers action. At the end, the customer can test against the user story.

Conversely, a developer task often doesn't need a user action to be tested (e.g. refactoring a large class files into multiple, smaller class files), and it doesn't need to be in a user story to be understood by developers. IMO, keeping user stories and developer tasks independent allows you to track how much time your spending on delivering direct customer value.

But that's probably beside the point, and I'd ask if the real issue is getting management to sign off on project maintenance / improvement tasks? If so, you may need to change your focus slightly.

How else could I request official recognition for these tasks, so I can allocate full days on them without feeling like I'm affecting the rest of the sprint?

The key here is to justify their need. Having a centralized, accepted build process is a very standard Agile practice with very obvious benefits. It will improve productivity and developer engagement, and reduce integration costs.

Conversely,

Refactor redundant (across multiple projects) code into independent libraries - could potentially be used by many projects.

requires some justification as to its value (buzzword there was potentially). If there's real use - e.g. there's duplication between projects - show it. Show the commits that were made. Show the stories they were tied to, and how having to write a routine multiply, maintain it multiply, etc - leads directly to increased time to production.

Refactoring is an important part of professionally handling code. If I can't regularly spend (small amounts of) time refactoring, then the code is on a downward spiral, and I'm looking for another job. Simply put, when you can't expect to refactor code, you're forced to spend excessive amounts of time with up-front architecture considerations (you break the YAGNI rule). If I trust we can re-visit modules in the future to improve them, I can focus on the delivering the simplest working solution possible and getting immediate user feedback.

Developer "stories" matter, and deserve a place in the work-flow. Whether or not to formulate them as a User story is subjective, but don't let that be the focus of the discussion. Get them into the workflow, then worry about how to label them.

Title: How to deal tasks that are probably not user stories but still need to get done?

Body:
We have a number of tasks that need to be completed, but are probably not real user stories, or if they are, they are very developer-centric user stories which will never be visible to the end-users. The problem is that because they do not get estimated as a part of a sprint and very little gets done on them. Eventually, it becomes enough of a problem that someone takes time out of a sprint to deal with them, but that affects progress on "official" sprint work, which makes some people a wee bit unhappy.

I've been pushing for making these tasks into official user stories, but no one else seems to like this. How else could I request official recognition for these tasks, so I can allocate full days on them without feeling like I'm affecting the rest of the sprint?

Some examples of the tasks, just to give you an idea:

Write small, custom maven plugins to simplify specific (and widely used, within the organization) build configurations.

Refactor old project(s) to build with Maven and newer tool set.

Refactor redundant (across multiple projects) code into independent libraries - could potentially be used by many projects.


问:
Difference between an architecture and a framework
A terminology question appeared when I was comparing EJB 3 and Spring.

Wikipedia says that

Enterprise JavaBeans (EJB) is a managed, server-side component
  architecture for modular construction of enterprise applications.

and also

The Spring Framework is an open source application framework and
  inversion of control container for the Java platform.

"EJB 3 in Action" suggests that

Together, the components, or EJBs, and the container can be viewed as
  a framework that provides valuable services for enterprise application
  development.

Is any framework an architecture? If not, what is the difference between these terms? Could EJB be considered a framework?

答:
In software, a Framework is a software module or set of modules that supports a generic programming concept by abstracting common functionality (code in a software sense) into a reusable format.

An Architecture is an assembly of systems that solves business needs. According to TOGAF

The definition of an architecture used in ANSI/IEEE Std 1471-2000 is:

"The fundamental organization of a system, embodied in its components,
  their relationships to each other and the environment, and the
  principles governing its design and evolution."

In itself TOGAF is a framework because it abstracts the reusable parts of architecture into a reusable format. It does so through documentation instead of code.

ContentLicense: CC BY-SA 3.0


答:
An architecture is the the abstract design concept of an application. Basically, a structure of the moving parts and how they're connected.

A framework is a pre-built general or special purpose architecture that's designed to be extended.

If an architecture is the design of a structure, a framework is the architecture of a foundation. Frameworks are specifically designed to be built on or extended.

Some frameworks deal primarily with scaffolding. Meaning, they provide pre-built modules that are easy to use/extend to save the developer from having to create them from scratch. For instance, most MVC web frameworks (ex django, pylons, codeigniter) make it much easier to implement sessions, database connections, templating, etc...

Other frameworks deal primarily with augmenting the capabilities of the language itself, filling in what some may consider to be 'missing pieces'. They add features that come from other languages, synctatic sugar, or extend the language. The Underscore lib is a perfect example of this. It doesn't do much to assist in building applications, it's primary purpose is to extend the core functionality of javascript.

Some frameworks exist to add new features to a language, or re-hash existing capabilities in a new way. For instance, jQuery took the -- previously painful -- process of querying the HTML DOM and made it trivial. They also provided a means to write cross browser compatible AJAX requests. While jQuery appears to add a new style of syntax, behind the scenes it runs on vanilla JavaScript. AngularJS is another framework that leverages JS/HTML in new and interesting ways using vanilla JS.

In your case. Spring and EJB are both scaffolding MVC frameworks, each with their own trade-offs.

Title: Difference between an architecture and a framework

Body:
A terminology question appeared when I was comparing EJB 3 and Spring.

Wikipedia says that

Enterprise JavaBeans (EJB) is a managed, server-side component
  architecture for modular construction of enterprise applications.

and also

The Spring Framework is an open source application framework and
  inversion of control container for the Java platform.

"EJB 3 in Action" suggests that

Together, the components, or EJBs, and the container can be viewed as
  a framework that provides valuable services for enterprise application
  development.

Is any framework an architecture? If not, what is the difference between these terms? Could EJB be considered a framework?


问:
should I store common data between two tables in a third separate table in my database?
If I have 2 tables in my database, let's say for instance 'buyers' and 'sellers' but I collect a common set of data for both for instance telephone number, email address, address etc. Is it  better practice to have one common table for 'contact_details' with a reference to the table and row that the contact details are for, or as they are seperate entities are they better off in seperate tables entirely?</p>

答:
My two cents:

Contact can be a buyer, a seller, both or just a contact.

Contact can have multiple phone numbers and addresses.

Contact table has basic contact attributes.

Buyer and Seller have attributes that only apply on that role.

A Contact that is neither a buyer or a seller has no related row in those tables


问:
Long vs short scripts? Big vs small scripts?
As a programmer, I have always wondered whether it is preferable to write (a) short modular functions that are each stored in their own script (i.e., file) or (b) long comprehensive scripts that contain all of their relevant functions.

For example, if I code a data analysis stream that includes a variety of operations performed on the same data (e.g., data cleaning, feature selection, clustering, supervised learning, etc.), should I write a single file even if it runs for hundreds of lines?

I have heard many opinions on the matter and I wonder what this community thinks. I understand that the answer may depend on the type of project, but, if this is the case, then it would be great to hear your thoughts on what factors one should consider in deciding between options (a) and (b).

I am currently coding in Python and I've wondered whether Python programmers have a preference to multiple functions in the same file or one file per function, but I imagine that this question is broader and applies to all programming languages.

答:
I would say it really much is dependent on how the language itself is structured:

In Mathematica, you tend to end up with quite large packages, that may contain several K lines. In java, you don't have much choice, the file to functionality is determined by the objects.

If you get annoyed by having too many files, or a too big file, it is an indication that something should change...


问:
Why chaining matters (Python & SQLite3)?
Why does

```<code>cursor = connection.cursor()
cursor.execute("...
return cursor.fetchall()
</code>```

return the expected non-empty result whereas

```<code>connection.cursor().execute("...
return connection.cursor().fetchall()
</code>```

returns an empty list the SQLite3-command being identical in both cases?

EDIT 2014-02-19: Added the last "...fetchall()"-line to code samples.

答:
For the sqlite3 library, the cursor.execute() call always returns the cursor object again. Both your statements are identical here:

```<code>>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.cursor().execute('SELECT DATE()')
<sqlite3.Cursor object at 0x1083d89d0>
>>> cursor = conn.cursor()
>>> cursor.execute('SELECT DATE()')
<sqlite3.Cursor object at 0x1083d8960>
</code>```

However, if you didn't store a reference to the cursor returned from the 'chained' call, you won't have access to the result set anymore, a new cursor object from connection.cursor() won't list those results as it'll be a different cursor object:

```<code>>>> conn.cursor().execute('SELECT DATE()')
<sqlite3.Cursor object at 0x1083d8a40>
>>> list(conn.cursor())
[]
>>> cursor = conn.cursor().execute('SELECT DATE()')
>>> list(cursor)
[(u'2014-02-18',)]
</code>```

That has nothing to do with chaining and everything with the purpose of cursors: to provide distinct views on the database, each with their own independent state.

Body:
For the sqlite3 library, the cursor.execute() call always returns the cursor object again. Both your statements are identical here:

>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> conn.cursor().execute('SELECT DATE()')
<sqlite3.Cursor object at 0x1083d89d0>
>>> cursor = conn.cursor()
>>> cursor.execute('SELECT DATE()')
<sqlite3.Cursor object at 0x1083d8960>

However, if you didn't store a reference to the cursor returned from the 'chained' call, you won't have access to the result set anymore, a new cursor object from connection.cursor() won't list those results as it'll be a different cursor object:

>>> conn.cursor().execute('SELECT DATE()')
<sqlite3.Cursor object at 0x1083d8a40>
>>> list(conn.cursor())
[]
>>> cursor = conn.cursor().execute('SELECT DATE()')
>>> list(cursor)
[(u'2014-02-18',)]

That has nothing to do with chaining and everything with the purpose of cursors: to provide distinct views on the database, each with their own independent state.


问:
Should we create a story for vacation?
We have had a situation with a scrum sprint where a team member went on vacation for a few days at the beginning of the sprint. This led to us being behind the ideal trend on the burndown chart at the beginning of the sprint, although we caught up later since we knew we had slightly less resource and as a result had committed to deliver slightly less.

In our retrospective it was suggested by the Product Owner that we create a vacation story. The time remaining would be reduced down as the vacation was completed. As a result the burndown chart would be corrected for the "hole" that would appear in effort when the team resource was lower, which would otherwise falsely indicate a problem.

Is this a good idea?

答:
This its like cheating to yourself; it's a very bad idea.

A burndown shows your real progress, and obviously someone's vacation is not progress on your product.

If your PO insists, I have one proposition: All user histories are people vacations!  The people are happy and the burndown its happy too!  And never, never is there a deviation in your precious burndown charts! (its a joke)

Title: Should we create a story for vacation?


答:
Generally speaking, architecture is an abstract plan that can include design patterns, modules, and their interactions. Frameworks are architected "physical" structures on which you build your application.

Your architecture may incorporate multiple frameworks. And multiple layers of framework. At each layer, the "architecture" is the oft-documented "thinking" from which the layer is built. The frameworks are the "physical" components used to build it.

When you call a target environment an "architecture", you're referring to the design implications on your software. When you call it a "framework", you're referring to the functionality it gives you.


答:
The first problem its that your are talking about "functions" and "files" in a object oriented language, the first you need to do is thinking in terms of classes and their relationships if you want to build good OO python code.

And speaking about classes and length, normally a good class its supposed to adhere to the Single Responsibility Principle, one class has one responsibility and one reason to change. Normally a good designed codebase is composed of a lot of small classes with very clear and simple responsibilities, more than 200 or 300 lines in a language like python its a red alert IMMO (an alert to take a second look at the code, not a rule to follow blindly!).

Title: Long vs short scripts? Big vs small scripts?

Body:
As a programmer, I have always wondered whether it is preferable to write (a) short modular functions that are each stored in their own script (i.e., file) or (b) long comprehensive scripts that contain all of their relevant functions.

For example, if I code a data analysis stream that includes a variety of operations performed on the same data (e.g., data cleaning, feature selection, clustering, supervised learning, etc.), should I write a single file even if it runs for hundreds of lines?

I have heard many opinions on the matter and I wonder what this community thinks. I understand that the answer may depend on the type of project, but, if this is the case, then it would be great to hear your thoughts on what factors one should consider in deciding between options (a) and (b).

I am currently coding in Python and I've wondered whether Python programmers have a preference to multiple functions in the same file or one file per function, but I imagine that this question is broader and applies to all programming languages.


问:
How are atomic operations are a dynamic language feature?
I was told that atomic operations are a dynamic language feature. I was too afraid to ask in that context what this actually means because I didn't want my coworkers to think I'm stupid. But I actually don't really understand this statement.

My understanding of the term "atomic operations" is any operation that is either wholly executed or wholly not executed; you will definitely never be halfway through the operation when the thread context switches.

What does this have to do with dynamic vs static typing?

答:
I was too afraid to ask in that context what this actually means because I didn't want my coworkers to think I'm stupid.

Actually, I think that asking questions is smart. It's how you learn things that you don't know. And in larger groups, it's likely that other people don't know it either, they're just afraid to ask too.

My understanding of the term "atomic operations" is any operation that is either wholly executed or wholly not executed …

Yes, but that's only part of it. Another important part is that the operation appears to execute instantaneously, that is, you can never observe it in half-completed state. (Though the following part of the sentence indicates that that's what you meant.)

… such as in C# with the volatile keyword when setting or getting the value of a primitive, you will definitely never be halfway through getting or setting a volatile primitive when the thread context switches.

That's not what volatile in C# is about. Setting the value of small primitive types (like int, char or reference, but not long or double) is always guaranteed to be atomic (see §5.5 Atomicity of variable references of the C# spec).

What volatile is about is the order of accessing the fields (§10.5.3 Volatile fields of the spec). Normally, if you write something like:

```<code>this.value = 42;
this.valueIsSet = true;
</code>```

and then observe it from another thread, then you could see valueIsSet to be already true and value to be still 0, due to compiler and processor optimizations that reorder instructions. With volatile, such reordering is forbidden.

This also guarantees that the field is read every time, without volatile a loop like

```<code>while (this.shouldRun)
{
    // whatever; does not set this.shouldRun
}
</code>```

might be compiled as:

```<code>if (this.shouldRun)
{
    while (true)
    {
        // whatever; does not set this.shouldRun
    }
}
</code>```

In any case, using volatile correctly is hard and you should avoid it unless you really need it for performance reasons. Most of the time, using locks and thread-safe library types is enough.

What does this have to do with dynamic vs static typing?

No idea. There certainly are non-trivial atomic operations in .Net (like those in the Interlocked class).

The only thing I can think of is that some languages can use user-mode threads instead of native threads, and thus have more control over what operations are executed atomically, because it's the language runtime that decides when to switch threads. But that has nothing to do with dynamic or static typing. (And I have no idea if there are languages that actually take advantage of that.)

Body:
I was too afraid to ask in that context what this actually means because I didn't want my coworkers to think I'm stupid.

Actually, I think that asking questions is smart. It's how you learn things that you don't know. And in larger groups, it's likely that other people don't know it either, they're just afraid to ask too.

My understanding of the term "atomic operations" is any operation that is either wholly executed or wholly not executed …

Yes, but that's only part of it. Another important part is that the operation appears to execute instantaneously, that is, you can never observe it in half-completed state. (Though the following part of the sentence indicates that that's what you meant.)

… such as in C# with the volatile keyword when setting or getting the value of a primitive, you will definitely never be halfway through getting or setting a volatile primitive when the thread context switches.

That's not what volatile in C# is about. Setting the value of small primitive types (like int, char or reference, but not long or double) is always guaranteed to be atomic (see §5.5 Atomicity of variable references of the C# spec).

What volatile is about is the order of accessing the fields (§10.5.3 Volatile fields of the spec). Normally, if you write something like:

this.value = 42;
this.valueIsSet = true;

and then observe it from another thread, then you could see valueIsSet to be already true and value to be still 0, due to compiler and processor optimizations that reorder instructions. With volatile, such reordering is forbidden.

This also guarantees that the field is read every time, without volatile a loop like

while (this.shouldRun)
{
    // whatever; does not set this.shouldRun
}

might be compiled as:

if (this.shouldRun)
{
    while (true)
    {
        // whatever; does not set this.shouldRun
    }
}

In any case, using volatile correctly is hard and you should avoid it unless you really need it for performance reasons. Most of the time, using locks and thread-safe library types is enough.

What does this have to do with dynamic vs static typing?

No idea. There certainly are non-trivial atomic operations in .Net (like those in the Interlocked class).

The only thing I can think of is that some languages can use user-mode threads instead of native threads, and thus have more control over what operations are executed atomically, because it's the language runtime that decides when to switch threads. But that has nothing to do with dynamic or static typing. (And I have no idea if there are languages that actually take advantage of that.)


问:
Gradual Typing: "Almost every language with a static type system also has a dynamic type system"
This claim by Aleks Bromfield states:

Almost every language with a static type system also has a dynamic type system. Aside from C, I can't think of an exception

Is this a valid claim? I understand that with Reflection or Loading classes at runtime Java gets a bit like this - but can this idea of 'gradual typing' be extended to a large number of languages?

答:
Dynamic languages are static languages. What is commonly called "dynamic typing" is really a special case of static typing - the case where you've restricted yourself to only having one type. As a thought experiment, imagine writing a program in Java or C# using only Object variables/fields/parameters and down-casting immediately before calling any method. It'd be more accurate to call languages like Python or Javascript "unityped". (This claim will likely confuse/bother many people, considering such a Java or C# program would use many sub-types, but that's because the average OOP language conflates types and classes. Read the blog post for more details.)

Note that even C has "dynamic" typing - you can cast any pointer to a void (and if memory serves me, char) pointer and back again. And note, also, that there is no runtime checking there; if you get it wrong, enjoy your undefined behavior!


问:
Private apps for iOS and Android
Is it possible to develop private apps for iOS (iPhone/iPad) and Android?

With "private apps" I mean apps that do not appear on the public app store, but can be downloaded and used only by selected clients.

答:
Most Android devices can install application simply by opening an apk file in the browser. You can use self-signed certificates, so no problem there.

It's more difficult with iOS applications. Everything you do there must go through Apple. Apple development site has lots of information about the different ways to do that but mostly it reduces to the following 3 types of distribution.

App store - the usual way to distribute Requires going through App store approval.

App store using B2B program - you can distribute to specific companies using App store. Requires going through App store approval.

Apple Enteprise distribution - apps can be installed from any web site but license forbids you to install them on devices not owned by your enteprise (or something similar). Basically usable only when developer company = customer company. Note there are no automatic updates when new version is released. Doesn't go through App store approval so even private APIs are possible.

Title: Private apps for iOS and Android


问:
Opinions on distribution of software via virtual appliance
I've created a distribution of my open source application framework in a working virtual appliance.  It includes everything to get started with the tutorial.  The distribution is Fedora 14 running Tomcat 5.5 and Oracle 10g Express Edition, plus my framework.  It is completely preconfigured and boots into a working running copy.

Would this be something you might try?

What assurances might you need to get you to try it?

Edit: The VM is just over a 2Gb download.  Alternatively it is also available via 23Mb download for the source and a PDF detailing how to configure the Tomcat and Oracle dependencies.

答:
No.

If you have an open source framework - note: Open Source - which you want me to use on a Linux platform, I want full integration with the package system on said platform.  This means a maintained yum installation site or - for Debian/Ubuntu an apt-get repository - so that updates are automatic.

Please let me emphasize that:  Installation, updates and removal should be automatic.

If your framework uses a database, I want the package system to pull it in as a dependency of your framework, and I want THAT too to be maintained automatically.   This might disqualify your choice of Oracle as the database, but that is just life.

I do not want to run any framework in a lone virtual machine.  I want to run my favorite distribution which usually do other things too and then use your framework in there.

ContentLicense: CC BY-SA 2.5


问:
Make a change that is ignored by future merges
I have a git repository, and I'd like to make a "debug" branch.

In the "debug" branch, I'd like to add a line:

```<code>debug = true;
</code>```

But I want to make sure that any merges back to master ignore that change. Is there any way to set that up in way that doesn't require me to manually handle all future merges?

答:
Create the branch (let's call it 'debug'), make the change and commit to that branch.

```<code>git checkout -b debug
vim config # add debug = true
git commit config -m "Turn on debug mode"
</code>```

Then check out master and start the merge process

```<code>git checkout master
git merge --no-ff --no-commit debug
</code>```

This will tell git to merge, create an actual merge commit instead of fast-forwarding, and stage the commit but not actually commit it yet. Then go into the file and remove the line that you added on the branch and finally commit.

```<code>vim config # remove debug=true
git commit
</code>```

If you run gitk master debug, you should see that debug has been merged into master, but master doesn't have the debug=true change. From now on, when you merge the debug branch into master, git will not try to reincorporate the debug=true because that was already "merged".

As other commenters have stated, config files like this shouldn't be checked into version control. The common way to avoid this is to have the application check for a local config file that is either outside the source directory or in a file that is in .gitignore. But if that's not possible, the above instructions will work.

Body:
Create the branch (let's call it 'debug'), make the change and commit to that branch.

git checkout -b debug
vim config # add debug = true
git commit config -m "Turn on debug mode"

Then check out master and start the merge process

git checkout master
git merge --no-ff --no-commit debug

This will tell git to merge, create an actual merge commit instead of fast-forwarding, and stage the commit but not actually commit it yet. Then go into the file and remove the line that you added on the branch and finally commit.

vim config # remove debug=true
git commit

If you run gitk master debug, you should see that debug has been merged into master, but master doesn't have the debug=true change. From now on, when you merge the debug branch into master, git will not try to reincorporate the debug=true because that was already "merged".

As other commenters have stated, config files like this shouldn't be checked into version control. The common way to avoid this is to have the application check for a local config file that is either outside the source directory or in a file that is in .gitignore. But if that's not possible, the above instructions will work.


答:
Assuming that the vacation is planned, then you just adjust the amount of time allocated for the developer accordingly.  In that case the burn down may not be as good in the beginning, but should catch up properly in the end.

However, if it isn't planned, you can add it as an Sprint Impediment.  Which needs to be noted.  In which case if some unplanned things occur you may discuss it on the retrospective to perhaps adjust the standard allocation or just ignore it (which is valid) because it may have been a one off incident.

Title: Should we create a story for vacation?

Body:
We have had a situation with a scrum sprint where a team member went on vacation for a few days at the beginning of the sprint. This led to us being behind the ideal trend on the burndown chart at the beginning of the sprint, although we caught up later since we knew we had slightly less resource and as a result had committed to deliver slightly less.

In our retrospective it was suggested by the Product Owner that we create a vacation story. The time remaining would be reduced down as the vacation was completed. As a result the burndown chart would be corrected for the "hole" that would appear in effort when the team resource was lower, which would otherwise falsely indicate a problem.

Is this a good idea?


问:
When to write Abstract code and when to be more specific?
I'm working on a small tool as a toy project to show the difference between two directories, showing which files/directories were added, removed, modified, etc.

I was trying to represent these changes as simply 'ChangeItem' objects, without distinction between whether it was a file or directory. However, that created a lot of problems, e.g how to display them in a tree, how to know who the parent of a child is, etc. And it was also very unintuitive.

I then split the changes between directory changes and file changes. That immediately made it very easy to code and to understand what was going on. Now its a lot simpler to select all files in a directory, etc.

My question is, how can one know whether to use abstraction or to get more specific in their code? How can you tell if you have too much or too little abstraction?

答:
Typically abstraction is useful to combat things like Complexity, Entropy, to make your code Cybernetic, and even at a low level readability. I would hardcode first - ONLY if abstraction is not obvious up front. Most abstraction occurs when more than one implementation share the same pattern.

Think of abstraction to be the congruence or unity of 2 or more Sets. Take a Venn Diagram as a simplistic model: The part where the circles overlap, or in other words, the Sets merge.

If I have two sets: A:{a,b,c,d,e} and B:{d,e,f,g,h}. The point where I would start looking to abstract is the unity of A + B; {d,e} is where to abstract. Similarly, if those in the difference of A & B (A-B or B-A) are isomorphic to each other, meaning its low cost to create a,b or c from f,g or h (and vise versa), then I would keep abstraction in the back of my mind.


问:
Is there any difference learning OOP on different programming languages?
I want to learn OOP. I know Python and I know very little things about OOP.

But when I search for "learn OOP" in forums I saw a guy saying that "Python is so new that's why you can't learn OOP on Python. you should learn Java then understand OOP on Java"

Is it true? Is there any difference understanding OOP on different programming languages?
like learn it on Java, C#, C++, Perl or Python?

答:
Yes, OOP implementations are very different.  The theory and principles are the same though, but so many people consider only "real OOP" what Java and C++ do, that you get many references that are supposed to be "language agnostic" but in fact assume class-based, statically typed languages.

That doesn't mean those references are bad, or even limited; for example the "gang of four" (GoF) seminal book "Design Patterns: Elements of Reusable Object-Oriented Software" is a prime example of a great work that says "OOP" when it really means "static class based OOP".

So, in my opinion: Yes, you can learn a lot of OOP on Python, Javascript, C, and many other languages; but some people (maybe a future employer) when ask for "OOP experience" mean Java/C++/C#.  So, it would be wise to check that other view too.

(and those aren't the only two 'types' of OOP....)


问:
Mixing declarative & imperative code (Implicit 'unit tests' ?)
Well I'm no expert, but as a student, I'm curious about languages and their design patterns / goals.

I'd like to know, whether there are any points I miss in the following examples, and why techniques like this are not widely used in popular languages. Why is it a better idea in a real-life program to explicitly define all unit tests, instead of using some declarative code. why don't languages use some declarations as tests and implementation as well in general? Why split these thing into two parts?

Suppose you have the following unit tests:

```<code>assertRaises(avg([]), ValueError)
assertEquals(avg([1], 1)
assertEquals(avg([1, -2]), -.5)
assertEquals(avg([1, 2]), .5)
</code>```

If you take this pseudocode,

```<code>def avg(items):
    if len(items) == 0:
        raise ValueError
    else if len(items) == 1:
        return items[0]
    else:
        return sum(items)/len(items)
</code>```

most parts of avg seem to do nothing, or very little more than just declaring the way to pass some unit tests. In other words, for me it feels a little like code duplication. Especially the first test seems to be superfluous in this example.

I wonder if it would be a good design to get rid of some unit test this way:

```<code>def avg(items) {
    len(items) == 0 => raises ValueError
    len(items) == 1 => items[0]
    len(items) > 1 => sum(items)/len(items)
    (test) items == [1, -2] => $avg == -.5
    (test) items == [1, 2] => $avg == .5
    (test) avg(items) <= sum(items)
}
</code>```

In this example, (test) indicates when a specific test case is not a useful definition (though maybe these could even be used for optimization in rare cases). Of course, this pseudocode is not well designed because it's less readable than the first implementation, but I think it's a more convenient way to declare unit tests. Actually the unit tests seem to be wrong here, since they do nothing but test the definition. And the last test is not trivial to perform. But it can be performed for example, when another test is run, which tests a code that has avg in it, so chances are, that it gives a useful set of test parameters. Also, for example, the last unit test has a secondary role too! If I have a code like this:

```<code>if avg(a) <= sum(a)
</code>```

It's not necessary at all to evaluate the complex definition, since at runtime one of the test cases implies it directly. OK, in this case, it's not a real optimization (though an IDE could notify the user, that the expression will always be true, which is useful). However, I can imagine, that there are many complex examples, that can be optimized this way, without making the developer explicitly test for special cases at every single place where they are relevant.

Maybe a better example for this optimization

```<code>def power(a, n) {
    n == 0 => 1
    n == 1 => a
    n > 1 => a * power(a, n - 1)
    (test) for any (x) power(a, n) % x == power(a % x, n) % x
}
</code>```

It's not secret I think, that a clever compiler could use it in many cases, and a clever interpreter/just-in-time compiler could use these in much more cases.

In order to understand tests and languages better, I'm curious whether my thoughts are useful, and if not, what am I missing, or if so, why popular languages don't implement such patterns.

答:
The “sufficiently advanced compiler” has become a common joke when talking about programming languages. Some compilers actually have amazing features, but often this is used as an excuse for sloppy language design, or for the performance of certain dynamic languages which don't have such an advanced compiler.

The way you defined your functions reminds me of pattern matching, a feature most often found in ML-like functional languages, e.g. along the lines of

```<code>let avg xs =
  match xs with
  | []      => throw (ValueError "array must contain at least one element")
  | x :: [] => x
  | xs      => (fold (+) xs) / (array_length xs)
</code>```

This is interesting because we can specify the semantics of some languages as a set of rewriting rules. Such a function definition specifies ways to rewrite an application of the form avg [1, 2, 3]. Certainly does this declarative phrasing of the solution make it easier to apply optimizations. But would it be that much harder given the more C-like form?

```<code>Num avg(Num[] xs) {
    if (xs.length == 0) throw new ValueError();
    if (xs.length == 1) return xs[0];
    return sum(xs)/xs.length;
}
</code>```

A compiler that is aware of idioms of the language won't find such a representation any more difficult to reason about.

Now to your main question, on unit tests. The value of tests is this repetition. Ideally, tests and implementation are written by two different people, which avoids that a bug is copy&pasted from one representation to the other. In other words: what are the chances that two people failed to understand the problem, or made the same typo? (For example, avg([-1, -3]) <= sum([-1, -3]) is not correct).

The test asserts that a certain interface will be honored, and checks representative inputs to give us good confidence that the implementation works as expected. For simple pieces of code as given here, it might be obviously correct without having to write many tests. However, we might want to change the internal workings of our implementation. We want to make sure that our code still works as expected after any change, even if an insane implementation using reflection or other unoptimizable things and might not be obviously correct. Therefore, an implementation cannot be its test at the same time, and we have to encode the interface in another, second way. Once we've done that, this makes it really easy to keep backwards compatibility – your users will thank you.

In the examples you've given, a test can be written on a single line. In other cases, this is most definitively not the case. Today I opened up a test file that had 100 lines to set up a simple grammar, all just for a single test that checked that a lexer implementation could interface correctly with this grammar. Placing such a verbose test inside the implementation would make the actual code excessively hard to read due to all the interruptions. Placing the tests in a separate file gets rid of any readability problem, and makes it easier for my testing tool of choice to “prove” correctness of my implementation.

Body:
The “sufficiently advanced compiler” has become a common joke when talking about programming languages. Some compilers actually have amazing features, but often this is used as an excuse for sloppy language design, or for the performance of certain dynamic languages which don't have such an advanced compiler.

The way you defined your functions reminds me of pattern matching, a feature most often found in ML-like functional languages, e.g. along the lines of

let avg xs =
  match xs with
  | []      => throw (ValueError "array must contain at least one element")
  | x :: [] => x
  | xs      => (fold (+) xs) / (array_length xs)

This is interesting because we can specify the semantics of some languages as a set of rewriting rules. Such a function definition specifies ways to rewrite an application of the form avg [1, 2, 3]. Certainly does this declarative phrasing of the solution make it easier to apply optimizations. But would it be that much harder given the more C-like form?

Num avg(Num[] xs) {
    if (xs.length == 0) throw new ValueError();
    if (xs.length == 1) return xs[0];
    return sum(xs)/xs.length;
}

A compiler that is aware of idioms of the language won't find such a representation any more difficult to reason about.

Now to your main question, on unit tests. The value of tests is this repetition. Ideally, tests and implementation are written by two different people, which avoids that a bug is copy&pasted from one representation to the other. In other words: what are the chances that two people failed to understand the problem, or made the same typo? (For example, avg([-1, -3]) <= sum([-1, -3]) is not correct).

The test asserts that a certain interface will be honored, and checks representative inputs to give us good confidence that the implementation works as expected. For simple pieces of code as given here, it might be obviously correct without having to write many tests. However, we might want to change the internal workings of our implementation. We want to make sure that our code still works as expected after any change, even if an insane implementation using reflection or other unoptimizable things and might not be obviously correct. Therefore, an implementation cannot be its test at the same time, and we have to encode the interface in another, second way. Once we've done that, this makes it really easy to keep backwards compatibility – your users will thank you.

In the examples you've given, a test can be written on a single line. In other cases, this is most definitively not the case. Today I opened up a test file that had 100 lines to set up a simple grammar, all just for a single test that checked that a lexer implementation could interface correctly with this grammar. Placing such a verbose test inside the implementation would make the actual code excessively hard to read due to all the interruptions. Placing the tests in a separate file gets rid of any readability problem, and makes it easier for my testing tool of choice to “prove” correctness of my implementation.


答:
I think the person you're quoting was simply displaying language chauvinism.

In reality, there is a difference between concepts of OOP and implementation of OOP. Poetically, this is best understood once you have a better grasp of some of the concepts of OOP.

A lot of programmers become comfortable with just a few similar languages, so they don't have to expand their capabilities or suffer not being capable for a time.

So the question comes down to, really, will Python teach you the concepts of OOP?

I will say you can, provided you have adequate learning support that pushes you try things you wouldn't normally explore in self-directed learning. A book or a mentor of some sort would be best. Mark Lutz writes very in-depth, very detailed, and very excellent books on Python, and I would recommend his books because they will push you to do and learn more.

What you have to remember is that Python's way is not the Only Way, nor is it the Only Correct Way. The more programming paradigms you master, the better a programmer you will become. The way Python does OOP is not exactly how C++ or Java does it, but the concepts transfer well.

Title: Is there any difference learning OOP on different programming languages?

Body:
I want to learn OOP. I know Python and I know very little things about OOP.

But when I search for "learn OOP" in forums I saw a guy saying that "Python is so new that's why you can't learn OOP on Python. you should learn Java then understand OOP on Java"

Is it true? Is there any difference understanding OOP on different programming languages?
like learn it on Java, C#, C++, Perl or Python?


问:
Using module level declared global "singletons" in python
Ok, I know that using singletons is generally a bad practice, but if I do it (for db connection, logging et al.) am I allowed to go (in respect of clean design) with a module defined variable that is initialized during the startup.

eg.:

```<code>if __name__ == '__main__':
    datasources.database.db = DB(dbpath)
</code>```

where db is declared here, at the top level of a module:

```<code>db = None

class DB(object):
    def __init__(self, path):
         ....
</code>```

What could be a reasonable compromise between passing the db for each object that uses it in the "true OO way" and having the global?

答:
The issue with global singletons comes down to code maintenance, architecture, and thread-safety.

In python, unless you're using Stackless Python, the GIL(Global Interpreter Lock: https://wiki.python.org/moin/GlobalInterpreterLock)  does help guarantee thread-consistency (as opposed to safety), so this is less of an issue in Python than other languages.

However, what you need to ask when you're looking at singletons is why?

What can a global singleton give you that a static method or class or cache can't? What about using a Factory design pattern to properly handle creating DB resources?

The problem with a singleton in use is that an object being a singleton is non-obvious, while static classes or methods or caches are much more obvious in how they can be used and interacted with.

Consider the following issue:

You decide to use a singleton in a library. Six months later, you find a user story where you need multiples of that singleton - but you've forgotten its a singleton. You try and create copies, instantiate new ones, etc etc and keep running into all these weird defects.

This is where singletons become a code maintenance issue, and until you've suffered the costs and frustrations brought about by this, its hard to understand why singletons are such a big code smell issue.

Imagine even worse, that you don't have the source code for the library, the documentation has been lost, and you didn't write it. How would you know a returned object was a singleton?

(I have experienced the above at a job previously... that was... fun for certain definitions of fun.)

OwnerDisplayName: zeller


答:
Learning OOP principles is not language specific at all, so if by "learn OOP" you mean "learn what the terminology means, what OOP is and why I might want to use it" then the language doesn't matter.

If you mean "learn how to develop using OOP" then yes, different languages handle it differently, but they all share the same set of principles. If you're anything like me you'll learn it best by just doing it. Choose an object-oriented language with a good tutorial or book that covers the object oriented aspects and have at it. If you have the principles of object oriented design down, you'll be able to use them in any other OO language.

"Python is so new that's why you can't learn OOP on Pyton. you learn Java then understand OOP on Java"

This just makes my head hurt. So much wrong crammed into one sentence.

Python dates to 1989.

http://python-history.blogspot.com/2009/01/brief-timeline-of-python.html

Java to 1995.

http://www.oracle.com/technetwork/java/javase/overview/javahistory-index-198355.html

You can draw your own conclusions on the validity of that bit of advice...


问:
How to support the sales team and avoid the "Often the sales team gets us into trouble just to get a commission" problem
With reference to this answer:

At the end of the day, we are delivering a product to a paying customer. This customer has needs and expectations, realistic or not. Often the sales team gets us into trouble just to get a commission.

I realise there are processes (mainly with communication and project managment) that can help minimise risk (these seem to have minimal impact, mainly due to being ignored by anyone other than dev) and believe a percentage of the problem is their complete lack of technical understanding rather than greed (though this does play a part). But when it isn't possible to get rid of commissions (very good article), get (train) better salesmen, or increase dev resources, how can you minimise the impact on developer moral, timelines and generally development department being held responsible?

How common is this damaging to the business (and no one higher up will believe how much better it could be - they don't see any problem now, but wonder why sales fall through and customers aren't happy) and how do others mitigate the risk, prove development is not the issue and handle such situations where the marketing is too aggressive and overselling is normal (which all propagates from the top)?

How can you support the sales team and upper management to improve the root cause of this situation and what changes can be implemented in dev department to help with this?

Additional information: the is only one product we create and as such is sold with additional functionality as required or work to let it integrate with existing systems.

I was worried about close votes, but this is a very real problem (and I have tried to word it objectively)- if you can comment on how to improve this question, please let me know.

答:
I realise there are processes ... (these seem to have minimal impact, mainly due to being ignored by anyone other than dev)

generally development department being held responsible

no one higher up will believe how much better it could be - they don't see any problem now, but wonder why sales fall through and customers aren't happy

They used to ignore the schedule and constantly re-prioritise projects, even asking for two things to have top priority, we've got that more under control now, but it still goes on, they just don't tell us until it is too late.

due to their size they can use threats

these issues occur before we are involved

Those are your root causes right there and they paint a picture of a very badly broken corporate culture.

How can you support the sales team and upper management to improve the root cause of this situation and what changes can be implemented in dev department to help with this?

I have my doubts that anything you change within the dev department will make any difference; you already communicate (and are ignored), instigate processes (which are also ignored) and try to manage projects and resources properly (only to be undercut by sales and management setting priorities and deciding on features without bothering to consult dev on their feasibility).

Dev team management needs to be in the loop and HEARD in any decision involving development resources; sales and management do not know how resources in dev are allocated, yet they are being allowed to make final decisions whose outcomes depend on that information.

Priorities need to be agreed upon between sales and dev and not constantly changed without VERY good reason. Dev needs to make it clear that changes have consequences, that prioritizing one thing will reduce the priority of another and that constant priority upheaval will merely result in nothing being completed. Yes, sales get to decide what is a priority for their customers, but only within the constraints of dev deciding what is realistic within the time involved. This must be a team effort between sales and dev, they have to work together to find the best compromise which actually serves the customers' needs with best use of the available development resources.

Good luck. I suspect you're going to need it.


问:
What are some good ways to represent relationship among three numbers
I'm trying to find a clean, intuitive way to implement this problem. Basically, I have three numbers, and based on relationship (less than, greater than, and equal to) among these numbers would change how I execute the next set of code.

For example, if there are numbers A, B, and C. Here are some examples of relationships among them:

A < B < C

A = B > C

A = B = C

B < A = C

A consumer of my framework would build this kind of relationships between the three numbers and would pass into a class that would process the relationships. So far, I could think of one way to implement that is relatively simple but not clean.

I would represent relationships between the three numbers in flags. So, there would three different flags (A to B, B to C, and A to C). Each flag would have LessThan, EqualTo, and GreaterThan options. I would have to run through many checks to make sure that the 3 given flags are valid. If A < B and B < C, then A cannot be greater than C. If A = B and A < C, then B cannot be greater than C. The list goes on.

Is there a better way to design this?

答:
Here are some cases and examples of ways to describe and classify them so they might be analyzed as a whole.

A < B < C - This is a distinct ordered set

A = B < C - This is an indistinct ordered set

A > B < C - This is an unordered set

A  B = C - This is an indistinct ordered set

A  C - This is an unordered set

A = B > C - This is an indistinct ordered set

A > B > C - This is a distinct ordered set

Grab whatever other terminological definitions you can think of for sets and lay them over those 9 cases and you may find more identifiable groupings than what I found using just 2 filters (distinctness and orderliness).

I'm sure the math lexicon is brimming with terms you could put on these for describing sets.

From Set theory on Wikipedia (emphasis mine):

Equivalence and order relations are ubiquitous in mathematics, and the theory of mathematical relations can be described in set theory.

Considering the area you're looking at, like I said there's a lot in math for you to find here. Here's a few things I would further suggest you read up on to give yourself some terminology and prior precedent to work from:

Transitive relationship:

For example, "is greater than," "is at least as great as," and "is equal to" (equality) are transitive relations:

whenever A > B and B > C, then also A > C

whenever A ≥ B and B ≥ C, then also A ≥ C

whenever A = B and B = C, then also A = C.

Commutative Property (in relation to your greaterthan/lessthan/equality operations, commutativity can help you derive transitivity):

The term "commutative" is used in several related senses.[7][8]

A binary operation * on a set S is called commutative if:

x * y = y * x\qquad\mbox{for all }x,y\in S

Associative Property (in relation to your operations, associativity can help you derive transitivity as well):

Within an expression containing two or more occurrences in a row of the same associative operator, the order in which the operations are performed does not matter as long as the sequence of the operands is not changed. That is, rearranging the parentheses in such an expression will not change its value. Consider, for instance, the following equations:

(5 + 2) + 1 = 5 + (2 + 1)=8

5 x (5 x 3) = (5 x 5) x 3=75

OwnerDisplayName: Brian

Body:
Here are some cases and examples of ways to describe and classify them so they might be analyzed as a whole.

A < B < C - This is a distinct ordered set

A = B < C - This is an indistinct ordered set

A > B < C - This is an unordered set

A < B = C - This is an indistinct ordered set

A = B = C - This is an indistinct ordered set

A > B = C - This is an indistinct ordered set

A < B > C - This is an unordered set

A = B > C - This is an indistinct ordered set

A > B > C - This is a distinct ordered set

Grab whatever other terminological definitions you can think of for sets and lay them over those 9 cases and you may find more identifiable groupings than what I found using just 2 filters (distinctness and orderliness).

I'm sure the math lexicon is brimming with terms you could put on these for describing sets.

From Set theory on Wikipedia (emphasis mine):

Equivalence and order relations are ubiquitous in mathematics, and the theory of mathematical relations can be described in set theory.

Considering the area you're looking at, like I said there's a lot in math for you to find here. Here's a few things I would further suggest you read up on to give yourself some terminology and prior precedent to work from:

Transitive relationship:

For example, "is greater than," "is at least as great as," and "is equal to" (equality) are transitive relations:

whenever A > B and B > C, then also A > C

whenever A ≥ B and B ≥ C, then also A ≥ C

whenever A = B and B = C, then also A = C.

Commutative Property (in relation to your greaterthan/lessthan/equality operations, commutativity can help you derive transitivity):

The term "commutative" is used in several related senses.[7][8]

A binary operation * on a set S is called commutative if:

x * y = y * x\qquad\mbox{for all }x,y\in S

Associative Property (in relation to your operations, associativity can help you derive transitivity as well):

Within an expression containing two or more occurrences in a row of the same associative operator, the order in which the operations are performed does not matter as long as the sequence of the operands is not changed. That is, rearranging the parentheses in such an expression will not change its value. Consider, for instance, the following equations:

(5 + 2) + 1 = 5 + (2 + 1)=8

5 x (5 x 3) = (5 x 5) x 3=75


答:
The core idea in OOP is encapsulating (which means bundling or hiding) variables and methods together inside of classes (which python absolutely supports). It's about designing your code around Nouns. Then it kind of goes on from there.

While there are implementation differences (for example, python doesn't support visibility the way Java does) and syntax differences (in Javascript, you have to inherit methods yourself), the basic design stays the same.

I do think it's easier to learn OOP in a language like Java, though, because the language requires it and the community is less adverse to it than, say, the python community.

But there is tons of writing about OOP design & practices out there, and reading it's not wasted effort. Even when I write python (which is a lot), I write lots of objects, and I use a lot of objects from third-party libraries.


答:
There are three possible relations between A and B:

A = B

A > B

A < B

Similarly, there are three possible relations between A and C, and three relations between B and C.

I feel that rather than storing one value representing the relationship between three values (an enum with 21 values after throwing out the degenerate cases), it would be better to store three relationships between each pair of values, each of which is an enum with three values.

```<code>public enum XCompY
{
    LessThan = -1,
    Equals = 0,
    GreaterThan = 1
}

public class MyData
{
    private XCompY aToB;
    private XCompY aToC;
    private XCompY bToC;

    ...

    public bool IsValid(MyObject a, MyObject b, MyObject c)
    {
        int aCompB = a.CompareTo(b); // MyObject.CompareTo returns exactly -1, 0, or 1
        int aCompC = a.CompareTo(c);
        int bCompC = b.CompareTo(c);

        return (aCompB == (int)aToB) && (aCompC == (int)aToC) && (bCompC == (int)bToC);
    }
}
</code>```

We now have something easy to read, we don't have a giant switch block, and we've added the ability to validate the relationship between fewer than 3 objects (or more than 3). (Yes, this approach is very close to what your initial idea was.)

Title: What are some good ways to represent relationship among three numbers

Body:
I'm trying to find a clean, intuitive way to implement this problem. Basically, I have three numbers, and based on relationship (less than, greater than, and equal to) among these numbers would change how I execute the next set of code.

For example, if there are numbers A, B, and C. Here are some examples of relationships among them:

A < B < C

A = B > C

A = B = C

B < A = C

A consumer of my framework would build this kind of relationships between the three numbers and would pass into a class that would process the relationships. So far, I could think of one way to implement that is relatively simple but not clean.

I would represent relationships between the three numbers in flags. So, there would three different flags (A to B, B to C, and A to C). Each flag would have LessThan, EqualTo, and GreaterThan options. I would have to run through many checks to make sure that the 3 given flags are valid. If A < B and B < C, then A cannot be greater than C. If A = B and A < C, then B cannot be greater than C. The list goes on.

Is there a better way to design this?

Body:
There are three possible relations between A and B:

A = B

A > B

A < B

Similarly, there are three possible relations between A and C, and three relations between B and C.

I feel that rather than storing one value representing the relationship between three values (an enum with 21 values after throwing out the degenerate cases), it would be better to store three relationships between each pair of values, each of which is an enum with three values.

public enum XCompY
{
    LessThan = -1,
    Equals = 0,
    GreaterThan = 1
}

public class MyData
{
    private XCompY aToB;
    private XCompY aToC;
    private XCompY bToC;

    ...

    public bool IsValid(MyObject a, MyObject b, MyObject c)
    {
        int aCompB = a.CompareTo(b); // MyObject.CompareTo returns exactly -1, 0, or 1
        int aCompC = a.CompareTo(c);
        int bCompC = b.CompareTo(c);

        return (aCompB == (int)aToB) && (aCompC == (int)aToC) && (bCompC == (int)bToC);
    }
}

We now have something easy to read, we don't have a giant switch block, and we've added the ability to validate the relationship between fewer than 3 objects (or more than 3). (Yes, this approach is very close to what your initial idea was.)


答:
An object as a theoretical construct is very simple: It's a structure that stores data, functions, or both. The idea being that these structures have a sense of "self" which is implicit in most languages outside of Python. This is called a "descriptor" and gives the object a point of self reference that binds data (variables or fields) and functions (typically called methods) to the particular object in question. The idea being that you are specifically using a variable or method that belongs to that particular instance (allocated block of memory typically underneath) rather than to some larger, more general construct.

Object systems tend to vary with regards to two big categories: Inheritance and Access.

Some, like Java or C++, have you declare classes that act as "blueprints" for objects that then become allocated. These classes and their objects cannot be structurally modified once instantiated. They can have their contents overridden in the sense that variables can change but their structure is static. You can't, for example, add new methods to HashMap in Java. You can extend the interface (basically partially implemented classes serving as contracts) or make a subclass to get the extra methods or variables you need along with all of the original variables and methods of the particular class in question.

Other class based languages, the most typically cited one being Ruby, allow you to easily open up an existing class and just add in methods as you see fit. This is a bone of contention and considered by many to be very, very dangerous.

Javascript is even looser, Objects are nothing more than a collection of slots for either variables or functions. They can be changed or overwritten whenever the programmer feels the need to do so. They can even be arbitrarily cloned as "Prototypes" for other objects, thereby passing all of their abilities on.

Access control is the other big point of difference between the various languages.

Some languages like Java have very strictly enforced access modifiers like "private" and "protected", that define exactly what classes and subclasses can use a given variable or method.

Others, such as Python are less formal, using the convention of an underscore before the method or variable name to indicate that it is private.

Ultimately, Python is a perfectly legitimate language to program in an object-oriented fashion, it just doesn't enforce it quite as rigorously as some of the others.


问:
Call the database every time, or create an object in memory, and if so, how and how often to update?
I'm creating an app in javascript/nodejs and using neo4j as database.

Let's say I have an entity User in my database. It has a bunch of properties, like boxes_collected and places_visited, which keep updating independently of one another throughout the course of running my app.

So far I have functions that talk to the database to update these properties directly. But it's getting a bit messy and I'm thinking of making a single high level object/class that handles everything in a much cleaner, nicer, and eloquent way.

Here's a tiny version of my "model" to better explain what I mean:

Suppose I have a function like this

```<code>function UpdateUserValue_plants(number) {// update database}
</code>```

But then if were to create a User object and incorporate the above into it,

```<code>var User = function User(plants, other...) {
    this.plants= plants;
}

User.prototype.updateValue_plants = function(number) {
    this.plants += number; // first update the model itself
}
</code>```

Then when am I supposed to update the database? And wouldn't I be doing the updatation twice that way: first the object's property, then the database?

Is there an elegant solution to this?

答:
One approach is to come up with some way of tracking your changes, then dumping them to the database in bulk.  There are different approaches to this, but you will need to have something keep track of all the original values, then figure out what has changed, then batch that up into inserts, updates, and deletes.

Martin Fowler calls the object that keeps track of this a Unit of Work.  This object handles CRUD for all the business objects.  From the link, it should be clear that you use registerNew, registerDirty, registerClean, registerDeleted from within properties setters, and use rollback or commit when you are ready to save everything.

There is discussion of pros and cons of various implementation details in Patterns of Enterprise Application Architecture as well.  Some things to think about are how often to hit the database, what to do if clients are engaged in a business transaction longer than your database transaction can feasibly be, and whether to talk to your Unit of Work via events or directly.

This functionality will be part of what an ORM does best, and if you can find one it will be better than writing one.  But understanding the concepts would still be valuable.


问:
How to deal tasks that are probably not user stories but still need to get done?
We have a number of tasks that need to be completed, but are probably not real user stories, or if they are, they are very developer-centric user stories which will never be visible to the end-users. The problem is that because they do not get estimated as a part of a sprint and very little gets done on them. Eventually, it becomes enough of a problem that someone takes time out of a sprint to deal with them, but that affects progress on "official" sprint work, which makes some people a wee bit unhappy.

I've been pushing for making these tasks into official user stories, but no one else seems to like this. How else could I request official recognition for these tasks, so I can allocate full days on them without feeling like I'm affecting the rest of the sprint?

Some examples of the tasks, just to give you an idea:

Write small, custom maven plugins to simplify specific (and widely used, within the organization) build configurations.

Refactor old project(s) to build with Maven and newer tool set.

Refactor redundant (across multiple projects) code into independent libraries - could potentially be used by many projects.

答:
Thanks for an informative question - for someone like me who has never formally used Scrum as a method for software development.  I am part of a product company - and we went from traditional waterfall to Iterative to what can best be described as Kanban - altho' Kanban by itself is not a software development method.

I am not trying to "sell" Kanban to you - having been around for over 25 years in the software industry, I am very familiar with the challenges involved in changing processes in a software organization!  But I thought I'd share ideas from Kanban which you might have the flexibility to try in your team.

Kanban's key points are to visualize your existing process, limit work-in-progress (limit WIP), establish Pull and improve gradually (evolutionary change rather than revolutionary). Since you are already practicing some of these, the rest might be easy to adopt.

We have - and had - a very similar situation to yours - lot of regular feature development and defect fixing work as part of the regular product enhancements, that needed to go out in a release; interspersed with code refactoring and other Engineering driven tasks - and our challenge was visualizing it for everyone in the company so the CEO and Sales and Marketing knew exactly how much work Engineering was handling, and allow them to weigh in on the priorities of all the work.

When we moved from an iterative process to Kanban, within a couple of iterations, our board looked as shown in the pictures shown below -

Our Dev process was mapped in the Dev lane of the Kanban board -

Our overall Kanban board looked like this, with the last lane being reserved for Engineering driven and other 'hygiene' work -

As you can see, we not only had a Dev lane and a Global/ Engineering items lane, but also some customer interrupts and a planning lane. Each lane also specified how much total work could exist in each lane - the WIP limit for that lane.  Developers would take up (pull) work in the Global task lane whenever they had any spare capacity. Once they pulled it, they would typically finish it before taking on a new user story.

This allowed us to map and visualize our situation exactly as it was - whether we liked it or not, a high-priority customer interrupt did delay or shift work on other items.  Instead of trying to map them as user stories, we mapped each type of work as is - and pushed work out to Staging and Production as it became ready.  The normal process we used was to include some of the engineering stories/ tasks ever 3rd release or thereabouts.

The beauty of this system was that it helped us study the volume of work in each category (Kanban calls it "class of service") and reorganize our board, our process, and the team as we went along. Within one year of adopting Kanban, we made a production release almost every month - which made our Sales and CEO - and our customers very happy of course! And of course, doing this meant that we automatically had 'official sanction' from the CEO and Product Management - recognition that this work was important (but not necessarily urgent) - and needed to be done whenever there was spare capacity available to do it.  Of course, there were times, when with the help of Prod Mgt, some of this work got specifically prioritized due to its urgency.

So, if possible in your environment, I'd suggest that you have a frank discussion within the team - and with any stakeholders that need to be involved - and work out a method that helps you map your current work and process - and helps you arrive at agreement to prioritize some of this work on a regular basis - and package them in the first possible sprint/ release that you can. In the process, you might find yourself doing somethings that are not necessarily "true to Scrum" - but might help you evolve to a better process that allows the team to work much more smoothly than it perhaps might be doing today.

Apologies for a long response, but I hope it helps. And again, this might not be a direct response to your question - but I hope some of these concepts might be useful for your situation.


问:
Relationship between user story, feature, and epic?
As someone who's still new to agile, I'm not sure I completely understand the relationship or difference between user story, feature, and epic.

According to this question, a feature is a collection of stories.  One of the answers suggests that a feature is actually an epic. So are features and epics considered the same thing, that is basically a collection of related user stories?

Our project manager insists that there's a hierarchical structure:

Epic -> Features -> User stories

And that basically all user stories must fall within this structure.  Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.

To me, that sounds awkward.  Can someone please clarify how user stories, features, and epics are related?  Or is there an article that clearly outlines the differences?

答:
In our organisation we have the following:

Theme = Used to group together a collection of stories

Epic = Describes a large user story (in truth a requirement) that needs to be broken down into user stories

Features = Does what it says on the tin, describes a feature of the product required

User story = This is the lowest level of detail from which tasks are derived.


问:
How to handle 'external' dependencies in scrum?
If you've planned a number of user stories for a sprint and one candidate story is dependent on some external provider delivering something to your team. For example an online service provider adding a new API call to their system or enabling your test account on their system or suchlike.

You know it's coming 'soon'.

Do you go ahead and add the story to the sprint hoping they'll deliver what is required in time for you to complete your story or do you wait till the next sprint, when you know it will be ready and you can start immediately even if it means not starting the story as early as you could.

If the former how do you handle 'unearned' story points lost because of the dependency?
partial credit (eek!) or take it on the chin.

答: If it doesn't depend on your team and you can do other tasks, I advise you to only take it when it's ready. Even if you got an mockup webservice, schema, interface and/or contract it may still break up (remember Murphy's Law?).</p>


答:
In Scrum there is a definition of done and there is a definition of ready for user stories. In a situation like yours its important to has a definition of ready that all the stakeholders understand and agree with. For example seems very reasonable to has a line in your definition of ready like:

All the external API's needed for the story must be delivered and tested.

If you needs this API to add value to your product the logical thing to do its wait until we really have this API to start our work. In the meantime we can do other US that add value to the product, i really don't like this US with mock implementations and the like, if there is not real value for the costumer there is no US, its waste of time and resources.

Title: How to handle 'external' dependencies in scrum?

Body:
If you've planned a number of user stories for a sprint and one candidate story is dependent on some external provider delivering something to your team. For example an online service provider adding a new API call to their system or enabling your test account on their system or suchlike.

You know it's coming 'soon'.

Do you go ahead and add the story to the sprint hoping they'll deliver what is required in time for you to complete your story or do you wait till the next sprint, when you know it will be ready and you can start immediately even if it means not starting the story as early as you could.

If the former how do you handle 'unearned' story points lost because of the dependency?
partial credit (eek!) or take it on the chin.


问:
Use global variables or methods in an API's frontend
I am currently designing a graphics library in Java and now it's come to making the frontend I am curious why I have never seen libraries using global variables for their settings/properties - in-fact some go out of their way to protect them such as JavaScript libraries, and of course choose to use getters and setters such as:

```<code>Viewport.VSyncEnabled(true)
</code>```

instead of simply

```<code>Viewport.VSyncEnabled = true;
</code>```

I assume that it is to let the library know what is happening, but there are so many variables that simply don't need monitoring such as output debug data.

I would really like to use global variables however if it very against the convention and there are benefits (that I don't know of right now) then I'll be happy to use methods. My reason for wanting to use global variables instead is by my benchmarks it is faster to access directly like that.

答:
Yes, of course assigning a variable directly is faster than calling a method. However, there are good reasons why using a method is better.

The Uniform Access Principle says that all data of an object (or here: library) should be accessed via the same interface. This would be violated if some properties could be set directly, and others could only be set via methods. At least some properties will use methods, because of …

Validation. It may be that some config variable has the type int, but perhaps it only accepts values >= 0. With a public variable, there's no way to check that. With a method, we can perform arbitrary validation.

Obviously, this does not apply to final fields. Making constants public is no problem, except possibly for the other two reasons here. It depends on how they are used.

Encapsulation is important. If our public API consists of variables, we can never remove them without breaking backwards compatibility. This affects the inner workings of our library. When we use methods to set/get values, we can rework the internals of our library without having to change the public-facing API. For example, executing some hook when a property has been set is no problem with methods.

Together, these are three good reasons to use methods. It's just so much more flexible, and far cleaner and extensible than the alternative.

There is another issue with global variables, or more precisely with global anything: We can only have one “instance” of your library at a time. This can make testing or other advanced usage very difficult. Instead, offer your API via normal objects with the understanding that normally one would only use one instance. Using  static anything is not object-oriented, it is just thinly veiled procedural programming.

Summary: public variable is very bad, public static method() isn't great either. private variable is good, as is public setVariable(…).

OwnerDisplayName: Lee Allan


问:
Should processing/filtering be performed client side or server side for catalog based apps
Device targeting for product XML catalog

We currently have a webservice that outputs an XML of products based on get parameters in the request. The webservice is consumed from a windows mobile application.

In front of the webservice we have an HTTP accelerator/cache that caches the results for identical URLs.

The business guys, want a new feature to allow products to be targeted for specific device configurations.

We consider a device configuration can be made of parameters such as:

hardware model

firmware

geographic location

cellular provider

etc...

This may drastically kill the cache hit/miss ratio (efficiency) since we will be sending a param "deviceConfigId" which will be different for many devices, but will affect the list of applications outputted. We are talking 10,000 configs minimum. Our hit/miss ratio went from 75% to 40% after adding a few new features and filters via the URL one year ago.

Except for using mechanisms such as Edge Server Includes ( https://stackoverflow.com/questions/5960598/varnish-and-esi-how-is-the-performance/9914643#9914643 ) , one of the ideas we are flirting with is to movie part of the filtering to the mobile devices.

Moving filtering client side

The mobile developers cringe because this may make their mobile devices less responsive. The client devices will need to download all product information(page by page as people scrolll down) but the device will need to filter out entries. Additionally, at the beginning of loading the device must download a list of rules applicable to the specific configuration in order to apply them on all future requests and the products listed in the XML.

Keeping all filtering on the backend

The backend developers cringe with the idea of adding the "deviceConfigId" to all the requests. This will require adding even more network infrustructure and resources. The problem can be solved by adding a better load balancer and adding more servers behind it (as well as moving to more distributed technologies later on).

If we consider that user experience should be the highest priority and that slower/older devices should function as smooth as possible it seems we should use server side filtering for the product listings.

However, newer devices are coming out and older devices are being thrown out continously. Forcing the clients to do some filtering but keeping load off the backend is quite tempting.

Are there any other pros/cons, and more importantly solutions to such an issue?

Thanks

答:
A good mobile developer should be able to handle the filtering on the client without affecting responsiveness by using a forward data reader.  With devices being multi-core these day, filtering should be fast on reasonable sized data sets without impacting the UI.  However, the time it takes to pull down the XML could make the user experience not so great.  The app will remain responsive since your developers are not pulling down the data on the UI thread (right?).  You can you mitigate some of this by using HTTP compression as XML is a great candidate for compression.

One reason I choose to go with a server side approach is you can fix bugs or make changes without pushing new versions of a mobile app out.  If you have never been through the process of getting stuff approved for app stores, this is a big win.  On top of this you don't have to worry about people running old versions of your app since you have control of version on the server.

Another option is to apply the filtering on the server side after the caching.  That way you can maintain and utilize the caching already in place.


答:
Object Oriented Programming is an idea about how to structure programming language to foster low coupling, information hiding (aka encapsulation), bundling data and methods that operate on that data together, and code reuse.  Lots of languages implement their take on these ideas so there are variations between languages about how they approach Object Orientation.  For example, Java only allows a class to extend 1 class.  However, Python and C++ allow you to extend any number of classes.  Java have specific reasons for its limitations.  Limitations that are meant to correct things from C++, but also because Smalltalk only supports a single base class.

OO languages can be grouped into two families.  The Smalltalk family (or class based OOP) of languages include C++, Java, Smalltalk, Ruby, C#, Python to name a few (there are tons in this family).  These are a mix of statically  and dynamically type languages and while they differ slightly on some concepts they are very similar in how they think about OOP.  What I mean by that is how they approach coupling, encapsulation, binding data and methods, and code reuse, and the tools they provide for you to do that.  Within this family lot of the concepts are the same.

The other family is the protoype based OOP.  These languages look very different in their OOP implementation.  Probably the best known example of this is Javascript, but Javascript copied these ideas from Scheme and Object LISP.  These are lesser known languages and typically dynamically typed.  I can't think of a statically typed prototype based language, but that doesn't mean there isn't one.  You can read up on it here:  http://en.wikipedia.org/wiki/Prototype-based_programming.  The point is they approach OOP in a very different way than the class based languages.  That means concepts aren't as portable between these two families.  Just because you know OO in one family doesn't mean you'll easily transition those ideas over to the other family.

Bear in mind that most programming languages mix concepts from lots of ideas.  Python and Ruby  incorporate both OOP and functional programming ideas into their languages.  And you can mix prototype based OO with certain extensions to class based languages so it's even more complex.


答:
OOP is a principle of programming - it's fundamentally an idea. The implementation of OOP varies throughout programming languages - but the pillars (Abstraction, Inheritance, Encapsulation, and Polymorphism) of OOP are usually present in some way or form.

I will say without preference to either language, that Java pushes the semantics a little harder on the programmer than say Python.

For example,

Java code: class Cat extends Animal {}

Is a little more obvious as to what you are doing in the OOP viewpoint of things than:

Python code: class Cat(Animal):

Sure they both define a class hierarchy in which Cat inherits from Animal. But I feel that for a programmer just starting out in OOP, the application and implications of OOP ideas might stick a little better in Java since it is spelling it out for the programmer.


问:
Store the result of a complex but frequent database query, in another temp persisting table
I have a slightly complex SELECT query which uses a number of JOINs and variables inside it and the query is run frequently throughout the application.

The result varies when one column is updated. Eg: When the product quantity is updated only, the result set changes.

So my question is, is it a good idea to run a trigger and update a temporary table in the database, with my SELECT queries results, whenever the product quantity is updated? Or to run the complex SELECT query every time?

Right now I tested with ~10 rows of data and the query execution time is 0.001 seconds. I want to use the best possible method which won't hinder the performance as the DB grows.

Thank you!

答:
In general, a question about optimization should always be proceeded by an example of why you need it. If you can query a database and get the result you need back in 0.001 seconds, then you have nothing to worry about--a database will happily return all the information you need.

Remember, just because you think the query is complex doesn't mean the database engine thinks so. A good database engine is built to query large amounts of data quickly. It will find a way to make your query run as efficiently as it can.

Now, if you come back and say that you can't generate the information you need in less than 30 seconds or that the number of transactions overwhelms your server, you might have a case to dump the data into a temporary table. However, you need to be careful about that--it's not as easy as pulling the data out of a table, you need to make sure that users only get one result, rather than parts of two as you re-generate the table. But my advice stands--you ain't gonna need it until you need it.


答:
Since this is tagged MySQL... MySQL already has built in support for query caching.  So there shouldn't be a need for you to roll your own unless you had very specific, unique challenges to get around.  You just want to make sure query caching is enabled in your MySQL installation.  It would not surprise me if most other DBMS's had similar functionality.

So, generally speaking, no, there shouldn't be a need for this for queries themselves.

If you are concerned about query performance, learn how to use EXPLAIN, and interpret the results to help you build indexes.  That is where you'll get the best 'bang for the buck' in terms of performance tuning.

Title: Store the result of a complex but frequent database query, in another temp persisting table

Body:
I have a slightly complex SELECT query which uses a number of JOINs and variables inside it and the query is run frequently throughout the application.

The result varies when one column is updated. Eg: When the product quantity is updated only, the result set changes.

So my question is, is it a good idea to run a trigger and update a temporary table in the database, with my SELECT queries results, whenever the product quantity is updated? Or to run the complex SELECT query every time?

Right now I tested with ~10 rows of data and the query execution time is 0.001 seconds. I want to use the best possible method which won't hinder the performance as the DB grows.

Thank you!


答:
It seems to me that you could build a look up table to dispatch handling.

You have three relationships which in turn have three values.

We can think of this as three indices:

Relation b/w A and B

Relation b/w A and C

Relation b/w B and C

enum Relation { less, equal, greater };

```<code>public delegate void Handle(int a, int b, int c);

class Handlers
{
    public void handleLessLessLess(int a, int b, int c) { }
    public void handleLessLessEqual(int a, int b, int c) { }
    public void handleLessLessMore(int a, int b, int c) { }

};
public class Dispatcher
{
    public Dispatcher()
    {
        table[Relation.less][Relation.less][Relation.less] = new Handle(h.handleLessLessLess);
        table[Relation.less][Relation.less][Relation.equal] = new Handle(h.handleLessLessEqual);
        table[Relation.less][Relation.less][Relation.greater] = new Handle(h.handleLessLessEqual);
        table[Relation.less][Relation.greater][Relation.less] = null; // cannot have a < b, a > c, b < c
    }

public void handle(Relation ab, Relation ac, Relation bc, int a, int b, int c)
{
    Handle h = table[ab][ac][bc];
    if (h != null)
        h(a, b, c);
    else
        // exception of what have you.
        ;
}

Handlers h = new Handlers();
Dictionary<Relation, Dictionary<Relation, Dictionary<Relation, Handle>>> table =
    new Dictionary<Relation, Dictionary<Relation, Dictionary<Relation, Handle>>>();
</code>```

};

Body:
It seems to me that you could build a look up table to dispatch handling.

You have three relationships which in turn have three values.

We can think of this as three indices:

Relation b/w A and B

Relation b/w A and C

Relation b/w B and C

enum Relation { less, equal, greater };

public delegate void Handle(int a, int b, int c);

class Handlers
{
    public void handleLessLessLess(int a, int b, int c) { }
    public void handleLessLessEqual(int a, int b, int c) { }
    public void handleLessLessMore(int a, int b, int c) { }

};
public class Dispatcher
{
    public Dispatcher()
    {
        table[Relation.less][Relation.less][Relation.less] = new Handle(h.handleLessLessLess);
        table[Relation.less][Relation.less][Relation.equal] = new Handle(h.handleLessLessEqual);
        table[Relation.less][Relation.less][Relation.greater] = new Handle(h.handleLessLessEqual);
        table[Relation.less][Relation.greater][Relation.less] = null; // cannot have a < b, a > c, b < c
    }

public void handle(Relation ab, Relation ac, Relation bc, int a, int b, int c)
{
    Handle h = table[ab][ac][bc];
    if (h != null)
        h(a, b, c);
    else
        // exception of what have you.
        ;
}

Handlers h = new Handlers();
Dictionary<Relation, Dictionary<Relation, Dictionary<Relation, Handle>>> table =
    new Dictionary<Relation, Dictionary<Relation, Dictionary<Relation, Handle>>>();

};


问:
How did separation of code and data become a practice?
Please read the question carefully: it asks how, not why.

I recently came across this answer, which suggests using a database to store immutable data:

It sounds like many of the magic numbers you describe - particularly if they are part dependent - are really data, not code. [...]  It may mean an SQL type database, or it may simply mean a formatted text file.

It would seem to me that if you have data that is part of what your program does, then the thing to do is to put it in the program. For example, if your program's function is to count vowels, what's wrong with having vowels = "aeiou" in it? After all, most languages have data structures designed for precisely this use. Why would you bother to separate data by putting it in a "formatted text file", as suggested above? Why not just make that text file formatted in your programming language of choice? Now is it a database? Or is it code?

I'm sure some will think this is a dumb question, but I ask it in all seriousness. I feel like "separate code and data" is emerging culturally as some sort of self-evident truth, along with other obvious things like "don't give your variables misleading names" and "don't avoid using whitespace just because your language considers it insignificant".

Take for example, this article: The Problem with Separating Data from Puppet Code. The Problem? What problem? If Puppet is a language for describing my infrastructure, why can't it also describe that the nameserver is 8.8.8.8? It seems to me that the problem isn't that code and data are mingled,1 but that Puppet lacks sufficiently rich data structures and ways to interface to other things.

I find this shift disturbing. Object oriented programming said "we want arbitrarily rich data structures", and so endowed data structures with powers of code. You get encapsulation and abstraction as a result. Even SQL databases have stored procedures. When you sequester data into YAML or text files or dumb databases as if you are removing a tumor from the code, you lose all of that.

Can anyone explain how this practice of separating data from code came to be, and where it's going? Can anyone cite publications by luminaries, or provide some relevant data that demonstrates "separate code from data" as an emerging commandment, and illustrates its origin?

1: if one can even make such distinctions. I'm looking at you, Lisp programmers.

答:
For example, if your program's function is to count vowels, what's
  wrong with having vowels = "aeiou" in it?

Storing configuration externally allows you to have one version of the code that is expected to work with many configurations, the alternative is to maintain many versions of the software that differ only by configuration.

You mention vowels = "aeiou" , what if i sometimes want "y", should I have to rebuild the entire program? Can i upgrade versions easily now that i have modified the code? If there is an error, did I cause it, or is the program broken?

If this is inside your program, it implies that your program does not expect users to change the definition of vowels without scanning the code to see the possible side effects.  If the definition is stored externally, it implies that the program should not break for any reasonable value set in the configuration.

When you sequester data into YAML or text files or dumb databases as
  if you are removing a tumor from the code

Some see it as the opposite, that is, you are removing the tumor of code from your precious data, see: Torvalds' quote about good programmer


答:
Communication and Agreements

Two systems are integrated by programmers, not by the methodology itself. If a company has decided to integrate an external system, there will be a contract between (minimum) 2 entities. The contract must ensure that integration takes place. Consequently, if the agreement between the companies, does not require a technical collaboration between both departments, the problem is not the development methodology. The problem is business methodology (basically the contract).

Having said that, it must be considered a risk during the planning of those cases and considering that you do not know the speed of the team, you will need to be generous with those margins.

How can a Project Manager manage a dependency on an external team?

https://pm.stackexchange.com/questions/1400/how-can-a-project-manager-manage-a-dependency-on-an-external-team


问:
Do validate non-input data from a client?
One of our developers has an opinion that all client data should be validated before using it. Even non-input data.

Say, our web service has an internal protection against database injections.

Examples: machine generated codes, various integers, indexes, calculated values.

We use ORM (Django). As I know there is a next approach in Django: validate only values entered as primary strings (usually via web forms).

For example: is there any reason to create validation rules to validate numbers if we know that there is 500th error (if the data are wrong) in the beginning of handling request? I think no. But probably I'm wrong.

Do my position requires to be changed?

答:
Personally, I think the client application, it must provide an ideal environment to perform properly the functions of the software solution (which also includes the back-end).

is there any reason to create validation rules to validate numbers

Why the web application should allow me to make mistakes?

The validation in the client is not about security system, because obviously does not have the possibility to play that role, but must be considered as a solution of usability.