问:
Best practice or design patterns for retrieval of data for reporting and dashboards in a domain-rich application
First, I want to say this seems to be a neglected question/area, so if this question needs improvement, help me make this a great question that can benefit others! I'm looking for advice and help from people who have implemented solutions that solve this problem, not just ideas to try.

In my experience, there are two sides of an application - the "task" side, which is largely domain driven and is where the users interact richly with the domain model (the "engine" of the application) and the reporting side, where users get data based on what happens on the task side.

On the task side, it's clear that an application with a rich domain model should have business logic in the domain model and the database should be used mostly for persistence. Separation of concerns, every book is written about it, we know what to do, awesome.

What about the reporting side? Are data warehouses acceptable, or are they bad design because they incorporate business logic in the database and the very data itself? In order to aggregate the data from the database into data warehouse data, you must have applied business logic and rules to the data, and that logic and rules didn't come from your domain model, it came from your data aggregating processes. Is that wrong?

I work on large financial and project management applications where the business logic is extensive. When reporting on this data, I will often have a LOT of aggregations to do to pull the information required for the report/dashboard, and the aggregations have a lot of business logic in them. For performance sake, I have been doing it with highly aggregated tables and stored procedures.

As an example, let's say a report/dashboard is needed to show a list of active projects (imagine 10,000 projects). Each project will need a set of metrics shown with it, for example:

total budget

effort to date

burn rate

budget exhaustion date at current burn rate

etc.

Each of these involves a lot of business logic. And I'm not just talking about multiplying numbers or some simple logic. I'm talking about in order to get the budget, you have to apply a rate sheet with 500 different rates, one for each employee's time (on some projects, other's have a multiplier), applying expenses and any appropriate markup, etc. The logic is extensive. It took a lot of aggregating and query tuning to get this data in a reasonable amount of time for the client.

Should this be run through the domain first? What about performance? Even with straight SQL queries, I'm barely getting this data fast enough for the client to display in a reasonable amount of time. I can't imagine trying to get this data to the client fast enough if I am rehydrating all these domain objects, and mixing and matching and aggregating their data in the application layer, or trying to aggregate the data in the application.

It seems in these cases that SQL is good at crunching data, and why not use it? But then you have business logic outside your domain model. Any change to the business logic will have to be changed in your domain model and your reporting aggregation schemes.

I'm really at a loss for how to design the reporting/dashboard part of any application with respect to domain driven design and good practices.

I added the MVC tag because MVC is the design flavor du jour and I am using it in my current design, but can't figure out how the reporting data fits into this type of application.

I'm looking for any help in this area - books, design patterns, key words to google, articles, anything. I can't find any information on this topic.

EDIT AND ANOTHER EXAMPLE

Another perfect example I ran across today. Customer wants a report for Customer Sales Team. They want what seems like a simple metric:

For each Sales person, what is their annual sales to date?

But that is complicated. Each sales person participated in multiple sales opportunities. Some they won, some they didn't. In each sales opportunity, there are multiple sales people who are each allocated a percentage of credit for the sale per their role and participation. So now imagine going through the domain for this...the amount of object rehydration you would have to do to pull this data from the database for every Sales person:

Get all the SalesPeople->

  For each get their SalesOpportunities->

  For each get their percentage of the sale and calculate their Sales amount

  then Add up all their SalesOpportunity Sales amount.

And that's ONE metric. Or you can write a SQL query which can do it quickly and efficiently and tune it to be fast.

EDIT 2 - CQRS Pattern

I've read about the CQRS Pattern and, while intriguing, even Martin Fowler says it's not tested. So how has this problem BEEN solved in the past. This has to have been faced by everyone at some point or another. What is an established or well-worn approach with a track record of success?

Edit 3 - Reporting Systems/Tools

Another thing to consider in this context is reporting tools. Reporting Services/Crystal Reports, Analysis Services and Cognoscenti, etc. all expect data from SQL/database. I doubt your data will come through your business later for these. And yet they and others like them are a vital part of the reporting in a lot of large systems.
How is the data for these properly handled where there is even business logic in the data source for these systems as well as possibly in the reports themselves?

答:
Use cache for query, use domain for caching.

There is a feature called "top users" on stackoverflow. You may find a line on the buttom of top users page, says"Only non community-wiki questions and answers are included in these totals (updated daily)". This indicates the data is cached.

But why?

For performance issue maybe. Maybe they have the same concern with leaking domain logic("Only non community-wiki questions and answers are included in these totals" in this case).

How?

I don't really know how they did this, so here is just a guess :)

First, we need to find target question/answers. A scheduling task could work, just fetch all potential targets.

Second, let's look at only one question/answer. Is it a non community-wiki one? Is it within 30 days? It's quite easy to answer with domain models. Count the votes and cache them if satisfied.

Now we have the cache, they're the output of domain derivations. The query is fast and easy because there is only simple criteria to be applied.

What if the results need to be more "real time"?

Events may do the help. Instead of triggering the caching with a scheduling task, we may split the process into many sub-processes. For example, when someone votes on hippoom's answer, we publish an event triggering the update of the hippoom's top users cache. In this case, we may see frequent quick small tasks.

Is CQRS neccessary?

Neither with scheduling task approach nor with events approach. But cqrs does have an advantage. The cache is usually highly displaying oriented, if some items are not required at first, we may not calculate and cache them at all. CQRS with event sourcing helps reconsititute cache for historical data by replaying events.

Some related questions:

1.https://stackoverflow.com/questions/21152958/how-to-handle-summary-report-in-cqrs
2.https://stackoverflow.com/questions/19414951/how-to-use-rich-domain-with-massive-operations/19416703#19416703

Hope it helps :)


问:
IS a command-line (Console) is important to learn for ASP.NET developer?
I saw many RoR developers use command line to interact with interfaces and to deploy their web applications. Is that necessary step to earn for asp.net developer?</p>

答:
ASP.NET development, by and large, encourages the usage of Visual Studio for most tasks that would be performed from the command line in other environments. Is is possible to set up builds that do not use the IDE (at one point, I set up an ASP.NET project that used nant to build with aspnet_compiler), but it will be generally slower going and something of an uphill fight.

So, to answer your question, I would say that it is not necessary to learn it. However, the command line is one of the most direct interactions you can have with a computer. As a result, I tend to find its use advantageous in whatever line of software development I find myself. Therefore, I would recommend learning it and being comfortable with it.

ContentLicense: CC BY-SA 3.0


问:
When must arbitrary precision arithmetic functions be used in PHP?
My colleague uses the Binary Calculator functions in bandwidth calculations; as much as terrabytes, and with percentage splitting on allocation. His usage of these functions appears correct in order not to lose a byte; although he seems to be using them now for everything.

The manual only says:

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

How much is any size? Is it really necessary? How big is the default float in PHP? Are there any good advice regarding this or things to keep in mind?

答:
"Are there any good advice regarding this or things to keep in mind?"

There is no real substitute for:

knowing the limitations of your PHP platform, and

understanding your problem's computational requirements.

In addition, some understanding of the mathematics of computation is always useful.


答: While one can develop in ASP.Net and not use the command line, there are various tools where learning how to use the command line may be important such as using nAnt, nUnit, and writing scripts that may automate tasks outside of using Visual Studio. It isn't necessary but can be quite useful, particularly if the developer ever plans on managing Linux/Unix environments as part of their skill set.</p>

Title: IS a command-line (Console) is important to learn for ASP.NET developer?

Body: I saw many RoR developers use command line to interact with interfaces and to deploy their web applications. Is that necessary step to earn for asp.net developer?</p>


问:
What are good unit tests to cover the use case of rolling a die?
I'm trying to get to grips with unit testing.

Say we have a die which can has a default number of sides equal to 6 (but can be 4, 5 sided etc.):

```<code>import random
class Die():
    def __init__(self, sides=6):
        self._sides = sides

    def roll(self):
        return random.randint(1, self._sides)
</code>```

Would the following be valid/useful unit tests?

test a roll in the range 1-6 for a 6 sided die

test a roll of 0 for a 6 sided die

test a roll of 7 for a 6 sided die

test a roll in the range 1-3 for a 3 sided die

test a roll of 0 for a 3 sided die

test a roll of 4 for a 3 sided die

I'm just thinking that these are a waste of time as the random module has been around for long enough but then i think if the random module gets updated (say i update my Python version) then at least i'm covered.

Also, do I even need to test other variations of die rolls e.g. the 3 in this case, or is it good to cover another initialized die state?

答:
You are right, your tests should not verify that the random module is doing its job; a unittest should only test the class itself, not how it interacts with other code (which should be tested separately).

It is of course entirely possible that your code uses random.randint() wrong; or you be calling random.randrange(1, self._sides) instead and your die never throws the highest value, but that'd be a different kind of bug, not one you could catch with a unittest. In that case, your die unit is working as designed, but the design itself was flawed.

In this case, I'd use mocking to replace the randint() function, and only verify that it has been called correctly. Python 3.3 and up comes with the unittest.mock module to handle this type of testing, but you can install the external mock package on older versions to get the exact same functionality

