问:
Best practice refactor n-tier into vertical slices architecture
What work path do there exist to identify reasonable vertical slices of a classic n-tier platform code base and infrastructure (enterprise size)? Regardles of refactor or a new solution I think there will be the same approach (more or less?) So i'm primary interested in steps and definitioning of modules, functions, then "test" them into a function-unit or if it's appproved as a vertical.

To extend my thoughs..

I understand that a vertical should be a actor, a kind of business value. But is a communication system a actor, or a functional unit in a vertical slice? Probably yes And no (depends on enterprise), but how to decide? Is shipment a part of Order, or are both Order and Shipment different verticals?

What should a vertical slice consist of, to be a true vertical? In terms of Levels of functions, like "an own data store, an own client configuration tool, an own business intelligence calculation" and so on. Btw: It's a requirement that the verticals should be deployed and operatable independently of each other.

Maybe there is a kind of "yes/no" schema to use? "Is this X used for Y?" Yes - then it's a vertical. "Is this X used with Z?" - Yes, then it's anti-pattern for vertical. "Is X depend on the funtion YY?" If yes, then..

And so on. Links to success stories when define verticals is also of interest.

答:
The correct way may not be strictly horizontal or vertical, but wavelet:

http://www.mathworks.com/help/wavelet/gs/ch01_intro42.gif

X-axis: functional units of an enterprise (Order, shipment, etc)

Y-axis: the layers of software architecture (database, transactions, message queues, services, web-services, front-end)

The key is to build the lower-level layers of software in a highly-reusable way, and easy for the higher-level users, so that the developers of the higher layers do not need to spend too much time redoing what the lower-levels ought to be doing.

The advantage of the reusable lower-levels can be extended beyond software programming - configurations, virtual-machine images, software licenses, and even hardware specifications (or even standardized server machines) can all be designed with reusability (by multiple business units) in mind.

The higher layer may need to talk to multiple functional units to get things done.

Consider the issue of customer support in your example.

If there is a problem in the Order system, the customer needs to be contacted.

If there is a problem with Shipping, the customer also needs to be contacted.

The blog post http://simpleprogrammer.com/2011/11/21/understanding-the-vertical-slice/ suggested by @user61852 talks about writing new software. When taking the vertical slice approach, one tries to satisfy a small facet of functionality requested by a single functional unit, by implementing the smallest amount of software.

Example: If shipping needs to talk to the customer, they will only be given an extension number to the customer representative department and a customer ID. Someone in the shipping department needs to do this manually.

In the future, it may be integrated with Skype, but that's the long future.

The blog post implies the use of a lot of mock-ups, throw-away UIs, and prop-ups (imperfect way of meeting part of functional requirements) while a more endurable implementation is scheduled later in the project.

The blog post does not talk about refactoring an existing enterprise software system.

As @GlenH7 implies, if it's working, don't make risky changes to it.


问:
If you were the manager of a team of 25 developers, how would you motivate them?
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.

答:
I manage a team of six programmers, so I give this topic a bit of thought. Here are my ideas -

Give them time to work - Interruptions kill productivity and motivation. Programmers like it best when they can get their heads down and get on with the work. You also need to give them time to do a job well - programmers hate rushing to get something finished by an arbitary deadline. I usually ask my programmers how long a task will take, and then respect their estimate. Part of my job as team leader is to manage that off with the business, and help them develop realistic expectations.

Give them good equipment - It is terrible having to program on slow computers, and most programmers hate using old development tools as well. Make sure your programmers have really good equipment - fast computers, latest tools, big screens, and also a very good chair. These things are not all that expensive in the grand scheme.

Give them respect - Programmers strongly desire respect for their technical skills. Honour the work that they have already done, and the work they are doing. Respect their opinions on technical matters. When you ask a technical question, take the answer at face value. If they have made a mistake, find a way to bring this up without them losing face. You can say things like, "I followed what you suggested, but I came across this issue. What do you think I should do?"

Give them permission to go home - Working long hours soon becomes counter-productive. When programmers know they can go home at 5pm, they are much more likely to come back the next day feeling motivated to work.

Give them responsibility - Programmers like making technical decisions, so give them the space to develop things the way they think best. If you have architectural or design standards, make sure these are understood up front. If problems come out during a design review, make sure these are communicated in a respectful and encouraging way.

Give them support - Make it easy for them to come and ask for help if they need it. Say, "if you've got any questions, don't hesitate to ask." Don't make them feel bad for not knowing some technology, instead say, "If you need a couple of hours to brush up on that tech, go ahead."

ContentLicense: CC BY-SA 2.5


问:
When to act on impediments?
During the meeting, each team member answers three questions:

What have you done since yesterday?

What are you planning to do today?

Any impediments/stumbling blocks? Any impediment/stumbling block identified in this meeting is documented by the Scrum Master and worked towards resolution outside of this meeting. No detailed discussions shall happen in this meeting.

In the last question, it states that "Any impediment/stumbling block identified in this meeting is documented and worked towards resolution outside of this meeting".

From my experience, just about every "impediment" results to slippage.  So how would you, the average Scrum Master respond to such slippage?  Do you assume that only a day slippage in a two or three week sprint is normal and hope for the best?  Do you assume that a three day slippage is reason to assign help?  What would 'your' tolerance level for slippage normally be?  Do you have a formula you stick to (ie: if the slippage is 20% late you automatically assign someone to help)?

I'd just like to get a better understanding of this third rule.

答:
You should act on those impediments, but only as far as providing advice and guidance. You should ask them if they require help, maybe negotiate with different developer if they can provide help. But do not provide help without developer's consent. They would get idea that they are micromanaging them too much.

But it is given that those slippages will affect burndown of the whole sprint. So if you happen to know that there will be few day slippage, you should discuss updating sprint backlog  with product owner. It will probably result in some low-priority tasks being dropped.

Also, during sprint retrospective, you should bring up this slippage and work out reason for it and what to do not to repeat it again. Maybe the code is mess and requires refactoring. Or maybe the requirements weren't clear enough and you should be more careful next time. Or the library the developer used was poorly understood so you should provide more training. Etc..

ContentLicense: CC BY-SA 3.0

Title: When to act on impediments?


答:
Seems to me you are treating a scrum stand-up meeting rules a bit too much like a formula and in your formula there's two steps: 1) someone says they are blocked; 2) I must do X -- help me find X.

Things aren't that simple. The goal of a stand-up meeting is for the entire team to get together and share where they are, what they've done and where they are going. Your rule #3 is there simply to ensure that the meeting stays short and to the point. Reason for that is because you do stand-up meetings everyday and if you start having discussions every time someone brings up a point, you'll end up with 1 hour+ meetings that will get very expensive, very fast... I've been in those, they are not fun.

So since you are looking for a formula, I'd like to propose a modified, 3-step version of what you had:

someone says they are blocked

after the meeting talk to ONLY people that need to be spoken to. Clearly person that is blocked might want to elaborate on what help he/she needs. Maybe another teammate or two want to be involved as well.  There's a very good chance, 75% of your team will be able to go back to their work and continue being productive, which is why the advice is to not have any discussions in the stand-up

Do X -- where X is the conclusion from (2), not what the Internet tells you to do.  And yes, it will be different for every situation because people get blocked for all kinds of various things.

Few more words of wisdom which I wanted to share...

As a scrum master, your role (and it is very important one) is to make sure your team functions as smoothly as possible.  It doesn't mean you can't have a single wrinkle and everything must be tip-top. There will always be blockages that you can't do anything about. It just means, do your best to ensure your team stays productive. So once you find out that something is blocking a story, let your team members go back to work and focus and you take a look to see if you can unblock them. Sometimes you can, sometimes you can't.

Mis-estimation is not same thing as blocked.  If someone started working on a story and then realized that it involves 5 times the amount of work.  Yes, that's a cause for concern but in this case, as a scrum master you should encourage process improvement to improve estimation. Unfortunately, there will be very little that you'll be able to do in current sprint. Sometimes stories do not get done as planned. That's life. The key question you should be asking yourself and the team is are you doing anything different/better to ensure that next iteration the team will perform better?

"assign someone to help" -- you mentioned that twice in just few lines of text and based on that, I formed an opinion (maybe not a correct one) of what kind of manager you might be.  Do not throw more people, technology, chairs at a problem whenever you are forced with one.  ASK YOUR TEAM.  The point is not to ask your team in a stand-up, but nothing is stopping you to have a one-off discussion and ask your blocked teammate if another person would help. In some cases, higher headcount could help. In MANY cases, higher headcount causes more headache, lowers quality and your schedule slips even further.  In ALL cases, your team will know what they need, not us.

Collect and analyze statistics. That's one of the reasons agile suggests short iterations. When we do same thing many times over and over. It gives us chance to improve ourselves, but only if we take the time to look back and see how we've been doing. Your team is too busy delivering work but you can take some time and write down some information. How many times were you blocked per iteration?  Is there a person that seems to be blocked more often than others? How much do you typically slip by? (can you compensate by planning less in next iteration).  Show this data to the team and ask them where/how they can improve.  As Euphoric suggested, a retrospective meeting at the end of an iteration is a great place to do this.

