问:
Design Question: Keep 1000 newest items; DB vs. application
I have a Qt application, which sends and receives messages. Messages are stored in a local MongoDB.

The application has a message list window, which shows sent, received and all messages (depending on the view). For performance reasons the application has a QList, which holds QPairs of Mongo ID and the message itself, so more or less all messages are available in the application.

We want to limit the no. of shown messages, because the view gets slower for 1000 and more messages.

The simple approach was just to limit the no. of pairs stored in the QList.

However, I'm not quite sure, if this is true. Recently I've read here (EDIT: found it) a question which basically said "Your application code won't be smarter/faster/better for stuff a DB is designed for (e.g. sorting, getting a subset, etc.)".
In addition keeping the QList in sync with the DB is causing us headaches and we have some corner cases like an very old message can be updated and then has to be displayed again.

So the question is, would a DB-only approach (e.g. querying the DB for 1000 messages whenever the view has to be updated) be faster then storing the acutally shown messages in the QList and trying to keep them in sync.

答:
This seems more like a separation of concerns between the: QList, view and MongoDB.

Focus on the purpose of the QList and then make sure the synch capabilities get the job done. Do you need all the records for some purpose outside of the view?

We want to limit the no. of shown messages, because the view gets
  slower for 1000 and more messages.

If the QList for whatever purpose outside of displaying a view, needs to hold more than the 1000 view limit, you need something else to limit the records coming from the QList to the view (if that's how you need it to work.). Otherwise, you may need some other logic pulling the MongoDB data with a 1000 record limit with the sole purpose of feeding the view.

Is the limitation of the view (not sure exactly what that is) holding enough records in memory or the control you're using as the display for the user (Data Grid, Combo Box, repeater, etc.)?


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
Yes

Come on, seriously: look at the first page or two of Stack Overflow users. Pick anyone at random. Look at three or four of the highly voted answers they wrote. If you've ever hired a programmer in your life, it's obvious those people are all some of the best programmers you could ever hire.

Then keep going deeper and deeper. Scroll to page 5. Edit the URL and go right to page 100 where they have reputations in the 3000 range. Look at everyone. With the very rare exception of someone who got a lot of points for a silly answer, these are all obvious superstar programmers... the kind that most teams would kill for.

Will this actually get them jobs? Ultimately, we're betting it will. You'll have to find a company where there are actual technical people making hiring decisions, not resume-reading-monkey-recruiters. And you may have to find a city to live in where there are a lot of good programming jobs: if you really, really don't want to leave Roswell, New Mexico, you'll be limited to a vanishingly small number of telecommuting jobs. But if you're in the top, say, 5000 Stack Overflow users, and you can work in Silicon Valley, New York, Seattle, Boston, Austin, Research Triangle, London, Hyderabad, Bangalore, Sydney, Beijing, or Tel Aviv, I would be extremely surprised if you aren't in high demand and earning in the top 10 percentile.

ContentLicense: CC BY-SA 2.5


答:
It's impossible to say whether loading from the database will be faster without running some tests or knowing how often the window gets refreshed. My guess is that the perceived performance loading or working in the messages window will become constant rather than getting worse as the number of messages increases.

A not-insignificant upside to it would be simplifying your code a bit - you'll no longer need any code to keep the list in sync with the database. You'll just grab the latest (perhaps configurable number of) messages when loading or refreshing the messages window, so you won't have to worry about stale data.

As you said in a comment:

Let's say 300 would probably be also sufficient.

Retrieving a very small amount of data from the database will very likely not be noticeably slower, and if 300 messages can cover 90% of use cases and you can provide a way for users to retrieve older messages when needed, I bet you'll come out ahead performance-wise.

ContentLicense: CC BY-SA 3.0

Title: Design Question: Keep 1000 newest items; DB vs. application

Body:
I have a Qt application, which sends and receives messages. Messages are stored in a local MongoDB.

The application has a message list window, which shows sent, received and all messages (depending on the view). For performance reasons the application has a QList, which holds QPairs of Mongo ID and the message itself, so more or less all messages are available in the application.

We want to limit the no. of shown messages, because the view gets slower for 1000 and more messages.

The simple approach was just to limit the no. of pairs stored in the QList.

However, I'm not quite sure, if this is true. Recently I've read here (EDIT: found it) a question which basically said "Your application code won't be smarter/faster/better for stuff a DB is designed for (e.g. sorting, getting a subset, etc.)".
In addition keeping the QList in sync with the DB is causing us headaches and we have some corner cases like an very old message can be updated and then has to be displayed again.

So the question is, would a DB-only approach (e.g. querying the DB for 1000 messages whenever the view has to be updated) be faster then storing the acutally shown messages in the QList and trying to keep them in sync.


问:
How to make sprint planning fun
Not only are our sprint planning meetings not fun, they're downright dreadful.

The meetings are tedious, and boring, and take forever (a day, but it feels like a lot longer).

The developers complain about it, and dread upcoming plannings.

Our routine is pretty standard (user story inserted into sprint backlog by priority >> story is taken apart to tasks >> tasks are estimated in hours >> repeat), and I can't figure out what we're doing wrong.

How can we make the meetings more enjoyable?

...

Some more details, in response to requests for more information:

Why are the backlog items not inserted and prioritized before sprint kickoff?

User stories are indeed prioritized; we have no idea how long they'll take until we break them down into tasks! From the (excellent) answers here, I see that maybe we shouldn't estimate tasks at all, only the user stories. The reason we estimate tasks (and not stories) is because we've been getting story-estimates terribly wrong -- but I guess that's the subject for an altogether different question.

Why are developers complaining?

Meetings are long.

Meetings are monotonous. Story after story, task after task, struggling (yes, struggling) to estimate how long it will take and what it involves.

Estimating tasks makes user-story-estimation seem pointless.

The longer the meeting, the less focus in the room. The less focused colleagues are, the longer the meeting takes. A recursive hate-spiral develops. We've considered splitting the meeting into two days in order to keep people focused, but the developers wouldn't hear of it. One day of planning is bad enough; now we'll have two?!

Part of our problem is that we go into very small detail (in order to get more accurate estimations). But when we estimate roughly, we go way off the mark!

To sum up the question:

What are we doing wrong?

What additional ways are there to make the meeting generally more enjoyable?

答:
Why are the backlog items not inserted and prioritized before sprint kickoff? Wasting developers time is not fun. Let your team leads work with the product owner and project manager a few days beforehand to prioritize stuff. This goes for planning who is on each sprint team too.

Why is it taking a day to break things out into tasks? If you have a reasonably sized team (2-4 developers, .5-1.5 QA people per developer, 1-2 misc) then you should have 2-4 user stories this sprint. Spend 30 minutes or so with the product owner clarifying requirements, then 30 minutes or so breaking it out to ~8 hour tasks. Don't enter the tasks during the meeting. Just agree as a team what the tasks are enough for sane people to understand them, who is responsible for them, and about how long they should take. Agree that "how long they should take (including testing)" fits comfortably within the sprint.

If it's not just breaking things into tasks, what else are you doing? Sure, retrospectives can take 30-60 minutes, but will be shorter as the teams get into a groove.

So in summary - quit wasting people's time and they'll dread the meetings a bit less.
Beyond that, fun and comradarie in the team isn't something you can address in meetings. Go to lunch together, joke around, mix people up to have better personality fits, have mustache growing contests... once the morale is up then people will naturally make sprint planning meetings more lighthearted.

Title: How to make sprint planning fun


问:
Learning basic graphics programming
After learning the basics of computing simple die throwing games and calendar applications, I want to explore simple graphics - drawing and moving around geometric objects is ok to start with, eventually adding pixel graphic of course.

I've taken an introductory Java course but would rather do it in C++, Python or a combination of them (that's what we will eventually be using in school). I also want to learn the principles behind it, not just blindly applying incomprehensible syntax to make the compiler happy.

Some posts seem to imply SFML is a solid choice, so I thought I'd get a book covering it and work through it, but there only seems to be ONE book on SFML available, and that one hasn't been reviewed at all. Not in the mood for a $30 gamble, so I'm feeling kind of lost!

How should I approach learning basic graphics programming?

答:
I've recently begun learning OpenGL using C++. It is usable on multiple platforms, and there are a plenty of options for binding it with other languages. Plus, you can also apply it to the variations of OpenGL such as WebGL, OpenGL ES, etc.

http://www.opengl-tutorial.org/

The website above is a good place to start and also suggests other resources for those just getting started.

Title: Learning basic graphics programming


问:
Drop table if it already exists and then re-create it?
I was just learning about sqlite in android programming from the New Boston Travis videos and I have come across something strange:

It is said that if the database does not already exists, onCreate() method is called to create it. so far, so good.
But, if the database already exists, then onUpgrade() method is called which simply drops the database and then re-creates it.

What is the sense behind such an update? why not just leave the database alone?

答:
```<code>  > if the database already exists, then onUpgrade() method is called
  > which simply drops the database and then re-creates it.
  > What is the sense behind such an update?
  > why not just leave the database alone?
</code>```

The Android specific virtual method SQLiteOpenHelper::OnUpgrade

```<code>    public void onUpgrade(final SQLiteDatabase db, final int oldVersion,
        final int newVersion) {...}
</code>```

is called because the database-structure has changed (oldVersion is not equal to newVersion, tables/fields have been modified/renamed/added/deleted).