```<code>import unittest
try:
    from unittest.mock import patch
except ImportError:
    # < python 3.3
    from mock import patch

@patch('random.randint', return_value=3)
class TestDice(unittest.TestCase):
    def _make_one(self, *args, **kw):
        from die import Die
        return Die(*args, **kw)

    def test_standard_size(self, mocked_randint):
        die = self._make_one()
        result = die.roll()

        mocked_randint.assert_called_with(1, 6)
        self.assertEqual(result, 3)

    def test_custom_size(self, mocked_randint):
        die = self._make_one(sides=42)
        result = die.roll()

        mocked_randint.assert_called_with(1, 42)
        self.assertEqual(result, 3)

if __name__ == '__main__':
    unittest.main()
</code>```

With mocking, your test is now very simple; there are only 2 cases, really. The default case for a 6-sided die, and the custom sides case.

There are other ways to temporarily replace the randint() function in the global namespace of Die, but the mock module makes this easiest. The @mock.patch decorator here applies to all test methods in the test case; each test method is passed an extra argument, the mocked random.randint() function, so we can test against the mock to see if it it indeed has been called correctly. The return_value argument specifies what is returned from the mock when it is called, so we can verify that the die.roll() method indeed returned the 'random' result to us.

I've used another Python unittesting best practice here: import the class under test as part of the test. The _make_one method does the importing and instantiation work within a test, so that the test module will still load even if you made a syntax error or other mistake that'll prevent the original module to import.

This way, if you made a mistake in the module code itself, the tests will still be run; they'll just fail, telling you about the error in your code.

To be clear, the above tests are simplistic in the extreme. The goal here is not to test that random.randint() has been called with the right arguments, for example. Instead, the goal is to test that the unit is producing the right results given certain inputs, where those inputs include the results of other units not under test. By mocking the random.randint() method you get to take control over just another input to your code.

In real world tests, the actual code in your unit-under-test is going to be more complex; the relationship with inputs passed to the API and how other units are then invoked can be interesting still, and mocking will give you access to intermediate results, as well as let you set the return values for those calls.

For example, in code that authenticates users against a 3rd party OAuth2 service (a multi-stage interaction), you want to test that your code is passing the right data to that 3rd party service, and lets you mock out different error responses that that 3rd party service would return, letting you simulate different scenarios without having to build a full OAuth2 server yourself. Here it is important to test that information from a first response have been handled correctly and have been passed on to a second stage call, so you do want to see that the mocked service is being called correctly.

Body:
You are right, your tests should not verify that the random module is doing its job; a unittest should only test the class itself, not how it interacts with other code (which should be tested separately).

It is of course entirely possible that your code uses random.randint() wrong; or you be calling random.randrange(1, self._sides) instead and your die never throws the highest value, but that'd be a different kind of bug, not one you could catch with a unittest. In that case, your die unit is working as designed, but the design itself was flawed.

In this case, I'd use mocking to replace the randint() function, and only verify that it has been called correctly. Python 3.3 and up comes with the unittest.mock module to handle this type of testing, but you can install the external mock package on older versions to get the exact same functionality

import unittest
try:
    from unittest.mock import patch
except ImportError:
    # < python 3.3
    from mock import patch

@patch('random.randint', return_value=3)
class TestDice(unittest.TestCase):
    def _make_one(self, *args, **kw):
        from die import Die
        return Die(*args, **kw)

    def test_standard_size(self, mocked_randint):
        die = self._make_one()
        result = die.roll()

        mocked_randint.assert_called_with(1, 6)
        self.assertEqual(result, 3)

    def test_custom_size(self, mocked_randint):
        die = self._make_one(sides=42)
        result = die.roll()

        mocked_randint.assert_called_with(1, 42)
        self.assertEqual(result, 3)

if __name__ == '__main__':
    unittest.main()

With mocking, your test is now very simple; there are only 2 cases, really. The default case for a 6-sided die, and the custom sides case.

There are other ways to temporarily replace the randint() function in the global namespace of Die, but the mock module makes this easiest. The @mock.patch decorator here applies to all test methods in the test case; each test method is passed an extra argument, the mocked random.randint() function, so we can test against the mock to see if it it indeed has been called correctly. The return_value argument specifies what is returned from the mock when it is called, so we can verify that the die.roll() method indeed returned the 'random' result to us.

I've used another Python unittesting best practice here: import the class under test as part of the test. The _make_one method does the importing and instantiation work within a test, so that the test module will still load even if you made a syntax error or other mistake that'll prevent the original module to import.

This way, if you made a mistake in the module code itself, the tests will still be run; they'll just fail, telling you about the error in your code.

To be clear, the above tests are simplistic in the extreme. The goal here is not to test that random.randint() has been called with the right arguments, for example. Instead, the goal is to test that the unit is producing the right results given certain inputs, where those inputs include the results of other units not under test. By mocking the random.randint() method you get to take control over just another input to your code.

In real world tests, the actual code in your unit-under-test is going to be more complex; the relationship with inputs passed to the API and how other units are then invoked can be interesting still, and mocking will give you access to intermediate results, as well as let you set the return values for those calls.

For example, in code that authenticates users against a 3rd party OAuth2 service (a multi-stage interaction), you want to test that your code is passing the right data to that 3rd party service, and lets you mock out different error responses that that 3rd party service would return, letting you simulate different scenarios without having to build a full OAuth2 server yourself. Here it is important to test that information from a first response have been handled correctly and have been passed on to a second stage call, so you do want to see that the mocked service is being called correctly.


问:
distributed computing with remote hetrogenous machines
The way i am doing it now is using boost::asio TCP sockets handling everything manually with a main server that orchestrates the processes between the available machines, but  the number of machines is increasing and when i need communication between specific machines i have to do it through the server and the number of machines is just to much to be handled by one server, so i am thinking about Open MPI.

However i have 3 problems

the machines are Heterogeneous.

the number of machines available can be for example 50 at a time and also can be only 10 and sometimes it gets to 300 which is too much for my server to handle and there is always tons of data to process, and i can seem to utilize more than ~70 connections at the same time.

most of the machines are remote and some of them share the same
network.

if i want to scale things with my current design i would get ugly trees with multiple layers, i don't have the money to hire network experts/programmers for a non profit project, but i am fairly good at grasping new concepts, so how would you go around this?

and with the above problems is OpenMPI for me?

In other words, i am looking for a better design than mine, and i have no problem implementing it from scratch no matter how long it takes and i will be supporting linux only at the start because i figured that native code has a measurable advantage, i would like to hear your ideas.

答:
There are a number of important missing bits of information:

Why is OpenMPI relevant?

Why is heterogeneous relevant?

What is the work that the server is orchestrating?

You mention one thread per connection is a problem.

If you're using Boost::Asio and you're having the problem of one thread per client, then you're likely doing something wrong. Make sure that you're doing things asynchronously and not blocking any one thread too long. This is probably the easiest thing for you to do at the moment.

OpenMPI is not what you need. MPI was designed originally for distributed memory architectures. It is possible to use it over the internet, but it is probably not the best choice. The fact you mention heterogeneous and MPI makes me think that you've done a CS course in HPC. That is not relevant in this case.

When deciding on a protocol and architecture, the type work that the clients are doing is important, how you share state between the clients and server and how long each message takes to process.

If you're optimizing for throughput, then a per message overhead is less important, so verbose serialization formats like XML and JSON are ok. You can even tear down connections between message processing jobs - meaning that the server does not have to maintain a thread.

If you're trying to keep things low latency, then per message overhead is important, so maintaining a connection and using terse serialization formats.

A Messages Broker is an architectural pattern that you could consider. It is responsible for distributing your messages between your applications.

You're better off using internet-friendly protocols, like HTTP. You don't want to worry about Proxies or NAT traversal. The internet can be considered a massive distributed system with millions of heterogeneous clients. REST is an architectural style inspired by that so it might be appropriate.

I'm going to assume that:

the server produces work item for clients to do and aggregates responses.

your clients receives a message, does some work and sends a response back.

My default choice of technology, would be a web server to implement this. It would have two URLs. One where the clients can GET new work, the other for clients to POST responses.

When you initially start the client it should periodically poll for new work (you could use WS or Long Poll HTTP requests). When the server returns a work item, one client should consume it. Each work item should be stamped with a unique id, so that you can ensure that their are no duplicates and correlate responses with the initial job.

When the client has completed the task it should POST the response and restart the process of polling for new work.

Web Servers don't work well for long requests so you would want to hand it off to something else, perhaps via a DB, IPC or a message queue.

The server then does not have to worry about the capabilities of each client (so it makes heterogeneous irrelevant). The clients will just consume at the rate they can.


问:
Where does the term 'serialization' come from?
In order to convert e.g. a python object to json you would use a serializer. As far as I understand it, serialization leaves the possibility to change the converted object back to the original.

Where does the term serialization come from/why is the process called serialization?

答:
From the fact that in order to transmit any information you need to put all parts of that information into a series of bytes.

