答:
Consider departing from normalization.  For every departure from one of the normal forms, there is a corresponding anomaly to be overcome.  For 2NF through 5NF the anomalies are generally in the area of harmful redundancy.

What makes this kind of redundancy harmful is the possibility that the database will contain mutually contradictory facts, and therefore yield erratic results.  You have to program in such a way that these contradictions don't occur.

For routine database work, it's usually better to normalize, and thereby obviate contradiction than to try to be careful with updates.

But if you were to carry this line of reasoning to its logical conclusion, you would never do any cacheing whatsoever.  A cache always contains data that is redundant to the underlying data it caches.  Whenever you build a cache, you have to guard against the cache delivering results that are no longer valid.  Programming to cope with harmful redundancy involves the same kind of disciplined thinking.

At the end of the day, you may decide to normalize after all.  But don't treat normalization as some sort of holy grail.  It isn't.

There is an alternative.  Whenever you add a data point to the cache, arrange the data so that zip1.lt.Zip2.  Whenever you do a lookup, arrange the two zips the same way.  It's a little extra arithmetic, but it may beat adding every point twice.

Title: Distance calculation and data normalization

Body:
I'm designing a system which needs to report basic distance between zip codes. It will use the Google Distance Matrix API but I want to cache the results in the database so that multiple requests for the same data points don't result in duplicate API calls.

A basic Distance class might look like this:

A basic data structure for the cache might look like this:

Since I'm not using fine-grained detail concerned with changes due to one-way streets or divided highways, interchanges, etc., it therefore doesn't matter to me whether I'm getting the data from point A to point B or from point B to point A. But I'm not sure how to express this with full normalization in the database. With this primary key, it would be perfectly legal for the same distance to exist in two separate row, i.e.

```<code>var row1 = new Distance("00001", "00002");
var row2 = new Distance("00002", "00001");
</code>```

It would probably be a good idea for me to require a SortedList parameter in the constructor, but is there a way I can design it from the database side to enforce full normalization?


问:
Does Scrum lend itself to multi-project environments?
I will be moving workplace in the near future and I believe they will be very interested in my experience of Scrum and how it may relate to their business. I am trying to understand if it will work in their environment.

My current place of work we have a 2 products/2 backlogs/2 separate teams. These backlogs are obviously prioritised based on what the business thinks it most needs for a platform that we develop. The place I will be moving to however has many projects on the go all at the same time with (2/3 individuals working on each), small bits of work come in and are fixed on a daily basis and I imagine all the customer deliverables are roughly equally as important.

So I'm wondering if anyone has experience of Scrum in a similar environment, what real examples have you got of things that worked? What didn't work? What considerations need to there for Scrum to work in this situation?

There are a few aspects that I'm not sure how would work out well:

I believe people in teams will work across projects, and therefore potentially across scrum teams if broken down.

How do you go about handling priority on so many moving parts which are probably changing frequently and have their own timescales?

If you have a scrum team that works on several projects (some many only require 1 Dev) then how do you understand the context of the stand-up?

答:
I'm not sure I understand, if you have "2/3 individuals working on each" then isn't that the same as having several teams, each working on a project.

They may change projects regularly, rather than having a 'product' they continually work on, but that's not much of a difference. Some places even expect teams to work on different parts of a product and change to work on something else after each project is complete - mainly to ensure a good spread of knowledge.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
When is the register keyword actually useful in C?
I am confused about the use of register keyword in C. It is generally told that its use isn't needed like in this question on stackoverflow.

Is this keyword totally redundant in C due to modern compilers or are there situations in which it can still be useful? If yes, what are some situations in which use of register keyword is actually helpful?

答:
You basically tell the compiler that you won't take the address of the variable and the compiler can then ostensibly make further optimizations. As far as I know, modern compilers are pretty capable to determine if a variable can/should be kept in a register or not.

Example:

```<code>int main(){
        int* ptr;
        int a;
        register int b;
        ptr = &a;
        ptr = &b; //this won't compile
        return 0;
}
</code>```

Body:
You basically tell the compiler that you won't take the address of the variable and the compiler can then ostensibly make further optimizations. As far as I know, modern compilers are pretty capable to determine if a variable can/should be kept in a register or not.

Example:

int main(){
        int* ptr;
        int a;
        register int b;
        ptr = &a;
        ptr = &b; //this won't compile
        return 0;
}


问:
Storing menu items with user permissions
I'm creating a menu system in PHP and MySQL. I will have several different menus and each menu will have a set of menu items connected to it.

On the site, I also have different user permissions, some users can see all menu items and some items are hidden from some users. I'm curious on how I could handle the permissions in a clean way that will allow for more types of users in the future to be easily added.

What I have thus far is something like this:

```<code>-------------------
|Menus
-------------------
|id| |display name|
-------------------

----------------------------------------------------------
|Menu items
----------------------------------------------------------
|id| |menu_id| |label| |link| |parent| |sort| |permission|
----------------------------------------------------------
</code>```

I'm thinking that the permission column could either be a comma separated string that I can match against the current user's permission id. It could also be a reference to some other table that defines all possible combinations of the currently existing permissions.

One solution could also be to simply store multiple menu items where the only difference is the permission although this would lead to duplicate storage and perhaps a pain to administer.

I'd love to hear some thought on how to structure this and what could be considered clean, dynamic and crappy.

Thanks.

答:
That classical approach to this is User -> UserGroup and then associated a Menu -> MenuItem -> UserGroup. Using an integer value to weigh the permission level.

```<code>-------------------
|Menu
-------------------
|id| |display name|
-------------------

-------------------------------------------------------------
|Menu Item
-------------------------------------------------------------
|id| |menu_id| |label| |link| |parent| |sort| | min_option1
-------------------------------------------------------------

-------------------------------------------
| User
-------------------------------------------
|id| | username | password | user_group_id
-------------------------------------------

-------------------------------------------
| User Group
-------------------------------------------
|id| option1 | option2 | option2
-------------------------------------------
</code>```

When you need to display a menu for the current user. You can query the database like this.

```<code>SELECT * FROM `MenuItem`
    LEFT JOIN `UserGroup` ON (`MenuItem`.`user_group_id` = `UserGroup`.`id`)
    LEFT JOIN `User` ON (`UserGroup`.`id` = `User`.`user_group_id` AND `User`.`id` = $current_user_id)
        WHERE `MenuItem`.`menu_id` = $menu_id AND `UserGroup`.`option1` >= `MenuItem`.`min_option1`;
</code>```

That will only select menus that are visible to the current user based upon the condition for option1.

Alternatively, if you store the current user's group details in the current session, then no join is required.

```<code>SELECT * FROM `MenuItem` WHERE `MenuItem`.`menu_id` = $menu_id AND `MenuItem`.`min_option1` >= $user_group_option1;
</code>```

When you talk about wanting to store multiple permissions per menu item. I'd be careful not to confuse user roles and business logic.

Body:
That classical approach to this is User -> UserGroup and then associated a Menu -> MenuItem -> UserGroup. Using an integer value to weigh the permission level.

-------------------
|Menu
-------------------
|id| |display name|
-------------------

-------------------------------------------------------------
|Menu Item
-------------------------------------------------------------
|id| |menu_id| |label| |link| |parent| |sort| | min_option1
-------------------------------------------------------------

-------------------------------------------
| User
-------------------------------------------
|id| | username | password | user_group_id
-------------------------------------------

-------------------------------------------
| User Group
-------------------------------------------
|id| option1 | option2 | option2
-------------------------------------------

When you need to display a menu for the current user. You can query the database like this.

SELECT * FROM `MenuItem`
    LEFT JOIN `UserGroup` ON (`MenuItem`.`user_group_id` = `UserGroup`.`id`)
    LEFT JOIN `User` ON (`UserGroup`.`id` = `User`.`user_group_id` AND `User`.`id` = $current_user_id)
        WHERE `MenuItem`.`menu_id` = $menu_id AND `UserGroup`.`option1` >= `MenuItem`.`min_option1`;

That will only select menus that are visible to the current user based upon the condition for option1.

Alternatively, if you store the current user's group details in the current session, then no join is required.

SELECT * FROM `MenuItem` WHERE `MenuItem`.`menu_id` = $menu_id AND `MenuItem`.`min_option1` >= $user_group_option1;

When you talk about wanting to store multiple permissions per menu item. I'd be careful not to confuse user roles and business logic.


答:
Having a comma separated list means doing a substring comparison each time you do a query against the menu.  This is less than ideal.

You need to normalize the table:

```<code>---------------------------------------------
|Menu items
---------------------------------------------
|id| |menu_id| |label| |link| |parent| |sort|
---------------------------------------------

+---------------------------+
| menu_permission           |
|---------------------------|
| |menu_permission_id| (pk) |
| |menu_id| (fk)            |
| |permission|              |
+---------------------------+
</code>```

If you still want the comma separated list (for some reason), you can pull it out with things such as group_concat in mysql wm_concat in oracle or similar functions in other languages.

The advantage for this is multi-fold.

First, there's the practicality of the call.  Doing a substring against an arbitrarily large string (if you fix size it, you can have problems later on with filling up the string so you start getting permissions like a instead of another_permission) means scanning the string on each row.  This isn't something that databases are optmized for.

Second, the query that you write becomes much simpler.  To determine if the permission 'foo' exists in a comma separated list, you need to check for 'foo'.

```<code>... permission like "%foo%" ...
</code>```

However, this will give a false positive if you also have the permission 'foobar'.  So now you need to have a test like

```<code>... permission like "%,foo,%" ...
</code>```

but that will give a false negative if 'foo' is at the start or end of the string.  That leads to something like

```<code>... (permission like "foo,%"
  or permission like "%,foo,%"
  or permission like "%,foo" ) ...
</code>```