Scrum master IS NOT a manager or a overlord. Remember, don't try to come up with a solution and throw it back at the team. Work with the team and encourage them to come up with their own solution.  Then do your best to help the team implement it.

Title: When to act on impediments?

Body:
During the meeting, each team member answers three questions:

What have you done since yesterday?

What are you planning to do today?

Any impediments/stumbling blocks? Any impediment/stumbling block identified in this meeting is documented by the Scrum Master and worked towards resolution outside of this meeting. No detailed discussions shall happen in this meeting.

In the last question, it states that "Any impediment/stumbling block identified in this meeting is documented and worked towards resolution outside of this meeting".

From my experience, just about every "impediment" results to slippage.  So how would you, the average Scrum Master respond to such slippage?  Do you assume that only a day slippage in a two or three week sprint is normal and hope for the best?  Do you assume that a three day slippage is reason to assign help?  What would 'your' tolerance level for slippage normally be?  Do you have a formula you stick to (ie: if the slippage is 20% late you automatically assign someone to help)?

I'd just like to get a better understanding of this third rule.


问:
Encapsulation in Domain Driven Design models?
I am using EF Code First and I had a model like below.

```<code>public class Account
{
    [Required]
    public string AccountNo { get; set; }
    [Required]
    public decimal Balance { get; set; }
}
</code>```

I used a Service class to withdraw and deposit amount to Account. Then I came across this and realised that Account is Anemic. So I happily added Withdraw and Deposit methods to Account.

```<code>public class Account
{
    [Required]
    public string AccountNo { get; set; }
    [Required]
    public decimal Balance { get; set; }
    public void Withdraw(decimal amount)
    {
        // TODO: Check if enough balance is available
        Balance -= amount;
    }
    public void Deposit(decimal amount)
    {
        Balance += amount;
    }
</code>```

}

I was very happy with this until I realised that this does not implement encapsulation correctly. You should not be able to modify the Balance directly - you should use Withdraw and Deposit methods. But in my solution you can modify the Balance directly.

But I cannot make Balance a readonly property as I am using EF code first approach and readonly properties won't result in the column being created in the database table.

I thought of leaving Account as anemic and create a higher level Account class which implements encapsulation and Withdraw/Deposit methods. But in that case the higher level class would not have validation data annotations and I won't get the free functionality provided by the framework.

What is the solution?

答:
The way in which you describe it, the Balance of an Account is the result of all the Transactions applied to that Account.  In this case Balance is a read-only property because you would modify it by appending a Transaction to the list attached to the relevant account.  So perhaps an additional Transaction class would get you what you want.

It is also normal to have smaller, simpler classes in your Data Access Layer that are composed by classes in the Business Layer.  If you need a read-only value that could be loaded from a database, then having a Business Layer object that can be constructed from your Data Access Layer, but doesn't then expose it publicly is a perfectly fine way to go.  Alternatively you can have Mappers that convert Data Access Layer classes to Business Layer classes and vice versa.


答:
So how would you, the average Scrum Master respond to such slippage?

There is two parts to this: impediments and slippage.

Slippage can happen due to impediments, but it can also happen due to unexpected problems (which do not need to be impediments) or someone getting sick or something as simple as an urgent field issue. When we're going to miss our goals (or even when we will probably not meet our goals), I will communicate that to product owners and other team leads. Slippage will happen, but where it hurts development is when expectations aren't set properly and estimates/process aren't adjusted to account for the things that cause you to slip. But I would not change anything mid-sprint, certainly not reassigning people to help. Deal with estimate/process improvement in your retrospective & sprint planning.

Impediments on the other hand are times when developers run into a roadblock... a missing tool, some prerequisite code isn't there, some person is out/missing/being unhelpful. They've tried to solve the problem, but cannot. That is your cue as scrum master to immediately track down the cause and unblock them. There should be no "tolerance" for impediments.

Title: When to act on impediments?


答:
in order or importance:

shared vision

clear expectations

predictable environment (TDD, nightly builds, daily team chats, weekly check-ins, whatever works for your team and product)

the best tools possible

serious salary with overtime

telecommute

stock options

Title: If you were the manager of a team of 25 developers, how would you motivate them?

Body:
Imagine yourself hired by a new startup backed with few millions coming from venture capitalists.

Your mission: organize the development of the next killer app.

25 developers is too much to take care of each individually, so what decision(s) you would make to motivate them?

I will appreciate any answers from stock options to free cookies ;)

Of course the trick here (unless you are really a manager of a such startup), is put yourself in the shoes of one of those programmers.

EDIT: it's an imaginary context. The purpose of this story is to stimulate your wishes. I want to capture what motivates developers.


问:
object oriented analysis, missing methodology
I've studied design pattern and oop principles, still feel that there is something missing in most design theories. Maybe the fact is that there is not a 'theory' as it is in database design.

Let me explain with an example.

Suppose that i want to model different ways to produce orange juice.

Let say that i start by a class Oranges, that models a lot of oranges that will be of a certain variety, of a certain ripeness, they may have been froozen etc., ant these will by my Oranges class properties.

Then i continue by providing Orange with a squeeze method.

This seems to be correct, because ties togheter the method to the data it applies to, that is the precondition to achieve encapsulation and other valuable oop principles.

But quickly it comes out that it has not been a good choiche because there is not just one way to squeeze an orange. It would be preferrable to have a Juicer class whose instances contains details of the juicing method: by hand, with an electric juicer, including the pulp, not to mention mixing different varieties of oranges. Where the latter opens an whole new cathegory of possibilities that were not available (or not achievable with ease) if each Oranges instance would have been processed using its squeeze method.

Say that we have performed a 'refactoring' of our oo architecture and move to another similar example that will get us to the point.

It is now a common practise to use an ORM to save class instances to database and get them back later.
In what is it similar to the Oranges class example? Well, here i have a class whose instances may be persisted to a database, that is 'allow a particular process'. But the class itself does not contain the logic for doing so, that actually is in the ORM classes. So it seems that the same process of 'externalization' of the Oranges example has taken place in this case too.

And here is the question

Given that it is desireable to reduce the number of attempts-and-refactorings to the minimum, what are the questions that a programmer should put in order to determine precociously if a method should be externalized to another class?
Are all the methods of a class exernalizable or is there a set of core methods that are inherently of the class itself and so not externalizable?

Ideas

As i said in the beginning, i'm not completely clueless, i feel more like that a 'comprehensive' theory is missing.

It's easy to put some examples:

if i have a class whose instances represent invoices, i will have a method 'calculateTotalAmount'. This is clearly an inthrinsic, core method of that class, as oppsed to the methods for saving that invoice to the database that will be 'external' of the class itself.
But this is not a 'final answer', but a starting point that serves to demonstrate that 'not all methods are equal', but methods may be divided into cathegories. How many (useful) cathegories can we make, and are there methodologies that put these questions?

答:
What are the questions that a programmer should put in order to
  determine precociously if a method should be externalized to another
  class?
  Are all the methods of a class exernalizable or is there a set of core
  methods that are inherently of the class itself and so not
  externalizable?

As I have learned about design ("Agile Principles, Patterns, and Practices in C#" by Robert and Micah Martin) one should fully understand the real process in order to create the correct abstraction. And once you have it -provided you base that abstraction on interfaces- you're rewarded with a "polymorphism gain".
Having that in mind I see an important question is "Is this behavior something this element does for itself or it's another element's behavior -acting on this- that produces the result? (orange juice, persistence, whatever)".

Additionally in Craig Larman's "Applying UML and Patterns" you find what he called "GRASP" (General Responsibility Assignment Software Patterns). For example:

Information Expert
A general principle of object design and responsibility assignment?
Assign a responsibility to the information expert— the class that has the information necessary
to fulfill the responsibility.

Low Coupling
How to support low dependency and increased reuse? Assign
responsibilities so that (unnecessary) coupling remains low.

High
Cohesion
How to keep complexity manageable? Assign
responsibilities so that cohesion remains high.

Pure
Fabrication
Who is responsible when you are desperate, and do not want to violate high cohesion and low
coupling?
Assign a highly cohesive set of responsibilities to an artificial or convenience "behavior"
class that does not represent a problem domain concept — something made up, in order to
support high cohesion, low coupling, and reuse.

Indirection  How to assign responsibilities to avoid direct coupling?
Assign the responsibility to an intermediate object to mediate between other components or
services, so that they are not directly coupled.

I've seen that when you manage to produce a good model you really have a group of cohesive objects sending messages to each other and everything runs smoothly. On the other hand you know that "something" is wrong because the interactions are not natural.


问:
How to track features in a big project ?
I am currently working on a project of my own for a little over 2 months (not much time on my hands). The purpose of this project is to be able to remotely update all of my Linux systems from one graphical application.

The problem I am having is I am building two applications: the client and the server. As the size of both the programs increases, I am finding it harder to manage what needs to be done.

While coding I am trying to think of things that need to be done and with the addition of another program it's starting to make my head spin.

Is there any technique by which I can track the features: yet to be implemented and currently under development features in a big project?

答:
I guess it will help You a lot if You try to right down every thought of List of activities on a paper. Then You attack one problem at a time. During Your Implementation  You might find some new ideas, You can write them.

Also it is a suggestion that before You write an implementation You write a pseudo code, that will reduce Your rework.