So the author of the sourcecode you are looking at has decided to recreate database from the scratch and loosing all the database-data.

The Programm would not run with the old database structure, because tables/fields would be missing.

Body:
  > if the database already exists, then onUpgrade() method is called
  > which simply drops the database and then re-creates it.
  > What is the sense behind such an update?
  > why not just leave the database alone?

The Android specific virtual method SQLiteOpenHelper::OnUpgrade

    public void onUpgrade(final SQLiteDatabase db, final int oldVersion,
        final int newVersion) {...}

is called because the database-structure has changed (oldVersion is not equal to newVersion, tables/fields have been modified/renamed/added/deleted).

So the author of the sourcecode you are looking at has decided to recreate database from the scratch and loosing all the database-data.

The Programm would not run with the old database structure, because tables/fields would be missing.


答:
The Sprint planning meeting has 2 parts:

Decide what the team will do

Decide how the team will do it.

The first part is relatively straight forward--based on the number of story points the team feels they can take on, the commit to completing that many user stories in their order of priority.  Done.

The second part is what developers should actually enjoy--elaboration of the story and designing the solution.  The tasks fall out of that.  So, have the product owner, or whatever SME he has provided explain a chosen story.  Then have whichever developer wants to take it on, lead the design discussion.  Use a white board. Bounce ideas around.  Have fun.

That's it, really.  If design meetings aren't fun, then there's just something plain wrong.

Title: How to make sprint planning fun

Body:
Not only are our sprint planning meetings not fun, they're downright dreadful.

The meetings are tedious, and boring, and take forever (a day, but it feels like a lot longer).

The developers complain about it, and dread upcoming plannings.

Our routine is pretty standard (user story inserted into sprint backlog by priority >> story is taken apart to tasks >> tasks are estimated in hours >> repeat), and I can't figure out what we're doing wrong.

How can we make the meetings more enjoyable?

...

Some more details, in response to requests for more information:

Why are the backlog items not inserted and prioritized before sprint kickoff?

User stories are indeed prioritized; we have no idea how long they'll take until we break them down into tasks! From the (excellent) answers here, I see that maybe we shouldn't estimate tasks at all, only the user stories. The reason we estimate tasks (and not stories) is because we've been getting story-estimates terribly wrong -- but I guess that's the subject for an altogether different question.

Why are developers complaining?

Meetings are long.

Meetings are monotonous. Story after story, task after task, struggling (yes, struggling) to estimate how long it will take and what it involves.

Estimating tasks makes user-story-estimation seem pointless.

The longer the meeting, the less focus in the room. The less focused colleagues are, the longer the meeting takes. A recursive hate-spiral develops. We've considered splitting the meeting into two days in order to keep people focused, but the developers wouldn't hear of it. One day of planning is bad enough; now we'll have two?!

Part of our problem is that we go into very small detail (in order to get more accurate estimations). But when we estimate roughly, we go way off the mark!

To sum up the question:

What are we doing wrong?

What additional ways are there to make the meeting generally more enjoyable?


问:
Pattern to use for different Stages in a software
I am developing a software for a laboratory to test some devices. To test each device there are multi subtests which should be done to reach to the final result.To perform a complete test, the software must pass Stage1 then automatically goes to Stage2 then Stage3 and so on until the whole test is finished. meanwhile the user can select to just have the Stage3 or Stage2 or any other Stages independently to be performed (which she selects that at runtime).
this is the thing I have done so far:

```<code>public class IronTestWorkFlow:ITestWorkFlow
    {
        private readonly List<ITestStages> _testStageses;

        public IronTestWorkFlow(List<ITestStages> testStageses )
        {
            if (testStageses == null)
            {
                throw new ArgumentNullException("testStageses");
            }
            _testStageses = testStageses;
        }
    }
</code>```

I am useing a DI container. But I don't know how to change the list of Stages in ITestWorkFlow at runtime.

Questions:

1- Am I designing this right?

2- If yes which pattern shall I follow to obey the principles and change the stages at runtime? and how can I do that?

答:
Things are Bass-Akwards

The technical term for this is inversion of control.

Your IronTestWorkFlow constructor:

```<code> public IronTestWorkFlow(List<ITestStages> testStageses )
</code>```

How did you know what stages to build before you knew what kind of Workflow you were building? You don't, which is why you're in this quandary I think. Premature injectulation.

Factory Pattern instead of DI Container

Let's use the Factory Pattern - put the Workflow and Stage building into WorkflowFactory and StageFactory classes respectively. The user will select an iron test for example so the IronTestWorkFlowFactory is called which in turn calls the StageFactory to build the stages it needs. Thus we have the context needed to build the right stages.

I take it from the problem description that higher level code should be able to call on a WorkFlowFactory or a StageFactory as desired, depending on how granular or customized of a thing the user wants. So make sure any dependencies between the factories is done via parameters; that's basic Dependency Injection. A DI container is not necessarily required to do dependency injection.

Stay object oriented

Think long and hard about the things you're manipulating: Stage, WorkFlow, other? Focus on the core "data structures" first.

Beware too much focus on high level abstract "framework" without some meat designed into core classes, which results in these classes badly un-encapsulated with numerous violations of single responsibility principle further resulting in undesirable and painful coupling.

For example I wonder what a Workflow - an ordered list of stages - looks like and what fundamental operations are done with them. I wonder if there is some business rules that define order independent of the order in which they just happen to be instantiated? If so then implementing IComparable can make a profound difference. Been there, done that.

OwnerDisplayName: Mehrdad Kamelzadeh

Body:
Things are Bass-Akwards

The technical term for this is inversion of control.

Your IronTestWorkFlow constructor:

 public IronTestWorkFlow(List<ITestStages> testStageses )

How did you know what stages to build before you knew what kind of Workflow you were building? You don't, which is why you're in this quandary I think. Premature injectulation.

Factory Pattern instead of DI Container

Let's use the Factory Pattern - put the Workflow and Stage building into WorkflowFactory and StageFactory classes respectively. The user will select an iron test for example so the IronTestWorkFlowFactory is called which in turn calls the StageFactory to build the stages it needs. Thus we have the context needed to build the right stages.

I take it from the problem description that higher level code should be able to call on a WorkFlowFactory or a StageFactory as desired, depending on how granular or customized of a thing the user wants. So make sure any dependencies between the factories is done via parameters; that's basic Dependency Injection. A DI container is not necessarily required to do dependency injection.

Stay object oriented

Think long and hard about the things you're manipulating: Stage, WorkFlow, other? Focus on the core "data structures" first.

Beware too much focus on high level abstract "framework" without some meat designed into core classes, which results in these classes badly un-encapsulated with numerous violations of single responsibility principle further resulting in undesirable and painful coupling.

For example I wonder what a Workflow - an ordered list of stages - looks like and what fundamental operations are done with them. I wonder if there is some business rules that define order independent of the order in which they just happen to be instantiated? If so then implementing IComparable can make a profound difference. Been there, done that.


问:
How to implement a message queue over Redis?

Why Redis for queuing?

I'm under the impression that Redis can make a good candidate for implementing a queueing system. Up until this point we've been using our MySQL database with polling, or RabbitMQ. With RabbitMQ we've had many problems - the client libraries are very poor and buggy and we'd like not to invest too many developer-hours into fixing them, a few problems with the server management console, etc. And, for the time being at least, we're not grasping for milliseconds or seriously pushing performance, so as long as a system has an architecture that supports a queue intelligently we are probably in good shape.

Okay, so that's the background.  Essentially I have a very classic, simple queue model - several producers producing work and several consumers consuming work, and both producers and consumers need to be able to scale intelligently.  It turns out a naive PUBSUB doesn't work, since I don't want all subscribers to consume work, I just want one subscriber to receive the work.  At first pass, it looks to me like BRPOPLPUSH is an intelligent design.

Can we use BRPOPLPUSH?

The basic design with BRPOPLPUSH is you have one work queue and a progress queue. When a consumer receives work it atomically pushes the item into the progress queue, and when it completes the work it LREM's it.  This prevents blackholing of work if clients die and makes monitoring pretty effortless - for instance we can tell if there is a problem causing consumers to take a long time to perform tasks, in addition to telling if there is a large volume of tasks.

It ensures

work is delivered to exactly one consumer

work winds up in a progress queue, so it can't blackhole if a consumer

The drawbacks

It seems rather strange to me that the best design I've found doesn't actually use PUBSUB since this seems to be what most blog posts about queuing over Redis focus on. So I feel like I'm missing something obvious. The only way I see to use PUBSUB without consuming tasks twice is to simply push a notification that work has arrived, which consumers can then non-blocking-ly RPOPLPUSH.

It's impossible to request more than one work item at a time, which seems to be a performance problem. Not a huge one for our situation, but it rather obviously says this operation was not designed for high throughput or this situation

In short: am I missing anything stupid?

Also adding node.js tag, because that's the language I'm mostly dealing with. Node may offer some simplifications in implementing, given its single-threaded and nonblocking nature, but furthermore I'm using the node-redis library and solutions should or can be sensitive to its strengths and weaknesses as well.

答:
I've run into some difficulties thus far I'd like to document here.

How do you handle reconnect logic?

This is a hard problem and an especially hard problem in designing and implementing a message queue. Messages must be able to queue up somewhere when consumers are offline, so a simple pub-sub is not strong enough, and consumers need to reconnect in a listening state.  Blocking pops are difficult state to maintain, because they are a non-idempotent listening state.  Listening should be an idempotent operation, yet when dealing with a disconnect with respect to a blocking pop, you have the pleasure of thinking very hard about whether the disconnect happened just after the operation succeeded or just before the operation failed. This isn't insurmountable, but it's undesirable.