You will note that it is quite likely that you will need to do multiple scans of the string.  This way leads to madness.

Note with all of these you lack the practical ability to do parameter binding (still possible, just gets even more ugly).

Normalizing the field gives you much greater flexibility and legibility in your database.  You won't regret it.

Title: Storing menu items with user permissions

Body:
I'm creating a menu system in PHP and MySQL. I will have several different menus and each menu will have a set of menu items connected to it.

On the site, I also have different user permissions, some users can see all menu items and some items are hidden from some users. I'm curious on how I could handle the permissions in a clean way that will allow for more types of users in the future to be easily added.

What I have thus far is something like this:

```<code>-------------------
|Menus
-------------------
|id| |display name|
-------------------

----------------------------------------------------------
|Menu items
----------------------------------------------------------
|id| |menu_id| |label| |link| |parent| |sort| |permission|
----------------------------------------------------------
</code>```

I'm thinking that the permission column could either be a comma separated string that I can match against the current user's permission id. It could also be a reference to some other table that defines all possible combinations of the currently existing permissions.

One solution could also be to simply store multiple menu items where the only difference is the permission although this would lead to duplicate storage and perhaps a pain to administer.

I'd love to hear some thought on how to structure this and what could be considered clean, dynamic and crappy.

Thanks.

Body:
Having a comma separated list means doing a substring comparison each time you do a query against the menu.  This is less than ideal.

You need to normalize the table:

---------------------------------------------
|Menu items
---------------------------------------------
|id| |menu_id| |label| |link| |parent| |sort|
---------------------------------------------

+---------------------------+
| menu_permission           |
|---------------------------|
| |menu_permission_id| (pk) |
| |menu_id| (fk)            |
| |permission|              |
+---------------------------+

If you still want the comma separated list (for some reason), you can pull it out with things such as group_concat in mysql wm_concat in oracle or similar functions in other languages.

The advantage for this is multi-fold.

First, there's the practicality of the call.  Doing a substring against an arbitrarily large string (if you fix size it, you can have problems later on with filling up the string so you start getting permissions like a instead of another_permission) means scanning the string on each row.  This isn't something that databases are optmized for.

Second, the query that you write becomes much simpler.  To determine if the permission 'foo' exists in a comma separated list, you need to check for 'foo'.

... permission like "%foo%" ...

However, this will give a false positive if you also have the permission 'foobar'.  So now you need to have a test like

... permission like "%,foo,%" ...

but that will give a false negative if 'foo' is at the start or end of the string.  That leads to something like

... (permission like "foo,%"
  or permission like "%,foo,%"
  or permission like "%,foo" ) ...

You will note that it is quite likely that you will need to do multiple scans of the string.  This way leads to madness.

Note with all of these you lack the practical ability to do parameter binding (still possible, just gets even more ugly).

Normalizing the field gives you much greater flexibility and legibility in your database.  You won't regret it.


答:
I will model it using an ER diagram.

A PERMISSION is the access granted to a ROLE on a given MENU_ITEM.

A ROLE is a set of pre-defined permissions which is given a name

A USER can have many ROLEs granted to it.

Having permissions assigned to roles instead of users, makes the administration of permissions much easier.

Then you can create a view so you don't have to write the joins every time:

```<code>create or replace view v_user_permissions
select
    distinct mi.id, mi.menu_id. mi.label. mi.link, mi.parent, mi.sort, u.user_id
from
    user u
    join user_role ur on (u.user_id = ur.user_id)
    join role ro on (ur.role_id = role.role_id)
    join permission per on (ro.role_id = per.role_id)
    join menu_item mi on (per.metu_item_id = mi.metu_item_id)
</code>```

Then each time you want to know what menu items a user have access to, you can query it:

```<code>select * from v_user_permissions up where up.user_id = 12736 order by up.sort
</code>```

EDIT:

Since a user can have multiple roles granted, roles' permissions can overlap, i.e. two distinct roles can have access to the same menu item. When you define a role you don't know beforehand whether it will have some permissions in common with other roles. But since it's about the union of sets, it only matters whether or not a given permission is part of the set, not how many times it appears, hence the distinct clause in the view.

Body:
I will model it using an ER diagram.

A PERMISSION is the access granted to a ROLE on a given MENU_ITEM.

A ROLE is a set of pre-defined permissions which is given a name

A USER can have many ROLEs granted to it.

Having permissions assigned to roles instead of users, makes the administration of permissions much easier.

Then you can create a view so you don't have to write the joins every time:

create or replace view v_user_permissions
select
    distinct mi.id, mi.menu_id. mi.label. mi.link, mi.parent, mi.sort, u.user_id
from
    user u
    join user_role ur on (u.user_id = ur.user_id)
    join role ro on (ur.role_id = role.role_id)
    join permission per on (ro.role_id = per.role_id)
    join menu_item mi on (per.metu_item_id = mi.metu_item_id)

Then each time you want to know what menu items a user have access to, you can query it:

select * from v_user_permissions up where up.user_id = 12736 order by up.sort

EDIT:

Since a user can have multiple roles granted, roles' permissions can overlap, i.e. two distinct roles can have access to the same menu item. When you define a role you don't know beforehand whether it will have some permissions in common with other roles. But since it's about the union of sets, it only matters whether or not a given permission is part of the set, not how many times it appears, hence the distinct clause in the view.


问:
Getting rid of Massive View Controller in iOS?
I had a discussion with my colleague about the following problem.

We have an application where we need filtering functionality. On any main screen within the upper navigation bar, there is a button in the upper right corner. Once you touch that button, an custom written Alert View like view will pop up modally, behind it a semitransparent black overlay view. In that modal view, there is a table view of options, and you can choose one exclusively.  Based on your selection, once this modal view is closed, the list of items in the main view is filtered. It is simply a modally presented filter to filter the main table view.This UI design is dictated by the design department, I cannot do anything about it so let accept this as a premise. Also the main filter button in the navbar will change colours to indicate that the filter is active.

The question I have is about implementation. I suggested to my colleague that we create a separate XYZFilter class that will

be an instance created by the main view controller

acquire the filtering options

handle saving and restoration of its state - i.e. last filter selected

provide its two views - the overlay view and the modal view

be the datasource for the table in its modal view.

For some unknown reason, my colleague was not impressed by that approach at all. He simply wants to do these functionalities in the main view controller, maybe out of being used to do this in the past like that :-/

Is there any fundamental problem with my approach? I want to

keep the view controller small, not to have spaghetti code

create a reusable component (for use outside the project)

have more object oriented, decoupled approach.

prevent duplication of code as we need the filtering in two different places but it looks the same in both..

Any advice?

答:
I don't see a problem with the approach you outlined. Your problem is one of being able to persuade your colleague that your approach is preferable to theirs. You might try:

it's less work, as the same filtering behaviour is needed more than once in different views;

it's easier to test, as you don't have to configure a view controller and all its views just to test some search code.

I think the "reusable component" argument is premature. It's more persuasive to focus on the reuse problems you currently have (i.e. the two views in the same app), than on speculative future reuse. That can be deleterious, as your colleague might think you're promoting unnecessary gold-plating work for a problem you don't know you'll ever have.


问:
Distance calculation and data normalization
I'm designing a system which needs to report basic distance between zip codes. It will use the Google Distance Matrix API but I want to cache the results in the database so that multiple requests for the same data points don't result in duplicate API calls.

A basic Distance class might look like this:

A basic data structure for the cache might look like this:

Since I'm not using fine-grained detail concerned with changes due to one-way streets or divided highways, interchanges, etc., it therefore doesn't matter to me whether I'm getting the data from point A to point B or from point B to point A. But I'm not sure how to express this with full normalization in the database. With this primary key, it would be perfectly legal for the same distance to exist in two separate row, i.e.

```<code>var row1 = new Distance("00001", "00002");
var row2 = new Distance("00002", "00001");
</code>```

It would probably be a good idea for me to require a SortedList parameter in the constructor, but is there a way I can design it from the database side to enforce full normalization?

答:
According to this Zip code FAQ, there are about 43,000 zip codes in the US.  The figure fluctuates a couple thousand per year.  Note the value returned by distance(zip1, zip2) may change over time possibly due to new road construction, zip code boundary changes, etc.

If you store the return values indefinitely, you might wind up with 43,000^2 (approx 1.8 billion) values.  In that case, avoiding the inverses (zip2, zip1) makes some sense.

If you let your cache records expire (keep them for a day? a week? a month?) then it may make more sense to not worry about the inverses.

As long as you're not coding for mobile or embedded devices, disk space is really cheap.


问:
Does modular programming affect computation time?
Everyone says that I should make my code modular, but isn't it less efficient if I use more method calls rather than fewer, but larger, methods? What is the difference in Java, C, or C++ for that matter?

I get that it is easier to edit, read and understand, especially in a group. So is the computation time loss insignificant compared to the code tidiness benefits?

答:
Typically when you would otherwise have a large function and you split it into a lot of smaller ones, these smaller ones will be inlined because the only downside of inlining (repeating the same instructions too much) is not relevant in this case. That means your code will act as if you had written one large function.

If they are not inlined for some reason and this becomes a performance problem, then you should consider manual inlining. Not all applications are networked CRUD forms with huge intrinsic latencies.


答:
It depends.

In the glacially-slow world that is Web programming, where everything happens at human speeds, method-heavy programming, where the cost of the method call is comparable to or exceeds the cost of the processing done by the method, probably doesn't matter.

In the world of embedded systems programming and interrupt handlers for high-rate interrupts, it most certainly does matter.  In that environment, the usual models of "memory access is cheap" and "the processor is infinitely fast" break down.  I have seen what happens when a mainframe object-oriented programmer writes his first high-rate interrupt handler.  It wasn't pretty.