Hope that helps

Update:

The key to writing Pseudo code is You don't think the problem as a giant chunk. If You think it like that You might end up in the situation as You are in now. Instead I would advice You to take that problem, break down into steps, further if possible break down those small steps into more smaller steps. Do this process recursively. You will certainly end up writing the pseudo code and hence Your problem will be solved. I will try to give an example.

Suppose I have a problem: I need a program that makes coffee.

Ask the question to Yourself: what Do I need to make a coffee?
Sugar, Milk, Some hot water, Kettle, Cup and coffee ofcourse :)

Step1: I need a kettle that should have some hot water in it.

Step2: I need to somehow add some coffee in it.

Step3: I need to add milk (as per the formula) in it.

Step4: I need to add some sugar in it.

Step5: I need to pour that into a cup and serve.

*Disclaimer: * I am not a good coffee maker :)

I guess You got a feeling of how to tackle the big problem.


答:
Are all the methods of a class externalizable?

Yes, you can completely separate all methods that operate on a class from the class its self. Should you completely separate all methods from a class? Well, that depends on how you want to organize your code.

is there a set of core methods that are inherently of the class itself and so not externalizable?

Yes, any method that requires only the values associated with an object. Anything else should probably be externalized and handled by another class.

You mentioned the database and ORMs, if you wanted to include the method for saving an orange to the database within an orange class, now your orange needs to know about your database. Why does your orange need to know about your database and what are the pros and cons of this decision? Well, the method for saving an orange is close to the data that is being saved, that seems good. However, now you cannot have an orange without having the database.

To me, that last line really drives it home. In the real world, oranges don't know about databases so why should they in your code. In short, there is no one size fits all theory/pattern, it is up to you as an engineer to see how all the pieces fit together.

Title: object oriented analysis, missing methodology

Body:
I've studied design pattern and oop principles, still feel that there is something missing in most design theories. Maybe the fact is that there is not a 'theory' as it is in database design.

Let me explain with an example.

Suppose that i want to model different ways to produce orange juice.

Let say that i start by a class Oranges, that models a lot of oranges that will be of a certain variety, of a certain ripeness, they may have been froozen etc., ant these will by my Oranges class properties.

Then i continue by providing Orange with a squeeze method.

This seems to be correct, because ties togheter the method to the data it applies to, that is the precondition to achieve encapsulation and other valuable oop principles.

But quickly it comes out that it has not been a good choiche because there is not just one way to squeeze an orange. It would be preferrable to have a Juicer class whose instances contains details of the juicing method: by hand, with an electric juicer, including the pulp, not to mention mixing different varieties of oranges. Where the latter opens an whole new cathegory of possibilities that were not available (or not achievable with ease) if each Oranges instance would have been processed using its squeeze method.

Say that we have performed a 'refactoring' of our oo architecture and move to another similar example that will get us to the point.

It is now a common practise to use an ORM to save class instances to database and get them back later.
In what is it similar to the Oranges class example? Well, here i have a class whose instances may be persisted to a database, that is 'allow a particular process'. But the class itself does not contain the logic for doing so, that actually is in the ORM classes. So it seems that the same process of 'externalization' of the Oranges example has taken place in this case too.

And here is the question

Given that it is desireable to reduce the number of attempts-and-refactorings to the minimum, what are the questions that a programmer should put in order to determine precociously if a method should be externalized to another class?
Are all the methods of a class exernalizable or is there a set of core methods that are inherently of the class itself and so not externalizable?

Ideas

As i said in the beginning, i'm not completely clueless, i feel more like that a 'comprehensive' theory is missing.

It's easy to put some examples:

if i have a class whose instances represent invoices, i will have a method 'calculateTotalAmount'. This is clearly an inthrinsic, core method of that class, as oppsed to the methods for saving that invoice to the database that will be 'external' of the class itself.
But this is not a 'final answer', but a starting point that serves to demonstrate that 'not all methods are equal', but methods may be divided into cathegories. How many (useful) cathegories can we make, and are there methodologies that put these questions?


答:
The simplest thing to manage a project is a list of things to do.