Furthermore, the listening operation should be as simple as possible.  Ideally it should have these properties:

Listening is idempotent.

The consumer is always listening, and throttling logic is processed outside of the listening logic code. RabbitMQ encapsulates this by letting the consumer bound the number of unacked messages it can have.

In particular I went with a poor design in which re-entering a blocking pop was contingent on success of previous operations, which was brittle and required thinking hard.

I'm now favoring a Redis PUBSUB + RPOPLPUSH solution. This decouples notification of work from consumption of work, which lets us factor out a clean listening solution. The PUBSUB is only responsible for notification of work. The atomic nature of RPOPLPUSH is responsible for consumption, and delegating work to exactly one consumer. At first this solution seemed needlessly complicated compared to a blocking pop, but now I see that the complication was not needless at all; it was solving a hard problem.

However this solution isn't quite trivial:

consumers should also check for work on reconnect.

consumers may want to do a poll for new work anyway, for redundancy. Should the poll actually succeed a warning should be emitted, since this should only happen between the consumption on the PUBSUB and the poll on an RPOPLPUSH. Therefore many poll successes indicate a broken subscription system.

Note that the PUBSUB/RPOPLPUSH design also has scaling problems. Every consumer receives a lightweight notification of every message, which means this has an unnecessary bottleneck. I suspect it's possible to use channels to shard the work but this is probably a tricky design to work out well.


答:
Your planning sessions are way too long!

Based on my experience, a sprint planning meeting should take no more than 2 hours per week being planned (e.g. a 2 week sprint should take 1/2 day at most), but successful ones should be shorter than that (half of it).

In your particular case: why are you estimating tasks? You should estimate only stories during planning. Tasks can be estimated later by the specific task owners.

A way that worked for me:

Quick intro to the sprint by the PO

Estimation of the sprint capacity

Stories run down and planning poker (timeboxed at 5/10 minutes per story) until there's enough estimated stuff to cover the sprint

Official commitment/forecast by the team

Then, in parallel/pairs/self organized at our desks, tasking and task estimation.

Title: How to make sprint planning fun


问:
Handling large web based processes
I am working on a new function for a ASP.NET MVC website. The execution time is quite long at present so I am considering options.

The function takes an excel spreadsheet, uploads it to the web server. It then needs to select all of the rows and using Entity Framework insert the rows in to a database. Each row matches the required entity model. Currently at only 50000 rows, this process takes a while and I would assume the row count will grow in the future.

I have a few options for processing here and I am wondering if there is a better way to handle it. The two ideas I have just now are

1) Pass the work off to a service, which on completion emails the user. The obvious upside being the user doesn't need to keep that browser window open.
2) Add a progress bar and have the service pass updates back to jquery/javacript to do visual updates.

I will attempt to reduce the time, possibly moving the queries away from relying on Entity Framework. Sometimes stored procedures are a lot faster than Linq To Entities but with that aside, the process may still take more than a few seconds, which I don't really want to burden the user with.

Can anyone think of other/better ways to handle long running processes on a web application? Are there any best practice schools of thought on handling these situations?

答:
You definitely need to go async at some point, however it's quite complex and I'd avoid doing it until you really have the problem.

There are a few different approaches but your webserver should do as little as possible. The simplest way to handle this is to let it handle the upload and put the file in a folder.

There are different approaches here but another worker process will need to take the file and process it (btw, entity framework might not be your best option for this kind of heavy lifting). To spin off the other process you can typically do one of these things

As you mentioned, you can invoke a separate service asynchronously.

Have a scheduled service scour the destination directory looking for new files. This is good because this can be run on a completely different server from the web server if needs be, however for the same reason it's very hard, to give real time progress reports to the user. Also, you induce a latency (e.g. if you scan the folder every 5 minutes, the user might have to wait for that long at least).

Have a the response thread spin off a background thread. Pro, it's fairly easy to get progress and push it to the browser, but con, you are using the web server to do non-web stuff, unless you are careful this won't scale as well as you would imagine.

Post a message to a message queue that dispatches it to the background worker. This makes it possible to have 2 way communication, but it's probably the most complex solution of the three (because it has many moving parts).

I would generally advise you to use the simplest possible solution that would work and only use a more complex one if you are forced by circumstance. These kind of things tend to become devilishly complex and hard-to-debug really quickly.

Title: Handling large web based processes


问:
Can a random number generator ever produce different output given identical seeds?
The title sums it up. I'm interested to know if there exists an algorithm capable of producing variable output given identical input without relying on other sources for randomness such as DateTime.Now or a number generated from a light sensor etc. In addition, the algorithm can not be run in sequence, just two distinct, unrelated runs that produce different output.</p>

答: I suppose if you implemented the algorithm on different hardware platforms and it used techniques like taking the middle N bits from an integer, you could conceivably get different answers if the integer encoding was different (big/little/mid-endian). You also might run into issues running on machines with FPUs versus those that don't if you're manipulating floating-point numbers.  Probably not an issue on desktop-class machines, but could be an issue on phones.</p>


问:
Code formatting SQL queries
Should I break SQL queries in different lines? For example in the project I am working on, we have a query that is taking 1600 columns! 1600 + tab chars. I wrote queries like this:

```<code>   "SELECT bla , bla2 , bla FROM bla " .
     "WHERE bla=333 AND bla=2" .
      "ORDER BY nfdfsd ...";
</code>```

But they demanded me to put them in one line and said that my style is bad formatting. Why it is bad practice?

答:
For source control reasons, we have linebreaks after every where clause, or comma. So your above turns into

```<code>SELECT bla
     , bla2
     , bla
FROM   bla
WHERE  bla=333
  AND  bla=2
ORDER  BY nfdfsd
        , asdlfk;
</code>```

(tabbing and alignment has no standard here, but commas are usually leading)

Still, makes no performance difference.

Title: Code formatting SQL queries

Body:
For source control reasons, we have linebreaks after every where clause, or comma. So your above turns into

SELECT bla
     , bla2
     , bla
FROM   bla
WHERE  bla=333
  AND  bla=2
ORDER  BY nfdfsd
        , asdlfk;

(tabbing and alignment has no standard here, but commas are usually leading)

Still, makes no performance difference.


问:
Explaining the difference between Product Backlog Item and a Task
I've run into this challenge a couple of times and I'm hoping someone can provide some references, training or advice on how to explain the difference between a Product Backlog Item and a Task in TFS.

I understand and have explained that a Product Backlog Item is the "What" and the Task is the "How".  I have also explained that the PBI is the requirement and the Task is how the requirement is met.

I'm repeatedly met with blank stares and head scratching when I explain this.  It seems that the Software Engineers I explain this to can not make the distinction.  It is all the same to them.

I believe my other challenge is that I am not able to effectively illustrate why it is important to make the distinction.

答:
The "Product backlog Item" is indeed the What, the functionality that needs to be built. The Task describes the steps that need to be taken to get there.

Many teams are not used to decompose into tasks, they just build what the spec says. For these people it's hard to see them as two separate things.

Maybe a simple anecdote would help:

See the Product Backlog Items as the items on their shopping list for their vacation. Maybe a "tent", a "fishing rod", a "prepare car for travel".

The Tasks for the "tent" item would be "Describe tent requirements", "Compare tents online", "Get advice from friends with outdoor experience", "Go to outdoor shop", "Buy tent", "setup tent in backyard to verify completeness", "pack tent for travel"

The Tasks for Fishing Rod will be very similar, but the tasks for "prepare car for travel" are probably very different: "Check requirements for states/countries on desired route", "buy safety vest", "replace expired contents from first aid kit", "inspect spare tire", "schedule appointment with garage to have engine checked", "go to garage to have engine checked", "go to state agency to buy highway pass", "check car insurance"

This clearly separates the question of what the product owner wants from what they need to do. Unless of course the product owner already decomposed into actionable items on the Product Backlog, in which case you also need to talk to them.

As I said, for many developers they think they already have enough information and know what to do, they don't want to decompose the What into How steps, they'll get there when they get there. When you start talking to them about tracking the sprint progress, improving estimations, tracking work that was forgotten during sprint planning and other items that have to do with professional improvements, ask them how they and their team will know where they can improve and how they know they're really done. When they can come up with a system that works without creating tasks and it works, then that's fine, but chances are very low that they actually can.

Before trying to work with TFS and the agile tools, your team will need to understand how this all works. The best way is to have them work with a paper board, which is visible on the work floor to all. Later, when the process is understood better, moving to the tools will help. Without the understanding, the tools won't be of much use and will meet a lot of resistance.

OwnerDisplayName: Brad J

OwnerDisplayName: jessehouwing

ContentLicense: CC BY-SA 4.0


答:
I think Jesse has provided a great answer. I'm simply going to try and make it, well, simpler (if possible) :) The Product Backlog Item (or User Story, if you prefer) is usually written like this:

As a New Customer
I want to register my details
So that I get informed of new product releases

In a developers head this may translate in to:

Create a registration form

Write registration data to the database

Send email to the new customer to confirm their registration

These three items are the tasks.

Hope that helps.

--
Make it as simple as possible but not simpler (Einstein)

Title: Explaining the difference between Product Backlog Item and a Task