Several years ago, I was doing nonrecursive 8-way connectivity blob coloring on real-time FLIR imagery, on what was at that time a decent processor.  The first attempt used a subroutine call, and the subroutine call overhead ate the processor alive.  (4 calls PER PIXEL x 64K pixels per frame x 30 frames per second = you figure it out).  The second attempt changed the subroutine into a C macro, with no loss of readability, and everything was roses.

You have to look HARD at what you are doing and at the environment in which you will be doing it.

Title: Does modular programming affect computation time?

Body:
Everyone says that I should make my code modular, but isn't it less efficient if I use more method calls rather than fewer, but larger, methods? What is the difference in Java, C, or C++ for that matter?

I get that it is easier to edit, read and understand, especially in a group. So is the computation time loss insignificant compared to the code tidiness benefits?


问:
What is the best solution for static memory allocation?
I'm working on image processing and I need to use big Images in a critical system.

A good practice for critical systems is to avoid dynamic allocation of memory but what is the design/recommendations for static memory allocation?

If we do a static allocation of a big matrix we get stack overflow.

```<code>class test
{
    public:
        test(){};
        ~test(){};

    private:
        float m_bigMatrix[3000000];
};
</code>```

To solve this problem we can define the matrix as static, but then this matrix will be the same for all the instance of this class.

```<code>static float m_bigMatrix[3000000];
</code>```

The other solution is to have a static object.

```<code>static test t;
</code>```

I've got a solution from another forum where it was suggested that the
best approach would be to use a class specific for memory management.

All the instances of the class are static and are used by other classes throughout the code.