The simplest tools for this that still allow you to filter and re-order your task in a convenient manner are a spreadsheet (see Joel's article Painless software schedules) and a (hierarchical) todo list.

A hierarchical todo list allows for subtasks in a more convenient way than a spreadsheet would (you would have to repeat the parent task there to maintain the relation between the task when re-ordering). The best I have come across and have used for many pet projects of my own is ToDoList from Abstract Spoon.

Software supporting SCRUM and/or kanban boards are another way of keeping track of what to do. Trello and Pivotal tracker come to mind easiest, but there are plenty more online, most of which offer personal (or limited) use for free.

Title: How to track features in a big project ?

Body:
I am currently working on a project of my own for a little over 2 months (not much time on my hands). The purpose of this project is to be able to remotely update all of my Linux systems from one graphical application.

The problem I am having is I am building two applications: the client and the server. As the size of both the programs increases, I am finding it harder to manage what needs to be done.

While coding I am trying to think of things that need to be done and with the addition of another program it's starting to make my head spin.

Is there any technique by which I can track the features: yet to be implemented and currently under development features in a big project?


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

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

答: Can you write a simple time entry and billing system for our new foreign office that uses a different language, currency and tax laws?</p>


问:
Finding all points that are located in one line in 2D coordinate system
I have an array of points. Each point has two members - x and y.

I want to get any 3 points and check, are they located in single line in 2D coordinate system.

For example - 1x2, 2x3, 5x6:

If yes, I want to search for another point in my array which is located in that line (line has no start and no end). And so on, while I didn't check all remained points.

Then, I want to check next combination of 3 points and repeat while all 3-points permutations are no checked. For every of that permutations I want to tell how many points are located in single line (0 - if these 3 points are no located in single line, 3 - if they are, 4 - if they are and that's other point which also is located in that line, etc.). Is there any effective algorithm that can do it in complexity equal or less than O(n3)?

答:
For two points you can calculate the slope and the y intercept. If two different segments are part of the same line they will have the same slope and the same y intercept. If they have the same slope but different y intercepts they are parallel.

The only issue is when the line is vertical, the slope is infinite and the there is no y intercept, unless it is the line x=0.

Calculate all the pairs of points, and then cluster them by slope and intercept.


问:
Better design for a generic doubly linked list around which I plan to make different wrappers?
I am currently writing a C code for a doubly linked list(dll) around which I want to write wrapers for implementing stack, queues etc. instead of writing separate codes for all of them.

I'll be using void * for making it possible for the doubly linked list to work with any data type. The idea is basically the same as this implementation of stack using pointers in my github.

I am thinking of 2 different designs

Placing the size of elements alongwith the maintenance data. That would make coding easier but any instance of dll would be able to use only a particular data type.

Placing the size of element in the nodes. That would make it more general but I have concerns whether this approach would be easier to use?

This is the confusion that I wanted to clear before implementing any particular one. If there is any confusion regarding what I am trying to implement then please ask and I'll clarify.

答:
Let me start by answering your question:

Storing the element size per-node or per-list isn't going to make the code any more or less complex one way or the other.  The only real difference will be that anyone calling to add a node will have to pass a size once or each time, and the amount of storage required for each node may grow by an extra size_t's worth of bytes.  The tradeoff between using less memory and having less flexibility versus using more memory and having more flexibility is something you'd have to evaluate on a case-by-case basis.

Let me finish by suggesting an alternative:

If you're implementing this to be general-purpose tools along the lines of the STL or Java's generic containers, I would suggest taking a completely different tack and not trying to do anything with the pointers you're given.  Just store them in your list and return them as it's traversed.

Your allocate-and-copy approach goes on the assumption that what's being stored are simple structures, which has a couple of pitfalls:

My structure may have additional pointers to allocated memory.  If I'm using your list as primary storage for my data and you take it upon yourself to free() it when I call your cleanup() function, there's no opportunity for me to free any of the additional memory unless I traverse the entire thing beforehand and do my own cleaning up.  If that's going to be the case, I might as well just do a traversal and remove the nodes one at a time.  You could work around this by providing a disposal hook, which you'd call anytime you wanted to de-allocate a node.

The pointer I hand you may not be a pointer to a structure.  For example, I may have a large block of memory and want to store a list of place markers or something which involves simply pointing at various places in the block.  Your implementation requires that I give you a place to copy data from/to during push, pop and peek operations.  I'd have to define another structure with a single member to hold my pointer value.  That's awkward and inconvenient.  (You could, however, write a wrapper that does allocate-and-copy and uses the pointers-only implementation.)


问:
How to call something that can be both a user and a usergroup?
My idea is, to create an abstract class / interface which can be extended into a user, and into a usergroup. </p>

<p>There actually is a good reason for there being this interface connecting the groups with the users as the only differences between a user and a group is that you can login as a user and you can't as a group, and that a group can contain multiple users or groups. Permissions and stuff are handled without taking notice of it being a user or a group. </p>

答:
In computer security, users and groups are referred to as Principals.

Security principals include the following:

Any entity that can be authenticated by the system, such as a user    account, a computer account, or a thread or process that runs in the

  security context of a user or computer account.

Security groups of these accounts.


答: "EndUser" may be? I thought it can be a name for a group of people related to both the group or single user, they all "use in the end"</p>

Title: How to call something that can be both a user and a usergroup?

Body:
My idea is, to create an abstract class / interface which can be extended into a user, and into a usergroup. </p>

<p>There actually is a good reason for there being this interface connecting the groups with the users as the only differences between a user and a group is that you can login as a user and you can't as a group, and that a group can contain multiple users or groups. Permissions and stuff are handled without taking notice of it being a user or a group. </p>


问:
What mistakes in managing software products must be avoided to keep people from hating the vendor?
A previous question about why people hate Microsoft was closed. This is an attempt at a somewhat more constructive question along the same general line. This one is both broader and narrower though. It's more general by being about software vendors in general, not just Microsoft. It's narrower by dealing only with management of software products.

So, what steps should be taken (and/or avoided) in managing individual software products to assure that not only the individual products, but the company as a whole is respected/liked/seen in a positive light?

答:
A non-exhaustive list, starting with two that can go a long way to creating really passionate customers, ones who will go out of their way to promote your product.

A responsive, respectful support model. Nothing like being fast and giving your customers good support. Ideally a direct response model. Even with a community support model like a bulletin board site where anyone can ask and anyone can answer questions but moderating it and seeding it with support staff will help. An old maxim about customer service - give someone good customer service and they may tell one person about it. Give them poor customer service and they will tell 10 people. In the web world that 10 people now gets multiplied many times.

Using good design - you want to aim for delighting people. This takes not just engineering but design - listening to customers, watching over their shoulders, prototyping, and continuous improvement of released products.

Two others I'd add:

Quality - yup, keeping a tight lid on the bug count, not releasing until it is solid. Focusing on a solid product rather than a flaky one with feature overload. I remember sometime during the frenzy of web 1.0, a large vendor announced how great it was to be able to develop software iteratively without a real quality process when developing websites. Around that time, I tried one of their new sites and it broke on me almost immediately. It seemed clear it had NO testing before release. A good way to frustrate your allies and turn away new customers.

A licensing model that works well for how people will use the software. People know they need to pay, but if you can reflect the flexibility people need in your policies, then it works for everyone. Example: per-seat licenses that allow you to use multiple computers, or a work and home computer. Because a lot of people have more than one computer.

-- Alex


问:
What are the good practices for including namespaces in C++ that avoid more typing?
I am starting out with C++ and almost everywhere I see there is these 2 sentences at the top.

```<code>#include <iostream>
using namespace std;
</code>```

As I understand namespaces are something to keep names separate and have same identifiers in different namespaces. So isn't including std in the beginning undoing all the hard work of creating namespaces? Isn't it better to have something like std::cout when I need a certain function from a particular namespace?

Would including the namespace in the particular function that uses it a good tradeoff between less typing (std::cout vs. cout everywhere) and avoiding the name conflicts(abc in foo and abc in bar avoided using foo::abc and bar::abc)? Something like

```<code>int function_using_abc_namespace(int a)
{
    using namespace abc;
    //Rest of the function
}
</code>```

I wanted to know because avoiding name conflicts is necessary but avoiding more typing is also important. If this isn't good way to get a middle ground then what are the alternatives?

答: It's usually recommended not to have using namespace std. Books do it (usually with explanation) just for brevity. Similarly for other namespaces, but there are cases where you might reasonably disagree, and use it anyway.


答:
Probably the cleanest answer is to use composition.

Have a class for the group.  Have a method on a user that gives the one element group that is the user.  Allow one group to be included in another one.  Inclusion is a transitive relation, implemented through recursion, that you can speed up at run-time by caching the fact that group X is or is not included in group Y.  Add the user to a group by including the user's group in the other group.

And now you never need to have a method that can accept either a user or a group.  Any given method either accepts a user and does things that a group cannot do, or accepts the group that you can get from the user.


问:
Different ways to generate the latest int type primary foreign key in code
I am new to sql. I have added 2 new tables in database. The primary key of first is a foreign key in the other. The type of the keys is integer. Now I want to generate the keys in the code and assign it to new data so that the association between different rows of the tables is right. How do I ensure uniqueness of keys and also get the latest key from the db so that there are no errors while saving.

If I had used guids then I would have assigned a new guid to the primary key and then assigned the same to the foreign key in the other table. Also there are multiple clients and one server which is saving the data.

The data to be inserted in both the tables is decided in the c# code and is not derived from the row inserted in the primary table. Even if get the id in db then also the relation between the rows should be stored in some form from the code because after that it is lost.

答:
If you must generate keys on the clients, then you'll need some way to avoid collisions (two clients creating the same key).  You can do this using GUIDs, because GUIDs are huge and the algorithms that generate them have been designed to minimise collisions.  If you must use INTs, then you'll need to roll your own method, probably having each client reserve a block of IDs ahead of time, which is just going to be convoluted, so don't do that.

It's much easier to generate keys on the server, because it's always around and it knows what has and hasn't been used.  In SQL Server, you can mark your id column with IDENTITY , to have SQL Server automatically generate an ID when you insert a record into that table.  You can get the value that SQL Server used in the insert you just made using the @@IDENTITY function or the SCOPE_IDENTITY function.  If you are using a stored procedure you can return the identity values as an output parameter or in the resultset, or you can SELECT SCOPE_IDENTITY() from your client.


答:
A very good principle that comes up a lot is that if you're going to make the next person have to learn something, then make sure that they get to amortize that knowledge over a lot of uses.

That means that using namespace std should be part of a coding standard.  Either you learn that anything from std is available, and you benefit everywhere.  Or you don't learn that but have to type std everywhere.  Either position is defensible.

The same principle goes for your internal code.  It is OK to have using namespace Foo in your project, but there should be a limited number of namespaces that you import that way.  And that list should be imported everywhere.  Exactly so that everyone on the project is forced to learn what's in Foo and can then benefit repeatedly.  But be very cautious about increasing that list - the people who are inclined to do so are the people who know your code best and who therefore have the least awareness of what it is like for people just learning your code.  If you're on the fence, always err on the side of being explicit.

This generalizes much farther.  Whenever you're setting up a project, thing long and hard about what people who work with the project need to know.  Write down that list.  Think hard about adding to it.  But anything that is added to that list, should get used heavily so that you get maximum value out of the forced learning.

Title: What are the good practices for including namespaces in C++ that avoid more typing?

Body:
I am starting out with C++ and almost everywhere I see there is these 2 sentences at the top.

```<code>#include <iostream>
using namespace std;
</code>```

As I understand namespaces are something to keep names separate and have same identifiers in different namespaces. So isn't including std in the beginning undoing all the hard work of creating namespaces? Isn't it better to have something like std::cout when I need a certain function from a particular namespace?

Would including the namespace in the particular function that uses it a good tradeoff between less typing (std::cout vs. cout everywhere) and avoiding the name conflicts(abc in foo and abc in bar avoided using foo::abc and bar::abc)? Something like

```<code>int function_using_abc_namespace(int a)
{
    using namespace abc;
    //Rest of the function
}
</code>```

I wanted to know because avoiding name conflicts is necessary but avoiding more typing is also important. If this isn't good way to get a middle ground then what are the alternatives?


问:
Add javascript to all pages (for caching), or only to the pages that require the scripts (for a smaller page size)?
I'm using bits of javascript on my website for an image gallery, smooth scrolling, etc. These scripts are not used on every page (not every page has an image gallery for example). However, the scripts aren't very big and most users will have to download them eventually (the image gallery is very central to the website).

Now what would be the pros and cons of these two (mutually exclusive) ways of including the scripts:

add them to every page (so that they'll all be cached after one page view)

add them only on the pages on which they are used (so they're cached only when they're needed, but some pages will take a little longer)?

I'm not asking for opinions, I'd just like to know if there are any pros and cons I've overlooked.

答:
I do not know what considerations you have made.  My recommend would be that you load into each page only what you need to load that page.  And then lazy load everything.  Make the lazy loading something you can switch on and off easily.

This will make initial page load as fast as possible on the first page you encounter.  The lazy loading will speed up the second page load.  And you can QA with lazy loading off to be sure that everything that is needed for a page is actually loaded.  (Else it would be easy to miss the fact that a user could get JavaScript errors because they are trying to interact with something that hits a library that isn't there yet.)


答:
Updated answer based on updated question

It is okay to using namespace std in *.cpp files.
It is okay to using namespace std inside function bodies.

Reason: In both cases, they aren't contagious. Contagiousness is the only reason why they shouldn't be used at the global namespace level in header files.

Single-file C++ projects (having just one *.cpp file, no headers, e.g. in programming puzzles and competitive programming) can use them liberally.

Original answer

The only hard rule with using namespace std; in C++ is this:

Do not put this in a header file, if this header file needs to be included by multiple source files (*.cpp).

Reason: it is contagious.

Other than that, I suggest taking a pragmatic approach to it:

Allow importing namespaces as long as it does not cause a compiler warning / ambiguity / conflict.

This brings up the question of: what is the true benefit of having namespaces? The simple answer is disambiguation. But disambiguation for who's benefit?

Disambiguation for programmers?

This is a relatively minor benefit, because most programmers are already accustomed to object-oriented programming, and the naming of objects is already sufficient for telling about the category and the purpose of that object.

However, only human can make sense from the name of objects - computers can't. (See the next point about automated tools.)

The human mind is excellent at resolving ambiguity by taking context and domain knowledge into account.

Disambiguation for automated tools, such as compilers, automatic comment-to-documentation generators (Javadoc, Doxygen, etc), and automatic refactoring tools?

I would argue that this is a more important reason for using namespaces.

By putting objects into namespaces, automated tools can present groups of objects as interrelated.

This helps hierarchical organization of class documentations, enforcement of package visibility rules, and many other neat things.

Therefore, as long as it does not cause a conflict, feel free to import namespaces.


答:
going directly from your example:

"certain ripeness" - is a core business rule that has control over the behavior of whatever is built. there are oranges that are unripe, and oranges that are ripe.

this is either automated - the oranges are compared against a ripeness scale. OR this has to be done manually by an Orange Juice Manager. either way thats where the implementation requirements of the objects comes from. the first question is - does the Orange Juice Manager also control the Juicing ? Or does the Orange Juice Manager hand off a "ripe" set of Oranges to a Orange Juicer Person?

if yes then that is the first clear boundary. the orange juice manager approves the oranges, determines the amount to be squeezed - and then hands it off to the Orange Juicer person. The Manager does not know how the juice is going to be squeezed or what kind of device is used.

Those are the important details of the design. the specifics of the oranges and how they are squeezed are implementation details and as such -- they are volatile and we expect them to change.

The Orange juice manager acts upon objects, but they will always be approving oranges and orders. The Juicer will always act upon objects - he always return orange juice. That is an abstract concept - it is stable and it does not change.  HOW he squeezes the oranges is a specific concept - therefore it it unstable, therefore it will change, therefore it is further down the class responsibility chain.


答:
1) Create a quality product

2) Understand the customer

3) Maintain consistency

Title: What mistakes in managing software products must be avoided to keep people from hating the vendor?

Body:
A previous question about why people hate Microsoft was closed. This is an attempt at a somewhat more constructive question along the same general line. This one is both broader and narrower though. It's more general by being about software vendors in general, not just Microsoft. It's narrower by dealing only with management of software products.

So, what steps should be taken (and/or avoided) in managing individual software products to assure that not only the individual products, but the company as a whole is respected/liked/seen in a positive light?


问:
Handling or preventing conflicts in a multi-user system
I have a web application that is accessed by multiple users from different locations worldwide. Let's say I have an "edit" form for a specific document and two (or more) users are editing the document at the same time. I know that both of the users can edit the document and submit it, but user1 will not see that user2 made changes to the document and might submit an older version of it.

I was thinking about adding some kind of a lock, but then, if user1 only opened the document for edit, but never changed anything (and kept it open) user2 will never be able to edit it. Therefore, I was thinking to add a Timeout for the editor, but then user1 might time out before he finished doing his changes to the document (let's say, went out for launch).

The question is, how would one prevent the document from being edited from one user while the other changes it?

Note: if this question does not belong here, please explain why and where could I ask such a question.

答:
The basics of implementing optimistic concurrency aren't that hard.

First, you'll need a way to identify a row (or series of rows) in your database (think version number).

Second, when your application loads the data for your user's to review or edit, load the version of the data as well (see above).

Third, when your user goes to save their changes, you'll want to ensure that the version of the data they're changing matches the version of data that exists in the database. If the version numbers don't match then you'll raise and handle some kind of stale data exception.


答:
If they're a bunch of small scripts, just roll them into one. Loading a few small files is slower than loading one file with equal size. The sum of size of all the files might be even smaller if they're compressed (i.e. by the http server). It's easier for both the server and the clients to use one file.

Another consideration is, sometimes we put random bits in script file name so browsers see it as a different file from the cached one. Having one file makes it easier to manage this too.

Title: Add javascript to all pages (for caching), or only to the pages that require the scripts (for a smaller page size)?

Body:
I'm using bits of javascript on my website for an image gallery, smooth scrolling, etc. These scripts are not used on every page (not every page has an image gallery for example). However, the scripts aren't very big and most users will have to download them eventually (the image gallery is very central to the website).

Now what would be the pros and cons of these two (mutually exclusive) ways of including the scripts:

add them to every page (so that they'll all be cached after one page view)

add them only on the pages on which they are used (so they're cached only when they're needed, but some pages will take a little longer)?

I'm not asking for opinions, I'd just like to know if there are any pros and cons I've overlooked.


问:
What is a good license for community submissions to commercial partially closed source software?
I am maintaining a small code base that I am considering selling– but I want to allow developers that use it to submit code for addition to the trunk.  This way they can extend the framework and the community can benefit.

I want them to retain copyright to their code, but to allow me to use it however I desire, for commercial and non-commercial purposes.

I don't want to be obligated to release any submitted source(although as copyright holders they may).

The end user product will be binary distributions of the compiled code base.

Is there a good existing license for a project of this nature?  I could compromise a little to use an existing license which does not fully match this, if it will save me the legal headache.

答:
#include <ianal.h>

// And for that matter, I'm not a license expert either

Unless the copyright is assigned to you, the original author maintains the copyright on the code.

The simplest approach to this is to have contributors license the code submission with a BSD license.  This license allows you to (with some strings attached) to incorporate the code into a compiled commercial product (you don't need to release your private contributions).

A reasonably thorough analysis of the BSD license for open source (your community edition) can be found at http://www.freebsd.org/doc/en/articles/bsdl-gpl/article.html

What is necessary (remember that 'IANAL' bit) for the modern BSD licenses is to simply say that it use it in your application's about information.  An example of this in an installer.

As long as they are licensing the submissions to you with the BSD license (or compatible one), you can then use it.

You may also wish to look at the MIT license.

As I understand it (which could be wrong), the difficulty with using an (L)GPL license for the contributions would be that they would need to be in a different part of the application that you would link to - a library - but not part of the core application.

Your desire to be able to deliver binary distributions (presumably without the source) would make anything that is GPL licensed difficult to use.

Going back to the original author, none of this prevents the original author from licensing the contribution again in another product.

If your community edition software is BSD licensed, there's nothing to say someone couldn't fork it into GPL and then start contributing to that, with the licensing of the contributions being GPL (and then you wouldn't be able to use that without releasing the source).  You may wish to find something that prevents the software from being licensed or forked into an open product that prevents you from reincorporating the contributions back into your closed version.  The advertising clause in the original BSD license would prevent it from getting foked into the GPL.

If you are concerned about the GPL forking possibility, another such open-but-anti-GPL license is the Microsoft Public License (Ms-PL).

If in doubt, or confused, talk to a lawyer.


问:
What is beautiful code?
I often read that developers must write beautiful code, but for a beginner as I am it remains obscure of what is beautiful code and how do you recognize it?

The corollary question is: How to write beautiful code and what are some practical habits to improve your code's quality?, what should I care about to make the code I write beautiful (and what shoud I learn).

答:
"Beauty is bought by judgement of the eye".

That said, I think most programmers will agree that beautiful code demonstrates a balance between clarity and transparency, elegance, efficiency and aesthetics.

Clarity and Transparency: Clarity is how easily a reader can deduce what the code does. Transparent code does what it seems to do. If code seems to do one thing but actually does something else (or something more), it's not transparent - it's misleading.

Elegance: there are many ways to implement most algorithms, but some ways are clumsy while other ways are neat and graceful. Succinctness often adds elegance, but excessive succinctness can reduce clarity.

Efficiency: avoiding unnecessary use of resources (such as CPU time, memory, and I/O).

Aesthetics: being easy on the eyes. This is quite subjective. It mostly comes down to style. One important consideration is to have a consistent style. Code which changes, for example, indenting style halfway through, is ugly.

Title: What is beautiful code?


答:
My take on this is that "Beautiful Code" is not an objective or particularly useful term.  And we should not try to define it.

Typical dictionary definitions of the English word "beauty" go like this:

"1. the combination of all the qualities of a person or thing that delight the senses and please the mind"

"1. the quality present in a person or thing that gives intense aesthetic pleasure or deep satisfaction to the mind or the senses."

"1. The quality that gives pleasure to the mind or senses and is associated with such properties as harmony of form or color, excellence of artistry, truthfulness, and originality."

(Source http://dictionary.com)

The common thread is that "beauty" is about what is aesthetically pleasing.  That is necessarily subjective ... as illustrated by the saying "Beauty is in the eye of the beholder".

We can apply the word "beauty" to code, and the obvious meaning is that the code is "aesthetically pleasing".

But to then say that "beautiful code" has a certain set of attributes (as suggested by other Answers) is a contradiction of the obvious meaning of aesthetically pleasing.  Aesthetics is about how people ... individual people ... perceive things.

Or to put it another way, there is something repugnant about someone telling me what I should think is beautiful, be it in people, works of art, or ... code.

As far as I am concerned beautiful code is code that I think is beautiful, and that is it.  It is subjective and individual, and lets just leave it at that.

Title: What is beautiful code?

Body:
I often read that developers must write beautiful code, but for a beginner as I am it remains obscure of what is beautiful code and how do you recognize it?

The corollary question is: How to write beautiful code and what are some practical habits to improve your code's quality?, what should I care about to make the code I write beautiful (and what shoud I learn).


问:
Is it possible to represent mutation of object-graph efficiently with immutable states?
I am practicing using of immutable object in C++. My personal goal is representing generic object graph (in heap) with sequence of immutable graphs.

Building the multi-version graph itself isn't that much hard. The problem is performance. Brute-force versioning needs full copy of graph, and this was not acceptable.

I tried to share unchanged nodes. But in this case, I got a new problem; references. Reference to other object must be updated in whole graph. This needs visiting all nodes for each time I derive a new graph version. And this mutates the nodes with references, so they also should be derived (by copying). Performance won't be better much than brute-force copying.

As far as I can imagine, there's no real efficient way to represent mutation of object graph with immutable states. So I am asking for some idea on this.

Is it possible to represent mutation of object graph efficiently with immutable state?

答:
If you don't consider connections between the objects to be part of your versioned resource (and you might -- in which case the following probably doesn't help much), you could consider splitting your objects into a part that represents the connectivity portion of the object and a part that represents the immutable state.

Then you could have each of the connectivity sub-objects contain a vector of the versioned states. This way you could operate with a graph version number to access the appropriate immutable state.

In order to avoid having to traverse the entire graph whenever there is an update to a specific node, you can make it so that if a node is accessed with a version number than is greater than the node's current version number, the current version is used. If the node is then updated, you fill in all the intermediate versions with the previous version -- thus allowing you to do lazy-updates to the object graph.

If the connectivity between objects is part of your versioned state, then the foregoing does not work. But maybe you can extend it as follows:

For each object in the graph, create a "handle object". The handle object contains the list of versioned immutable states. Rather than storing object references in any of the objects of the graph, you would store a reference to the handle object. Then each references to the objects would be de-rereferenced through the handle using the handle and the version number of view of the object graph that was currently being processed. This would return the correct immutable state for the object. The immutable states use the handles for referring to other objects in the graph, so you always get the consistent date for the version of the graph you want to process.

The same logic described above applies for updating the versions within the handles -- which allows lazy, localized updates.


问:
What are the prerequisites for learning Go
I am considering learning Go. As far as I know about it, it's a systems language geared toward parallel programming. (correct me if I'm wrong)

Should I have a very good understanding of C in order to be good Go programmer?

How much systems concepts (*nix OS concepts) I need to master before delving into Go

What other things I should know/learn before starting Go

答:
Go can be a lot easier to learn when compared to C. The only thing that may throw you off is pointers. I wrote a blog post that aims to be an introduction to pointers and in depth explanation of what they do.

A few pointer pointers.


答:
Here is my advice.

Look through the answers to How can you explain "beautiful code" to a non-programmer? and see what characteristics they say to focus on.  Then pick up a book like Code Complete and read it through to learn advice on how to write better code.

At some point it will hit you while looking at older code of yours, "This is ugly."  It will be a direct aesthetic reaction.  And looking at it you'll realize that you're viewing your code like a programmer, and can see the ugliness because you know what better looking code should look like.

Title: What is beautiful code?


问:
Benefits of setting PHP memory_limit to lower value for specific PHP script?
I need to execute just few lines of PHP code on every single page of my website. This PHP code does not require more than 4MB memory. That is why i want to allocate just 4MB memory to all pages by using following code :

```<code>ini_set('memory_limit','4M');
</code>```

Does it give any benfits in any of the following areas :

1. Website speed

2. Bandwidth optimization

3. Optimizing server memory usage

答:
It won't give you any speed boost, nor bandwidth optimization, nor server memory usage.

What memory limit says is that when a script tries to use more memory, a error occurs. This is the only effect. PHP won't magically optimize memory if you reach the memory limit. If an object takes 16 bytes of memory, it will always take 16 bytes, no matter what is the actual memory limit and if it is reached or about to be reached.

Website speed depends on many factors such as the size of HTML, CSS, JavaScript and images, the number of requests per page required to load all the content, the time it takes to the code-behind to process the input and generate the output, etc. Memory limit has no effect on this.

Bandwidth usage depends on the size of HTML, CSS, JavaScript and images, the number of requests per page required to load all the content. Setting 2 MB or 200 MB as a limit won't change anything.

Memory usage for a given script won't change neither, since it depends on the number of objects and their respective size. If and only if the different scripts are randomly taking too much memory and the only response you have is to kill them, then it will have a positive impact on memory usage: instead of filling the memory, those bogus scripts will simply be stopped by a PHP error.

I highly doubt such case exists. When a script takes too much memory, what should a developer do is to inspect it with a profiler and to fix the parts which are allocating too much memory. Killing the instances which fill up memory is the weirdest way to "solve" the problem.

So why would anyone use the memory limit?

The memory limit can be useful in debug, to be sure that your application doesn't start to take too much memory.

This doesn't replace a profiler, but can be a good solution where you don't want so use more complex tools, but still want to be alerted when, one day, your app grows enough to fill 2, 50 or 200 MB of memory.

Note: PHP documentation is very clear on that:

This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server.

Source: Description of core php.ini directives, emphasis mine.


问:
Reusing open-source code that doesn’t specify a license
I am creating a module for a CMS. I found a PHP code in github that does some work for me. The author has not clearly stated the license for the code. Since it is in github and is publicly available, can I use the code in my module or should I get the author's written permission? I am planning to sell my module for a small price.</p>

答:
Just because it's on the Internet and/or is open source, does not mean it's free to use!

You need to find out what license the code is written under.

It might be prohibited from commercial use (maybe unless you pay for it...).

It may be an "copy-left" license which forces you to share that code, or all your code, with your customers.

It might simply be something that requires you to give credits to the original author/project.

.. or it might be public domain, which means DWTHYWWI (Do What The Hell You Want With It).


问:
Apple Dispatch Queue vs Threads
I've heard a  lot about apple's famous dispatch queues and the GCD but today was the first time I decided to understand exactly what is going on, so I started reading Concurrency Programming Guide and this paragraph caught my eye.

If you have two tasks that access the same shared resource but run on different threads, either thread could modify the resource first and you would need to use a lock to ensure that both tasks did not modify that resource at the same time. With dispatch queues, you could add both tasks to a serial dispatch queue to ensure that only one task modified the resource at any given time. This type of queue-based synchronization is more efficient than locks because locks always require an expensive kernel trap in both the contested and uncontested cases, whereas a dispatch queue works primarily in your application’s process space and only calls down to the kernel when absolutely necessary.

What I understand is that they are suggesting executing two tasks serially to avoid use of locks, which can be done the same way in threads. For example in Java you can put two functions in your thread's runnable and the thread will execute them serially and you will not need locks in that case two.

Now my question is that am I missing something ?

答: No, I don't think you're missing anything. If you don't run things in parallel then you don't (necessarily) need locking. The distinction, insofar as there is one, is that the GCD interface makes it pretty easy to do.</p>

Title: Apple Dispatch Queue vs Threads


问:
Why are some minor update versions of Java skipped?
Up until around January 2013, the minor updates of major Java versions were always consecutive: 6u30, 6u31, 6u32, 6u33 and so on. The same is true for Java 7 updates.

But, starting around January or February 2013, some minor version numberings were skipped. Take a look here: http://en.wikipedia.org/wiki/Java_version_history#Java_7_updates As you can see, the minor updates are 7u10, 7u11, 7u13, 7u15, 7u17, 7u21, 7u25. Where did 7u12, 7u14, 7u16 etc. dissapear ? Was there a specific reason why they were skipped ?

If they were actually faulty and couldn't be released, then:

how come there is no significant uptake in the time-gap between them ?

how come up until January/February this year this never happened, but is constantly happening ever since ?

I tried searching for an answer to this, but couldn't find anything. So I thought someone here might have a clue about this.

答:
Orace has adopted a pretty weird numbering scheme:

Since the initial release of JDK 5.0, Java update releases have either
been Limited Update releases that include new functionality and
non-security fixes or Critical Patch Updates (CPUs) that only include
fixes for security vulnerabilities. We will continue releasing Limited
Update and CPU Java releases, however we are changing the frequency
and way in which these releases are numbered:

Limited Update releases will be numbered in multiples of 20.

We intend for Critical Patch Updates to continue to use odd numbers. The numbers will be calculated by adding multiples of five to the
prior Limited Update and when needed adding one to keep the resulting
number odd.

[...]

This numbering scheme will leave several numbers between releases which will allow us to insert releases – for example security alerts or support releases, should that become necessary - without having to renumber later releases.


问:
Is the Dart philosophy compatible with testability and dependency injection?
One of the Dart criticized features are named and factory constructors.

There are opinions (from dependency injection people), that constructors should be simple and just assign some fields and the object graph creation is a responsibility of factories.

There are also some argues against the static methods.

It seems, that Dart constructors bring complexity to constructors. You can not even have a lot of named constructors to create the object in a various ways, you can even have a static factory supposed to construct object of other type than the class it is in.

So, what is the philosophy of Dart and how does it relate (or respond) to the Dependency Injection and no-static state philosophies?

答:
Constructors are where you should construct things. That's why they are so named :)

The alternative to constructing everything in the constructor is that you will have a half-constructed object that you then rely on the rest of the program to handle well until its had its properties initialised. This makes things more complicated than they should be - compared to always having a fully constructed object. Martin Fowler talk about this.

I'm not sure about Dart's philosophy of constructing - if you can't overload the constructor for different cases, it sounds a bit limiting.


问:
How do I find a good middle way to make this library safe for concurrent operations
I've made a little library called SignalR.EventAggregatorProxy

Before I push it into 1.0 state I need to fix so it works safely with concurrent operations. Easiest way is lock all operations but thats a huge performance impact.

The library queues event subscriptions and when a event comes in it checks the subscriptions and updates the clients using SignalR

This is the class that holds the subscriptions

There are 3 methods that write/read to the subscription collection(s) (I aggregate the subscription both on a client level and event level, so its two collections)

Subscribe

UnsubscribeConnection

Unsubscribe

And one that that reads

Handle

I realize since this is a library I can't make it optimum for all users of the library, but how do I find a good middle way that does not use locks?

I think the Handle method is the most important method and should be prioritized for performance over the other 3.

I made this little Unittest to test for Concurrency fail

update:
I choose to have locked writes and unlocked reads. The writes didnt mutate existing state but overwrite the collection completely.

答:
You can't get away from using locks. You must ensure that calls to the Subscribe method will always atomically set the internal state with the new subscriber - so you must assume that someone will call that subscribe method in 2 threads at exactly the same time. Last thing you want is for 1 thread to succeed and add the new subscriber, only for the 2nd thread to jump in and set its subscriber only to stomp over the 1st subscriber's entry in the internal collection. Finding that bug would be a nightmare as the user report will be "I subscribed and nothing happened" or worse "I subscribed, it returned success but I received no subscriptions".

It is possible the Handle method doesn't need to lock - as long as you can be sure that someone removing or adding a new subscriber doesn't trash the state of the internal collection (ie a naive implementation would loop over all subscriptions... but what if the next loop comes across an entry that has just been removed? The answer is usually a crash, but sometimes undefined, even in a GC system where the removed object isn't collected yet, it will be one day, usually just when its being used in a demo and then you'll get the crash :-) ).

So to avoid locks.. you could make a copy of the internal collection of subscribers and use it in the Handle method without locking, so you have 2 collections - one of all subscribers, and one of 'active' subs. You can then block the Handle method and swap them when new members are added or removed in the Handle method as you'll be the only one calling that method to send out to the subscribers.

Or you can extend this to add new subscribers to a different collection and safely merge them in the Handle method, but you will still have to cater for the case where 2 new subs are added simultaneously.


答:
Not all open-source software is free software.

In the absence of any specific license, under U.S. law the work is the copyright of its author, who reserves all rights. Especially if commercial use is involved, you must contact the author and ask them to provide you a written license; otherwise you are infringing on their copyright. That license may be a general free software license such as BSD or MIT, or it may be an individual license for your use only.

Title: Reusing open-source code that doesn’t specify a license

Body: I am creating a module for a CMS. I found a PHP code in github that does some work for me. The author has not clearly stated the license for the code. Since it is in github and is publicly available, can I use the code in my module or should I get the author's written permission? I am planning to sell my module for a small price.</p>


问:
Can you apply agile/TDD in all circumstances?
I'm not against agile/TDD and use it under most circumstances. However, in some circumstances I feel it doesn't work well.

For example, the other day I was building a fairly complex data processing app. In an ideal world I'd layout the foundation, design the components, write unit tests and demo on each sprints as I finish "features". In practice however, I don't think this works before the first version is released because:

The foundation/component design changes frequently as I figure out
how to do things better, and simple test drivers are much more useful
than richer unit tests

If you are building a MVC app., the foundation
isn't going to change, but with an app. where you more or less build
the framework yourself, and don't quite know how to do things best
beforehand this isn't the case. I feel simple test drivers with no
automated verification are much more useful than richer unit tests at
this stage.

Until the basic infrastructure is in place, it's hard to break
down things into individual "features"

If you already have an MVC
framework, this is easy. But imagine how the the first MVC framework
ever was developed. It must have been much less useful to think
things as individual "features" in the initial stages, because the
most important thing was to work out the principle and philosophy of separating
Model, View and Control, and how to do that.

Demos help very little until a sizable part of the app. is done

In a
UI, you can just put up a mocked up interfaces and
get lots of valuable feedback. However, e.g. in a web crawler, you can't
really do a meaningful demo to non-technical people until quite a bit
is done, and even if you did, they usually won't be able to give useful inputs anyway. Sure,
you can demo to your developer colleagues, but it's hard to give
input based on some log output. It's usually much more productive to
explain how you did things and how you plan to do things perhaps
showing illustrations and code, and get feedback this way.

Or am I just doing it wrong?

答:
You seem to be developing in a very agile way, actually. A non-agile way would be to spend weeks drawing the design on paper and sticking to it when you program it and (inevitably) find that the whole thing is a house of cards.

That is speaking about the general principle. For the concrete meanings of the terms like test driver, demo, feature etc. they are specific to the situation.

They are always specific to the situation. The common meaning is the one applicable to the most common kind of application, which is business information system. That kind of application has a generic foundation that you already have and on that are built individual forms, reports and workflows, that can be added one at a time. So you can add the few most basic things, demo it, than add some more, demo again etc.

But there are many applications where that is not true. You can still use agile process, but kind of internally in the project. Your "user" stories become defined in terms of programming APIs implemented, your tests test just those raw APIs and such. It is agile process in the sense you implement the minimal functionality for each component and refactor it as you need more functionality from it, and it may be test driven in that you have unit tests for the components. You just don't have the eventual customer involved (yet), because you have nothing to show them. You eventually will and than you'll still be refactoring the foundation, because some fundamental problems can still appear than.


问:
Why would anyone invest time in Microsoft "Roslyn"?
I have just been reading through some of the white papers & examples from Microsoft "Roslyn" and the concept seems very interesting.  From what I can tell, it opens up the black box that is the compiler and provides an interface that we can use to get information and metrics about code written in Visual Studio.

Roslyn also appears to have the ability to "script" code and compile/execute it on the fly (similar to the CodeDom) but I have only come across limited uses for that type of functionality in my experience.

Whilst the code analysis & metrics element is an interesting space...it is something that has been around for a very long time and there are numerous providers that have already invested a lot of money into code analysis & refactoring tools (e.g. ReSharper, CodeRush, nCover, etc) and they do a pretty good job of it!

Why would any company go out of their way to implement something that can be provided at a fraction of a cost through buying a license for one of the existing tools?

Maybe I have missed some key functionality of the Roslyn project that places it outside the domain of the mentioned tools...

答:
I eagerly await the day when all compilers routinely offer Compiler as a Service (CaaS). We need to stop thinking that compilers emit only pre-linker code and start thinking that compilers emit trees which can be transformed into multiple targets. All compilers should have a feature to emit trees and optionally JSON/XML. The output can then be transformed into many types of targets such as beautified same language, C, IL source, IL binary, Java, Javascript, LLVM, PIC executable, and even pre-linker code.

I write compilers for a living. My customers are sold on CaaS because it opens the door to fantastic flexibility, portability and analysis.

I'm really disappointed that Microsoft hasn't implemented CaaS a long time ago. For example, it could have been used as a migration path for VB6 to something else, or .Net to C++.


问:
MVVM pattern - Best design approach to manage an application
One year ago, I discovered the WPF technology and I developed a little application, as first experiment, to compare the content of two different directories. The content of each directory is shown in a different DataGrid.
At that time, I didn't develop the application using MVVM pattern, because it was only an experiment, not so good, but it worked.

Now that I've much more experience with WPF and with the design patterns, I'm not so proud of that work, and I want to rewrite the application, improving it and following the recommended MVVM pattern.

Actually, I designed the application in this way:

the MainModel, with the main common algorithm.

the MainView is the unique view of the application with the datagrids where I can show the results of my algorithms.

a MainViewModel, that it will take care of handling the connection between other two ViewModels, the MainModel and the MainView.

One ViewModel for each DataGrid. In this way, I'll separate the behavior and the data of the two DataGrids.

The MainModel contains the main algorithm used to search the files in a given directory, like this:

```<code>public class MainModel
{
    public MainModel()
    {}

    public List<Results> GetFiles(string directoryPath)
}
</code>```

The MainViewModel will instantiate an object for each ViewModel (I have a ViewModel for each datagrid), using some properties to do it:

```<code>public class MainViewModel
{
    public MainViewModel()
    {
        FirstViewModel = new ViewModelDG1();
        SecondViewModel = new ViewModelDG2();
    }

    public ViewModelDG1 FirstViewModel
    {get;set;}

    public ViewModelDG2 SecondViewModel
    {get;set;}
}
</code>```

I wanted to apply a design pattern to help me manage the application, like a Factory Method or Builder, or a Template Method, but I think they're not suitable for my application for the different usages/conditions of those design patterns.

I'm not so sure of this design, I don't know if this a is correct implementation of the MVVM pattern and if it promotes a loose coupling and high cohesion. Can you help me in the design? Is mine a correct implementation of the MVVM? If not, then what is the correct one? What are your opinions?

Thank you.

答:
Hello I think it's to late to give this question answer but I think it may be useful to others who search same content.

as per my view the best Design Approach should be .

Your Application have below mentioned folder

1.Resources

2.Models

3.ViewModel

4.View

5.ServiceAgent //Which is used for reduce the dependance injection

6.Libs

Ok, All Views of your Application must have end with View Name. e.c MainPage is your xaml
then it name should be MainPageView.xaml

All same as All Viewmodels and models.

Your Viewmodel folder contain one ViewmodelLocator which is used to initialized all Viewmodel  Which are used in your application.

you have to create object of Vuewmodel locator in App.xaml file and use it all view as a staticresource

e.c

```<code>xmlns:vm:"Your ViewModel namespace"

<resource><VM:YourViewModelLocatorName X:key="Key Name" /></resource>
</code>```

Your View Datacontext Should be

Datacontext="{Binding ViewModelName,Source="{StaticResource KeyName}"

Thanks

Body:
Hello I think it's to late to give this question answer but I think it may be useful to others who search same content.

as per my view the best Design Approach should be .

Your Application have below mentioned folder

1.Resources

2.Models

3.ViewModel

4.View

5.ServiceAgent //Which is used for reduce the dependance injection

6.Libs

Ok, All Views of your Application must have end with View Name. e.c MainPage is your xaml
then it name should be MainPageView.xaml

All same as All Viewmodels and models.

Your Viewmodel folder contain one ViewmodelLocator which is used to initialized all Viewmodel  Which are used in your application.

you have to create object of Vuewmodel locator in App.xaml file and use it all view as a staticresource

e.c

xmlns:vm:"Your ViewModel namespace"

<resource><VM:YourViewModelLocatorName X:key="Key Name" /></resource>

Your View Datacontext Should be

Datacontext="{Binding ViewModelName,Source="{StaticResource KeyName}"

Thanks


答:
The term beautiful code is a very vague and abstract term.
Its easy to figure out what it represents, and what it means, but it should never be seen as more than a secondary goal.

It reminds me a lot of the code coverage metric. When you get the number high enough you can relax and go onto something else.  Having a codebase with about 80% coverage is great, not bulletproof, but enough to chill and do other things. Having 40% coverage is pretty scary and should encourage you to get that number up.

Point is just that code coverage is only really meaningful if the number is low. So don't let it be low. When the coverage rises to a certain point, move on to something else.

Similarly beautiful code is great. If you have pretty code, great, move on to something else. Don't stress too much about it. You'll never ever hit that 100% mark, and if you do you'll find you've focused too much on what it reads like, or what it looks like, and not enough on what it does, or how it does it. So get to a reasonable mark and then stop.

But if your code is fugly, if its a giant convoluted mess of spaghetti code, if it physically pains you to open the file, if you have no comments or documentation etc etc etc then fix it. And do it asap.

You'll find over time your code base ends up generally cleaner, generally brighter and generally more beautiful and more importantly more usable when you focus on making it less fugly. Writing beautiful code is not a one step process.

There is no magic philosophy. Its 1000 smaller steps all done together, all of which serve a concrete purpose that has nothing to do with how beautiful the code looks. But, when you serve them up all together, they form beautiful code as the sum of its parts. Like voltron. Or captain planet.

Title: What is beautiful code?


问:
Better design for a generic doubly linked list around which I plan to make different wrappers?
I am currently writing a C code for a doubly linked list(dll) around which I want to write wrapers for implementing stack, queues etc. instead of writing separate codes for all of them.

I'll be using void * for making it possible for the doubly linked list to work with any data type. The idea is basically the same as this implementation of stack using pointers in my github.

I am thinking of 2 different designs

Placing the size of elements alongwith the maintenance data. That would make coding easier but any instance of dll would be able to use only a particular data type.

Placing the size of element in the nodes. That would make it more general but I have concerns whether this approach would be easier to use?

This is the confusion that I wanted to clear before implementing any particular one. If there is any confusion regarding what I am trying to implement then please ask and I'll clarify.

答:
Perhaps you should take a look at the intrusive linked list implementation used in the Linux kernel. The source can be browsed here.

An intrusive design has the advantage that any type can be placed into a list just by including a list element in the structure definition.

Disadvantages include slightly more cumbersome syntax (a matter of personal preference, of course) and the requirement to include multiple members of the same type when your data needs to go into more than one list.

Intrusive lists are mostly useful when you only need a small number of lists and especially when your module/app are focused on adding and removing nodes from one list. A different design might be more suitable if your code needs to deal with local or disposable lists. The former consideration is true for most uses of lists in the kernel.


答:
What you are looking for is called a Persistent Data Structure. The canonical resource for persistent data structures is Chris Okasaki's Book Purely Functional Data Structures. Persistent data structures have gathered interest in recent times due to their popularization in Clojure and Scala.

However, for some strange reason, Persistent Graphs seem to be mostly ignored. We have lists, dozens of different kinds of trees, arrays, priority queues, maps, but no graphs.

I really only found one paper: Fully Persistent Graphs – Which One To Choose?

Title: Is it possible to represent mutation of object-graph efficiently with immutable states?

Body:
I am practicing using of immutable object in C++. My personal goal is representing generic object graph (in heap) with sequence of immutable graphs.

Building the multi-version graph itself isn't that much hard. The problem is performance. Brute-force versioning needs full copy of graph, and this was not acceptable.

I tried to share unchanged nodes. But in this case, I got a new problem; references. Reference to other object must be updated in whole graph. This needs visiting all nodes for each time I derive a new graph version. And this mutates the nodes with references, so they also should be derived (by copying). Performance won't be better much than brute-force copying.

As far as I can imagine, there's no real efficient way to represent mutation of object graph with immutable states. So I am asking for some idea on this.

Is it possible to represent mutation of object graph efficiently with immutable state?


答:
Don't let people fool you into thinking that beautiful code is the following:

clever algorithms

sneaky language features

solving a problem with the least amount of key strokes

Because it's not.  Code like that is cute, and it's certainly worth a glance, but it's not the kind of code you want to settle down with.

And you know that fancy recursive meta templated static polymorphism that inherits variatic lambdas-- or whatever it was you read about online? You might be eager to jump on innovative and nifty tricks without a clear reason to use them.
But code that pushes the boundaries of a language aren't beautiful either.

They're sexy.

Tons of fun, but ask yourself this: Do I really want to spend time exploring the anatomy of this language, or do I want to work together with a language and build something beautiful?  After all, a programming language is merely the tool to create.

So what is beautiful code then?

Beautiful code = maintainable code.  THAT'S IT!

THAT'S THE FORMULA!

If you can write something, come back to it a few months later, and continue making progress on it, then that's beautiful.  If a year later you realize that you want to add functionality as well as tweak an existing feature, and you manage to do it with relative ease, then THAT'S beautiful.  If other people can step into your codebase and quickly figure out what's going on because things are organized, they'll have more hair, and also be beautiful.

So the real question you want to ask is: "How do I write more maintainable code?".
I'm afraid that's a bigger question and it's quite a creative discipline.  Just keep writing code, but this time don't ask yourself if it can be more beautiful.  Ask yourself if you can make it more maintainable.

Title: What is beautiful code?


问:
Organising staggered user story in Scrum
How would you organise a backlog item that is planned to change in future releases?

I've got a requirement that states that:
In release 1 users can open content from local machines.
In future releases users can open content from remote servers, FTP and web streams.

Is it typical to just create 2 backlog items to describe that requirement. Then just assign the enhancement to a future release?

(Using TFS for any contextual answers)

答:
Yes, definitely have different User Stories for the two different features you've described.

User Stories are better off as small as is practically possible, so long they are individually testable, which each of those things sounds like it is.

In fact, even if you weren't planning the 2 features you describe above to be in different releases, I would still have 2 User Stories.

The only challenge this introduces is that neither Scrum nor TFS include a strong way to manage any dependency that doing Story-2 has on Story-1 having been done first. To manage this, when using TFS my team records on the Story-2 Work Item that Story-1 has to be done first. We also create a link between the two User Stories in TFS, although it's easy to overlook this in the Visual Studio TFS UI.


答:
User stories aren't descriptions of the final product being built. They describe units of work. Or, perhaps more accurately, they are a placeholder for a conversation about a unit of work. A story defines what you want built for the current iteration.

If you know you are building a feature over time, the story  you work on now will only describe the feature as you want it by the end of this iteration. If the feature will evolve over time, you will need a story (or more) for each phase of its evolution.

Title: Organising staggered user story in Scrum

Body:
How would you organise a backlog item that is planned to change in future releases?

I've got a requirement that states that:
In release 1 users can open content from local machines.
In future releases users can open content from remote servers, FTP and web streams.

Is it typical to just create 2 backlog items to describe that requirement. Then just assign the enhancement to a future release?

(Using TFS for any contextual answers)


答:
Just because you often read about beautiful code doesn't mean people who write about it have the same definition. Sadly, judging by your question it doesn't seem that they even bothered to define it in the first place.

To me beautiful code is :

Expressive

Concise

Concise code that is not expressive can be cryptic, and expressive code that is not concise tends to be bloated and tedious to read, so you need both.

I wouldn't include maintainability as part of what makes code beautiful, because beauty is something you see/read, not something you act upon. But then again it's my personal view.

Title: What is beautiful code?