Body:
I've run into this challenge a couple of times and I'm hoping someone can provide some references, training or advice on how to explain the difference between a Product Backlog Item and a Task in TFS.

I understand and have explained that a Product Backlog Item is the "What" and the Task is the "How".  I have also explained that the PBI is the requirement and the Task is how the requirement is met.

I'm repeatedly met with blank stares and head scratching when I explain this.  It seems that the Software Engineers I explain this to can not make the distinction.  It is all the same to them.

I believe my other challenge is that I am not able to effectively illustrate why it is important to make the distinction.

OwnerDisplayName: Derek Davidson


问:
iOS In-App Purchases with dynamic content
I want to built an app that it will support In-App Purchases.

In short, user will download the app (with some basic features), and he will have the ability to download extra layers (delivery content) with additional info (e.g. a recipe).

I want the content of this layer (the recipe) to be dynamic, and be downloadable (through web services) from a server.

What concerns me is, how i will secure the web services to be available, only to the users that have pay for the extra layer (using In-App Purchases)?

Is this functionality possible to be implemented in Google Play?

答:
There's two parts to this question.

How do I ensure that people have to buy the in-app purchase before they can access the external data?

How do I ensure that people can't access the external data from outside the app?

The first question is straightforward.  Just make sure you're implementing the in-app purchase APIs correctly, and that the request to your external server is inside one of those purchases, and you should be good.

The second question is fundamentally the same as any question about securing web services.  You just need to make sure that your app knows some secret which enables it to access your web service securely.


问:
Why don't companies ship multiple modules within a mobile app? Are there concerns about tight coupling?
Preface: My question does not exclusively pertain to Google and it doesn't exclusively pertain to iOS. I'm only using Google and iOS as examples because they are familiar to many. I could have just as easily used 'Company X', apps 'A', 'B', 'C', 'D', and 'E', and 'Android', but I wanted to keep my question rooted in the real world with a tangible example.

In the iOS app store, Google has many apps. At a glance, I can see 'Google Search', 'Google+', 'Google Maps', 'Google Earth', and 'Gmail'.

But I wonder - Why didn't Google simply create a 'Google' app which can provide all of the functionality that these five apps provide? The black menu bar at the top of each Google webpage makes this possible on the web; so why don't they make this possible by way of a menu button at the bottom of one "global" Google app?

Is Google concerned about tight coupling between the apps?

Is Google concerned about tight coupling between the teams that develop the apps?

Is Google concerned about app size?

Is Google concerned about the memory footprint or CPU load that such a monolithic app might incur when it is loaded?

[Not a rant. Merely playing devil's advocate.]

In spite of many advantages, some iOS critics say that multiple pages of apps leave the iPhone and the iPad feeling "cluttered". This is particularly relevant to my question because it seems a bit much to expect a user to know about (and manage) so many Google mobile offerings. From a product standpoint, and arguably a usability standpoint, it seems like it would be wise to ship a single app.

If you're curious, I own an iPhone and a Nexus 7; so I'm not wedded to either of the two major mobile platforms.

And I have a real problem to solve here - Whether to bundle multiple apps inside of one large app, or to distribute separate bits of functionality in multiple apps.

EDIT: In response, to @MichaelT's comment

While there is indeed a 2GB size limit for apps, the size of your sandbox is only limited by the remaining capacity on the device.

答:
Three words: Separation Of Concerns
Do one thing (and do that good). ;-)

And on a sidenote: You can't multitask in a single app without reimplementing either some kind of "window management" or some other crazy logic. Which leads back to my initial statement…


问:
When is it okay to open-source something?
When is it okay to open-source something? If I have a big project I like to publish it, but is it looked-down-upon to publish, say, a small function?</p>

答:
Publishing a small function can be very helpful, especially when accompanied by a blog or something similar which provides an explanation as to the purpose. I have been helped many times by open source functions.

The gist feature of GitHub also encourages publishing small code snippets.

You should only open source code that you own, or have permission to publish.


答:
The biggest reason is that smaller teams are more effective at delivering software that customers actually want to use, so you want to use as small a team as possible. You might think "well, why not use small teams for the individual features, and combine them later?" It turns out that combining work from more than one team in a seamless, consistent manner is very difficult. And managing such a product (what features does it need? how do you advertise it? and so on) is also very hairy.

Now some Android apps do actually do this to a limited extent. The Google Maps app has three different entry points: Maps, Navigation, and Local. These look to the user like three separate apps, but you get all three when you install one package, Maps. This makes sense because there are a lot of similar functionality required for all of these, they need the same graphics and icons, and so on. Basically it's taking the choices that would be on the main menu of an "all-in one" map app and "pushing it up" to the launcher rather than making the user answer a question every time they use the app. This feels to the user like one less step since "choosing the function in the app" feels the same as "choosing the app" -- pick an icon in the launcher.

Title: Why don't companies ship multiple modules within a mobile app? Are there concerns about tight coupling?

Body:
Preface: My question does not exclusively pertain to Google and it doesn't exclusively pertain to iOS. I'm only using Google and iOS as examples because they are familiar to many. I could have just as easily used 'Company X', apps 'A', 'B', 'C', 'D', and 'E', and 'Android', but I wanted to keep my question rooted in the real world with a tangible example.

In the iOS app store, Google has many apps. At a glance, I can see 'Google Search', 'Google+', 'Google Maps', 'Google Earth', and 'Gmail'.

But I wonder - Why didn't Google simply create a 'Google' app which can provide all of the functionality that these five apps provide? The black menu bar at the top of each Google webpage makes this possible on the web; so why don't they make this possible by way of a menu button at the bottom of one "global" Google app?

Is Google concerned about tight coupling between the apps?

Is Google concerned about tight coupling between the teams that develop the apps?

Is Google concerned about app size?

Is Google concerned about the memory footprint or CPU load that such a monolithic app might incur when it is loaded?