In order to transmit a record full of information you would have to "serialize" all the bytes that comprise the record, send them over the wire and at the other end would have to deserialize them back into a record.

With the advent of client / server applications, the concept was generalized to serializing objects into some kind of (textual) form that could be transmitted across a network and deserialized back into objects at the other end.

Client / server communication started with several proprietary protocols that handled the deconstruction and reconstruction of object before and after transmission between client and server. With SOAP for client server communication xml became a defacto protocol standard for the textual representation of objects. Javascript and the abundance of web clients using it brought the need for a more concise representation and led to Json.


问:
Software on Budget and on time?
We've all (almost all) have heard about the horror stories as well as perhaps studied about them.

Its easy to find stories of software that is over budget and late.

I wanted to hear from developers the opposite story:

Question:

Do you know, or have worked on a project that was on budget and on time?

What is the most valuable lesson you learned from it?

答:
The first time I worked on an agile like project (Agile wasn't a term used then).  We learned that working daily with the client and prototyping ideas (either screenshots or business workflows) that the users could actually play with kept the project focussed, fun and in the end delivered exactly what the client wanted, on time and on budget.

It helped that the client were really focussed on their vision and that I was blessed with a pretty talented team that worked really hard during the working day and were able to socialise/bond afterwards as well.

ContentLicense: CC BY-SA 2.5

Title: Software on Budget and on time?


问:
If we close browser window without getting logout, what will happen when we provide same URL in the browser?
A few days ago, I appeared in an interview in a software company for .net developer. There I was asked the following question:

If we close browser window without getting logout, what will happen when
  we provide same URL in the browser?

My answer was that user will be able to view the home page with login details instead of being prompted to provide username and password as session of the user has not ended. Login information will actually be retrieved from cookies. But it depends upon the logic we have implemented for Login.

But the interviewer didn't seem be satisfied with my answer and didn't accept my answer. I am wondering what might be answer of this question. So, I need your kind guidance regarding correct answers. So please explain what I was supposed to reply.

答:
I think there are five scenarios:

1- The meaning of browser window may be the tab of the browser and user will not lost session. Therefore if he redirects to url there will be no login screen.

2- Developer can keep a flag in database and information from user (ip,browser type, browser fingerprinting, and so on) and can directly authenticate user.

3- The meaning of browser window may be whole browser itself. And if developer did not used cookies user wil not be authenticated.

4- Developer can use cookies and user will be authenticated directly if he even closes the computer.

Lastly, a theory but i am not sure of it. Server kills session by considering users actions. So if user can close and reopen browser so that fast that browser did not stop at background  services (etcs windows services) user can be authenticated.


问:
Modeling objects as functions
I want to model simple objects as functions, to see where the pure functional approach gets me. Let's say my object is a person. There is some function that returns me a new person, but instead of just some data structure, it returns me a function that represents the person. I'm having difficulties to see what this function should exactly look like, because I mostly associate data/state with a person but not any function. So if I call this person, which is a function now, what input should it take and what should it return?

If I look at the lambda calculus and some examples of how to model numbers, 0 is just the identity function. 1 is a function that takes another function and a value as input and returns the argument function applied to the value. 2 applies the function twice, etc.

So should the implementation of a person be a function that takes another function as input and applies it to the person, returning its output? So it's actually just a container for the person's data allowing other functions to operate on it.

May be it makes no sense to think about this without knowing exactly what a persons consists of. In a most simple case a person could be just a name. A briefly tried to outline this in Clojure:

```<code>(defn new-person [firstname lastname] (fn [f] (f firstname lastname)))
(defn get-firstname [person] (person (fn [x y] x)))
(def p (new-person "Maja" "Abel"))
(get-firstname p)
"Maja"
</code>```

Then again the names are strings and not very functional ...

Hope this makes some sense, glad if anybody has some thoughts on it!

答:
We can implement numerics as pure functions – but we don't actually do so for performance reasons. We can model a cons cell (and thus arbitrary lists) through pure functions, but we don't usually do that. Again, for performance reasons. And if we can model numbers and lists, we can model arbitrary strings or other things.

However, it might be useful to think about that cons cell/a pair for a moment.

A cons constructor takes two elements and returns something. The car function somehow accesses the first element in this something, whereas the cdr accesses the second entry. Here is one implementation in JavaScript:

function cons(x, y) {
  return function (gimme_first) {
    if (gimme_first) return x;
    return y;
  };
}

function car(cell) {
  return cell(true);
}

function cdr(cell) {
  return cell(false);
}
```

<p>So essentially what we did was return a closure over the state. We can access the state by applying the closure to a specific identifier.</p>

<p>We can easily extend this to arbitrary objects: Our constructor sets up some contents of the object, and returns a closure over it. This closure can be applied to a field name to return a value or a method (which also closes over the object's data):</p>

<pre class="lang-js prettyprint-override"><code>function Person(firstname, lastname) {
  // set up the methods as closure over our data
  // they could also take parameters if you'd like
  var get_firstname = function() { return firstname; };
  var get_lastname  = function() { return lastname;  };
  var get_fullname  = function() { return firstname + " " + lastname; };

  // set up the dispatcher
  return function(method) {
    if ("get-firstname" == method) return get_firstname;
    if ("get-lastname"  == method) return get_lastname;
    if ("get-fullname"  == method) return get_fullname;
    throw "Unknown method name " + method;
  }
}
</code>```

Now we can instantiate multiple objects:

var maja = Person("Maja", "Abel");
var freddy = Person("Freddy", "Smith");
maja("get-firstname")(); // Maja
freddy("get-lastname")(); // Smith
```

<p>How does inheritance work? Our constructor defers to another constructor, and our dispatcher passes control to the parent:</p>

<pre class="lang-js prettyprint-override"><code>function Employee(firstname, lastname, department) {
  // set up the parent object
  var parent = Person(firstname, lastname);
  // override a method
  var get_fullname = function() {
    return parent("get-fullname")() + " (from " + department + ")";
  };

  // set up the dispatcher:
  return function (method) {
    if ("get-fullname" == method) return get_fullname;
    return parent(method); // method lookup continues here
  };
}
</code>```

Etc.

This is actually quite similar to how JavaScript handles object orientation anyway: The dispatcher is usually a dictionary (called "object" anyway) which is more efficient than our functions, and object state is communicated via the implicit this parameter instead of closures.

Title: Modeling objects as functions

Body:
We can implement numerics as pure functions – but we don't actually do so for performance reasons. We can model a cons cell (and thus arbitrary lists) through pure functions, but we don't usually do that. Again, for performance reasons. And if we can model numbers and lists, we can model arbitrary strings or other things.

However, it might be useful to think about that cons cell/a pair for a moment.

A cons constructor takes two elements and returns something. The car function somehow accesses the first element in this something, whereas the cdr accesses the second entry. Here is one implementation in JavaScript:

function cons(x, y) {
  return function (gimme_first) {
    if (gimme_first) return x;
    return y;
  };
}

function car(cell) {
  return cell(true);
}

function cdr(cell) {
  return cell(false);
}

So essentially what we did was return a closure over the state. We can access the state by applying the closure to a specific identifier.

We can easily extend this to arbitrary objects: Our constructor sets up some contents of the object, and returns a closure over it. This closure can be applied to a field name to return a value or a method (which also closes over the object's data):

function Person(firstname, lastname) {
  // set up the methods as closure over our data
  // they could also take parameters if you'd like
  var get_firstname = function() { return firstname; };
  var get_lastname  = function() { return lastname;  };
  var get_fullname  = function() { return firstname + " " + lastname; };

  // set up the dispatcher
  return function(method) {
    if ("get-firstname" == method) return get_firstname;
    if ("get-lastname"  == method) return get_lastname;
    if ("get-fullname"  == method) return get_fullname;
    throw "Unknown method name " + method;
  }
}

Now we can instantiate multiple objects:

var maja = Person("Maja", "Abel");
var freddy = Person("Freddy", "Smith");
maja("get-firstname")(); // Maja
freddy("get-lastname")(); // Smith

How does inheritance work? Our constructor defers to another constructor, and our dispatcher passes control to the parent:

function Employee(firstname, lastname, department) {
  // set up the parent object
  var parent = Person(firstname, lastname);
  // override a method
  var get_fullname = function() {
    return parent("get-fullname")() + " (from " + department + ")";
  };

  // set up the dispatcher:
  return function (method) {
    if ("get-fullname" == method) return get_fullname;
    return parent(method); // method lookup continues here
  };
}

Etc.

This is actually quite similar to how JavaScript handles object orientation anyway: The dispatcher is usually a dictionary (called "object" anyway) which is more efficient than our functions, and object state is communicated via the implicit this parameter instead of closures.


问:
Learning Zend Framework 1 or 2?
I have programmed for a few years in php and now I'm going to learn zend framwork.
Zend is very popular and there are a lot of tutorials, books and documentation out there. But I saw in the last months that there is a second version of Zend, but it's not so used and popular, not yet.

I think it is better to start with a new version, but I don't know what to do now, as when I see job offers many people require the first version.
Which version do you suggest me?

答: To update the status on here, there is no point learning Zend Framework 1 now. It is End of Life and ZF2 is mature enough for all uses.</p>

Title: Learning Zend Framework 1 or 2?


问:
Any tips to learn how to program with severe ADHD?
I have a difficult time trying to learn how to program from straight text-books. Video training seems to work well for me in my past experiences with PHP. I am trying my hardest to stay focussed and push through. Specifically I am looking to start indie game development.

Over the last two weeks I have been trying to pick the "right" language and framework to develop with. I started going through Python, but I am not really enjoying the language so far. I am constantly looking through this website to compare this language to that, and keep getting distracted.

Aside from all of this, is it possible to become a programmer when you have trouble focussing? Has anyone been through this that can recommend some advice?

答:
I was diagnosed (at around age 9) with ADD. That was 26 years ago and "ADHD" seems to be the more prominent diagnosis these days.

You've probably found two things to be quite true:

It is very difficult for you to become engrossed in something that you don't find stimulating

It is very difficult for you to disengage from something that you DO find stimulating

Modern medicine wants us to take all kinds of stimulants (It's amazing what any hydrochloride will do to boost attention span), but I discontinued Ritalin (and others) within a year of starting them. The side effects on my mood, sleep cycle and the few social skills that I had was just too much to deal with.

This means, your criteria should be "What grabs me?" vs "What does everyone else think the right tool would be?".

Additionally, I think you might be ignoring some low hanging and language agnostic fruit. Have you come up with an idea for a game? Have you thought of how (in meta terms) the mechanics of it might be implemented? From my own experience, I find it much easier to conduct research when the criteria is quite narrow. Finding the solution to a specific problem is much easier than tackling a question that almost always entails answers that start with "that depends".

I also agree with others. Stay off this site for a while. What you are doing now is trying to convince yourself that you are working to a solution by soliciting advice. You are basically trying to study in an amusement park; that isn't going to work.

Incidentally, have you looked at C or C++ with Lua?


问:
How should developers go about managing complex plural words with ActiveRecord?
I'm playing with pluralize at the command line, and it's beginning to scare me.

Multiples of leaf is leafs (not leaves)
Multiples of cactus is cactus- not cacti, or even cactuses. Radius becomes radius instead of radii

Yet it correctly gets women, octopi, knives, and errata (the finer things in life).

As I understand it, ActiveRecord uses the same pluralize method that I'm using. And from my tests, it seems that if made enough tables without thinking, you would eventually run into a problem where you couldn't locate the proper table because you were expecting the plural to be different.

Is the conventional recommendation to just test all plurals in the command line, and make a note of what the table will be called? Or do most developers just label something as uncountable when it gets fuzzy?

Side note- no ActiveRecord tag??

答:
Simply add new inflection rules as needed</p>

```<code>ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'cactus', 'cacti'
end
</code>```

Body:
Simply add new inflection rules as needed

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'cactus', 'cacti'
end


问:
Is eventual consistency a wrong solution for e-commerce applications?
I'm reading about eventual consistency in couchDB. I'm somewhat confused by the term and its consequences on an application.

Let's say I'm building a distributed e-commerce website where monetary transactions are critical. There could be online auctions running and people bidding on them in real time.
Will using a eventual consistent DB such as couchDB be a wrong solution? Should I favor a more consistent solution such as a relational database?

Is couchDB suitable for something non critical such as a social network where one wouldn't mind if his news feed isn't up to date or when comments on his posts are somewhat delayed by few seconds?

Update

I'm talking about building a distributed system. I think in case of a single server nothing of this will matter.

答:
The eventual consistency part has to do with distributed systems-- that is, when there is more than one copy of the data and it needs to be consistent. It's basically the difference between synchronous and asynchronous replication.

So, it's not an issue if you have a single server. It's also not an issue if your system (Couch) has a synchronous mode of operation.

There's also no guarantee that conventional databases wouldn't succumb to this problem (think MySQL replication where slaves are lagging behind the master).

So the answer to your question is:  it depends.


问:
Verify 0 or 2+ sub sections in a section
There is a rule in writing: When you break a section into subsections, typically it should have more than one subsection. This goes back to the old high school composition rules: if you have an A. section you also need a B. section.

To check a chapter of a book I'm writing in LaTeX I do this:

$ egrep -h '^\\(chapter|(sub)*section)\**{' CHAPTERFILE.tex | sed -e 's/\*{/{/g'
```

<pre class="lang-latex prettyprint-override"><code>\chapter{My Chapter}
\section{Topic}
\subsection{Subtopic}
\subsection{Another Subtopic}
\subsection{Subtopic the Third}
\section{More}
\subsection{More more}
\subsection{Less is more}
\section{Odyssey}
\subsection{Marge and Homer}
\subsubsection{Bart}
\subsubsection{Lisa}
\subsubsection{Maggie}
\subsection{Example}
\section{Lore}
\section{Data}
</code>```

What is an efficient algorithm to verify the rule has been obeyed?  This rule goes for sub sections in a section, subsub sections in a subsection, and so on. (Though in my case there are no subsubsub sections)

Thanks to Bart's advice, here is the code I created.  It is hacky in places but it is simple and found bugs in my LaTeX files:

#!/usr/bin/env python

import sys
import fileinput

TOKENS = [
    ['\chapter', 0],
    ['\section', 1],
    ['\subsection', 2],
    ['\subsubsection', 3],
    ['\subsubsubsection', 4],
    ]

def getlevel(line):
  """Report the line's level (number of subsections)."""
  for token, level in TOKENS:
    if line.startswith(token):
      return level
  raise Exception()

def store(lst, level, value):
  """Store value in the level'th position."""
  while len(lst) < level:
    lst.append('EMPTY')
  return lst[:level] + [value]

def segments():
  """Read the input text, yield lists of segments."""
  path = []
  last_level = 0
  for line in fileinput.input():
    value = line[line.index('{') + 1 : line.index('}')]
    path = store(path, getlevel(line), value)
    yield path

def get_tree(segs):
  """Build a tree out of segment lists returned by generator segs"""
  tree = {}
  for s in segs():
    t = tree
    for i in s:
      t = t.setdefault(i, {})
  return tree

def audit(t):
  """Audit: Leafs are ok, nodes are ok if they have >1 children."""
  error = False
  for k, v in t.items():
    if audit(v):
      error = True
    if len(v) == 1:
      print 'ERROR: part with only one subpart: %s' % (k, )
      error = True
  return error

def main():
  tree = get_tree(segments)
  if audit(tree):
    return 1

if __name__ == '__main__':
  sys.exit(main())
```

答:
What you describe is a tree structure where each non-leaf node has at least two children. As leaf nodes don't have any children (by definition), once you have built your tree, go over all the nodes and verify that none of them have only a single child.

To build your tree, you can use the structure of the LaTeX sectioning commands by counting the number of occurrences of sub in the sectioning command to determine on which level in the tree it belongs.


问:
What is an algorithmic programming language?
"... You need to understand the core language: is it algorithmic, functional, object-oriented? ..." - Effective Java, Joshua Bloch, 2ndEd. 2008. Foreword, p xiii

Functional: Lisp, OO: Java, but what is ( would Bloch mean by ) an algorithmic programming language?

答: Most programming languages are algorithmic, like OO, functional, imperative and all that. The only type of languages I can think of that could be said being non-algorithmic are the reactive languages. But even the reactive languages are compiled to the algorithmic machine languages that is simulated by the reactive processor hardware, so under the hood even reactive languages are in fact algorithmic. The only way to really get away from algorithmic programming is to use processors with reactive machine language. They should be very common in the future.</p>


答:
You can get two out of the three from this list correct before the work starts:

Budget

Schedule

Feature Set

To get the missing var, you have to start the process and measure progress based on the missing data.

If you want to be on budget and on time, you have to be working on the assumption that the feature set must be flexible. Agile methodologies happen to make this same assumption.

Title: Software on Budget and on time?

Body:
We've all (almost all) have heard about the horror stories as well as perhaps studied about them.

Its easy to find stories of software that is over budget and late.

I wanted to hear from developers the opposite story:

Question:

Do you know, or have worked on a project that was on budget and on time?

What is the most valuable lesson you learned from it?


问:
What is the most effective grammar to use for issue titles?
When choosing a title for a new issue, there are several grammatical options to choose from. Here are four different options for an example issue I just made up:

Descriptive: "Newlines are not stripped when multi-line headers are parsed"

Imperative - negative: "Avoid leaving newlines when parsing multi-line headers"

Imperative - context first: "Fix parsing of multi-line headers: strip newlines"

Imperative - desired action first: "Strip newlines when parsing multi-line headers"

At my workplace the issue titles alternate between all of these formats, but I keep thinking it's better to pick a convention and stick to it.

Which option (from the above, or a different one) is the preferred one, i.e. the one that will minimize the effort of developers reading these issues?

Edit: as noted in the comments, different issue types may warrant a different choice of grammar, where an especially important distinction is between bugs and new work. To make the question more specific, let's say we choose, as msell offers in his answer, the descriptive option. Now let's look at a suggestion to improve an existing feature:

"Add city information to geolocation"

If we stick to the descriptive grammar, we should replace that title with

"City information missing from geolocation"

However, this seems less clear, since the lack of city information is not a bug, it is the expected behavior. The reporter is merely suggesting to improve that behavior. So it seems the imperative option is the way to go with that issue.

Let's look now at an entirely new feature. Consider these options:

"No ability to export report to XML"

"Add ability to export report to XML"

"Export report to XML"

Describing the current behavior seems even more ridiculous here, but the imperative option doesn't look so good too. The third option simply describes the new feature itself, which might be the way to go here, assuming the issue has meta-data that indicates this is a “new feature” issue.

So what's more important - sticking to one convention, or matching the grammar to the issue?

Where would you draw the line between a descriptive title and an imperative title?

When would you describe the current behavior and when the desired behavior?

答:
Always why, rather than what. From the perspective of the user, what is the actual problem you're trying to solve? For example,

Search doesn't work if looking for a string that spans two lines.

It's impossible to tell from any of your examples. The problem being that you can't prioritise tasks, unless you have someone handy who knows why those changes need to happen.

If, when creating an issue, you have an idea what the solution is, write that into the comment instead. It's no effort for a developer to read the whole issue but, when you're prioritising, you need to look at that issue in the context of other issues. So it's important to have useful information to that end.


问:
"A well designed system is a testable system"
I'm thinking about something I've read in a book: "A well designed system is a testable system" and I'm wondering why it is so.

Certainly, a system that is much tested is probably well designed. Build from the ground up on test-first principles and assuming basic competence, it is hard to imagine a very bad design.

But the statement reverses the idea: that a well designed system is testable.
Why? Is it because good tests are small and simple by default, so making good tests on a bad design (where bad design usually means large and complex classes) is more difficult? Or that it is hard to, say, test a single aspect of a class in isolation when the class in question is a god class?

答:
Your goal is to release software with a certain level of quality. Assuming you cannot write every single line of code precisely free of bugs or introduce bugs somewhere in the interaction between those lines of code, how do you verify that you've achieved that level of quality? What about other team members, who may not be aware of all the implications of their changes, modifying the software you wrote.  Or you yourself making changes 6-12 months after you haven't seen the code?  You need to be able to test your software initially and with every change you make to it, and changes will always happen in anything but the most trivial projects.

If you consider act of design as the act of planning and defining structure for your software, then to produce testable software, you need to have good execution on planning and defining that structure.  So that kind of follows that one attribute of good design is a software that you can test.

Keep in mind when most say "ability to test", it is not a binary yes or no, but a linear scale of how much effort it takes to get to certain level of certainty (95%, 99%, almost never a 100%) that your software works.  So on one end of the spectrum, you setup a test and you have N people run your piece of code for a full week through every possible scenario, maybe do stress testing to flush out race conditions.  On the other end of the spectrum, you run a set of unit tests that you already produced as part of your TDD process, and within 10 seconds, you get 287 OKs and no failures.


问:
How do programs generally get information from the OS?
In many languages there are libraries, either built into the language itself or built separately outside of the language, which allow information to be taken from the operating system at some level. Examples are metadata about a file, current memory usage and the OS version itself.

How is this information generally accessed?

At the moment the only way I can see it working is through executing command line functions and parsing the answer.

For example, to list the files in a current directory on Linux your application would execute 'ls' at the specified directory and then parse the output to produce the required format. Is this the only way?

This example assumes you are using no libraries which do it for you of course (or maybe you're building a library for this purpose.

答:
Every operating system offers so-called application programming interfaces (APIs) that allow a user program to access such information. The command line commands effectively use these APIs -- e.g. ls does just that.

Wikipedia has a list of operating system APIs.


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

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

My Position

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

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

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

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

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

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

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

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

My Question

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

My Conclusion

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

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

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

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

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

答:
if you want to understand how the machine works, and not just the virtual machine on which your high-level language depends, then Assembly will teach this to you

if you have no reason to care - and most programmers really don't these days - then don't worry about it.

it will improve your foundation, but it probably won't improve your web apps


问:
A programmer as project manager or non-programmer?
We are a team of programmers and are employing a new person who will be a project manager only. Our project are only programming ones and we are not sure how to decide who will be the best for project manager.

Shall we find a senior programmer from our programming field?

Or we must find a regular guy (economics or management studies) who never coded in his life?

EDIT

A project manager will_

Create tasks for developers

Monitor that our ticket workflow is respected

Warn developers is they cross estimated work time

Manage weekly finance timesheets

Help client and reply to his questions

Set meetings between client and developers (internet meetings)

And similar things.

Now, when I wrote this I see that there are no IT tasks in here. But what about simple questions the clients ask and which an educated It person will be able to reply? we obviously cannot bother programmers for this all the time. this is the main reason whay we are in doubt.

答:
What would be the role of the manager?

First case: team and project manager

If he would handle the team and organize how the project is done, then indeed, without technical background, such manager might become a real treat which will lead to project failure. For this task, you need a person who understands:

How developers are working and thinking by comparison to other jobs:

What are their motivations?

Why new features should be in production as soon as possible?

Why comparing the raw productivity of two developers is so difficult?

What are the real skills (such as communication skills) required from a developer?

etc.

How project is managed, especially:

What is technical debt and why should it be taken in account?

What are the techniques used for risk mitigation in software development projects?

What iterative development brings to the project?

Why tasks, such as refactoring, which don't deliver immediately visible features are often much more important than shipping just another feature?

Why it's ok to go back and forth, instead of moving towards a goal?

Why “solve this bug ASAP”/“deliver this feature ASAP” is crazy in practically every situation?

What is the difference between a prototype and a solid production code?

etc.

What are the points which should be in focus from the beginning. While a team of developers with minimum experience will not forget to do unit tests or regular refactoring, they may be too focused on their own job.

Sometimes, they forget about UX, security, deployment or end-user documentation, simply because it's not their job, and when the product appears unusable, insecure, a nightmare for system administrators or lacking basic documentation, it's often too late.

It belongs to the manager to determine all the tasks required for a successful project, and to find the resources needed for their accomplishment. Having a bunch of programmers is not enough.

Second case: an intermediary between IT and non-technical world

If, instead, his task is to ensure good relations between the technical stuff and non-technical stakeholders, then a person who studied management, but has only light understanding of technical stuff may be ok.

Even then, try to pick a person who understands the specificity of software development and who have already a professional experience of several project failures: it would be a disaster to hire someone who would treat developers as “the guys who play with computers and are never able to get the stuff done”.

Let's consider the points you included in your edit:

Create tasks for developers

What does that mean? Do you mean user stories? As is, there is no way to answer without knowing how those tasks are created in your team.

Monitor that our ticket workflow is respected

If it's not, what would happen?

The good answer is: “Retrospective will be used to identify what went wrong, in order to solve the previous issues and adjust the schedules to the speed of the team.” This requires technical background.

The bad answer is: “The project manager would scream to team members, and tell that either they start programming faster, or somebody among them will be fired.” This doesn't require any specific skill.

Warn developers is they cross estimated work time

See the previous points.

Manage weekly finance timesheets

No IT-related skills required here. But the manager should be aware of the specificity of software development, including the fact that it's often impossible to predict how much a feature would cost to implement.

Help client and reply to his questions

Questions such as “When do we have our next meeting?” don't require technical background. Questions such as “Is it possible to still use the synchronization mechanism we talked about the last week in a context of frequent connection loss?” requires to understand the inner workings of the project.

Set meetings between client and developers (internet meetings)

No technical skills needed here.


答:
Testability implies loose coupling. A system is significantly more testable if each of its components can be tested in isolation. This is only achievable if the coupling between each components is kept loose.

Loose coupling is an aspect of good design.

Body:
I'm thinking about something I've read in a book: "A well designed system is a testable system" and I'm wondering why it is so.

Certainly, a system that is much tested is probably well designed. Build from the ground up on test-first principles and assuming basic competence, it is hard to imagine a very bad design.

But the statement reverses the idea: that a well designed system is testable.
Why? Is it because good tests are small and simple by default, so making good tests on a bad design (where bad design usually means large and complex classes) is more difficult? Or that it is hard to, say, test a single aspect of a class in isolation when the class in question is a god class?


答:
I think that sentence asserts definition of "well designed". If you say it as "For system to be well designed it has to be testable." then it starts making sense.

Testability is good property of the system, it is much cheaper to be able to create and run automated tests than manual tests.

Title: "A well designed system is a testable system"


答:
Another perspective:

One characteristic of a "well-designed" software system, is that it will generally be built up from orthogonal, composable parts. Each part should be conceptually "pure" -- it should deal with one and only one "concern" or aspect of the problem to be solved.

Writing programs like this requires a lot of thought to find the right breakdown. But when you do, there are many benefits -- testability is usually one of them.


问:
How should I introduce a new programmer to a complex project?
We have a pretty complex project with 100 or so classes, multiple custom elements, etc. We have a new senior programmer who will work on this project.

How should we approach the task of introducing the senior programmer to the project? How can we make sure the programmer does not break some other feature while fixing the current one? I have seen too many similar situation.s Sometimes, new bugs are not noticed immediately -- but pop up months later.

Shall I direct the programmer by first giving them smaller tasks and waiting for them to finish them? Or there is a better solution?

I am asking this because I don't want to become micromanager but I also don't want to have nasty bugs created because of my bad approach to the new programmer.

答:
We have a pretty complex project with 100 or so classes, multiple custom elements, etc. We got a new senior who will work on this project.

This actually a small project, unless the classes have been allowed to grow to thousands of lines of code.  A project of 100 classes should be easily managed by one or two developers.

How can we make sure he does not break some other feature while fixing the current one?

After every change, you should run automated tests to largely ensure that no features were broken.  However, I get the impression that you do not have such tests.  In that case bugs are almost inevitable, and they will occur more and more frequently as the size of the code increases.  You can mitigate this somewhat by carefully reviewing code before it goes into production.

I have seen too many similar situation and such bugs are not noticed immediately, but sometimes months later.

This is a result of inadequate testing.  Errors in programming are inevitable.  All we can do is reduce the frequency.  The first line of defense is automated tests.

Shall I direct him by first giving him smaller tasks and wait him finish them?

You should have him work on tasks with another experienced developer.  Perhaps they will both learn something.

... I also don't want to have nasty bugs created because of my bad approach to new guy.

Automated tests will largely prevent this.  Whenever a bug is discovered, create a test that fails.  Then fix the bug so that the test passes.


问:
Can you change a license once you pick one?
I am working on a product that I don't feel is completely ready but I have a set of users that are very interested in using it now as "alpha" testers.  I would like to give them the product now for free as "alpha" testers, but I would like to later license the software.

Is this possible?  Can anyone point me to any links/books/articles/etc?

Thanks.

EDIT:  Due to the lack of my clarity and the reponses to the question I thought I should add this statement.

I haven't decided if I am going to close-source or open-source this project yet. The user base that wants to get their hands on it now has kind of surprised me and I was concerned about what my options are as far as being able to give it to them now as open-source and later change to closed-source, or even vice versa.

Thanks to everyone who has answered and commented.  I appreciate it the insights.

答:
This is a tricky question, which depends on how unique the software is, and whether you expect outside people to be able to make a lot of significant contributions.

If people only send you trivial changes to your software, then you (as the original author) would remain as the only person who would hold the copyright rights to the software, and, as such, you can close it down at any time you wish.  However, realise that if you've released prior version of the software under a standard open-source licence, then anyone would be able to fork your software from such old copy, and thus, chances are, you might always have an open-source competitor to your proprietary software package.  This is actually exactly what has happened to Tatu Ylonen, the original author of SSH, who has since been the founder and CTO of ssh.com, having not much to do with OpenBSD and OpenSSH, even though they distribute files with his copyright.  (Although Tatu Ylonen's main publicly known regret is not related to copyright, but rather that he lost the marks "ssh" and "secure shell" into generic use, losing his trademarks.)

So, what if people do send you significant changes to your software, which would be covered under copyright, and which you'd want to integrate into your source tree?  You could set up one of those legal agreements, whereby contributors would assign their copyright to you, thus, legally, you'll still be the only "author" of the software.  I come from the FreeBSD/OpenBSD camp, and in our view, copyright assignment is generally considered bad taste.  FSF is pretty infamous for their copyright assignment on most of their software; NetBSD has it as an option to their members (which allowed The NetBSD Foundation to remove two clauses from their licence in all files where none of the individuals claimed an individual copyright to); many commercial companies have all sorts of contributor agreements that do all kinds of assignment.  Where does Linus Torvalds stand?  Linus also dislikes the contributor agreements, and, as you may guess, Lunux kernel doesn't have any, apart from GPLv2 itself.

So, what if you do accept copyrighted changes into your tree, without copyright assignment?  This is where your original choice of licence comes into play.  If you choose GPL, and thus the contributors will licence their own code to you under GPL, too, then you're pretty much stuck with GPL, and will always have to release the source code to any subsequent commercial product (but so will all of your competitors).  If you choose a BSD/ISC/OpenBSD licence, then you could close the source to add extra pay features at any time you wish, without having to release any of the source changes (but you're also giving the same right to your competitors).

Of course, if years down the line you decide that, in retrospect, you would have wished for your software to be under a different licence, you could always try contacting all of your past contributors to re-license their changes under your new licence.  This is a very painful and long project -- what if someone cannot be contacted?  Mozilla and VLC did such relicensing in the past; they've certainly must have enjoyed the benefits of their new licence, but I highly doubt they've enjoyed the years-long process.

Anyhow, regardless whether you choose to go GPL or BSD, having an open-source version of your software would always have a great deal of benefits, proven by many successful commercial companies that revolve around writing and releasing open-source software.


答:
Yep, I've seen it happen.

Key elements:

1) Well defined requirements, clearly agreed, with a solid change control process.

2) Developers involved in the estimates, with no pressure on them to produce estimates which were what the client wanted to hear, just what they really thought would be needed to complete the work properly

3) Estimates that also took account of risks and uncertainties

4) Facilitate early feedback from the client - we've provided videos, demos (hands on and hands off depending on stability) as early as possible

5) A stable team whose availability has been realistically figured into the schedule (for instance if they spend a day a week doing support and admin, then they're only expected to complete 4 days a week work on the project)

It's not rocket science but removing the commercial pressures and, critically, getting the requirements clear and controlling them is challenging (and where things normally fall down).

Title: Software on Budget and on time?


问:
Martin Fowler's Refactoring book: switch statement is using other object's data, why is that bad ? A deeper explanation is sought for.
In the code sample below the Rental object is using Movie's fields to do a switch statement. Martin says : this is a bad idea but he does not give any deeper explanation as to why ?

Of course, you can say that this means a lot of coupling between Movie and Rental, or that Movie is badly encapsulated but those are just (almost meaningless) words, again, they don't explain the why? They don't go to the root of the question, so to say. They don't provide much understanding.

What I would like to know if there is a deeper, more general design principle why having a switch on Rental is a bad idea ?

In other words, how does Martin knows that the switch statement is on the wrong object ? Where does he get this insight from ? What is his thought process ?

答:
I can only agree with that if PriceCode is another object. In this case, it would be more appropriate to make the switch like PriceCode.REGULAR and not Movie.REGULAR for example. So Martin would be talking about Movie having constants defined on PriceCode, which looks like bad design.

Or maybe he's idea is to think on classes with very low coupling, for example, you want Rental to work with another class compatible with Movie but that is something else (for example, you want to rent a CD instead of a Movie).

Probably he's talking about the second option.

OwnerDisplayName: jhegedus

OwnerDisplayName: Leo


答:
There are two issues:

Since the priceCode is part of the Movie class, the switch should likely be located within the Movie class. That localizes the work in the switch to the class which define what a priceCode is. If the Movie class were to decide to return different codes, then it is in the best position to modify the switch.

The switch is probably not the only thing in the Movie class which depends on the priceCode. This would suggest creating derived classes of the Movie class, one per priceCode. Each would have its own overridden version of getCharge. This overridden method would not only have the separate algorithms which are currently in case statements, it could also depend on data that is specific to the individual derived classes.

Title: Martin Fowler's Refactoring book: switch statement is using other object's data, why is that bad ? A deeper explanation is sought for.

Body:
In the code sample below the Rental object is using Movie's fields to do a switch statement. Martin says : this is a bad idea but he does not give any deeper explanation as to why ?

Of course, you can say that this means a lot of coupling between Movie and Rental, or that Movie is badly encapsulated but those are just (almost meaningless) words, again, they don't explain the why? They don't go to the root of the question, so to say. They don't provide much understanding.

What I would like to know if there is a deeper, more general design principle why having a switch on Rental is a bad idea ?

In other words, how does Martin knows that the switch statement is on the wrong object ? Where does he get this insight from ? What is his thought process ?

OwnerDisplayName: John Saunders


问:
How should a senior programmer monitor another senior programmer?
I'm working with a new senior programmer who has almost the same amount of experience as me. He his own project to work on -- but I have to make sure he does not mess things up.

Now, how can I monitor him since he's not junior?

Do I examine his code? Cons of this are that I am not as deep into project as himself so it's time consuming for me (have my own project besides this).

Do I only do QA from the perspective of another senior?

Any advise here is appreciated. I was recently in the same situation where I relied that another senior will handle all tickets properly, and then it took me 3 weeks to fix his oversights. So I do not want to be in the same situation again.

答:
I would recommend pair programming. You would pair program with him as long until you are sure he got everything he needs. Ultimately you can not check everything and can only trust that he does things proper in the end. Because, as you said, if you check all his work you are stuck yourself.

Also pair programming is/should be common and it would be no offence to offer/demand it in the beginning. You do not want to offend the new guy. Also he would learn about your work which helps also you in case of absence or need of a second opinion.

Problem is that as you say, you are working separately. Maybe this is not a good way of organization anyway because if you want to monitor him you need to work closer with him anyway. So if this is not possible you could do 2 hours a day for the beginning maybe?


答:
What happens when Movie has a new type added to it like Movie.DISCOUNT?

Of course, you can say that this means a lot of coupling between Movie and Rental, or that Movie is badly encapsulated but those are just (almost meaningless) words, again,

They're deeply meaningful words. They mean that when you change Movie, you now get to change Rental too since they're tightly coupled. Worse yet, in a language like Java there's nothing to tell you that this switch statement needs to be modified (though most IDEs do, to be fair). So if you don't modify the switch statement, you now have a bug that's giving people free movie rentals.

The primary focus of program design (and by extension refactoring) is optimizing code around the question "what happens when this changes?". That's the thought process that will help you understand many of the motivations in the book.


答:
I think you can take two approaches, one could be giving the new person a piece of work where something a bit isolated would be developed (e.g. a new page/screen) this way the developer can explore the current project and check how some things were already done in the past.
While doing this piece of work he/she will also start taking some decisions related to the design of the new piece of work that he/she is working on. This can lead to questions and discussions that can be useful for the developer to get more understanding on the project and how things have been done. You can also make peer reviews on the work or do some pair programming at the beginning of the task.

Another approach can be to give small assignments related to support, like fixing small bugs. On this case I agree with kevin cline that automated can be extremely helpful to make sure that everything is still ok.

Title: How should I introduce a new programmer to a complex project?

Body:
We have a pretty complex project with 100 or so classes, multiple custom elements, etc. We have a new senior programmer who will work on this project.

How should we approach the task of introducing the senior programmer to the project? How can we make sure the programmer does not break some other feature while fixing the current one? I have seen too many similar situation.s Sometimes, new bugs are not noticed immediately -- but pop up months later.

Shall I direct the programmer by first giving them smaller tasks and waiting for them to finish them? Or there is a better solution?

I am asking this because I don't want to become micromanager but I also don't want to have nasty bugs created because of my bad approach to the new programmer.


答:
For starters, monitoring sounds not like an environment where trust is valued highly. Yet, that's the opposite of what a senior needs -- an environment where she or he is trusted (and expected) to do whatever is necessary to get the job done, in an appropriate manner, without instruction. I presume you want this guy to succeed, so I wouldn't take a "monitoring" approach.

Having said that, I would do this:

make yourself available -- let her know that she can ask you questions, even seniors need to clarify things, especially in the beginning.

don't expect her to know everything on the first day -- show her where to find information, even seniors need time to get to know a new system.

clarify rules -- let her know the rules, how the system or department is run, what to look out for, what expectations and no-gos are. Even seniors need to know these things.

involve the new guy -- include her on every meeting and discussion where she might benefit, and in particular those meetings that concern her areas of responsibility.

clarfify responsibilities, and practice hands off -- for any areas of responsibilities that were previously yours (or anyone else's), make sure decisions are taken by the new person, including the risk of failure.

agree objectives -- make sure the teams' expectations and your own are clarified. I say agree because it should be a process where you sit together, discuss priorities and then agree on the objectives to be reached. Remember the SMART rule -- any fair objective is Specific, Measureable, Achievable, Relevant and Time-bound.

review progress and praise achievement -- review progress and achievements regularly

Finally, whatever you do, always give direct, personal and timely feedback: If you see something that doesn't work the way it should, take him or her aside, explain what you observed, why you think its no good, how it should be. Be sure to be open for discussion, because new people tend to see things with a fresh perspective and might just have a good reason to do things differently than what is considered usual. Oh, and do give positive feedback, too, even seniors like getting some.

PS: "her" includes "him", just saying

Title: How should a senior programmer monitor another senior programmer?

Body:
I'm working with a new senior programmer who has almost the same amount of experience as me. He his own project to work on -- but I have to make sure he does not mess things up.

Now, how can I monitor him since he's not junior?

Do I examine his code? Cons of this are that I am not as deep into project as himself so it's time consuming for me (have my own project besides this).

Do I only do QA from the perspective of another senior?

Any advise here is appreciated. I was recently in the same situation where I relied that another senior will handle all tickets properly, and then it took me 3 weeks to fix his oversights. So I do not want to be in the same situation again.


问:
When is Singleton appropriate?
There is a widely accepted opinion that Singleton is an anti-pattern. As usual, there are always exceptions to the rule. Can you explain why Singleton is a bad choice in general and give an example of some valid use cases for it?</p>

答:
I agree that it is an anti-pattern. Why? Because it allows your code to lie about its dependencies, and you can't trust other programmers to not introduce mutable state in your previously immutable singletons.

A class might have a constructor that only takes a string, so you think it is instantiated in isolation and does not have side effects. However, silently, it is communicating with some sort of public, globabally available singleton object, so that whenever you instantiate the class, it contains different data. This is a big problem, not only for users of your API, but also for the testability of the code. To properly unit-test the code, you need to micro-manage and be aware of the global state in the singleton, to get consistent test results.

ContentLicense: CC BY-SA 4.0

Title: When is Singleton appropriate?


问:
Online vs Web - write once application
I have been asked to write an application (visual application) that can be run both online and locally.

This application contains a lot of external data (video, images and audio) files so the main issue I have is deploying this over the web.

I want to architect this so that I only have to write 1 system and not a separate code base for the online version.

What I and a colleague have come up with so far is;

Tomcat/Application server - for the code logic

HTML Pages for the delivery of the content

A number of small Silverlight Scenes depending on the page that is severed.

I have only got a few months so writing 2 sets of applications is not efficient for me.

Is this a scalable approach? Are there better ways to write/deploy this type of application?

答:
The basic approach is scalable.

Where you will run into issues is with Silverlight. MS goes back and forth about if they are still supporting it or not. It seems mostly not.

HTML5 with support for the Canvas object in the DOM mostly eliminates the need for Flash or Silverlight. It will run almost anywhere. And for those places where it doesn't (notably IE8 and below), you can shim your pages to include the additional functionality. The end user experience will be close to the same between all of the browsers, but not identical.

Pick a good framework for your needs. AngularJS and Backbone both are built toward business needs, not fancy graphics, so they would not be a good choice for the graphical side of your application. They both might be what you need for the standard I need a registration form, a place to pay form, etc. Either would be a good choice in that case.

A quick internet search turns up several canvas related frameworks. One in particular looks interesting: CAKE. It says:

CAKE is a JavaScript scene graph library for the HTML5 canvas tag. You
  could think of it as SVG sans the XML and not be too far off.

Title: Online vs Web - write once application


答:
TL;DR: Alternative Solution - Rotate Project Lead

At my work we rotate project lead as each project comes up.  Projects are just whatever set of work is needed to get to the next release, not tied to the actual codebase.  The lead is responsible for all due diligence required to make the project a success.  Not successfully developed, but successfully released and deployed.  This means the lead has to collaborate with operations, customers, other stakeholders and programmers.

Why do this?  I have found that this has a few benefits.  For a lead engineer:

once the business problem is well understood they are easily able to break down the tasks required to complete the project

they can often provide alternatives that are cheaper to develop, but satisfy the business need

they have a higher likelihood of knowing where the most risk lies (at least in development)

there is less chance of misunderstanding among the development team, and even among the larger technical team

for projects where there isn't significant cross team dependence or co-development, the projects often can started earlier and complete quicker.

familiarity with the codebase allows for more accurate planning and development, and understanding which things may cost a amount significant time which can then be communicated to the customer

I cannot emphasize how big a deal some of the points above have been for the various business I've worked at in the past that followed this model.

This places special requirements on the people that may become project lead.

They need to be able to see the bigger picture, and be able to shift between the micro and macro.

They need to be able to communicate with customers and other non-technical people.

They need to work well with others.

They need to understand how to break down a project in order to have other work on it to completion

They need to think about what is required for deployment and running the software.

They need to work with whomever will be running the software and collaborate with them throughout the project's lifetime.

Title: A programmer as project manager or non-programmer?

Body:
We are a team of programmers and are employing a new person who will be a project manager only. Our project are only programming ones and we are not sure how to decide who will be the best for project manager.

Shall we find a senior programmer from our programming field?

Or we must find a regular guy (economics or management studies) who never coded in his life?

EDIT

A project manager will_

Create tasks for developers

Monitor that our ticket workflow is respected

Warn developers is they cross estimated work time

Manage weekly finance timesheets

Help client and reply to his questions

Set meetings between client and developers (internet meetings)

And similar things.

Now, when I wrote this I see that there are no IT tasks in here. But what about simple questions the clients ask and which an educated It person will be able to reply? we obviously cannot bother programmers for this all the time. this is the main reason whay we are in doubt.


问:
Are optional parameters helpful or a hindrance to application maintenance?
As stated in the title, are optional parameters, such as those used in C# helpful or are they a hindrance to application maintenance and should be avoided as they can make the code harder to understand?</p>

答:
Optional parameters have, in my experience, been a good thing.  I have never found them confusing (at least no more confusing than the actual function), since I can always get the default values and know what's being called.

One use for them is when I have to add another parameter to a function that's already in general use, or at least in the public interface.  Without them, I'd have to redo the original function to call one that's got another argument, and that can get really old if I wind up adding arguments more than once.


答:
In the title I prefer describing the bug, not the fix. Also as opposed to pdr's answer, I focus on the actual bug, not what I was trying to achieve. There is plenty of space available in the detailed description for the expected behaviour, background information and even proposals on how to fix the bug.

To help me writing good titles for bugs, I try to come up with a description that sounds good in release notes. Consider the given examples:

Fixed bug #1001: Newlines are not stripped when multi-line headers are parsed

This sounds good.

Fixed bug #1001: Avoid leaving newlines when parsing multi-line headers

It is a little unclear if the bug is about leaving newlines or avoiding them.

Fixed bug #1001: Fix parsing of multi-line headers: strip newlines

While the bug in this format is clear, it sounds clumsy with the repetition of the word "fix" and usage of an additional colon.

Fixed bug #1001: Strip newlines when parsing multi-line headers

This has the same problem as the second example. It's unclear if the described line is the correct or incorrect behaviour.

Thus I prefer the first example "Descriptive".
A benefit of this approach is that less effort is needed when creating the release notes, as the information is already (mostly) in correct format. However even if release notes are not needed, this guideline still works well and produces bug titles that are easy to read and understand.

Title: What is the most effective grammar to use for issue titles?

Body:
When choosing a title for a new issue, there are several grammatical options to choose from. Here are four different options for an example issue I just made up:

Descriptive: "Newlines are not stripped when multi-line headers are parsed"

Imperative - negative: "Avoid leaving newlines when parsing multi-line headers"

Imperative - context first: "Fix parsing of multi-line headers: strip newlines"

Imperative - desired action first: "Strip newlines when parsing multi-line headers"

At my workplace the issue titles alternate between all of these formats, but I keep thinking it's better to pick a convention and stick to it.

Which option (from the above, or a different one) is the preferred one, i.e. the one that will minimize the effort of developers reading these issues?

Edit: as noted in the comments, different issue types may warrant a different choice of grammar, where an especially important distinction is between bugs and new work. To make the question more specific, let's say we choose, as msell offers in his answer, the descriptive option. Now let's look at a suggestion to improve an existing feature:

"Add city information to geolocation"

If we stick to the descriptive grammar, we should replace that title with

"City information missing from geolocation"

However, this seems less clear, since the lack of city information is not a bug, it is the expected behavior. The reporter is merely suggesting to improve that behavior. So it seems the imperative option is the way to go with that issue.

Let's look now at an entirely new feature. Consider these options:

"No ability to export report to XML"

"Add ability to export report to XML"

"Export report to XML"

Describing the current behavior seems even more ridiculous here, but the imperative option doesn't look so good too. The third option simply describes the new feature itself, which might be the way to go here, assuming the issue has meta-data that indicates this is a “new feature” issue.

So what's more important - sticking to one convention, or matching the grammar to the issue?

Where would you draw the line between a descriptive title and an imperative title?

When would you describe the current behavior and when the desired behavior?


问:
A pattern to "atomically" update a pair of objects
Is there a standard pattern in OOP to kind of "atomically" update a pair of objects, like a pair of bank accounts on a transaction?

I would like to have somehow a single public method exposed that does it all at once, but can only come up with ways of doing it by making two calls of public methods to update objects separately.

I am currently experimenting with Racket, but i would appreciate examples in any language, or a description of a standard pattern.

Here is an example of what i have experimented in Ruby (with which i am more comfortable than with Racket).  I am not concerned with locking here, just with class interface.

class Account
  def initialize(total)
    @total = total
  end

  def total
    @total
  end

  def transfer_to(another, sum:)
    change_total_by(-sum)
    another.change_total_by(sum)
  end

  protected

    def change_total_by(sum)
      @total += sum
    end

end

a = Account.new(10)
b = Account.new(20)
a.transfer_to(b, sum: 5)
print "New a.total = #{ a.total },\nnew b.total = #{ b.total }"
```

This works using protected instead of private.

答:
You can abstract the transaction as an object in itself, which then provides a single interface to manage the transaction and its participants. First property of transactions, Atomicity satisfies your requirement of atomicity/single point.

I.e.  something like this:

```<code>public class Transaction {
    ...
    private Account _source;
    private Account _destination;

    public void Commit() {
        lock( _globalAccountWriteLock )
        lock( _source )
        lock( _destination )
        lock( this ) {
            try {
                UpdateSource( _source );
                UpdateDestiantion( _destination );
            }
            catch( Exception e ) {
                // Rollback
            }
        }
    }
</code>```

The important part is, you have to use respective locks for every access to these three objects for it to work.

Body:
You can abstract the transaction as an object in itself, which then provides a single interface to manage the transaction and its participants. First property of transactions, Atomicity satisfies your requirement of atomicity/single point.

I.e.  something like this:

public class Transaction {
    ...
    private Account _source;
    private Account _destination;

    public void Commit() {
        lock( _globalAccountWriteLock )
        lock( _source )
        lock( _destination )
        lock( this ) {
            try {
                UpdateSource( _source );
                UpdateDestiantion( _destination );
            }
            catch( Exception e ) {
                // Rollback
            }
        }
    }

The important part is, you have to use respective locks for every access to these three objects for it to work.


问:
What are and how do (data-) types work?

What is a "variable"/data type?

How does a compiler / interpreter handle types?

My specific concern has to do with the different types in lower and higher level languages. For instance in Python, as list is really flexible. You can just define it and put in at runtime whatever you want.

ints

floats

strings

sets

even other lists

Basically objects of any type (if I'm not mistaken).

So I imagine list to be a class written in C with really a lot of stuff in there, dynamic memory allocation and so on and so forth, to handle all this.

Is that right?

..and does that mean all those e. g. Python types are C classes?

Then what are types in C?

Are they "classes"?

..or somehow related to assembler code?

PS: I'm not looking for some precise illustrative hints and answers rather than for a wide exhaustive explanation. And: This questions are not related to "There are no variables in Python, but identifiers".

答:
Data types are a way to convey information about an object or variable in a computer program. The information provided by data types is

How much storage does an object of this type occupy

What sub-elements, if any, does such an object have and by what names can these sub-elements be accessed

What operations can be performed on an object of this type

There are two ways that types can be handled by a compiler/interpreter, statically and dynamically. How each type is handled depends on the definition of the programming language and the implementation of the compiler/interpreter.

With static types, the compiler (these types are mostly used in compiled languages) knows at any point in the program exactly which operations are valid for a given variable/object and, if you invoke an operation, which instructions to generate or which exact function to invoke. The runtime environment does not need any access to type information.

With dynamic types, the compiler/interpreter may roughly know what operations are valid for a given variable/object, but it may not know all the details. For example, the compiler knows that variable X is of type A or a sub-class of A, but it may not know exactly which sub-class. In this case, some type information must be accessed by the runtime environment to invoke the correct function of the correct sub-class.

In C, all types are static. All type information is handled by the compiler and there is no type information stored in the executables.

In Python, all types are defined as classes and they are in principle dynamic and it is likely that type information gets stored along with the actual data. This type information makes it possible to determine (at a later time) what exact kind of data was stored in a list.

An example of a language that uses both static and dynamic types would be C++. There, most types are handled statically, except for classes that contain virtual members. Those are handled dynamically.

Title: What are and how do (data-) types work?


答:
Instead of a public addAmount(amount) method, your class Account could have a public addAmountFrom(otherAccount, amount) method which automatically checks the other account and performs the counter-operation on it.

When each balance-change of a account must specify another account, you also automatically enforce the "no entry without counter-entry" rule of double-entry bookkeeping.

The counter-operation could be done through a private or protected method subtractAmountTo(this, amount). Most OOP languages allow private and protected methods to be called from objects of the same class. It should be private because the method assumes that the counter-entry is taken care off by the caller.

Title: A pattern to "atomically" update a pair of objects

Body:
Is there a standard pattern in OOP to kind of "atomically" update a pair of objects, like a pair of bank accounts on a transaction?

I would like to have somehow a single public method exposed that does it all at once, but can only come up with ways of doing it by making two calls of public methods to update objects separately.

I am currently experimenting with Racket, but i would appreciate examples in any language, or a description of a standard pattern.

Here is an example of what i have experimented in Ruby (with which i am more comfortable than with Racket).  I am not concerned with locking here, just with class interface.

class Account
  def initialize(total)
    @total = total
  end

  def total
    @total
  end

  def transfer_to(another, sum:)
    change_total_by(-sum)
    another.change_total_by(sum)
  end

  protected

    def change_total_by(sum)
      @total += sum
    end

end

a = Account.new(10)
b = Account.new(20)
a.transfer_to(b, sum: 5)
print "New a.total = #{ a.total },\nnew b.total = #{ b.total }"
```

This works using protected instead of private.