Here is a sloppy version for this solution (it's just an example):

```<code>class MemManager
{
public:
    MemManager(){ m_counter = 0u; }
    ~MemManager(){ printf("Out of MemManager nbr %d\n", m_counter); }

    uint16_t getCounter() { return m_counter; }
    uint16_t getData(uint32_t pos) { return m_data[pos]; }

    void setCounter(uint16_t val) { m_counter = val; }
    void setData(uint16_t val, uint32_t pos) { m_data[pos] = val; }

private:
    static const uint32_t MEM_SIZE_DATA = 100000000u;
    uint16_t m_counter;
    uint16_t m_data[MEM_SIZE_DATA];

protected:
};

class MemUser
{
public:
    MemUser(){ m_memManager = NULL; }
    ~MemUser(){ printf("Out of MemUser\n"); }

    void init(MemManager& memManager) { m_memManager = &memManager; };
    uint16_t getCounter() { return m_memManager->getCounter(); }
    uint16_t getData(uint32_t pos) { return m_memManager->getData(pos); }

    void setCounter(uint16_t val) { m_memManager->setCounter(val); }
    void setData(uint16_t val, uint32_t pos) { m_memManager->setData(val, pos); }

private:
    MemManager *m_memManager;

protected:
};

int main()
{
    static MemManager mManager;
    mManager.setCounter(1);
    {
        MemUser mUser;
        mUser.init(mManager);
        printf("Exit scope\n");
    }
    for(uint8_t i = 1u; i<5u; i++)
    {
        static MemManager mManager2;
        printf("Note that mManager2 is the same: %d\n", mManager2.getCounter());
        mManager2.setCounter(i);
    }
    printf("Exit process\n");
    return 0;
}
</code>```

So, is this correct? What is the best solution?

答:
Images are normally stored uncompressed - typically 3 or 4 bytes per pixel, but possibly more.  Therefore a 12 megapixel image takes maybe 48 megabytes of RAM.  HDR etc might take rather more, but still not much in the big scheme of things.

I used to sort out these kind of budgets on early camera phones, when it was scarily much and we did all kinds of tricks to reduce it.  But on today's low-end phones, 48 MB is simply not much.

Don't make complicated code.  Just have a byte-array for the image.  Focus on correctness.  If you don't have the RAM, then this isn't a static memory allocation question but a compression or demand paging question and is a whole different level of complexity.


答:
In the 16-bit computer days, one often needed multiple registers to execute 32-bit multiplies and divides. As floating point units were incorporated into chips and then 64-bit architectures 'took over', both the width of the registers and the number of them expanded.  This eventually leads to a complete re-architecting of the CPU.  See Register Files on Wikipedia.

In short, it would take you a bit of time to figure out what is actually going on if you're on a 64-bit X86 or ARM chip.  If you're on a 16-bit embedded CPU, this might actually get you something.  However, most small embedded chips don't run anything time critical - your microwave oven might be sampling your touchpad 10,000 times a second - nothing that strains a 4Mhz CPU.

Title: When is the register keyword actually useful in C?

Body:
I am confused about the use of register keyword in C. It is generally told that its use isn't needed like in this question on stackoverflow.

Is this keyword totally redundant in C due to modern compilers or are there situations in which it can still be useful? If yes, what are some situations in which use of register keyword is actually helpful?


问:
How Lua handles both integer and float numbers?
As far as I remember myself programming I was taught not to compare floating point numbers for equality. Now, while reading Programming in Lua about Lua number type, I found following:

The number type represents real (double-precision floating-point)
  numbers. Lua has no integer type, as it does not need it. There is a
  widespread misconception about floating-point arithmetic errors and
  some people fear that even a simple increment can go weird with
  floating-point numbers. The fact is that, when you use a double to
  represent an integer, there is no rounding error at all (unless the
  number is greater than 100,000,000,000,000). Specifically, a Lua
  number can represent any long integer without rounding problems.
  Moreover, most modern CPUs do floating-point arithmetic as fast as (or
  even faster than) integer arithmetic.

Is that true for all languages? Basically if we don't go beyond floating point in doubles, we are safe in integer arithmetic? Or, to be more in line with question title, is there anything special that Lua does with its number type so it's working fine as both integer and float-point type?

答:
Doubles are stored as a mantissa and an exponent.  See the format for more information.  Basically, all numbers are of the form: mantissa * 2exponent.  For any integer smaller than 252, the exponent will be zero, making the mantissa bit-for-bit equivalent to a 52-bit unsigned integer.  A separate sign bit is used to indicate negative numbers.

In fact, even some integers larger than 252 can be represented exactly, as long as all the digits past the 52nd are zeros.  Also, some fractions, like 0.5, can be represented exactly.  It's only when the fraction is continuously repeating (like 1/3) in base 2, or otherwise requires too many bits past the radix point that you lose precision.


问:
Decoupling Components - Design
I have created a a number of non-trivial scripts in Python that do some long running reporting. At first these reports started off as scripts with a config file. Then I added in the a database component to persist data. Now I'm building a GUI to sit on top of all of them.

My question relates to design. Each time I add an additional requirement, I find myself wishing I had decoupled the components of these scripts more than I did. When I consider how to recfactor my code to be more modular, I find that I need to pass quite a few references around the code, to the point that class initializers and function signatures have a ton of parameters. Also I find myself having parameters that are simply "pass-through", in that one object needs them only to pass to another object, doing nothing with them.

What is the best way to approach modularity in Python while minimizing the need to pass references all over the place?

I understand this is very conceptual and will vary by design, but I'm looking for guiding principles.

答:
I don't tend to run into this problem when I'm trying to modularize.  So clearly I am doing something different, but without seeing what you're doing, I can only guess what.

So I'll limit myself to general platitudes.

First of all, when writing a number of related scripts, it is usually best to build small scripts and a common library.  This type of design tends to survive multiple refactors better.

Second, if you have a lot of parameters to a function, use named parameters and sensible defaults.  (See http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html if you don't know how to use named parameters.)

Third, there is nothing wrong with having methods in classes that just pass stuff through to another class.  As long as the classes really serve different purposes, that is fine.

Fourth, there is everything wrong with having a ton of classes around simply because it serves some aesthetic purpose.  For each and every class, unless you can explain exactly what having that class is doing to make your life easier, you can remove it.

Fifth, the book Code Complete has a tremendous amount of very detailed advice on everything from the proper naming of variables to effective modularization.  If you have not worked your way through it, I highly recommend that exercise.

Sixth, if you can you really, really want a mentor that you trust to start reviewing your code.  I would be willing to bet that what you most need to be taught is something you would never see (which is why you need help with it) which is fairly obvious to a more experienced person.  Teaching someone without being able to see what they are doing is no more effective than driving a car without being able to see the road.

Title: Decoupling Components - Design


问:
How should I implement "queueing" of approval on my objects?
I have a list of objects that will need to go through an approval process.

I am curious if it would be best to simply add some properties to my object, like ApprovedBy, and ApprovedOn.

Another option is to create an ObjectApproval class that contains this information as well as other information that needs to be stored.

If I wanted a list of objects that still needed approval, I could simply query for a null ApprovedBy in the first scenario. In the second scenario, I would have to maintain an accurate list of ObjectApproval items.

The next thing is, what if I need a multi-step approval process? In this case, I think it would be better to create an ObjectApproval type to track all the intricate details, and I could simply query for the ObjectApproval.Step (or something similar) to find out the items a specific user needs to approve based on their role

Any thoughts on this? Or perhaps design patterns to recommend?

答:
If the approval is an integral part of the object (clearly a part of its design), then make it part of the object.  In essence, the object can approve itself (via an Approve() method).  But it's more likely that there are other objects that go through a similar (if not identical) approval process, and it becomes a cross-cutting concern.

In practice, some state will have to be stored with the object, even if that is merely an identifier for each object instance so that the approval object knows which objects have been approved.  Typically this happens because your application talks to a database, and an Object-Relational Mapper provides you with domain objects that contain their own identifiers.  The approval information would thus be contained in a different table.

Approval should not simply involve a bare boolean field or property on the object.  Any object can change that field, and there is no accountability because a record of the approval is not kept.  That's why an Approve() method is needed; it does the necessary work of archiving a record of the approval.


问:
I have 200k lines of poorly designed code, will units tests or integration tests be more valuable?
I've inherited a lot of poorly designed code; the code has no tests. I am putting tests in place before I attempt a major refactor, but I have run into a problem with my unit tests.

The problem is, I will unit test a function, and then later decide that function is a liability.  I will either get rid of the function, or change its purpose.  Either way, the original function gone and the unit tests fail.

Should I spend a lot of time putting unit tests into a design I will change dramatically? Wont those unit tests be useless after a major redesign?

Would integration tests be more valuable?  I can chose program features I know will not change and create some integration tests to ensure they, indeed, do not change. I might change all the code behind the feature, but the feature should still work, and the integration tests should still pass.

I know there are lot of questions on similar topics. I am asking specifically about the use and value of unit test vs integration tests in messy legacy code.

答:
Should I spend a lot of time putting unit tests into a design I will change dramatically?

This is arguable. If you're changing the design dramatically, I might argue for simply leaving the old code as is and writing it anew. 200kloc isn't that much in the grand scheme of things. If you're not modifying the old code, unit testing it is probably worthless.

If you're modifying it in any way, unit tests will (likely) save you time and effort.

Wont those unit tests be useless after a major redesign?

Sure, but during the redesign, they're invaluable.


答:
There's an awesome book that covers what you're doing in great depth. Working Effectively with Legacy Code describes a number of techniques for doing just what you're doing. The table of contents is available here. It had been recommended to me for years, and I only recently picked it up.

Basically, yes you're correct. Test for the functionality that the users (or consuming components) will depend on, ensuring you can cover edge cases as much as humanly possible. Unit tests (via TDD) will be helpful for the new code that you'll write to replace the existing code, while the integration tests that you wrote to cover the existing code will ensure that you're not breaking anything and are still fulfilling your contracts.

Title: I have 200k lines of poorly designed code, will units tests or integration tests be more valuable?

Body:
I've inherited a lot of poorly designed code; the code has no tests. I am putting tests in place before I attempt a major refactor, but I have run into a problem with my unit tests.

The problem is, I will unit test a function, and then later decide that function is a liability.  I will either get rid of the function, or change its purpose.  Either way, the original function gone and the unit tests fail.

Should I spend a lot of time putting unit tests into a design I will change dramatically? Wont those unit tests be useless after a major redesign?

Would integration tests be more valuable?  I can chose program features I know will not change and create some integration tests to ensure they, indeed, do not change. I might change all the code behind the feature, but the feature should still work, and the integration tests should still pass.

I know there are lot of questions on similar topics. I am asking specifically about the use and value of unit test vs integration tests in messy legacy code.


答: In this case I think regression/integration tests would be more useful. But you'd still want to create unit tests as you're refactoring. Also, keep in mind that unit tests are for testing what a function is supposed to do, not what it currently does. So write your tests as if the code were perfect, then refactor to make the code fit the tests.</p>


答:
Don't worry about what the test is called - focus on the fact that the purpose of the tests is to ensure that when you refactor code it still does the same thing.

So you will be writing tests to two purposes:

To ensure that you don't break the existing functionality when you refactor the existing code to something more manageable.

To define and test the function of new code you add.

In theory you should only ever be doing one or other of the above - although the challenge is that you will probably need to refactor the code to facilitate addition of new features and further - if it really is legacy - to make it testable in the first place (which is why there is an emphasis on refactoring and adding features being distinct activities).

In either case you want add tests to a purpose - you're unlikely to be refactoring the code because just because you can, you will have objectives to be achieved and the tests that you write (unit, integration, whatever) should be those needed to support the work that moves you toward that objective.


答:
The whole point of avoiding dynamic memory allocation is that if your program has enough memory to complete initialization, then you know for a certainty you won't hit an out of memory condition in the middle of your program, under some borderline set of conditions you hadn't thought of.

Writing your own memory manager defeats that benefit.  In fact, it makes it less safe. Instead of running out of heap with the built in memory manager that is highly tested, optimized, and used by millions of programmers, you are instead running out of memory on an untested memory manager, written by programmers who probably haven't written a memory manager before, and used only by you.

If you're getting stack overflows from your object being too large, the solution is to not allocate the object on the stack, as in your static test t; or static float m_bigMatrix[3000000];.  Yes, it's annoying.  Yes, it goes against your instincts from what you've been taught are best practices on non-critical systems.  That's just how it goes.

One compromise I've seen is to only avoid dynamic deallocation, and make sure to perform all your dynamic allocation when the program first starts up.  This makes it feel more natural, but still gives you the benefit of a known memory bound.  However, it's much more difficult to audit.  When I worked before on critical systems, this was only allowed in very exceptional circumstances.

Title: What is the best solution for static memory allocation?

Body:
I'm working on image processing and I need to use big Images in a critical system.

A good practice for critical systems is to avoid dynamic allocation of memory but what is the design/recommendations for static memory allocation?

If we do a static allocation of a big matrix we get stack overflow.

```<code>class test
{
    public:
        test(){};
        ~test(){};

    private:
        float m_bigMatrix[3000000];
};
</code>```

To solve this problem we can define the matrix as static, but then this matrix will be the same for all the instance of this class.

```<code>static float m_bigMatrix[3000000];
</code>```

The other solution is to have a static object.

```<code>static test t;
</code>```

I've got a solution from another forum where it was suggested that the
best approach would be to use a class specific for memory management.

All the instances of the class are static and are used by other classes throughout the code.

Here is a sloppy version for this solution (it's just an example):

```<code>class MemManager
{
public:
    MemManager(){ m_counter = 0u; }
    ~MemManager(){ printf("Out of MemManager nbr %d\n", m_counter); }

    uint16_t getCounter() { return m_counter; }
    uint16_t getData(uint32_t pos) { return m_data[pos]; }

    void setCounter(uint16_t val) { m_counter = val; }
    void setData(uint16_t val, uint32_t pos) { m_data[pos] = val; }

private:
    static const uint32_t MEM_SIZE_DATA = 100000000u;
    uint16_t m_counter;
    uint16_t m_data[MEM_SIZE_DATA];

protected:
};

class MemUser
{
public:
    MemUser(){ m_memManager = NULL; }
    ~MemUser(){ printf("Out of MemUser\n"); }

    void init(MemManager& memManager) { m_memManager = &memManager; };
    uint16_t getCounter() { return m_memManager->getCounter(); }
    uint16_t getData(uint32_t pos) { return m_memManager->getData(pos); }

    void setCounter(uint16_t val) { m_memManager->setCounter(val); }
    void setData(uint16_t val, uint32_t pos) { m_memManager->setData(val, pos); }

private:
    MemManager *m_memManager;

protected:
};

int main()
{
    static MemManager mManager;
    mManager.setCounter(1);
    {
        MemUser mUser;
        mUser.init(mManager);
        printf("Exit scope\n");
    }
    for(uint8_t i = 1u; i<5u; i++)
    {
        static MemManager mManager2;
        printf("Note that mManager2 is the same: %d\n", mManager2.getCounter());
        mManager2.setCounter(i);
    }
    printf("Exit process\n");
    return 0;
}
</code>```

So, is this correct? What is the best solution?


答:
There is probably no computation cost. Usually the compilers/JITs for past 10-20 years or so deals with the function inlining perfectly fine. For the C/C++ usually it is limited to 'inlinable' functions (i.e. the definition of function is available for compiler during compilation - that is it is in header of the same file) but current techniques of LTO overcome this.

If you should spent time on optimization depends on the area you are working on. If you deal with 'normal' application that spent most of the time waiting on input - probably you should not worry about optimizations unless application 'feels' slow.

Even in such cases you should concentrate on many things before doing micro-optimization:

Where the problems are? Usually people have hard time to find the hotspots as we read the source code differently. We have different ratio of operation time and we perform them sequentially while modern processors don't.

Is doing some calculation needed every time? For example if you change a single parameter out of thousands you might want to compute just a part affected instead of whole model.

Do you use optimal algorithm? Change from O(n) to O(log n) might have much larger impact then anything you could achieve by micro-optimization.

Do you use proper structures? Say you are using a List when you need HashSet so you have O(n) lookups when you could have O(1).

Do you use parallelism efficiently? Currently even mobile phones can have 4 cores or more it might be tempting to use threads. However they are not a silver bullet as they have cost of synchronization (not mentioning that if problem is memory bound they make no sense anyway).

Even if you do decide that you need to perform micro-optimization (which practically means that your software is used in HPC, embedded or just used by very large number of people - otherwise the additional cost of maintenance overcome the computer time costs) you need to identify the hotspots (kernels) you want to accelerate. But then you probably should:

Know exactly the platform you are working on

Know exactly the compiler you are working on and what optimization it is capable of doing and how to write idiomatic code to enable those optimization

Think about memory access patterns and how much can you fit into cache (exact size of which you know from point 1).

Then if you are compute bound think about reorganizing computation to save the calculation

As a final remark. Usually the only problem you have with method calls is the indirect jumps (virtual methods) which were not predicted by branch predictor (unfortunately indirect jump is the hard case for it). However:

Java have a JIT which in many cases can predict the type of class and therefore a target of jump beforehand and therefore in hotspots you should not have many problems.

C++ compilers often perform a program analysis and at least in some cases can predict the target at compile time.

In both cases when the target have been predicted the inlining should work. If the compiler couldn't perform the inlining chances are we couldn't too.


问:
Graph theory problem (name unknown)
I am trying to solve the following kind of problem.  I do not know if there is already a name for this, or a solution; however, I'm willing to bet there is.  I was hoping someone could point me in the direction of implementing a solution for it, or at least tell me the name of the problem?

Suppose a traveler has a certain amount of Gold coins, and some Bronze coins.  He must start a city A, and go to city B, then city C, and finally city D.

There are two (or more) roads that pass from A to B, labeled AB1, and AB2 (etc.).
Road AB1 has a toll of 5 gold coins, and AB2 has a toll of 5 bronze coins.

Roads from city B to C: BC1 has a toll of 10 coins, which can be either currency.  BC2 requires 8 gold coins.

Roads from C to D have some sort of similar setup.

Assuming that we know how much money the traveler has, and that there is no possible exchange between bronze and gold coins: is there a method to determine if the traveler has enough money to pass through from A to B, to C, and finally to D?

This is the kind of problem I need a solution to...  Is there a name for this problem?  Is there a solution to this problem (other than brute force)?  I'm assuming this is a similar problem to flow problems, but I don't know quite how to approach it.

答: If your traveler had to return to the start it would be a variation on the http://en.wikipedia.org/wiki/Travelling_salesman_problem.  As is, it's just a path optimization problem.  I'd tackle it using Depth First Search, but that's because it's one of only two or three graph traversal algorithms I remember from grad school.</p>

Title: Graph theory problem (name unknown)


答:
I'm currently working as part as a 4-person scrum team that is responsible, to one degree or another, for everyone of our company's products. Totaling at roughly 16 products, plus a mess of semi-connected one-off's, I can tell you from experience that scrum doesn't endear itself to a multi-project environment. As stated above, it is tough to build team synergy when you're constantly working individually on different things. Furthermore, it is tough to cross-relate to the working details of your teammates' assignments, since your focus is on a completely different assignment, in a completely different project.

Moreover, 'falling-in-love' or even unassigned analysis with a particular product is nearly impossible due to the rate of assignment turnover, which can lead to code rot, among other things.

If you find yourself in a position where you can't escape multiple projects assigned to your team, I wouldn't recommend SCRUM.

Title: Does Scrum lend itself to multi-project environments?

Body:
I will be moving workplace in the near future and I believe they will be very interested in my experience of Scrum and how it may relate to their business. I am trying to understand if it will work in their environment.

My current place of work we have a 2 products/2 backlogs/2 separate teams. These backlogs are obviously prioritised based on what the business thinks it most needs for a platform that we develop. The place I will be moving to however has many projects on the go all at the same time with (2/3 individuals working on each), small bits of work come in and are fixed on a daily basis and I imagine all the customer deliverables are roughly equally as important.

So I'm wondering if anyone has experience of Scrum in a similar environment, what real examples have you got of things that worked? What didn't work? What considerations need to there for Scrum to work in this situation?

There are a few aspects that I'm not sure how would work out well:

I believe people in teams will work across projects, and therefore potentially across scrum teams if broken down.

How do you go about handling priority on so many moving parts which are probably changing frequently and have their own timescales?

If you have a scrum team that works on several projects (some many only require 1 Dev) then how do you understand the context of the stand-up?


答:
I'm not sure it could be related to a flow algorithm, because a flow problem would allow you to go partially down road AB1 and partially down road AB2, for example.

I think you're pretty much stuck with depth first search, but you have opportunities for pruning.  For example, if one road requires 8 gold coins and another between the same two cities requires 10 gold coins, you don't need to bother traversing the latter.  That leaves you with one gold, one bronze, and one "either" path between each city.  Also, keep in mind that the order you visit the cities doesn't matter from the algorithm's point of view.  If the CD roads are all higher cost than the AB ones, you might be able to speed things up by moving them first.

Title: Graph theory problem (name unknown)

Body:
I am trying to solve the following kind of problem.  I do not know if there is already a name for this, or a solution; however, I'm willing to bet there is.  I was hoping someone could point me in the direction of implementing a solution for it, or at least tell me the name of the problem?

Suppose a traveler has a certain amount of Gold coins, and some Bronze coins.  He must start a city A, and go to city B, then city C, and finally city D.

There are two (or more) roads that pass from A to B, labeled AB1, and AB2 (etc.).
Road AB1 has a toll of 5 gold coins, and AB2 has a toll of 5 bronze coins.

Roads from city B to C: BC1 has a toll of 10 coins, which can be either currency.  BC2 requires 8 gold coins.

Roads from C to D have some sort of similar setup.

Assuming that we know how much money the traveler has, and that there is no possible exchange between bronze and gold coins: is there a method to determine if the traveler has enough money to pass through from A to B, to C, and finally to D?

This is the kind of problem I need a solution to...  Is there a name for this problem?  Is there a solution to this problem (other than brute force)?  I'm assuming this is a similar problem to flow problems, but I don't know quite how to approach it.


问:
choice of design for OO-linear algebra library
I'm writing a library for sparse linear algebra computations as a backend for my thesis work and I've come to a bit of a crossroads. I'm using modern Fortran (don't groan, it's had inheritance and polymorphism and all that jazz for 10 years now).

From a software design standpoint, my main issue was making iterative solvers be able to use sparse matrices without knowing what storage format they're in. The only functionality that an iterative solver has to know about is how to multiply a matrix by a vector.

I did this by having an abstract class sparse_matrix with a virtual method matvec for matrix-vector multiplication; then there were several child classes, representing each storage format, which override the parent matvec with their own implementation. I believe this is called the "template" pattern yes?

I'm considering refactoring my code to use composition over inheritance. To that end, a sparse matrix consists of an underlying graph with some extra data -- sometimes it's an array of real or complex numbers, sometimes an array of dense matrices, etc. There are multiple different sparse matrix formats which use the same underlying graph storage scheme. Every sparse matrix has a graph object as an attribute, and has a collection of function pointers which change to use that graph in different ways. Before, I had to effectively redefine the same graph storage scheme for each sparse matrix format that used it.

The advantages I can discern are:

fewer classes make it easier to hook my code up to C/C++/Python

easy to choose different parallel implementations of the same algorithm; write every implementation and redirect function pointers at runtime. Before I had to use big conditional blocks.

I think this design will be easier when the underlying graph is better thought of as a hyper-graph, and matrices as heterogeneous compositions of several matrices in possibly different formats. (This happens in some PDE applications.)

Can anyone think of a good reason why I should stick with the old inheritance-based design? If the new approach is more sensible, any advice beyond what's said in GoF would be appreciated.

答:
My read is that the inheritance-based approach was correct.

What you fundamentally want is a matrix-vector product operation, that your solvers can call.  The solvers don't care how the matrix OR the vector are stored in memory.  All they care about is being able to multiply them and get back the result.  That is just about the canonical use case for a polymorphic approach.


答:
If each of these components uses some subset of all possible references, you might want to consider creating a "controller" object that has a handle to all the references. You would then pass the controller to the functions, and the functions call pull out the references that they need.

For example, instead of:

```<code>def foo(a,b,c):
    print "a:", a
    bar(b,c):

def bar(b,c):
    print "b:", b
    baz(c)

foo("this is a", "this is b", "this is c")
</code>```

You would do:

```<code>class Controller(object):
    def __init__(a,b,c):
        self.a = a
        self.b = b
        self.c = c
    }

def foo(controller):
    print "a:", controller["a"]
    bar(controller)

def bar(controller):
    print "b:", controller["b"]
    baz(controller)

controller = Controller("this is a", "this is b", "this is c")
foo(controller)
</code>```

Title: Decoupling Components - Design

Body:
I have created a a number of non-trivial scripts in Python that do some long running reporting. At first these reports started off as scripts with a config file. Then I added in the a database component to persist data. Now I'm building a GUI to sit on top of all of them.

My question relates to design. Each time I add an additional requirement, I find myself wishing I had decoupled the components of these scripts more than I did. When I consider how to recfactor my code to be more modular, I find that I need to pass quite a few references around the code, to the point that class initializers and function signatures have a ton of parameters. Also I find myself having parameters that are simply "pass-through", in that one object needs them only to pass to another object, doing nothing with them.

What is the best way to approach modularity in Python while minimizing the need to pass references all over the place?

I understand this is very conceptual and will vary by design, but I'm looking for guiding principles.

Body:
If each of these components uses some subset of all possible references, you might want to consider creating a "controller" object that has a handle to all the references. You would then pass the controller to the functions, and the functions call pull out the references that they need.

For example, instead of:

def foo(a,b,c):
    print "a:", a
    bar(b,c):

def bar(b,c):
    print "b:", b
    baz(c)

foo("this is a", "this is b", "this is c")

You would do:

class Controller(object):
    def __init__(a,b,c):
        self.a = a
        self.b = b
        self.c = c
    }

def foo(controller):
    print "a:", controller["a"]
    bar(controller)

def bar(controller):
    print "b:", controller["b"]
    baz(controller)

controller = Controller("this is a", "this is b", "this is c")
foo(controller)


问:
What is this algorithm for converting strings into numbers called?
I've been doing some work in Parsec recently, and for my toy language I wanted multi-based fractional numbers to be expressible.  After digging around in Parsec's source a bit, I found their implementation of a floating-point number parser, and copied it to make the needed modifications.

So I understand what this code does, and vaguely why (I haven't worked out the math fully yet, but I think I get the gist).  But where did it come from?  This seems like a pretty clever way to turn strings into floats and ints, is there a name for this algorithm?  Or is it just something basic that's a hole in my knowledge?  Did the folks behind Parsec devise it?

Here's the code, first for integers:

```<code>number' :: Integer -> Parser Integer
number' base =
    do { digits <- many1 ( oneOf ( sigilRange base ))
       ; let n = foldl (\x d -> base * x + toInteger (convertDigit base d)) 0 digits
       ; seq n (return n)
       }
</code>```

So the basic idea here is that digits contains the string representing the whole number part, ie "192".  The foldl converts each digit individually into a number, then adds that to the running total multiplied by the base, which means that by the end each digit has been multiplied by the correct factor (in aggregate) to position it.

The fractional part is even more interesting:

```<code>fraction' :: Integer -> Parser Double
fraction' base =
    do { digits <- many1 ( oneOf ( sigilRange base ))
       ; let base' = fromIntegral base
       ; let f = foldr (\d x -> (x + fromIntegral (convertDigit base d))/base') 0.0 digits
       ; seq f (return f)
</code>```

Same general idea, but now a foldr and using repeated division.  I don't quite understand why you add first and then divide for the fraction, but multiply first then add for the whole.  I know it works, just haven't sorted out why.

Anyway, I feel dumb not working it out myself, it's very simple and clever looking at it.  Is there a name for this algorithm?  Maybe the imperative version using a loop would be more familiar?

答:
This is an application of Horner's method for evaluating polynomials. It is based on the observation that a number abcdef in a positional numeral system with base k is the polynomial a*x^5+b*x^4+...+f*x^0 evaluated at x=k.

As to why there is an asymmetry between the integer and the fractional parts, this simply mirrors the asymmetry between the exponents 0, 1, 2, ... on the one side and -1, -2, ... without the zero on the other.


答:
It's just a shortest/minimum-cost path problem stated as a decision problem. But with a 2 dimensional cost. Is there a path that costs less than x gold coins and less than y bronze coins?

That makes the problem a lot harder to solve in the general case, as there can be a huge number of potential optimal (gold, bronze)-cost pairs per node. The real challenge in this is dealing with the 2-dimensional cost, the graph search is part is just there to tell the story. It could be any kind of optimization.

Title: Graph theory problem (name unknown)


答:
When you use inversion of control techniques such as dependency injection you can give classes only the components they need to do the job so they do not have to worry about what their dependents depend on. This will greatly reduce the number of parameters you are passing to functions, reduce the complexity of your scripts, and introduce loose coupling between components. To give a good example in psudo code, say we are building a car.

You could pass all the parts of a car into the constructor, but then it has to know about the piston, coil and spark plugs even though it doesn't need to know about them. It only needs them to assemble the engine.

```<code>Car(Tires tires, Pistons piston, Coil coil)
{
    SparkPlugs sparkPlugs = new SparkPlugs(piston, coil)
    Engine = new Engine(sparkPlugs, tires)
    Tires = tires;
}
</code>```

A better way to do it is to build the engine beforehand and pass it to the car. Then the car only needs to know about the parts it uses

```<code>Car(Engine e, Tires t)
{
    Engine = e;
    Tires = t;
}
</code>```

Title: Decoupling Components - Design

Body:
When you use inversion of control techniques such as dependency injection you can give classes only the components they need to do the job so they do not have to worry about what their dependents depend on. This will greatly reduce the number of parameters you are passing to functions, reduce the complexity of your scripts, and introduce loose coupling between components. To give a good example in psudo code, say we are building a car.

You could pass all the parts of a car into the constructor, but then it has to know about the piston, coil and spark plugs even though it doesn't need to know about them. It only needs them to assemble the engine.

Car(Tires tires, Pistons piston, Coil coil)
{
    SparkPlugs sparkPlugs = new SparkPlugs(piston, coil)
    Engine = new Engine(sparkPlugs, tires)
    Tires = tires;
}

A better way to do it is to build the engine beforehand and pass it to the car. Then the car only needs to know about the parts it uses

Car(Engine e, Tires t)
{
    Engine = e;
    Tires = t;
}


问:
Breaking Up A Model Class - MVC
I am not sure whether there is a 'right' or 'wrong' answer to this one, but I was curious about the general consensus.

I have a User model that currently performs user functions (such as retrieving user details from the database, inserting new users to the database, updating user details etc.)

This leads to a fairly large class.

Is there any accepted thought on the breaking up of models, when the model already relates to one kind of entity? Or are large classes permissible in this case?

At the moment, the class will resemble something like this:

```<code>    <?php
class Users_Model
{

    public function userExists($user_id)
    {
        //Code to check if user exists
    }

    public function fetchUser($user_id)
    {
        //code to fetch User object from ID...
    }

    protected function fetchUserPassword($user_id)
    {
        return $this->fetchUserValue($user_id, "password");
    }

    protected function fetchUserLowercaseUsername($user_id)
    {
        return $this->fetchUserValue($user_id, "lower");
    }

    private function fetchUserValue($user_id, $value)
    {
        //fetch a user value from the database
    }

    public function logout()
    {
        //code to log user out
    }

    public function doesPasswordMatch($user_id, $password)
    {
        //checks if inputted password matches that which is on record...
    }

    public function createSession($user_id)
    {
        //creates sessions for DATABASE
    }

    private function createCookie($code, $user_id)
    {
        //create cookies for session
    }

}
?>
</code>```

My concern was doing too many things (it was performing retrieval of user information from the database, and handling the database side of logging out and sessions for the user).

答:
Permissible?...yes

I would break-up a User class into parts in cases where it might need to scale really big.

Model Breakdown Example (Composition):

User HAS

LoginCredentials

ContactInfo

Favorites

Friends

Roles

Title: Breaking Up A Model Class - MVC


问:
Does dealing with legacy code help one evolve as a programmer?
I'm a Java developer with a bit more than a year of experience which places me somewhere above a junior, but not among mid-level developers yet. Recently I was offered a long-term project which is about studying an existing banking application code for 4 months and then introducing changes when needed. As a not-so-experienced programmer I'm looking for ways to develop and I wonder what such a project might give.

Would you consider dealing with a big and probably not-so-well written application a good practice for a beginner?

答:
This is good practice for any developer at any point in their career. If you can review and analyze existing software and find ways to improve it, you will demonstrate that you are a valuable developer. Not only will you learn how others have designed and developed software, but along the way you will learn what not to do, which is valuable knowledge in itself.

If you're up for the challenge, take this project head on and make it better.


答:
I think it's excellent practice for a beginner anyone.  Learning from others experience can be very effective.

The real challenge is not to find mistakes, but to get into the head of the other developer and try to figure out why the code was written that way.  Sometimes it's because they were sloppy, and sometimes it's because they had a darn good reason.  Assume the dev was at least as good as you but may have had more domain knowledge.

Title: Does dealing with legacy code help one evolve as a programmer?

Body:
I'm a Java developer with a bit more than a year of experience which places me somewhere above a junior, but not among mid-level developers yet. Recently I was offered a long-term project which is about studying an existing banking application code for 4 months and then introducing changes when needed. As a not-so-experienced programmer I'm looking for ways to develop and I wonder what such a project might give.

Would you consider dealing with a big and probably not-so-well written application a good practice for a beginner?


答:
Troubleshooting existing code is a super way to develop as a programmer. If the code is bad, you will learn the impact of the mistakes they made, and maybe avoid some of them when you are doing the designing. If the code is good, you will learn something about how to make a maintainable application.

You will also learn to deal with the complexity of a real business application. Since this is in the banking sector, you will learn about things like federal regulation and internal accounting controls that you may never have even thought of. These are good things to know when you get asked to design something else in the financial world. And financial programming can be quite a lucrative sector to work in, so getting banking experience may be very good for you.

You may even learn that just because something was written 15 years ago, in a language that you would prefer not to use, it is not necessarily bad. It has been running successfully all this time after all.

If, as with most legacy apps, the application doesn't have unit testing you need to really be sure a change won't affect something else, you may learn how to add that testing and how to sell management on why adding that testing is a good idea.


答:
Ask yourself whether the class has more than one reason to change.

Acording to Bob Martin's explanation of Single Responsability Principle:

As an example, consider a module that compiles and prints a report.
  Such a module can be changed for two reasons. First, the content of
  the report can change. Second, the format of the report can change.
  These two things change for very different causes; one substantive,
  and one cosmetic. The single responsibility principle says that these
  two aspects of the problem are really two separate responsibilities,
  and should therefore be in separate classes or modules. It would be a
  bad design to couple two things that change for different reasons at
  different times.

The example talks about separation of cosmetics from substantial, but it applies to any other two or more concerns, like business logic, persistence, logging, formatting, etc.

If you think your class ( model or not ) has more than one reason to change, then split it.

Title: Breaking Up A Model Class - MVC

Body:
I am not sure whether there is a 'right' or 'wrong' answer to this one, but I was curious about the general consensus.

I have a User model that currently performs user functions (such as retrieving user details from the database, inserting new users to the database, updating user details etc.)

This leads to a fairly large class.

Is there any accepted thought on the breaking up of models, when the model already relates to one kind of entity? Or are large classes permissible in this case?

At the moment, the class will resemble something like this:

```<code>    <?php
class Users_Model
{

    public function userExists($user_id)
    {
        //Code to check if user exists
    }

    public function fetchUser($user_id)
    {
        //code to fetch User object from ID...
    }

    protected function fetchUserPassword($user_id)
    {
        return $this->fetchUserValue($user_id, "password");
    }

    protected function fetchUserLowercaseUsername($user_id)
    {
        return $this->fetchUserValue($user_id, "lower");
    }

    private function fetchUserValue($user_id, $value)
    {
        //fetch a user value from the database
    }

    public function logout()
    {
        //code to log user out
    }

    public function doesPasswordMatch($user_id, $password)
    {
        //checks if inputted password matches that which is on record...
    }

    public function createSession($user_id)
    {
        //creates sessions for DATABASE
    }

    private function createCookie($code, $user_id)
    {
        //create cookies for session
    }

}
?>
</code>```

My concern was doing too many things (it was performing retrieval of user information from the database, and handling the database side of logging out and sessions for the user).


问:
Multiple Object Instantiation
I am trying to get my head around object oriented programming as it pertains to web development (more specifically PHP).

I understand inheritance and abstraction etc, and know all the "buzz-words" like encapsulation and single purpose and why I should be doing all this.

But my knowledge is falling short with actually creating objects that relate to the data I have in my database, creating a single object that a representative of a single entity makes sense, but what are the best practises when creating 100, 1,000 or 10,000 objects of the same type.

for instance, when trying to display a list of the items, ideally I would like to be consistent with the objects I use, but where exactly should I run the query/get the data to populate the object(s) as running 10,000 queries seems wasteful.

As an example, say I have a database of cats, and I want a list of all black cats, do I need to set up a FactoryObject which grabs the data needed for each cat from my database, then passes that data into each individual CatObject and returns the results in a array/object - or should I pass each CatObject it's identifier and let it populate itself in a separate query.

答:
What you need is Object Relational Mapping. You have mentioned that you already have a class Cat that creates objects which represent one row in the database table. What about a class CatList that represents a list of Cats?

Here is a short example how it conceptually can work:

```<code>$catList = new CatList();
$catList->readObjects();
$cats = $catList->getObjects();
</code>```

In the readObjects method you then make a query that loads either all cats (SELECT * FROM cat) or cats with certain limitations (SELECT * FROM cat WHERE xy = ? or SELECT * FROM cat LIMIT 30).

For each of the read rows you create a Cat object. But in the constructor you have the opportunity to either give an ID (and let the Cat load the data) or the data (and skip the load step).

That way you just have one query for all the Cat objects you need. If you wanted a list of black cats only, you could do the following:

```<code>$catList = new CatList();
$catList->addCondition('color = ?', 'black');
$catList->readObjects();
$cats = $catList->getObjects();
</code>```

Inside the CatList you generate the query dynamically depending on possible conditions. As you won't change the list of cats very often, you could then cache the resulting array $cats in a file via serialization. Upon need you would simply need to unserialize the array and then use the stored Cat objects. If you change something to the cat table, you recreate the cache.

Result: Problem solved.

Title: Multiple Object Instantiation

Body:
What you need is Object Relational Mapping. You have mentioned that you already have a class Cat that creates objects which represent one row in the database table. What about a class CatList that represents a list of Cats?

Here is a short example how it conceptually can work:

$catList = new CatList();
$catList->readObjects();
$cats = $catList->getObjects();

In the readObjects method you then make a query that loads either all cats (SELECT * FROM cat) or cats with certain limitations (SELECT * FROM cat WHERE xy = ? or SELECT * FROM cat LIMIT 30).

For each of the read rows you create a Cat object. But in the constructor you have the opportunity to either give an ID (and let the Cat load the data) or the data (and skip the load step).

That way you just have one query for all the Cat objects you need. If you wanted a list of black cats only, you could do the following:

$catList = new CatList();
$catList->addCondition('color = ?', 'black');
$catList->readObjects();
$cats = $catList->getObjects();

Inside the CatList you generate the query dynamically depending on possible conditions. As you won't change the list of cats very often, you could then cache the resulting array $cats in a file via serialization. Upon need you would simply need to unserialize the array and then use the stored Cat objects. If you change something to the cat table, you recreate the cache.

Result: Problem solved.


答:
My answer probably won't expand too much on the existing answers, but I feel like my two cents may be helpful.

First off; yes, for modularity, you usually give up some level of execution time. Writing everything in assembly code is going to give you the best speed. That said...

You know YouTube? Likely either the most high-bandwidth site in existence, or second to Netflix? They write a large portion of their code in Python, which is a highly modular language not quite built for top-notch performance.

The thing is, when something is going wrong, and users are complaining about videos loading slowly, there's not many scenarios where that slowness would ultimately be attributed to the slow execution speed of Python. However, Python's quick re-compilation, and its modular ability to try new things without type-checking will probably allow the engineers to debug what's going wrong pretty quickly ("Wow. Our new intern wrote a loop that does a new SQL sub-query for EVERY result.") or ("Oh, Firefox has deprecated that old caching header format; and they made a Python library to set up the new one easily")

In that sense, even in terms of execution time, a modular language can be thought of as faster because once you find what your bottlenecks are, it will likely become easier to reorganize your code to get it working in the best way. So many engineers will tell you that the heavy performance hits weren't where they thought they'd be (and in fact the things they DID optimize were hardly needed; or, didn't even work the way they'd expect!)


答:
If I'm reading your question correctly, your problem has a two interesting properties:

The graph is connected sequentially, A->B->C->D. There may be multiple edges between nodes, but there are never edges that "skip" nodes (A->C, B->D) or loop back (C->A).

The ultimate goal is feasibility versus optimality. That is, you want to know if a traveler has enough money versus which path costs the absolute least.

Is that correct? If so, there are a few tricks available.

First, calculate the expected value in both gold and bronze between each city. The expected value would be the minimum you would expect to pay. Given AB1 = 5 gold, AB2 = 5 bronze, and AB3 = 10 gold or bronze (I'm adding the road to illustrate a point), you would never select AB3. AB1 or AB2 give you a better solution regardless of the coin you use. Therefore, the expected value between A and B is 5 gold and 5 bronze. The expected value between B and C is 8 gold and 10 bronze. Again, we would never select BC1 (10 gold or bronze) when spending gold as BC2 (8 gold) is always cheaper. Continue calculating the expected values for the rest of your path.

Next, total your expected values for each coin. You're basically acting as if you paid all tolls using one coin type, but you're doing it for both types in one pass. If your expected values are:

A->B 5 gold, 5 bronze

B->C 8 gold, 10 bronze

C->D 10 gold, 7 bronze

Your totals are 23 gold and 22 bronze. If you started with 23 or more gold and 22 or more bronze, you're done. You know that a feasible solution exists. More likely, your expected totals will be greater than your coins available.

In that case, make a choice between expected value pairs versus considering both options. If you're short on gold, spend bronze where it returns the most gold. For example, if I start with 13 gold, I can select the bronze payment option between C->D to create a feasible solution. If I start with 5 bronze, I can select the gold payment option between B->C and C->D to create a feasible solution.

Again, that's probably wishful thinking. It's likely you'll be short both gold and bronze. If that's the case, start with a heuristic to resolve expected values: if you have a larger gold deficit, select expected values that yield the greatest savings in gold before resolving bronze, try to make up the deficit with the fewest "choices" possible, etc... In the end, you may still have to try every combination of expected values to prove a feasible solution does or does not exist.

Note that this doesn't account for tolls that involve both currencies. A toll of 2 gold and 5 bronze ruins my expected value trick.

Title: Graph theory problem (name unknown)


问:
Small self-contained windows desktop application technologies?
Firstly, I'm not new to this. I've written desktop applications for Windows going back to 1991 with Visual Basic 3.0. I've used C/C++ and Win32 API, VB3-6, C# 1.0-4.0 and currently knock out web applications in ASP.Net MVC. However I haven't touched desktop stuff since 2000 in depth bar playing around with some ClickOnce deployed WPF stuff in C#.

However, I've recently stumbled on a requirement to throw out a small, self-contained .exe standard windows desktop application. I don't want to ship any major dependencies with it. In fact, I'd rather like it to be uTorrent style i.e. small, self-contained and without masses of crud around it and possibly UPX packed. This is part of the manifesto of the software: simplicity and the ability to install in a user LocalAppData folder. This is a diagnostic tool which will be used by our users and will scan the system and report various bits of specific information back to our web servers. This has to work on pretty much everything back to win2k. I really don't want to have to go right back to Win32 if possible.

Now when I look around, everything has descended into a confusing mush of MFC, ATL, Managed C++, WTL, WPF, Metro and various other bits of string and sticky tape. Either that or heavy frameworks like Qt, Gtk and Wx.

The question is simply:

What, apart from Win32, is the best starting point for an application of this type?

Or should I just write "yet another win32" wrapper?

答:
This is one area where its very difficult to beat Delphi.  It's able to build standalone, native Win32 (and 64 now) executables.  No runtimes, not even .NET is required.  (its possible some dll's would be required, if you were specifically using them)

Or the Delphi-like, open-source Lazarus IDE


问:
Determining the aggregates in this domain
I'm working on an ordering system where we receive tab delimited files that look like this (I removed most of the columns for clarity):

```
      OrderId   OrderLineId    BuyerName   BuyerAdress   RecipientName     RecipientAdress

         1            1         John        123, Street      Doe              25, street
         1            2         John        123, Street      Doe              25, street
         1            3         John        123, Street     Michael           11, France
         2            1         Sam         66,Somewhere     Lily             25, Poland
         2            2         Sam         66,Somewhere     Dave             25, Russia
         ...
```

Applying DDD I primarily extracted few entities as shown in the image below:

Some facts about the data received in the files:

An Order must have a Buyer and a Buyer must have an Order .

An Order contains at least 1 OrderLine and each OrderLine must belong to an Order.

Each OrderLine must have a Recipient and each Recipient must have an associated OrderLine.

The status history for the OrderLine must be tracked by the system (hence the Line History entity)

Questions:

Which entity is the aggregate root? Most of the articles I read about DDD would put the Customer entity as its own aggregate root and the Order with its OrderLines as the other root. However, since the Buyer and Recipient can NOT exist by themselves how can they be treated as their own aggregate root?

Should OrderLines be a value object or an entity? I have seen some answers on numerous blogs suggesting the OrderLines should be a VO, but I don't see why it shouldn't be treated as an entity since its identity will be needed in its relation with the History entity.

Similarly the Line History should be modeled as entity or value object

答: It looks like your buyer and recipient are value objects as they have no identity outside the relationship to an order and order line. I would therefore say that Order is an aggregate root and also order history is an aggregate root that is updated from events that happen within the order aggregate. I cover this in my free DDD book https://leanpub.com/Practicing-DDD</p>


问:
Refactoring the shipping application code to use DDD factories
I was trying to find examples for using DDD factories and I came across the shipping application from Eric Evans' book.

However when I checked the BookingService the code to create a Cargo had this comment at line 37:

```<code>34    public TrackingId bookNewCargo(final UnLocode originUnLocode,
35                                   final UnLocode destinationUnLocode,
36                                   final Date arrivalDeadline) {
37      // TODO modeling this as a cargo factory might be suitable
38      final TrackingId trackingId = cargoRepository.nextTrackingId();
39      final Location origin = locationRepository.find(originUnLocode);
40      final Location destination = locationRepository.find(destinationUnLocode);
41      final RouteSpecification routeSpecification = new RouteSpecification(origin, destination, arrivalDeadline);
42
43      final Cargo cargo = new Cargo(trackingId, routeSpecification);
44
45      cargoRepository.store(cargo);
46      logger.info("Booked new cargo with tracking id " + cargo.trackingId().idString());
47
48      return cargo.trackingId();
49    }
</code>```

How should the DDD factory be used here? Which parts exactly should be refactored to use the factory in these piece of code?

答:
Lines 38 to 43 could be classed as domain logic as this is how you create a valid cargo. Given that the booking service is an application service it should be delegating to the domain layer to create a cargo. Maybe the code would look like so...

```<code>37      // TODO modeling this as a cargo factory might be suitable
38      final TrackingId trackingId = cargoRepository.nextTrackingId();
39      final Location origin = locationRepository.find(originUnLocode);
40      final Location destination = locationRepository.find(destinationUnLocode);
42
43      final Cargo cargo = CargoFactory.create(trackingId, origin, destination);
</code>```

Check out my free book on DDD https://leanpub.com/Practicing-DDD for more info on factory implementations.

Body:
Lines 38 to 43 could be classed as domain logic as this is how you create a valid cargo. Given that the booking service is an application service it should be delegating to the domain layer to create a cargo. Maybe the code would look like so...

37      // TODO modeling this as a cargo factory might be suitable
38      final TrackingId trackingId = cargoRepository.nextTrackingId();
39      final Location origin = locationRepository.find(originUnLocode);
40      final Location destination = locationRepository.find(destinationUnLocode);
42
43      final Cargo cargo = CargoFactory.create(trackingId, origin, destination);

Check out my free book on DDD https://leanpub.com/Practicing-DDD for more info on factory implementations.


问:
How should I tackle code testing on a solo project?
I am writing a piece of software and I would like to release it open source.

Should I try just getting it stable on my computer (with normal use; no "things a monkey wouldn't even do") before releasing it, or should I take a different approach?

What I am leaning towards doing right now is:

Write it myself during the pre-alpha stage to get it partially usable. Play around with the functions (like a normal person would).

Release it publicly and add some bells and whistles during the alpha stage

Say it's in beta once all features are complete, and then, along with some others (hopefully) do the "monkey testing."

Generate the publicity for my [fairly basic and boring, but still good enough for free and stable] project.

Then keep improving it. This seems to be a usual system (to me, the one who has never really done this whole thing ever before).

Is there something I could do to automatically test for basic errors before I go alpha? Or is this one of the best things I can do? How should I go about testing?

答:
Unit testing will make your initial development time increase. But in compensation you will avoid many of those stealthy emergent bugs as your system grows. Also, when you hit a certain level of project complexity your unit tests might start saving development time, since most coding will probably involve previous code and unit tests give you a pretty solid assurance in regards of not breaking anything that was previously working.

One more point in favor of coding unit tests is that it tends to result in better code since, in general, testable code is less coupled than hard to test code.

If it is a web application you're developing, then functional automated tests are a very good way to reverse test your application after some changes were made. I've used Selenium for this purpose before.


答: Tcl/tk fits your requirements, when you add in the starpack / starkit technology. Essentially, you can wrap up an entire virtual filesystem and executable into a single executable that runs as-is, no unpacking or installation required.</p>

Title: Small self-contained windows desktop application technologies?

Body:
Firstly, I'm not new to this. I've written desktop applications for Windows going back to 1991 with Visual Basic 3.0. I've used C/C++ and Win32 API, VB3-6, C# 1.0-4.0 and currently knock out web applications in ASP.Net MVC. However I haven't touched desktop stuff since 2000 in depth bar playing around with some ClickOnce deployed WPF stuff in C#.

However, I've recently stumbled on a requirement to throw out a small, self-contained .exe standard windows desktop application. I don't want to ship any major dependencies with it. In fact, I'd rather like it to be uTorrent style i.e. small, self-contained and without masses of crud around it and possibly UPX packed. This is part of the manifesto of the software: simplicity and the ability to install in a user LocalAppData folder. This is a diagnostic tool which will be used by our users and will scan the system and report various bits of specific information back to our web servers. This has to work on pretty much everything back to win2k. I really don't want to have to go right back to Win32 if possible.

Now when I look around, everything has descended into a confusing mush of MFC, ATL, Managed C++, WTL, WPF, Metro and various other bits of string and sticky tape. Either that or heavy frameworks like Qt, Gtk and Wx.

The question is simply:

What, apart from Win32, is the best starting point for an application of this type?

Or should I just write "yet another win32" wrapper?


答:
Unit testing is what your project needs for several different reasons.

Allows you to test your application's basic functionality.

Allows you to ensure that new features are not causing regressions.

Good unit tests give consumers and maintainers an idea of what your application is capable of.

Good concise unit tests encourage you to write good concise code. After all, good concise code is easier to test.

Title: How should I tackle code testing on a solo project?

Body:
I am writing a piece of software and I would like to release it open source.

Should I try just getting it stable on my computer (with normal use; no "things a monkey wouldn't even do") before releasing it, or should I take a different approach?

What I am leaning towards doing right now is:

Write it myself during the pre-alpha stage to get it partially usable. Play around with the functions (like a normal person would).

Release it publicly and add some bells and whistles during the alpha stage

Say it's in beta once all features are complete, and then, along with some others (hopefully) do the "monkey testing."

Generate the publicity for my [fairly basic and boring, but still good enough for free and stable] project.

Then keep improving it. This seems to be a usual system (to me, the one who has never really done this whole thing ever before).

Is there something I could do to automatically test for basic errors before I go alpha? Or is this one of the best things I can do? How should I go about testing?


问:
GWT vs JSF vs ZK vs Restful+JS
I'm planning to develop a web based ERP, which should be full-ajax and with desktop-like UI. It will be a data-entry & data-report application. For developing it I'm considering all technologies.

GWT: I saw that with GWT Designer you could create cool UIs, but databinding seems to be too complex

JSF: Netbeans no longer supports the visual web editor

ZK: supports databinding in a relatively easy way, and has got an Eclipse-based visual editor

Some people talk about REST + javascript as a winning choice

I'd like to have your opinion about what could be the right choice.

Thank you very much in advance!

答:
You are comparing a language (js), with a language framework(zk), with an architectural design style (rest), with a development toolkit (gwt).

Have you experience with any of them ?  I'd start with the core basics.

I've been building websites and enterprise scale systems for ten years and have never used a visual designer, and neither has anyone I worked with, so I wouldn't worry about that too much.

Related:
GWT or Vaadin

ContentLicense: CC BY-SA 2.5

Title: GWT vs JSF vs ZK vs Restful+JS


问:
Should we design programs to randomly kill themselves?
In a nutshell, should we design death into our programs, processes, and threads at a low level, for the good of the overall system?

Failures happen. Processes die. We plan for disaster and occasionally recover from it. But we rarely design and implement unpredictable program death. We hope that our services' uptimes are as long as we care to keep them running.

A macro-example of this concept is Netflix's Chaos Monkey, which randomly terminates AWS instances in some scenarios. They claim that this has helped them discover problems and build more redundant systems.

What I'm talking about is lower level. The idea is for traditionally long-running processes to randomly exit. This should force redundancy into the design and ultimately produce more resilient systems.

Does this concept already have a name? Is it already being used in the industry?

EDIT

Based on the comments and answers, I'm afraid I wasn't clear in my question. For clarity:

yes, I do mean randomly,

yes, I do mean in production, and

no, not just for testing.

To explain, I'd like to draw an analogy to multicellular organisms.

In nature, organisms consist of many cells. The cells fork themselves to create redundancy, and they eventually die. But there should always be enough cells of the right kinds for the organism to function. This highly redundant system also facilitates healing when injured. The cells die so the organism lives.

Incorporating random death into a program would force the greater system to adopt redundancy strategies to remain viable. Would these same strategies help the system remain stable in the face of other kinds of unpredictable failure?

And, if anyone has tried this, what is it called? I'd like to read more about it if it already exists.

答:
It depends on the type of application that you're designing.

Random crashes are a great way to test and improve the robustness of distributed (networked) systems.

In the Netflix example, when your program is depending on remote services that can fail for a variety of reasons that are out of your control (hard disk goes bad, power loss, meteor crashes into the data center, etc). Your service needs to still keep running somehow though.

How do you do that? Add in redundancy and scaling is a common solution.

For example, if a mouse chews through your server's power cable then your service should have some solution to keep running. It can for example keep redundant backup servers that it'll start using instead.

However, if your program is a single process application that doesn't operate in a network, then having it kill itself isn't going to test anything since there's no way to recover from that.

Here's some extra commentary on the Chaos Monkeys concept
http://www.codinghorror.com/blog/2011/04/working-with-the-chaos-monkey.html