[Not a rant. Merely playing devil's advocate.]

In spite of many advantages, some iOS critics say that multiple pages of apps leave the iPhone and the iPad feeling "cluttered". This is particularly relevant to my question because it seems a bit much to expect a user to know about (and manage) so many Google mobile offerings. From a product standpoint, and arguably a usability standpoint, it seems like it would be wise to ship a single app.

If you're curious, I own an iPhone and a Nexus 7; so I'm not wedded to either of the two major mobile platforms.

And I have a real problem to solve here - Whether to bundle multiple apps inside of one large app, or to distribute separate bits of functionality in multiple apps.

EDIT: In response, to @MichaelT's comment

While there is indeed a 2GB size limit for apps, the size of your sandbox is only limited by the remaining capacity on the device.


问:
Session or request scope for account details
I have a (browser based) web application. On each page, I want to have a little label and link in a corner that displays the user's username and other account information along with a logout button. The information that will be displayed is immutable.

Should I store that account information in session attributes when a user logs in and forget about it or should I use a filter/interceptor and load it on each request in the request attributes?

答:
I would use a Session, as the information is sensitive. So the information displayed in your case would be (Account Information and UserName.) If it was only the UserName I would have thought of Request Scope, but since it is Account Information (Assuming Account numbers, etc) I would go for a session. Once the session is out, the user needs to log in again.

Or I would not display anything but the userName and the logout button.


答:
When is it okay to open-source something?

Assuming that you have legal permission to do so (I am not a lawyer; if the code in question originated at your workplace, consult your manager and legal department before publishing anything as open-source), you can do it whenever you want. Usually before putting it on display for all the world to see, people like to spend some time cleaning up dead code, formatting the code, adding proper comments and documentation, and any special instructions for compiling or running. Once your code is nice and clean looking, go ahead and publish it!

And no, publishing a small function, with a demo project that shows how to use it will not be looked down upon. Somebody somewhere might find it useful and they will be thankful you chose published it.

Body: When is it okay to open-source something? If I have a big project I like to publish it, but is it looked-down-upon to publish, say, a small function?</p>


问:
Is it sometimes reasonable to cut corners and expect to re-write software in a couple of years?
I work for an organization with one developer (me) and one DBA.  When I started, the previous developer had developed applications that had bad architectural practices and it was getting and more time consuming after a couple of years to add features, fix bugs as the story usually goes.

I came in and started re-writing a couple of apps from scratch.  Now being the only developer, it's taking me quite a while to stick with TDD, do good UX, good architectural principles, create common libraries for business logic as it's used by many applications, etc.

I'm wondering if in an environment like this it'd be more feasible to cut corners and churn out web applications (I'm not sure about desktop applications) with the intent of re-writing them every 2-3 years.  I mean cutting corners in things like unit tests and architecture.  I'd expect such applications to be hard to maintain over a long term, and that'd be ok, because we'd just rewrite from scratch and copy and paste any business logic we needed to carry forward - as long as the requirements, documentation, and the data modeling is solid.

Anybody see any pitfalls to this?  I guess it wouldn't be good for my career in the long term, but from the organizational perspective, I think it makes sense.  The pay is kind of low because they're constrained by budget (govt. job) and I think the developer wouldn't last more than 2 years.  I'd really appreciate any insights.

答:
I'm wondering if in an environment like this it'd be more feasible to
  cut corners and churn out web applications (I'm not sure about desktop
  applications) with the intent of re-writing them every 2-3 years. I
  mean cutting corners in things like unit tests and architecture.

I'd agree that it is tempting to cut corners and churn out web applications ever 2-3 years though I'd wonder if you've tried this cycle a few times to see what happens?  The cutting corners is a contributing factor of what leads to the issues you are facing now, you do realize, right?

I'd expect such applications to be hard to maintain over a long term,
  and that'd be ok, because we'd just rewrite from scratch and copy and
  paste any business logic we needed to carry forward - as long as the
  requirements, documentation, and the data modeling is solid.

Have you run into cases where some of the business logic that was handled by default behavior gets buggy in a new version of the language or platform because things were upgraded?  What kind of change over would you have for users of the application?  That may be the more important point as while you can re-write the guts of the application, if the data model changes a great deal, how well do you handle converting all that data?

I'd also question if after a couple of rounds of this, how well is anyone keeping all the requirements and documentation up to date which while you have an "as long as..." that from some managers may not be that high of a priority and thus we have more problems compounding.

At one of my previous jobs, we spent 2 years getting the first phase of a new content management system running.  In that case, to try to re-write it every 2-3 years would not work well for the company paying millions of dollars for the project if one adds up all the licenses, labor costs, and other things.  Thus, it can be worth considering how long does a re-write take as if it takes a few years, then you're forever dealing with parallel systems, no?  There's a current live system being tweaked and the next one still being built at any given point in time.  I doubt you intend for this situation but it is a way to interpret what you are doing here.

Joel Sposky did write about rewriting software some years ago that may be worth reading to see how applicable are his points on this.


答:
It's okay whenever it's legal, or otherwise obviously not okay. For instance, if you find a security hole in DNS, please don't open source an exploit without making a few phone calls first.

When should you open source something? In the current era, the following benefits are most salient:

Other people can use your stuff. So try to make useful. For instance, npm packages tend to be very small, often only one file of a few hundred lines, simply because they solve one problem that many people run into often.  And if you are successful enough to garner attention, other people will start working on it and improving it for you. This is, of course, the business value in open sourcing something.

It builds your portfolio. When applying for jobs it's nice to be able to hand someone a github link that shows what you've done. This is a good reason to open source stuff.

Companies like github will gladly manage your open code for you. Github's business model is, if you contribute to our site with your code, it's free. If you don't want to contribute, you can share. More generally, it's obviously just easier to work with code, a document, or whatever, when it's not a problem if someone reads it. Even my boring to-do lists are "open" on my small personal site. If you happen to read one, then not much happens besides your wasting 15 seconds of your life, but it means from a mobile phone or any random computer I can just look up a post with no authentication whatsoever.

There are many more reasons and it's a big topic, but I think this speaks to what you were asking moreso than simply documenting when it's okay. I will take the stance that unless you're planning on monetizing some proprietary code in the near future, it's probably very good for you and a little good for the community to open source whatever you can.

Title: When is it okay to open-source something?


问:
What are some well known applications written in F#?
As part of a continuing quest for knowledge, I'm spending some time this week learning the basics of F# as an introduction to functional programming. I think I am understanding the construction of software under this model and some of the proposed benefits, but am still a little fuzzy on the real-world use cases.

I was hoping that a F# success stories, or at least a few applications that I'd be familiar with might make it a little clearer about when F# (or any functional programming language) would be appropriate for a project.

So back to the question, what are some well known applications that use F# or a similar functional programming language?

BTW: I am also open to hearing about some lesser-known apps, but if you mention one, please give the basics of what the app is about and why the language used was the appropriate choice.

答:
The entire F# system (compiler, libraries and tools)

IronJS (already mentioned)

The XBox Live TrueSkill algorithm, as well as the whole Achievements system, the ranking system and the matchmaking system surrounding it

I guess the main reason why there are no "well-known" applications written in F#, is because it takes years, even decades to become "well-known" and F# simply isn't that old yet.

However, the overwhelming majority of applications are not "well-known". There is only one PowerPoint, but there are literally millions of hand-written custom little one-off in-house payroll apps.

And F# is certainly used in-house in many financial companies, doing scientific and numeric computing in, say, biotech or greentech, doing statistics god knows where and so on. These applications aren't well-known, either because they simply aren't "sexy" or often because the companies consider F# their secret weapon which gives them a competitive edge. (OCaml, Smalltalk and APL fill similar roles. Many financial companies use APL, for example, but they don't widely publicize it. Indeed, oftentimes the APL users aren't even programmers, and thus wouldn't even know where and how to publicize it even if they wanted to.)


答:
Firstly, that's how the Y2K bug happened. But let's continue.

You are going to drastically overestimate the amount of time until a corner comes back to bite you.  If you cut a corner, do you think it's going to be years until you have a problem with it?  Or sometime a few days later, when you do a bug patch on code you thought you wouldn't have to touch again? Doing things wrong means you have to spend some time each day worrying about it.

But more generally, it sounds like you've framed this in a very self-harming manner.  Are you under pressure to get things done "faster" and cut corners? If so, then you need to improve your business skills to the point that you can make the case to your manager that "cutting corners" is not the fastest way to get things done. Are you under no pressure at all?  Then what do you possibly have to gain out of cutting corners?  This is a very YOLO way to live, where you assume that "I'll be dead by then!" and...  well, are just alive and in bad health, and haven't particularly enjoyed life in the meantime.  Is it really fun for you to cut corners?  Probably not. It actually sounds like it's making you unhappy with your job, when you could spend the same time being happy with your job by doing a good job at it - and finish with a much better resume and skill set. So I strongly recommend against this strategy, if you can call it that.

Title: Is it sometimes reasonable to cut corners and expect to re-write software in a couple of years?

Body:
I work for an organization with one developer (me) and one DBA.  When I started, the previous developer had developed applications that had bad architectural practices and it was getting and more time consuming after a couple of years to add features, fix bugs as the story usually goes.

I came in and started re-writing a couple of apps from scratch.  Now being the only developer, it's taking me quite a while to stick with TDD, do good UX, good architectural principles, create common libraries for business logic as it's used by many applications, etc.

I'm wondering if in an environment like this it'd be more feasible to cut corners and churn out web applications (I'm not sure about desktop applications) with the intent of re-writing them every 2-3 years.  I mean cutting corners in things like unit tests and architecture.  I'd expect such applications to be hard to maintain over a long term, and that'd be ok, because we'd just rewrite from scratch and copy and paste any business logic we needed to carry forward - as long as the requirements, documentation, and the data modeling is solid.

Anybody see any pitfalls to this?  I guess it wouldn't be good for my career in the long term, but from the organizational perspective, I think it makes sense.  The pay is kind of low because they're constrained by budget (govt. job) and I think the developer wouldn't last more than 2 years.  I'd really appreciate any insights.


答:
I can't add comments to expand on k3b's answer... so I have to add a new answer.

YOU should decide how to handle the onUpgrade process yourself.

Notice the arguments in onUpgrade:

```<code>public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {...}
</code>```

You are provided with the "oldVersion" and the "newVersion".
oldVersion is the version of the DB schema that is on the device at the time this method is called.
newVersion is the version of the DB schema that is in your application being run.

Potential solutions:

Solution #1 - Brute Force

If you don't care a lick about the data currently on the device:

```<code>public void onUpgrade(...)
{
  dropDatabase();    // whatever it takes
  createDatabase();
}
</code>```

Solution #2 - Save some data you care about

Maybe you only care about some list of favorites.

```<code>public void onUpgrade(...)
{
  var currentFavorites = saveFavoritesTo();

  dropDatabase();    // whatever it takes
  createDatabase();

  loadFavorites(currentFavorites);
}
</code>```

Solution #3 - Maintain a list of migrations

When schema changes get complex AND you need to keep data in tact, you will need to write the sql statements to alter tables and migrate data.  You might consider using the versions to figure out which migrations to run.

Somewhere you need to decide which migrations to run.  That's up to you.
But that's why you're provided with the old and new versions.

```<code>public void onUpgrade(...)
{
  var migrations = getMigrationsToRun(oldVersion, newVersion);
  foreach (migration in migrations)
  {
    runMigrationOnDb(db, migration)
  }
}
</code>```

You asked in your comment about keeping the schema but dropping the data.
In that case, you'd want to execute a "truncate table" sql statement on the tables you want to clean the data from.
In sqlite this would probably be: "DELETE FROM table_name;"

http://www.sqlite.org/lang_delete.html

Title: Drop table if it already exists and then re-create it?

Body:
I was just learning about sqlite in android programming from the New Boston Travis videos and I have come across something strange:

It is said that if the database does not already exists, onCreate() method is called to create it. so far, so good.
But, if the database already exists, then onUpgrade() method is called which simply drops the database and then re-creates it.

What is the sense behind such an update? why not just leave the database alone?

Body:
I can't add comments to expand on k3b's answer... so I have to add a new answer.

YOU should decide how to handle the onUpgrade process yourself.

Notice the arguments in onUpgrade:

public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {...}

You are provided with the "oldVersion" and the "newVersion".
oldVersion is the version of the DB schema that is on the device at the time this method is called.
newVersion is the version of the DB schema that is in your application being run.

Potential solutions:

Solution #1 - Brute Force

If you don't care a lick about the data currently on the device:

public void onUpgrade(...)
{
  dropDatabase();    // whatever it takes
  createDatabase();
}

Solution #2 - Save some data you care about

Maybe you only care about some list of favorites.

public void onUpgrade(...)
{
  var currentFavorites = saveFavoritesTo();

  dropDatabase();    // whatever it takes
  createDatabase();

  loadFavorites(currentFavorites);
}

Solution #3 - Maintain a list of migrations

When schema changes get complex AND you need to keep data in tact, you will need to write the sql statements to alter tables and migrate data.  You might consider using the versions to figure out which migrations to run.

Somewhere you need to decide which migrations to run.  That's up to you.
But that's why you're provided with the old and new versions.

public void onUpgrade(...)
{
  var migrations = getMigrationsToRun(oldVersion, newVersion);
  foreach (migration in migrations)
  {
    runMigrationOnDb(db, migration)
  }
}

You asked in your comment about keeping the schema but dropping the data.
In that case, you'd want to execute a "truncate table" sql statement on the tables you want to clean the data from.
In sqlite this would probably be: "DELETE FROM table_name;"

http://www.sqlite.org/lang_delete.html


问:
Threads or ThreadPool? Fixed or Dynamic ThreadPool?
I have a java program which listens on a port for input. Based on Input, it calls a webservice and then returns a success/failure back to the client program.

I fork a thread for each client connection. The response back to the client which connects to the program has to be quick.

These are the choices I am considering

use regular threads

use ExecutorService with newFixedThreadPool

use ExecutorService with newCachedThreadPool

The reason I am considering Pools is because my threads are shortlived - they just call a webservice, return result to the client and close the connection.

I don't think newFixedThreadPool would be the right thing because then connections would be waiting in queues to get a thread.

newCachedThreadPool would have been perfect except for one thing - threads die after a minute. In my case, I get bursts of connections - i.e. multiple connections and then there may be a lull for a few minutes and then again bursts. I think the threads in the CachedThreadPool would die and and would again have to be recreated - so in this case, it may work like #1 sometimes.

Ideally I would have loved to have newCachedThreadPool with a minimum - i.e. a setting which says number of threads would never go below say 20. So idle threads are killed but never allow to go below a minimum threshold.

Is there anything like this available? Or are there any better alternatives?

答:
Regarding the RejectedExecutionException:

Instead of a BlockingThreadPoolExecutor, we can simply set the RejectedExecutionHandler in the ThreadPoolExecutor to use the CallerRunPolicy handler.


答:
Yes, there are definitely situations where it makes sense to create some down and dirty "throwaway" code with the intent of tossing it after a couple years and starting over.  Perhaps your company is trying to quickly prove out a new business model and want to get a sense of the market reaction to a "test product".  Perhaps there is an untapped market and getting a product out the door (time to market) trumps concerns over longer term cost of ownership (maintenance).

But here's the important part: as a programmer this is not your decision to make.  The above are business reasons why it might be feasible.  Your job is to implement code against business requirements, and those business requirements include architectural qualities such as maintenance cost, time to market, scalability, etc.  There is a balance to be struck in time to market vs. cost of ownership, but they play against one another and it is not a one-size-fits-all answer.  Your job is to raise these points to the business, try to do your best to highlight the different options and different resulting costs and times to market, and then act on whatever business decision is made.

In your specific case you seem to be deciding to rewrite the same business logic over and over again to save on app time to market - I don't think this makes sense in the general case.  It is almost always very difficult to extract all of the business logic (remember that one required field that you highlighted with a red border in CSS rules - that's business logic from a certain perspective) and get it right again in a second app.  I would lean toward maintaining the first app in this case.


答: After 2-3 years you will have an application into which you will have invested 2-3 years of development time. What makes you believe that re-creating it from scratch will take significantly shorter than that? Maybe due to more experience with the domain you can go down to 1 year, but that's still a very long time. What will you do while re-writing the app: tell your customers there will be no bug fixes and no new features for a year? It's not gonna work.</p>


答:
Ethically, I'd say it is almost always OK - at worst, it will be ignored, at best, you'll change the world, but more likely it will make someone's life somewhere a miniscule bit better. You're giving it away for free, and you're not forcing anything on anyone - that's about as ethical as you can get, in general. I have a hard time coming up with examples where it would not be OK to share your code; the only thing that comes to mind would be if you have discovered a security vulnerability and written an exploit. Publishing the exploit without prior warning is questionable, and in most cases "responsible disclosure" (tell the maintainer/author first, and only release the information to the general public after a grace period long enough to get the problem fixed, ideally in cooperation with the maintainers) is a better way to go.

Legally, the story is different. If you have written the code under an employment or consulting agreement, you may not have copyright over it, and you cannot legally publish it as yours. The code may also contain trade secrets or other restricted information, or it may do things that are considered illegal in at least some jurisdictions: for example (I may be wrong, but this is my understanding) publishing DVD playback software that can play encrypted DVD's is illegal in the USA unless you have a valid license to do so (and such a license is incompatible with free software in general). Software that is written to perform crimes may also be illegal in and of itself - e.g., if you were to write a program that automatically analyzes Google Maps imagery to find homes that are likely to be easy targets for burglary, it could be argued that you have made the software equivalent of a lock-picking tool. And then there's the wild world of patents, which may also pose an obstacle to legally releasing your code to the world.


答:
The pitfalls? You have an opportunity to create the work environment of your choice. I don't see how creating code that is not easy to add features makes your life any easier. Most devs despise and look for answers on how to fix poorly developed software.

Your predesessor chose to use bad practices and you want to do the same. It's obvious your company has no idea how to create and manage software or developers.

Unless you are being pressured to deliver changes faster regardless of the quality, I don't see why you would want to take this path. Write code you can be proud of. If the company doesn't appreciate this, you seem to think your stay is temporary anyway. Life is too short to write bad code.

Edit - I'm not arguing you have to write the world greatest code (As MichealT pointed out), but take every chance you can to do your best and continue the process of improvement.


问:
generic chaining technique for overloaded method
A common operation in JavaScript is to replace an object method with a new one while still calling the original method. This is often done like this:

```<code>var originalMethod = obj.method;
obj.method = function(arg) {
    // call original method
    originalMethod.call(this, arg);
    // do my stuff new stuff
}
</code>```

I'd like to create a utility function for a specific object method that handles the chaining part so that the user doesn't need to be concerned about it. One option is to use the above design, in which each added function is wrapped in a new function that calls the previous one. Another option is to create an array of functions and make the object method just iterate over the array, calling each function in turn.

```<code>function addXyzMethod1(fn) {
    if (obj.method) {
        var previousMethod = obj.method;
        obj.method = function(value) {
            value = previousMethod.call(this, value);
            return fn.call(this, value);
        };
    } else {
        obj.method = fn;
    }
}

function addXyzMethod2(fn) {
    if (obj._methodList) {
        obj._methodList.push(fn);
    } else if (obj.method) {
        obj._methodList = [obj.method, fn];
        obj.method = function(value) {
            for (var i = 0, n = obj._methodList.length; i < n; i++) {
                value = obj._methodList[i].call(this, value);
            }
            return value;
        };
    } else {
        obj.method = fn;
    }
}
</code>```

At this point, I can't decide which method to use since I feel the trade-offs of each are about even. So my question here is: Which of these method is better (more natural, or accepted, or quicker) or is there another method that improves on both of these?

答:
This question is quite similar, or at least comes down to a similar question here: https://stackoverflow.com/questions/660337

Reading the favored answer there, I would recommend you to stick with addXyzMethod1 if you know that you do not have to overwrite the function so often that you are running into the dangers of a stack overflow.

If you want an alternative solution (which would be desirable in my opinion), a better understanding on what you are trying to do exactly would be helpful. I have not required this technique in a long time and from my experience this is bad practice in most cases. There are design patters which help you avoid this situation. E.g. use composition. Have an object representing a collection of functions (can be a simple array of functions) and inject that one into your object via its constructor and store it as a member. Then use it in that method you originally wanted to replace. The collection you injected, you can still add and remove functions from it. This would be kind of similar to your addXyzMethod2 just without having that global util function and without the need to overwrite your object's original method.


问:
Jumping around to work on different features when you get stuck, is it a source of project failures?
On personal projects (or work), if one gets stuck on a problem, or waiting to figure out a solution to the problem, if you jump to another section of your code, don't you think it will be a good reason your application will be buggy or worse yet never get completed?

Assuming you are not using git and code each feature to a specific branch, things can get out of hand since you have 3 different features you are working on, and you have unresolved issues in each.

So when you get done to work, you get stressed out because you have these hanging issues and half-baked code lingering about.

What's the best way to avoid this problem? (if you have it)

I'm guessing using something like git and creating a branch per feature is the safest way to avoid this bad habit.

Any other suggestions?

答: Sometimes it can be helpful to limit the number of features that are implemented in parallel. Refuse to start implementing an extra feature if that limit would be exceeded until one other feature is finished. This approach is called Kanban</p>


问:
Need a simple compact program to execute few commands
(On Windows 7 64 bit)...
I am looking for a program, something similar to the default Windows Terminal, what I need it to do is:

Load text from a given URL, split the code in two variables and then trigger a simple Windows command based on these two variables.

Currently I am doing this with PHP ...

```<code><?php
$my_vars = file_get_contents('http://site.com/data.txt');
list($var1, $var2) = explode($my_vars);
exec("my command $var1 $var2");
?>
</code>```

This does the job fine but I don't like having PHP installed on Windows for something as simple as this. I am looking for a more compact file that maybe can be triggered from command prompt and doesn't have many additional files or dependencies, I need it to run on 2-3 computers too.

答:
Looks like you want some form of general purpose scripting language. Windows batch scrips are the traditional way of doing simple tasks like this on Windows. In more modern versions this has been replaced with Powershell Scripts.

Seen as you want to get things from a URL you might want to use a more powerful language however such as Ruby or Python. Both are quite capable of accomplishing the task as simply as PHP does it in your example. The choice between the two is more a matter of style and familiarity rather than one of capability.


问:
How to make sprint planning fun
Not only are our sprint planning meetings not fun, they're downright dreadful.

The meetings are tedious, and boring, and take forever (a day, but it feels like a lot longer).

The developers complain about it, and dread upcoming plannings.

Our routine is pretty standard (user story inserted into sprint backlog by priority >> story is taken apart to tasks >> tasks are estimated in hours >> repeat), and I can't figure out what we're doing wrong.

How can we make the meetings more enjoyable?

...

Some more details, in response to requests for more information:

Why are the backlog items not inserted and prioritized before sprint kickoff?

User stories are indeed prioritized; we have no idea how long they'll take until we break them down into tasks! From the (excellent) answers here, I see that maybe we shouldn't estimate tasks at all, only the user stories. The reason we estimate tasks (and not stories) is because we've been getting story-estimates terribly wrong -- but I guess that's the subject for an altogether different question.

Why are developers complaining?

Meetings are long.

Meetings are monotonous. Story after story, task after task, struggling (yes, struggling) to estimate how long it will take and what it involves.

Estimating tasks makes user-story-estimation seem pointless.

The longer the meeting, the less focus in the room. The less focused colleagues are, the longer the meeting takes. A recursive hate-spiral develops. We've considered splitting the meeting into two days in order to keep people focused, but the developers wouldn't hear of it. One day of planning is bad enough; now we'll have two?!

Part of our problem is that we go into very small detail (in order to get more accurate estimations). But when we estimate roughly, we go way off the mark!

To sum up the question:

What are we doing wrong?

What additional ways are there to make the meeting generally more enjoyable?

答:
Planning is one area of scrum where teams have a lot of flexibility.  Try something new every sprint until you hit on something that works for your team.

Some successful ideas I've either tried personally, or heard about from other teams:

Do user story creation and prioritization without the entire team.  The product owner and/or scrum master can handle a lot of the busy work and just let the team tweak it.

Make your backlog significantly longer than a single sprint.  It can take a while to build it up, but if your backlog is long enough, planning meetings are reduced to making small tweaks or addressing recent business developments.

Have estimation meetings separate from sprint planning.  If people think the meetings are too long, there's no reason not to split them up.

Specifically plan breaks into the agenda.  This is useful if you're often wasting time waiting for one or two team members to return.

Break in the middle of the meeting and assign everyone to task out one or two user stories, then meet back together to report and gain consensus.

Make sure your planning meeting is about what to do, not how to do it.  Engineers fall very easily into the latter.  If you need to, set up separate design meetings where you discuss the how.

Separate your stories into investigation and implementation.  Planning meetings often go too long when team members know too little about what they will be working on, and try to figure it out during the meeting.
For example, say you needed to integrate with an API that your team has no experience with.  Rather than try to create estimates and tasks during the planning meeting about something you are clueless about, make one investigation story to learn the API, do a simple "hello world" app, and teach it to the team.  Then you'll be equipped to plan the actual work.

Keep track during your meetings of specific issues.  Not just "planning is boring," but a level of detail like, "we spend a lot of time talking about unclear requirements, and no one seems to know the right answer."  Then discuss those specific issues in your retrospectives and brainstorm for specific solutions.  Break your problem down until the pieces are easy to solve.

We hold our sprint planning and retrospective at the same time, and are almost always done in 90 minutes, but we are one of the faster teams.  We do a big company-wide longer-term planning every 5 sprints that takes 4-6 hours.  Every team is different, of course, but if you're spending an entire day every sprint, there's a lot of room for improvement.

Title: How to make sprint planning fun


答:
What you are trying to do is a JavaScript version of call super, which is described as a code smell by Martin Fowler.

I would suggest instead that you either

Contain the "super" object instead of inheriting from it.

Use template method, such as below

```<code>templateMethod = function () {
     baseMethod();
     if (overrideMethod) {
          overrideMethod();
     }
};
</code>```

Other objects would call templateMethod. The overrideMethod is where child objects would have their code.

Title: generic chaining technique for overloaded method

Body:
A common operation in JavaScript is to replace an object method with a new one while still calling the original method. This is often done like this:

```<code>var originalMethod = obj.method;
obj.method = function(arg) {
    // call original method
    originalMethod.call(this, arg);
    // do my stuff new stuff
}
</code>```

I'd like to create a utility function for a specific object method that handles the chaining part so that the user doesn't need to be concerned about it. One option is to use the above design, in which each added function is wrapped in a new function that calls the previous one. Another option is to create an array of functions and make the object method just iterate over the array, calling each function in turn.

```<code>function addXyzMethod1(fn) {
    if (obj.method) {
        var previousMethod = obj.method;
        obj.method = function(value) {
            value = previousMethod.call(this, value);
            return fn.call(this, value);
        };
    } else {
        obj.method = fn;
    }
}

function addXyzMethod2(fn) {
    if (obj._methodList) {
        obj._methodList.push(fn);
    } else if (obj.method) {
        obj._methodList = [obj.method, fn];
        obj.method = function(value) {
            for (var i = 0, n = obj._methodList.length; i < n; i++) {
                value = obj._methodList[i].call(this, value);
            }
            return value;
        };
    } else {
        obj.method = fn;
    }
}
</code>```

At this point, I can't decide which method to use since I feel the trade-offs of each are about even. So my question here is: Which of these method is better (more natural, or accepted, or quicker) or is there another method that improves on both of these?

Body:
What you are trying to do is a JavaScript version of call super, which is described as a code smell by Martin Fowler.

I would suggest instead that you either

Contain the "super" object instead of inheriting from it.

Use template method, such as below

templateMethod = function () {
     baseMethod();
     if (overrideMethod) {
          overrideMethod();
     }
};

Other objects would call templateMethod. The overrideMethod is where child objects would have their code.


答:
is it looked-down-upon to publish, say, a small function?

This seems to be the core of the question, and it's a social consideration.

Looking at the open source community in general, I'd say that it would view publishing any code as open source as a good thing.

But communities are made up of individuals, and individual reactions can be wildly variable. Some may find your function useful and thank you personally, or even build a story of a new generation of open source hackers out of it, warranted or not. Some will use it as an opportunity to assert their superiority and will mock your for doing things obviously wrong (i.e. different than what they would have done).

Realistically though, chances are that hardly anyone will notice.


答: Another way of doing things like this when Windows batch scripts are not powerful enough is using VBScript - not so nifty as Powershell, but IMHO easier to "grok". See here for an example routine for HTTP downloading, and here how to execute a command. VBScript is part of every Windows installation since ~2000. Powershell is only preinstalled for Win7 and later (which may suffer your needs).</p>

Title: Need a simple compact program to execute few commands

Body:
(On Windows 7 64 bit)...
I am looking for a program, something similar to the default Windows Terminal, what I need it to do is:

Load text from a given URL, split the code in two variables and then trigger a simple Windows command based on these two variables.

Currently I am doing this with PHP ...

```<code><?php
$my_vars = file_get_contents('http://site.com/data.txt');
list($var1, $var2) = explode($my_vars);
exec("my command $var1 $var2");
?>
</code>```

This does the job fine but I don't like having PHP installed on Windows for something as simple as this. I am looking for a more compact file that maybe can be triggered from command prompt and doesn't have many additional files or dependencies, I need it to run on 2-3 computers too.


问:
C++ Web Development: Wanting a minimalist start
I'm currently working on a Computer Science degree, and I want to build my own Web Server library. The problem? Every search I've done on interacting with web sites points to "Use this library that was built by someone else" - instead of explaining the basics of sending and receiving information.

I'm not asking for a lot - I just want to enter a single alpha-numeric character on a web page, hit a button, and have that one byte of information sent to a C++ program, without the aid of a non-standard library.

答:
Correct me if I'm wrong, but it sounds like you want to program your own web server from scratch, using only standard C++ components.

First of all you are in a bit of a bind as there is no standard tcp/ip socket library, so you'll need to use Windows sockets, or Posix sockets depending on platform.

Then you'll need to research the format of requests/responses. I'm sure with a bit of searching you'll find a resource on the http protocol.

After that you'll need to create a server that listens for connections, responds to requests and sends responses.

If that isn't what you are asking, then MichaelT's suggestion sounds reasonable.


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
If you're looking for a good paying job, my recommendations are as follows:

Love what you do and be passionate about it.

Educate yourself, don't fools others - Most people neglect the fundamentals and jump into the advance stuff thinking it'll make them look smart. All tall buildings are built upon a stable foundation.

Know your worth - Don't accept a job only because the employeer said they want to hire you. It's a two way street. What are they offering you long term? Is there growth? Does the work appeal to you?

Good pay is subjective, so know what you're willing to accept and settle for nothing less.

Build a reputation! Speak at conferences, Write articles, commit to Open Source projects

Don't be lazy. Just because someone will Google your name up and find out you answered a million questions on stackexchange.com that it makes you any way qualified for more money. Any code monkey can use Google to answer a question. Problem solving, strong technical knowledge, good personal skills, etc. make the world of difference when it comes to money.

I'm not perfect. Just perfect enough to know I'm good, but I'm not sure how good.


答:
Some of tye info that you want is here - http://en.wikipedia.org/wiki/Common_Gateway_Interface . It might not sound like what you are trying to do is very complicated, but it's a bit more complicated than you might think. As Dominic said the tricky part will be opening the port and reading from the socket - quite difficult in c++ land.

I would recommend that to start with, use an existing web server and write your own CGI module. The web server will take care of the sockets side of things, and basically you're just reading data from environment variables or command line arguments (if it's a GET request) or from the stdin if it's a POST (I think, this is data from my memory that's about 15 years old). What you want is something like this:

```<code>#include <stdio.h>
#include <string.h>

int main(){
    char *s=getenv("CONTENT_LENGTH");
    int i=atoi(getenv("CONTENT_LENGTH"));
    printf("Content-type: text/html\n\n");
    printf("%s\n<br />",s); //Shows you CONTENT_LENGTH works
    printf("%d\n<br />",i); //Shows you it was converted to int
    char *tmp = new char[100];
    fread(tmp,i,1,stdin); //read from stdin something of i bytes to tmp
    printf("%s\n<br />",tmp);
    return 0;
}
</code>```

BTW as a lesson for the reader this application has a buffer overflow bug.. you probably want to fix that :)

Title: C++ Web Development: Wanting a minimalist start

Body:
I'm currently working on a Computer Science degree, and I want to build my own Web Server library. The problem? Every search I've done on interacting with web sites points to "Use this library that was built by someone else" - instead of explaining the basics of sending and receiving information.

I'm not asking for a lot - I just want to enter a single alpha-numeric character on a web page, hit a button, and have that one byte of information sent to a C++ program, without the aid of a non-standard library.

Body:
Some of tye info that you want is here - http://en.wikipedia.org/wiki/Common_Gateway_Interface . It might not sound like what you are trying to do is very complicated, but it's a bit more complicated than you might think. As Dominic said the tricky part will be opening the port and reading from the socket - quite difficult in c++ land.

I would recommend that to start with, use an existing web server and write your own CGI module. The web server will take care of the sockets side of things, and basically you're just reading data from environment variables or command line arguments (if it's a GET request) or from the stdin if it's a POST (I think, this is data from my memory that's about 15 years old). What you want is something like this:

#include <stdio.h>
#include <string.h>

int main(){
    char *s=getenv("CONTENT_LENGTH");
    int i=atoi(getenv("CONTENT_LENGTH"));
    printf("Content-type: text/html\n\n");
    printf("%s\n<br />",s); //Shows you CONTENT_LENGTH works
    printf("%d\n<br />",i); //Shows you it was converted to int
    char *tmp = new char[100];
    fread(tmp,i,1,stdin); //read from stdin something of i bytes to tmp
    printf("%s\n<br />",tmp);
    return 0;
}

BTW as a lesson for the reader this application has a buffer overflow bug.. you probably want to fix that :)


问:
Ajax - Responding business errors
This might sound like another of those questions with "best way" or "best practice" but I couldn't find anything related that could give me some light.

The scenario... I have some ajax calls. Everything works alright. I make the calls, get the results back, change fields, values, colours. Nothing interesting here.

But then, yesterday, I was writing another ajax method. Basically, two date fields to return number of days without holiday days. Again, nothing interesting here... until the point where I could pass invalid dates.

Now, my question... in an ajax interaction, whenever I have a scenario where the data passed by an ajax call is invalid (understand invalid, the formatting is wrong or the data does not suit some sort of business), should I respond any ajax call that contains data not suitable for my server side processes with a http status different of 200 or create a model with errors and messages and everything?

I've found people doing like AjaxRespond models and responding that. My point here is that if the data is not good, I could respond a http status 200 and deal with the ajax model to check if there are errors or not but I could also respond a 500 and be sure that there is an error.

I can see two perspectives here.

1- the call was successful from javascript/ajax side and therefore 200 is the logical way to respond. This one sounds like "I have good news and bad news".

2- the call was successful but the data was busted and therefore 500 (or any other suitable status) was returned. This one is more doing business logic inside try/catches.

答:
This is a good place to use deferreds. Here is jQuery's implementation, but you don't have to use jQuery. In a nutshell, you have all your ajax calls return a promise that any callbacks bind to. When the response comes back from the server, you evaluate it via a middleware method (then in jQuery's implementation) and resolve or reject the promise depending on the status. That way, callbacks are triggered or not depending on the status, not on whether the ajax request itself succeeded or failed. You can also use this middleware approach to instantiate or populate an error model...

Note: Do not change your HTTP response code at the headers level! Send status along with the data so that you truly know whether the server handled the request predictably or not.

OwnerDisplayName: Desorder

Title: Ajax - Responding business errors


问:
Processing every leaf under a node in a tree efficiently
Short version:
In a tree (non-binary) with many levels of children, where each node can have multiple leaves, what is the best way to tally leaves that meet a certain condition given a node?

Long, convoluted version:
Say you have Folders, which can contain more Folders.  In production, my system has about 15 layers of folders at the deepest.  Each folder may have documents.

When a user navigates to a folder, they need to know how many documents are in that folder, total.  They also need to know how many of those documents have been "flagged".  Documents can be flagged if, after a certain time period, they have not been updated.  This is determined based on history entries - take the last history entry for the folder, if it's bigger than X, then it's flagged.

Right now I'm iterating over all folders > subfolders > etc > children to check the history entry and tally recursively.  This is getting pretty slow now so I need a new approach.

I've come up with two options but want to know if there's a better approach, or which one of these is best.

option 1: Whenever adding a document or removing a document, iterate up the parent graph and increment / decrement a "DocumentCount" property that's stored in the Folder entity.  This means that adding / removing take a minimal performance hit.  But the problem here is that I actually need to count total number of documents, as well as total number of documents that are flagged (by checking history entries), so that means that I'll need another field and another process to call when this status changes.  This introduces even more complexity as checking whether or not something is flagged is a method call, not a property.

option 2: Have a timer job run through and update the "documentCount" and "unopenedDocumentCount" properties of each folder in the system, would be lots of CPU cycles and seems wasteful.

option 3: Just thought of this - maybe iterating over every document and seeing if the document is a direct or distant child of the target node before evaluating would be better than iterating via recursion.  I feel like this would be better for nodes high-up in the tree, but iterating over every child for a low-level node would be ridiculous.  Hmmm...

I'm tempted to implement option 1.. what other options are there?

答:
If you know the condition(s) you want to tally when you add the node to the tree, you can design your add routine to recur down through the tree, instead of just stepping down, and then unwind the recursions and update the tallies in the parent nodes.

Similarly, as you update nodes, you recur down to them, and then unwind the recursions and update the parents.

If you don't know the condition(s) beforehand, you're screwed.  You have no choice but to traverse the tree in whatever order makes sense.  From what you've said, it sounds as though whatever you're doing at a node is a function of the whatever of the left and right subtrees, which makes a postorder traverse look like the right answer.

Note: If the above does not make sense to you, read Knuth vol. 1.


问:
how to use the same behaviour in different classes
I have a behaviour that I'd like to use in different classes. Those classes are unrelated to each other (no inheritance). I'm using AS3, where multiple inheritance is not possible.

I could use an interface but then I'd have to rewrite the same implementation every time, which is basically what I'm doing now (but without the interface).

As en example I have many situations where I have an icon and a text label. In buttons, signs, etc. I'd like to centralise the alignment behaviour between the icon and the label.

What is the best OOP pattern for that?

答: When the same behavior is needed in multiple classes, factor out that behavior into a new class.  In this case, create a new LabeledIcon class containing an icon and a label, properly aligned.  Create new instances of LabeledIcon as needed.</p>


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Some people, when confronted with a
  problem, think "I know, I'll use
  regular expressions."

  Now they have  two problems.

— Jamie Zawinski

LastEditorDisplayName: Roger Pate


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答: Not being allowed to use the STL or other standard C++ libraries because the CTO believed 'we' could do it better and faster. Even basic constructs like lists and the string class.</p>


问:
Google App Engine -- should we use it?
I'm considering using Google App Engine for an online matchmaking (and possibly ranking, not sure) of users in a (currently hypothetical) RTS game. However, I just read this bad review, which has made me nervous. Which problems have they solved (or are planning to solve), which might be an issue for me, and are there any alternatives?</p>

答:
It all depends, if you don't want to do lot of coding for base services like caching, emails and all that then you are better off with Google app engine, else you should go with Amazon EC2 or Rackspace.

And yes, not to forget, Amazon EC2 has a micro plan which is free for 1 year starting Nov-1

Check this out : http://www.buzzingup.com/2010/10/amazon-announces-free-cloud-services-for-new-developers/

Title: Google App Engine -- should we use it?

OwnerDisplayName: buzzingup


答:
Well it seems the best solution is simply using composition.

I found the answer here https://stackoverflow.com/questions/10714984/same-implementation-in-different-subclasses

In my example that would be having an Aligner class, and compositing an instance in my classes.

Title: how to use the same behaviour in different classes

Body:
I have a behaviour that I'd like to use in different classes. Those classes are unrelated to each other (no inheritance). I'm using AS3, where multiple inheritance is not possible.

I could use an interface but then I'd have to rewrite the same implementation every time, which is basically what I'm doing now (but without the interface).

As en example I have many situations where I have an icon and a text label. In buttons, signs, etc. I'd like to centralise the alignment behaviour between the icon and the label.

What is the best OOP pattern for that?