答:
Most Service Layers I've seen are a complete mess. Services tend to have a lot of different methods, 1500 LOC are not rare. The different methods have nothing in common, but do share code. This results in high coupling, low cohesion. It also violates OCP, because every time a new operation is needed, you have to modify the code instead of extending the code base. A well constructed service layer is theoretically possible, but I never seen it in practice.

CQRS solves these problems and prevents you from having to create one of those procedural service layers.


问:
How to unit test a function that is refactored to strategy pattern?
If I have a function in my code that goes like:

```<code>class Employee{

    public string calculateTax(string name, int salary)
    {
        switch (name)
        {
            case "Chris":
                doSomething($salary);
            case "David":
                doSomethingDifferent($salary);
            case "Scott":
               doOtherThing($salary);
       }
}
</code>```

Normally I would refactor this to use Ploymorphism using a factory class and strategy pattern:

```<code>public string calculateTax(string name)
{
    InameHandler nameHandler = NameHandlerFactory::getHandler(name);
    nameHandler->calculateTax($salary);
}
</code>```

Now if I were using TDD then I would have some tests that work on the original calculateTax() before refactoring.

ex:

```<code>calculateTax_givenChrisSalaryBelowThreshold_Expect111(){}
calculateTax_givenChrisSalaryAboveThreshold_Expect111(){}

calculateTax_givenDavidSalaryBelowThreshold_Expect222(){}
calculateTax_givenDavidSalaryAboveThreshold_Expect222(){}

calculateTax_givenScottSalaryBelowThreshold_Expect333(){}
calculateTax_givenScottSalaryAboveThreshold_Expect333(){}
</code>```

After refactoring I'll have a Factory class NameHandlerFactory and at least 3 implementation of InameHandler.

How should I proceed to refactor my tests? Should I delete the unit test for claculateTax() from EmployeeTests and create a Test class for each implementation of InameHandler?

Should I test the Factory class too?

答:
You're taking one class (employee that does everything) and making 3 groups of classes: the factory, the employee (that just contains a strategy) and the strategies.

So make 3 groups of tests:

Test the factory in isolation. Does it handle inputs correctly. What happens when you pass in an unknown?

Test the employee in isolation. Can you set an arbitrary strategy and it works as you expect? What happens if there is no strategy or factory set? (if that's possible in code)

Test the strategies in isolation. Does each perform the strategy you expect? Do they handle odd boundary inputs in a consistent manner?

You can of course make automated tests for the whole shebang, but these are now more like integration tests and should be treated as such.

ContentLicense: CC BY-SA 3.0


问:
Do good project managers need a programming background?
Sometimes I can't stand it when project managers ask me to estimate time to complete for various tasks.  An estimate is a guess, and guesses can be wrong.  Generally, bad requirements and documentation will lead to bad guesses.

So I often wonder if the project managers were ever in my shoes trying to guess at how long task X and Y will take, and how difficult it is to assign a number to it based on what little is known and collected from the client.

My question then is: Do good project managers need to have a programming background?

Or maybe the question should be, do good project managers need to have been a good programmer before?  Is there any correlation?

答: I would say yes, he should have some programming background. If the manager doesn't have a clue as to what is it like to program, then he'll end up with unrealistic estimates for development and bug fixing. Also, he wouldn't understand any technical problem well enough to make a decision. Programmers in the team could lie to him and he may not realize, also programmers could tell him a problem and he may think that they're bullshitting around</p>

ContentLicense: CC BY-SA 2.5


问:
Is it Ok if Domain Object cross Service Boundary
Is it Ok if Domain Object cross Service-Boundary?

Everyone recommend that only DTO should be returned by Services.
I am creating simple CRUD application.

Is it ok if my service methods return Domain object instead of flat DTO objects.
It will save me from lots of mapping related setup. Is there any alternative approach?

答:
Martin Fowler states the first rule of distributed object design is: Don't distribute your objects!

It's understandable that you don't want to write mapping code to map from Domain to DTO and vice versa. Especially, because initially their data might be same. But doing so you couple the domain model to all the clients of the service. Changing your domain becomes impossible without breaking all the clients.

In .NET there is a library called AutoMapper to help mapping between objects. Other languages probably have similar tools.


问:
Relative Scoring system - How to solve this?
I am trying to assign scores to phone's specifications to calculate a final rating score for each phone. </p>

<p>However, when I was scoring based on megapixels, I found that one of the phones 'A' has a 41MP camera. But all other phones have 8MP or less, which is pretty good for a phone. Right now, when I grade relatively wrt phone A (rating 5/5), all other phones get a score of 1 or 2 out of 5. I would like it to be a little more fair, as it was just one phone with a very high value. Could you suggest me the best way to go about solving this issue where the relative grading is more fair? </p>

答:
Despite the fact "megapixels" is a bad metric - you may define some explicit intervals for this kind of thing. For example, you assign these values

1P : 2 MP

2P : 3 MP

3P : 5 MP

4P : 8 MP

5P : 15 MP

For values above 15MP, you give 5 points, for other values you interpolate linearly. For example: 12 MP will result in

(12-8)/(15-8) + 4P = 4.428... points

It may be a bit more complicated to implement than @PieterB's suggestion, but the advantage is that you can adapt it easily to whatever scoring you "feel" to be fair. There's is nothing more to be expected due to the arbitrary nature of such a scoring.

Note that your scoring schematics has to be adapted for every dimension, for example, if you are giving a score for "battery time", 41 hours to 8 hours would most probably need a different scoring. And for "monthly costs", 41 euros/dollars/yen compared to 8 units of the same currency may need a reverse scoring. So whatever you do, there is no "one size fits all" solution.


问:
Philosophy behind the memento pattern
I have been reading up on memento pattern from various sources of the internet. Differing information from different sources has left me in confusion regarding why this pattern is actually needed.

The dofactory implementation says that the primary intention of this pattern is to restore the state of the system.

Wiki says that the primary intention is to be able to restore the changes on the system. This gives a different impact - saying that it is possible for a system to have memento implementation with no need to restore. And that ability of restore is a feature of this.

OODesign says that

It is sometimes necessary to capture the internal state of an object
  at some point and have the ability to restore the object to that state
  later in time. Such a case is useful in case of error or failure.

So, my question is why exactly do we use this one? Is it to save previous states - or to promote encapsulation between the Caretaker and the Memento? Why is this type of encapsulation so important?

Edit: For those visiting, check out this Implementation!

Edit: I am working in implementing a memento solution to my problem. I will post another question regarding that and link that question to this one. Thanks all for responding with valuable suggestions!

Edit 3: Here is the link to my sample implementation

答:
All these definitions steer you in the same direction; they are all saying the point is to be able to restore something to its previous state. That something can be the entire system, or just a single object.

This pattern is useful if a record changes state over time, but you have the business requirement to be able to restore it to any previous state at any time.  Or alternatively, if you need to be able to view the record as it was at any previous point time.  These types of requirements are very common in many types of systems.

OwnerDisplayName: TheSilverBullet

Title: Philosophy behind the memento pattern


答:
By itself, the Memento Pattern is just used to capture and save states. The encapsulation exists only to protect the states from the rest of the system - once a state is captured, it needs to be controlled carefully. For example, it doesn't make sense to be able to change a previous state once it's been saved (that would be changing history) and it might not make sense to simply return to a previous state of one object without affecting others (to prevent the system from entering an entirely invalid state).

The most common use of a Memento that I've seen is to support undo functionality. It is also related to storing redo functionality by moving back forward in time.

Title: Philosophy behind the memento pattern

Body:
I have been reading up on memento pattern from various sources of the internet. Differing information from different sources has left me in confusion regarding why this pattern is actually needed.

The dofactory implementation says that the primary intention of this pattern is to restore the state of the system.

Wiki says that the primary intention is to be able to restore the changes on the system. This gives a different impact - saying that it is possible for a system to have memento implementation with no need to restore. And that ability of restore is a feature of this.

OODesign says that

It is sometimes necessary to capture the internal state of an object
  at some point and have the ability to restore the object to that state
  later in time. Such a case is useful in case of error or failure.

So, my question is why exactly do we use this one? Is it to save previous states - or to promote encapsulation between the Caretaker and the Memento? Why is this type of encapsulation so important?

Edit: For those visiting, check out this Implementation!

Edit: I am working in implementing a memento solution to my problem. I will post another question regarding that and link that question to this one. Thanks all for responding with valuable suggestions!

Edit 3: Here is the link to my sample implementation


问:
Effective ways to make your OSS project popular?
After writing a few (relatively obscure) OSS frameworks, I've learned the hard way that writing a good framework isn't enough--there has to be some time spent marketing your framework as much as the time you spend coding it. So here's my question: What are some effective ways for making your OSS project become well-known? Aside from blogging, how do I gain the most market attention for my code with the least amount of effort as humanly possible?

(EDIT: I'm a lazy programmer and I hate documentation, but I'm biting the bullet. I want to be famous)

答:
If you are referring to LinFu - the library has an incredible amount of promise! I was very excited when I first read up on it, in particular its AOP parts.

I tried to mess about with it, but I couldn't get the latest version to work. I couldnt find any documentation beyond the CodeProject tutorials - which were out of date. Then, being a lazy programmer myself - I gave up.

Every so often I do a search on Linfu to see if there have been any updates - and if there is any new documentation about.

To attract the average programmer like myself, it needs to be easy to start using the library. This means it has to work and it has to be simple to start - either through documentation, or through simplicity of design.

You may want to consider setting up a homepage to act as a centralised place where the documentation, future plans, feature requests can go. This would help give me faith that the library is an active one this isn't going to go away and I can take seriously.

Funky graphics do help here too! The main reason I use Ninject is because I like the ninjas they have on their site.

Linfu has a lot of potential and could easily turn you into a .net God with just a bit of extra icing on top.


问:
CTO has left — codebase is a huge kludge, any advice on how to manage/handle/damage control?
I began work at a company 2 months ago as a PHP developer. I stepped in to somewhat of a kludge, but I've yet to find a company that isn't... The development stable is currently two developers (including myself) who will act as the interim CTO while the company seeks out a replacement CTO.

The company is a news site that runs on top of an inhouse WordPress theme with enhancements in the form of arbitrary plugins, features built into the actual theme, and plugins some built in-house and some 3rd party ((some whose core code has been modified, which renders upgrading a nightmare). No coding standards have been upheld in the creation of the WordPress code and it appears that it has been a number of developers managing the code and no two components are completed using the same methodology, which is beyond a huge mess when it comes to debugging. I am the "WordPress" developer. The other developer is in charge of the latest foray which is developing an e commerce platform to complement the news site, which will be run on top of Magento.

As the only WordPress developer I am handling all bugs and feature requests on a prioritized basis - I am interacting with business directly to hammer this out. The biggest issue I foresee is any bug/enhancement/project that is deemed a priority and requires a significant amount of work (read: 1 week+) becomes a bottleneck and essentially nothing can get worked on until I complete the project. They say that they understand that now but I foresee that becoming an issue when they actually see it in practice. I am looking towards the future and fully expect it to become a stressful situation (14+ hour days 7 days a week anyone?) - which is something I need to avoid at all costs.

Until we restaff a CTO or I am considering proposing that I write up coding standards for the WordPress development and utilize odesk or another outsourcing solution for handling feature requests - ensuring they conform to the standards set forth. In the proposed environment I will (a) manage the odesk developers (ensure I communicate exactly what is needed, ensure they are coding to proper standards) (b) handle any quick feature requests / bug fixes (c) begin refactoring the WordPress code so that it conforms to the aforementioned in-house coding standards - to get us to a manageable state. The company has used outsourcing solutions in the past, so I am confident that the idea of using one would not be an issue.

At this point I am only forumlating the plan to propose to management -- not yet thinking of HOW to do what I accomplish - I just want to get the full OK from them before doing that. What are your thoughts on this plan? Is there anything else that I should think about/consider? Thanks.

答:
If the code base is large as you seem to imply, you should freeze the development of new features, and take time documenting what you already have. Then do a first stab at the coding standards, trying to make sure that as much code as possible is compliant right away, at least in cases when you do not have a strong opinion one way or the other (tabs, spacing, naming conventions, and so on).

Since you are relatively new to the code, try fixing as many bugs as you can. If you do not have a bug database in place, create one, and catalog as many bugs as you can while going through the code. Also make sure that you put tests in place for the bugs that you fix, at least where it is practical (which should be "everywhere", at least in theory).

This will earn you a lot of points with the incoming CTO, and put you in a good spot when the time comes to grow your team.


问:
Is it acceptable for projects to go over budget?
This question is something that's been bugging me for the past 3 months since I switched from being a freelancer to working at a Web Design firm.

Our sales people often ask us something similar to the following series of questions:

How much does it cost to program a widget

How many hours will it take to convert this website to this software.

(Without knowing what the website currently runs)

etc

How can we give a quote without any information? (No, I can't ask for more info!)

I have another question if a project goes over budget it's bad. Recently, I missed an entire menu when calculating the cost of transferring a website over to a new platform so the project went over budget. My boss was not happy at all, and it's my opinion that some things like this can't be avoided.

   2.  What is the general practice for dealing with going over budget

           and do projects like web development often go over budget?

If you work at a web development/design/similar company:

   3.  How does your billable hour system work?

For me, we have a time tracking application that we record how many hours we spend on which project and if they are billable or internal (AKA non-billable). If don't meet xx billable hours a week we can get in trouble/fired eventually. Work you do for the company or for clients that isn't billable isn't part of this system, and we often have to do internal work, so I'm wondering if any alternative systems exist.

EDIT: Ok I am a developer at this firm not a designer :)

Second, I am paid salary, but here is how management looks at it. You have 35 hours a week that you must work. You could be doing work that they bill to clients in that 35 hours and you should. If they figure out a project will take 50 hours and I take 55 hours, that 5 hours could have been spent on another project that wasn't over budget so we just "lost" money.

Another example is that if I only have 1 project, that is due in two weeks and I spend a day  doing internal work, some how we lost money because I wasn't working. If I worked that day, I would finish a day early and still have no work. Either way, the work is contract so we will get paid the same amount regardless of which days I work!

答:
This is really only an answer to the first part of your three-parter, but it's a BIG question.

Here's what I've recently started doing. And this is after a LOT of soul-searching about this very sort of thing.

I reply to a request from a prospect or client with what I call a "Good-Faith Estimate". It's a dollar figure that is padded nine ways from sunday for total CYA. I tell them this number is based on my experience of projects of roughly the scale of the one being considered here.

I tell them their first invoice, due at kick-off, is 25% of the estimate. For that price, we will perform a complete requirements-gathering effort and write full, detailed specifications. Depending on the size of the project, that might be several weeks of work. At the end of that, we'll have a complete set of documentation, AND we'll know how we did on that estimate. If at that point we need to fine-tune the price (and it could go up OR down), we'll do that and let the client know.

If the price goes up and the project is now unsustainable, it's called off at that point with no further payment due. This is obviously an undesirable outcome, and should be considered the last-resort outcome. Plan B is to rework the project requirements to bring the scope down into the project budget, etc.  There's a lot we can try before we call the whole thing off, but if we NEED to, right there is where we can.

Assuming we don't, we'll go forward with the (possibly revised) total price, 50% of which is billable at that point, and the final 25%-or-so at delivery and acceptance. Everybody is on the same page, nobody is feeling like they had to pay money for an intangible like "analysis", and everybody is (ideally) happy.

So far I've had pretty good results with this. It certainly beats hitting the client up for a separate billable for analysis/specification work. Nobody wants to pay for that. But if you hide it in the first 25% of a total project price, it becomes instantly palatable and understandable.


答: Unit tests. Any section of code that looks unmaintainable should be thoroughly covered by unit tests so that you can confidently rewrite the underlying code without breaking anything. Once you have a handle on that, it will make refactoring the structure a lot easier.</p>

Title: CTO has left — codebase is a huge kludge, any advice on how to manage/handle/damage control?

Body:
I began work at a company 2 months ago as a PHP developer. I stepped in to somewhat of a kludge, but I've yet to find a company that isn't... The development stable is currently two developers (including myself) who will act as the interim CTO while the company seeks out a replacement CTO.

The company is a news site that runs on top of an inhouse WordPress theme with enhancements in the form of arbitrary plugins, features built into the actual theme, and plugins some built in-house and some 3rd party ((some whose core code has been modified, which renders upgrading a nightmare). No coding standards have been upheld in the creation of the WordPress code and it appears that it has been a number of developers managing the code and no two components are completed using the same methodology, which is beyond a huge mess when it comes to debugging. I am the "WordPress" developer. The other developer is in charge of the latest foray which is developing an e commerce platform to complement the news site, which will be run on top of Magento.

As the only WordPress developer I am handling all bugs and feature requests on a prioritized basis - I am interacting with business directly to hammer this out. The biggest issue I foresee is any bug/enhancement/project that is deemed a priority and requires a significant amount of work (read: 1 week+) becomes a bottleneck and essentially nothing can get worked on until I complete the project. They say that they understand that now but I foresee that becoming an issue when they actually see it in practice. I am looking towards the future and fully expect it to become a stressful situation (14+ hour days 7 days a week anyone?) - which is something I need to avoid at all costs.

Until we restaff a CTO or I am considering proposing that I write up coding standards for the WordPress development and utilize odesk or another outsourcing solution for handling feature requests - ensuring they conform to the standards set forth. In the proposed environment I will (a) manage the odesk developers (ensure I communicate exactly what is needed, ensure they are coding to proper standards) (b) handle any quick feature requests / bug fixes (c) begin refactoring the WordPress code so that it conforms to the aforementioned in-house coding standards - to get us to a manageable state. The company has used outsourcing solutions in the past, so I am confident that the idea of using one would not be an issue.

At this point I am only forumlating the plan to propose to management -- not yet thinking of HOW to do what I accomplish - I just want to get the full OK from them before doing that. What are your thoughts on this plan? Is there anything else that I should think about/consider? Thanks.


答:
About 3 months ago I started working for a company in a similar situation.  My bosses boss is supposed to be the IT Director and yet he has no IT experience.  Basically the mode here is Urgent and Urgent which means there are no priorities.

My boss was working 60-70 hour weeks, nights, weekends, etc and then decided he could not do it anymore and that he needed some sanity for the management of projects.

He installed a simple project management tool (Redmine: http://www.redmine.org/) and started putting every urgent request into the system (this is critical!) and labeled them all Urgent.

Then he made sure the IT Director was 'following' all of the issues via automatic email - eventually the director started to realize that no single person or people could do everything that was being asked - by making the tasks visible and making the IT Director make the call on priorities things eventually got better.

Fast forward to a year later, I am here helping my boss out with projects and I still see the constant influx of Urgent requests which are promptly seen by the IT Director - then the director is having to handle the negotiations.

So that's management of tasks...

Regarding coding standards:  that's a good idea but I would not do that now.  I would put that in the system as a task that needs to be done and let the manager set the priority.  Everytime there is an issue where standards would make a difference then I would trot out that task to the manager and point out how it would have helped.

This is not opinion but a current practice so there is validity at least in our situation for how things are handled.

Coding wise I would pick the low hanging fruit, make sure it's in the management tool (redmine or whatever) and make sure everyone knows the status and when it's done - show you are making a difference - that will give you some weight in terms of negotiations about future projects.

I would NOT refactor the wordpress code in one go but I would put together the top 10 refactoring tasks, add them to your task management system and let the manager set the priority.  Trot them out when doing the refactorings would have saved some new pain that has erupted.

Sorry so long, I could go on for an hour!


答:
Technical skills don't make a good manager, good management skills do.  It can be helpful if a manager has done their time in the "trenches" as they can have an appreciation of the process that laymen can't have.  However, it can also result in a kind of control freakery that even control freak layman managers don't have.  They may try to do all the work themselves or scrutinize yours in an extremely uncomfortable way.

In my personal experience, the best manager I ever had was fairly clueless about technology, but he knew that the people working under him knew their stuff, and he knew how to earn the loyalty and respect of his team.  I worked under him for four years, and only left the company because he'd left and been replaced by a manager who wasn't as good.

One of the worst managers I've had is versed in coding (if not software design) and does so much of the work himself that he leaves the rest of us with little more than scraps, bug fixing or the projects he doesn't want to do himself.

Title: Do good project managers need a programming background?

Body:
Sometimes I can't stand it when project managers ask me to estimate time to complete for various tasks.  An estimate is a guess, and guesses can be wrong.  Generally, bad requirements and documentation will lead to bad guesses.

So I often wonder if the project managers were ever in my shoes trying to guess at how long task X and Y will take, and how difficult it is to assign a number to it based on what little is known and collected from the client.

My question then is: Do good project managers need to have a programming background?

Or maybe the question should be, do good project managers need to have been a good programmer before?  Is there any correlation?


问:
Is there an "ask for only what you need" interface principle?
I have grown into using a principle for designing and consuming interfaces that says basically, "ask for only what you need."

For instance, if I have a bunch of types that can be deleted, I'll make a Deletable interface:

```<code>interface Deletable {
   void delete();
}
</code>```

Then I can write a generic class:

```<code>class Deleter<T extends Deletable> {
   void delete(T t) {
      t.delete();
   }
}
</code>```

Elsewhere in code I will always ask for the smallest possible responsibility to fulfill the needs of the client code.  So if I only need to delete a File, I'll still ask for a Deletable, not a File.

Is this principle that is common knowledge and already has an accepted name?  Is it controversial?  Is it discussed in textbooks?

答:
To expand on Vadim's very good answer, I will answer the "is it controversial" question with "no, not really".

In general, interface segregation is a good thing, by reducing the overall number of "reasons to change" of the various objects involved. The core principle is, when an interface with multiple methods must be changed, say to add a parameter to one of the interface methods, then all consumers of the interface must at least be recompiled, even if they did not use the method that changed. "But it's just a recompile!", I hear you say; that may be true, but keep in mind that typically, anything you recompile must be pushed out as part of a software patch, no matter how significant the change to the binary. These rules were originally conceptualized back in the early 90s, when the average desktop workstation was less powerful than the phone in your pocket, 14.4k baud dial-up was blazin', and 3.5" 1.44MB "floppies" were the primary removable media. Even in the current era of 3G/4G, wireless internet users often have data plans with limits, so when releasing an upgrade, the fewer binaries that must be downloaded, the better.

However, like all good ideas, interface segregation can go bad if improperly implemented. First off, there is a possibility that by segregating interfaces while keeping the object that implements those interfaces (fulfilling the dependencies) relatively unchanged, you may end up with a "Hydra", a relative of the "God Object" anti-pattern where the all-knowing, all-powerful nature of the object is hidden from the dependent by the narrow interfaces. You end up with a many-headed monster that is at least as hard to maintain as the God Object would be, plus the overhead of maintaining all its interfaces. There isn't a hard number of interfaces that you shouldn't exceed, but each interface you implement on a single object should be prefaced by answering the question, "Does this interface contribute to the object's single, narrow core purpose, or goes it give the object a new purpose?". If it's the former, implement away; if it's the latter, split the object in two to maintain the Single Responsibility Principle.

Second, an interface per method may not be necessary, despite what SRP may tell you. You may end up with "ravioli code"; so many bite-size chunks that it's difficult to trace through to find out exactly where things actually happen. It's also unnecessary to split an interface with two methods if all current users of that interface need both methods. Even if one of the dependent classes only needs one of the two methods, it's generally acceptable to not split the interface if its methods conceptually have very high cohesion (good examples are "antonymic methods" which are exact opposites of each other).

Interface segregation should be based on the classes that are dependent on the interface:

If there is only one class dependent on the interface, don't segregate. If the class doesn't use one or more of the interface methods, and it is the interface's only consumer, odds are you shouldn't have exposed those methods in the first place.

If there is more than one class that is dependent on the interface, and all dependents use all methods of the interface, don't segregate; if you must change the interface (to add a method or change a signature), all current consumers will be affected by the change whether you segregate or not (though if you're adding a method that at least one dependent will not need, consider carefully if the change should instead be implemented as a new interface, possibly inheriting from the existing one).

If there is more than one class dependent on the interface, and they do not use all the same methods, it's a candidate for segregation. Look at the "coherence" of the interface; do all methods further a single, very specific programming goal? If you can identify more than one core purpose for the interface (and its implementors), consider splitting the interfaces along those lines to create smaller interfaces with fewer "reasons to change".


答:
There seems to be some confusion:

The PM is not the boss of the developers. The person responsible for the dev team (Team Leader, Manager) and does the hiring and evaluations should decide if you're working hard enough.

Estimations are not perfect. I think the PM understands this more than you think. Do you seriously expect no one to ever ask you how long it will take to do something? Everyboy wants to know when it's done and it's the PM's job to track it.

You can be a PM is you:  A) understand how to manage projects B) understand the development process. Neither of these requires coding knowledge, but it can help.

Determining if the programmers are getting enough done is not the PM's job unless he doubles as the team leader. To know whether or not anyone is "blowing smoke" about the time to complete a task, a manager will always have an advantage if he understands what is involved.

Estimates get better with experienced programmers who have a history of working on a particular type of project. No one expects them to be perfect, but they do expect you do come close and get better over time.


问:
How to manage a growing team?
I'm the admin assistant of the CTO and our organization has recently experienced a lot of growth.  Within six months, we have merged with another organization and our Dev team has grown from 8 to 16, with another 8 people in QA.    </p>

<p>What we're dealing with now is a highly technical individual, with little patience, managing a  much larger team than he's accustomed to, 40% of which is junior as well as an increase in the number of projects.  Needless to say, my boss is being pulled in too many directions at once.  How can I help him manage his workload and his team so that the team feels they're getting enough help and support and remain effective?  Also, where can I find additional resources on managing a growing team? </p>

答:
With a somewhat significant grows in a short time, I would expect the number of non-technical decisions that your boss is expected to make to grow out of proportion. Simply tracking the progress and managing roadblocks may become a challenge. Technical people often view their non-technical tasks as non-productive, trying to minimize them.

This is where your help may come in handy: ask your boss which non-technical tasks cause him the most pain, and see if you can take them on. In my experience, a lot of administrative tasks can be greatly simplified with the right process. For example, progress tracking can be simplified if you ask the team to e-mail you a single line describing what they did today, and then you compose the replies in a format that your boss finds convenient.

Tracking key metrics of the project may be another helpful thing: technical managers often rely on a set of measurable items about a project to guide their decisions. For example, one of my bosses tracked weekly number of unit tests, number of new bugs, number of fixed bugs by category, the number of feature requests completed, and the number of coding violations reported by the nightly process. You can collect the inputs, and prepare these metrics for your boss.

Your boss should be careful about creating too much process, though, because asking the team to follow a lot of new process may be counterproductive.

Title: How to manage a growing team?


答:
A similar pattern, Memo, or Memoization, stores state as well, but it is often used as a program-speed optimization.  If a time-consuming operation has a limited number of common inputs and outputs, the most common ones (or all of them) can be stored in a hashtable.  When called again with the same inputs, it first checks the hashtable and if it finds them, it returns the previous output without recalculating it.

I imagine a Memento pattern could be used for performance as well - instead of doing all the reverse-calculations for a reverse state change, just restore from the previous state.  Some functions are one-way, so there is no undo unless you store the previous state.

You could use a Memento pattern to memoize a periodic, or symmetric function like sine.  Calculate all the values from 0-180 degrees, then go backwards through them to get the negative values from 180-360.  Better yet, calculate values from 0-90, then go backwards through those values to get 90-180, forwards for 180-270, and backwards from 270-360.

Ctrl-Z in Word, or the undo function of any software is likely implemented by using the memento pattern, or in some cases, possibly by a reverse of the function that made each change.  In the second case, the history of which functions were called would be mementos, so I suppose the memento pattern is always used for undo.

Title: Philosophy behind the memento pattern


答:
I'm reminded of the old saying: "you don't have to be crazy to work here, but it helps".

The short answer is that hands-on coding experience isn't a requisite of a good software PM, but it is usually preferred. What is critical to being an able PM is understanding the development process (whatever methodology is used), and trusting that the developers are willing and able to do their job. The development experience gives hands-on knowledge of that process, therefore it helps. PMs who work their way up the ladder in a company additionally know the corporate culture (and the codebase), and have a rapport with the other long-serving members of the dev team, which is why IMO the best PMs are promoted from within instead of being brought in from outside. If someone outside the company can manage the team better than someone from inside can, things are VERY wrong.

One thing I mentioned is a rapport between the PM and dev team. This is both at an interpersonal and a technical level. The key here is communication; the devs must feel they can bring issues, both technical and interpersonal, to the PM, and the PM must understand the dev team members when they describe a problem.

As to the specific nature of your question, an estimate is exactly that; an educated guess as to a quantity (as opposed to a hypothesis, which is a more general prediction of the outcome of a future event). The manager will usually either mathematically or intuitively apply some modifier, based on your recent estimates versus actual timelines. Agile builds this into the estimation process; the client intuitively estimates the complexity of the requirements, then the devs do the same, and then the devs actually go out and develop the solution, giving the manager data points to calculate a ratio of requirements points to dev points, and dev points to man-hour requirements.

In short, a manager will only take your estimate at face value in one of three scenarios:

You've been pretty accurate with your estimates of similar tasks in the past.

He's under pressure to deliver, and your estimate is better than he thought.

He's looking for a reason to fire you.

If it's that last situation, there will be many other clues around the workplace that maybe you should get the hell out.


问:
How essential is it to make a service layer?
I started building an app in 3 layers (DAL, BL, UI) [it mainly handles CRM, some sales reports and inventory].

A colleague told me that I must move to service layer pattern, that developers came to service pattern from their experience and it is the better approach to design most applications. He said it would be much easier to maintain the application in the future that way.

Personally, I get the feeling that it's just making things more complex and I couldn't see much of a benefit from it that would justify that.

This app does have an additional small partial ui that uses some (but only few) of the desktop application functions so I did find myself duplicating some code (but not much). Just because of some code duplication I wouldn't convert it to be service oriented, but he said I should use it anyway because in general it's a very good architecture, why programmers are so passionate about services??

I tried to google on it but I'm still confused and can't decide what to do.

答:
Adding an interface (a service layer is a type of interface) takes time.  A good one takes a lot of time to design and test.  It is very important to get it right on the first try because changing it later breaks all the clients.  Also, consider that you probably won't know what needs to be in that interface until you have a second client with slightly different needs.  Maintaining a service is a never-ending project in itself.

In most organizations, if you go to your business sponsor and ask them, "Do you want other departments to get the benefit of (reuse) this system we are developing with your budget?" they will laugh at you.  Get it working for your business sponsor first, then start twiddling around with reusing that code (on your department's own time).

If you know, for a fact, that the functionality you are writing today will be reused by multiple different service clients, then consider designing a service layer from day one.  If you are unsure, or there are many unknowns in the project already, get something simple working first and separate it into service and client later if you have time and budget.  It much easier to get the service interface right on the first try when you start with a working system.

P.S. If you are working in Java, Joshua Bloch has a lot of fantastic interface advice throughout his book, Effective Java.


问:
Can a compiled C++11 library (lib,dll,etc.) be linked in older C++ compilers?
Could older C++ compilers (e.g. VS2008 and gcc3.4) link with external libraries written in C++11?

My thought is that the C++11 .lib files are just byte code at this stage, and it shouldn't bother the older compilers how it was generated, as long as it is somehow resolvable and callable.

I'm developing a small library whose API should still support C++03 users. So, looking forward, I'm wondering whether it's ok to implement my library using helpful features like std::unique_ptr and such, or do I have to just stick with boost::?

答:
Provided your library only uses C++11 in its implementation and doesn't expose C++11 facilities or types publically, and especially if you use static linkage, then yes, this is possible and even standard.

Consider the common case where a library exposes a C-level interface (to be usable by the widest variety of clients) but which is internally implemented in C++. Clients linking against such a library need only worry about the public binary API (exported functions), which you'll have constrained to be legacy C/C++ for maximum compatibility. A Java program can link to C-level APIs which are internally implemented in C++. This does not mean that Java needs to "support C++". Similarly, an old-style C/C++ client can link to a C-level or C++-level API which internally uses some more avant-garde version of the C++ libs or any other libs. Two separate things: what's required to link to the library's interface, and what the library itself internally links to (or pulls in statically).

You simply don't expose clients of your library to the dependencies of your implementation.

If you can statically link your dependencies (C++11 or whatever else) into your library, this is clean and self-contained. The library is a true black box: nothing but bytecode. But even if your library links to your dependencies via "implicit dynamic" linkage (not to be confused with the explicity LoadLibrary/GetProcAddress kind and the similar methods on *nix and OS X), older clients should still be able to link to that library's public interface, even if they couldn't link to the libraries the library depends on.


问:
Methodologies for Managing Users and Access?
This is something I'm having a hard time getting my head around. I think I might be making it more complicated than it is.

What I'm trying to do is develop a method to store users in a database with varying levels of access, throughout different applications. I know this has been done before, but I don't know where to find how they did it.

Here is an example of what I need to accomplish:

```<code>UserA - Access to App1, App3, App4 & can add new users to App3, but not 4 or 1.
UserB - Access to App2 only with ReadOnly access.
UserC - Access to App1 & App4 and is able to access Admin settings of both apps.
</code>```

In the past I've just used user groups. However, I'm reaching a phase where I need a bit more control over each individual user's access to certain parts of the different applications. I wish this were as cut and dry as being able to give a user a role and let each role inherit from the last.

Now, this is what I need to accomplish. But, I don't know any methods of doing this. I could easily just design something that works, but I know this has been done and I know this has been studied and I know this problem has been solved by much better minds than my own.

This is for a web application and using sql server 2008. I don't need to store passwords (LDAP) and the information I need to store is actually very limited. Basically just username and access.

答:
This is the setup in the application I maintain:

active directory has groups which can access the application with users in each group

fine grained permissions are held in tables linked to groups so that all IT has to do is to add a user to an Active directory group

a buggy service that synchronizes Active Directory users to a table of application users

you need

Users table: with name, userId (numeric), enabled (numeric) and whatever users sign on with. (Usually a text string like your initials)

Role Table: Active Directory groups with numeric ID and text identifier

Action Table: group your permissions by type: access to Applications, access to Administrative, can grant permissions. create a table for each with numeric identifier and descriptive string.
In the application I maintain top level permissions include ACCESS the master application, GRANT permissions, READ, UPDATE, ACCESS a linked sub application

so a query to see what groups have top level permissions looks like this

SELECT   cr.NAME "AD_Group",
            CR.ID GROUP_ROLE_ID,
            DECODE (a.NAME,
                    'APPROVE', 'Approve Organizations',
                    'CONTACTS', 'Contact information',
                    'GRANT', 'Grant permissions',
                    a.NAME)
               "Stage/Permission",
            gp.role_id,
            gp.action_id,
     FROM   action a,
            general_permission gp,
            role cr
    WHERE   a.ID = gp.action_id
            AND gp.role_id = cr.ID

When your user logs on you query LDAP for what groups that they are a member of. Then query the database for what permissions the groups have.  Make it easy on yourself and make permissions additive.


问:
Is rotating the lead developer a good or bad idea?
I work on a team that has been flat organizationally since it's creation several months ago.  My manager is non-technical and this means that our whole team is responsible for decision-making.

My manager is beginning to realize that there are several benefits to having a lead developer, both for his sake (a single point of contact and single responsible party for tasks) and ours (dispute resolution, organized technical guidance, etc.).

Because the team has been flat, one concern is that picking one lead developer may discourage the others.  A non-developer suggested to my manager that rotating the lead developer is a possible way to avoid this issue.  One developer would be lead one month, another the next, and so on.

Is this a good idea? Why or why not?

Keep in mind that this means all developers — All developers are good, but not necessarily equally suited to leadership.

And if it is not, how do I recommend that we avoid this approach without seeming like it's merely for selfish reasons?

答:
If your organization is flat, then have all your dev's go through Requirements and Solutions Analysis (RSA) training to have them follow a formal process.  You can then assign multiple subject matter experts (SME) to a project and get a documented process to all the solutioning.

Also, since you mentioned that the manager is non-technical, that individual can still drive the RSA process and facilitate the communication.  You can also assign a particular SME as a lead on a project by project basis to assist in facilitation and build their individual skillsets.


问:
Emacs/Vim/Vi - do they have a place in modern software development ecosystem?
Watching all those screencasts (and listening all those podcasts) with more-or-less famous hackers/programmers I hear that many of those use emacs/vi(m) for their daily work.

Now, I myself tried using both emacs and vim, and I honestly cannot understand why would anybody use these for any kind of serious development.

The most advertised feature is something along the lines of "you'll be able to work with text (meaning cutting, pasting, duplicating, moving, etc) up to ten times faster than with conventional IDEs", but I don't buy that. When has the success of a software project been defined by how fast a programmer can juggle lines in a text editor or by saving a couple of keystrokes here and there?

Plugins and extensions? I bet nothing comes close to R# or IDEA in terms of refactoring support ("Rename" refactoring implemented by means of "Search and Replace" is not a refactoring IMO); others are trivial.

Ubiquitous and available everywhere? So what? How often do you find yourself editing files over a 300 baud connection on an esoteric *nix installation without a VCS?

So here goes: do said editors have a justified place in a modern software development ecosystem?

答:
I find them useful for quickly editing a configuration file on some system (possibly production), that I only have terminal access to. I would never use it for actually developing software because of how sophisticated IDEs are today.

I never really understood why people even bother talking about optimizing typing speed, as if that's the bottleneck in development or something. It's not even close to the time I save from using an IDE.

Also, how does does switching from keyboard to mouse break your train of thought?

Once you set up your IDE you almost never have to worry about any configuration. It's not like you're constantly wasting time figuring out how to do something IDE-related.


答:
The interesting thing about Vim and Emacs is not simply how quickly you can work. It's the simple fact that Vim and Emacs let you edit your text at nearly the speed with which you think about making your changes. Since you have no need to make selections, to switch to the mouse, or to hunt through menus, your mind is free to focus on what's important while you edit: Your code.

This is to say that when you're writing code, there is only one thing you want to think about: What your code must do and how it must do it. Whenever you stop to make changes to code you've written, it's an interruption; you're forced to think not about what your code is doing but how to make the changes that are necessary. So, instead of stepping back and make a visual selection and changing my mode of thought from code-writing to text-editing, Vim and Emacs allow me to perform the edit and be done with it, without having to expend more mental energy on the task of making the change.

And when you take your hand off the keyboard to grab the mouse, it's another kind of context switch: You're no longer thinking about the code, but about the text you can see on the screen and the visual elements that surround your editing area. Then, you must make the switch back to writing code, as your hand hunts for the home keys. With Vim or Emacs, this context switch never needs to be done, and your mind never needs to leave the task at hand: that of writing code.

A lot of people, myself included, use Vim or Emacs as their preferred tools because they're liberating in the sense that you spend less time thinking about editing and more about what changes you're making. Because, really, what is programming but juggling lines of text?

Plugins and extensions? I bet nothing comes close to R# or IDEA in terms of refactoring support [...]

These kinds of tools exist. Tips and methods abound. The only limit to Vim and Emacs is that their primary purpose is editing text. But that still doesn't stop anyone from making it the umbrella under which their entire IDE is built.

I think the source of your consternation is that you choose not to see value in Vim and Emacs. That's fine. I'm not going to try to convert you.

But I will say that having tried every text editor and IDE I've come across, I still go back to Vim. I'm comfortable with it, I'm happy with the tools it gives me, and my Linux desktop meets my every need as an IDE, all in the terminal window. It has made me dependent on Vim's peculiar command structure, but because Vim runs everywhere, that has never been a hindrance; only a boon.

Title: Emacs/Vim/Vi - do they have a place in modern software development ecosystem?

Body:
Watching all those screencasts (and listening all those podcasts) with more-or-less famous hackers/programmers I hear that many of those use emacs/vi(m) for their daily work.

Now, I myself tried using both emacs and vim, and I honestly cannot understand why would anybody use these for any kind of serious development.

The most advertised feature is something along the lines of "you'll be able to work with text (meaning cutting, pasting, duplicating, moving, etc) up to ten times faster than with conventional IDEs", but I don't buy that. When has the success of a software project been defined by how fast a programmer can juggle lines in a text editor or by saving a couple of keystrokes here and there?

Plugins and extensions? I bet nothing comes close to R# or IDEA in terms of refactoring support ("Rename" refactoring implemented by means of "Search and Replace" is not a refactoring IMO); others are trivial.

Ubiquitous and available everywhere? So what? How often do you find yourself editing files over a 300 baud connection on an esoteric *nix installation without a VCS?

So here goes: do said editors have a justified place in a modern software development ecosystem?


答: Intellisense/refactoring support is really the only compelling features for IDEs today. I expect in the future pluggable libraries will be created to provide intellisense/refactoring for various languages, so one can have the same level of language support in Emacs/Vim as in IDEs. (For some languages such libraries exist already.) If it happens then Emacs/Vim will be the preferred development tool for a number of developers, because they provide a different experience than an IDE (leaner, quicker, simpler, etc.).</p>


答:
I bet nothing comes close to R# or IDEA in terms of refactoring support ("Rename" refactoring implemented by means of "Search and Replace" is not a refactoring IMO); others are trivial.

Not all code is nicely statically typed or in a language that allows good tooling (refactor, find references, auto-complete, etc) support. These editors still have strong arguments for them when working with these languages.

They also work well with build scripts, config files, log files, and other shrapnel that needs to be built/analyzed/grep'd/coddled/tweaked on (often CLI only) *nix environments, which still make up a sizable portion of production code platforms.


答: The linux command line is the ultimate integrated development environment; vim and emacs seamlessly interpolate with the unix toolbox to create a streamlined development environment that really has no equal.


问:
Story points for bug fixing tasks: Is it suitable for Scrum?
I'm just wondering if we should assign story points to bug fixing tasks or not. JIRA, our issues-tracking software, does not have story point field for Bug type issues (it's only for Storys and Epics).

Should we add the Bug issue type to the applicable issue types of the Story Points field?  What are the pros and cons? Would it be suitable for Scrum?

答:
Some tasks are estimateable, some are not.  For things that cannot be estimated, use a budget.

Fixing a defect is not a readily estimateable task because it has several unknown components to it.  What is causing the defect?  Once the cause is understood, how can it be fixed?  What impact does this change have on the rest of the system?  How many new defects did you inject fixing this defect?

Keep in mind that the cause of a defect can come from any point in the software lifecycle -- misunderstood or miscommunicated requirements, poor design or wrong assumptions, poor coding, bad testing, new knowledge about the problem based on information learned from the current release...

Creating a budget can be done in a couple of different ways for bug fixing tasks.  Here's some ideas I've used effectively:

Use historical data (say from a previous iteration) to help you understand how much time to set aside for bug fixing.

Put "blocks" of bugfixing (say 5 points or 20 hours) in your backlog and let the customer choose this in lieu of stories.

Require that each member of your team dedicate a specified amount of time each iteration fixing defects.

Your goal is then to fix as many defects as possible within the budget allocated.  Discuss with your customer strategies for prioritizing reported defects.  For example, do you sort defects by criticality then priority?  Strict priority?  Should you attack "low-hanging fruit" first?  UI bugs first?

Also, fixing bugs does not earn value.  Fixing defects are a form of waste.  You already earned value on the feature so you should not get "bonus points" for fixing bugs.

Having a budget helps with planning and still gives you an accurate picture of Velocity.  Budget a specific number of points for bug fixing, give the budget an approximate amount of time based on your historic data, and then squash as many bugs as you can in the time budgeted!


答: I personally feel like that coding in vim has helped my coding ability, much the same way that learning to properly handle memory and pointers in C or learning functional languages like Haskell has helped me to grow as a programmer. It is much easier to understand and be able to effectively utilize something at the higher level when you understand how to handle it at a lower level. </p>


答:
Two points.  First, it's not the typing throughput that makes a difference, it's the latency.  In other words, the elapsed time between when you've decided to make an edit and when you're done making the edit and back thinking about the problem.  A couple of seconds can make the difference between losing your train of thought or not.

Take something simple like swapping two lines of code, for example.  An experienced vim user can do that essentially from muscle memory with ddp.  You use more mental capacity than is apparent when you have to precisely maneuver a mouse, make sure everything you want is selected, hit ctrlx, up arrow, ctrlv, and then make sure you included the line break and everything is still indented correctly.  It's like texting and driving.  You think you're paying better attention to the road than you really are.  I prefer to keep my mind on the problem.

Second, nothing precludes a vim user from using an IDE when it suits him.  There's a reason why almost every IDE has an option to specify a custom editor.  I quite frequently use an IDE for navigating and debugging, and vim for editing.


答:
Do said editors have a justified place in a modern software development ecosystem?

Yes.

1) If there is no good IDE for the programming language you work with (which is most of them, really).

2) If the IDE can't handle the size of your project.

3) For various tasks when you just want to change a text file quickly without waiting for an IDE to open and initialize.


问:
What do you call "X <= $foo <= Y" comparison?
While writing a Perl statement like if ( $foo >= X && $foo <= Y ) yet again, I wondered why many programming languages do not support the more comfortable form if ( X <= $foo <= Y ) and what this is called.  I came up with "3-legged comparison" but no results when searching for it. By the way there is also the "element-of-set" form if ( $foo in X..Y ) which I only consider more readable when provided via a short keyword.

Is there a term for X <= $foo <= Y comparison?  Which languages support it?

答:
In languages like C, a < b < c is compiled as

```<code>  (a<b) < c
  a<b evaluates to 0 or 1, so you end up executing
  (1 < c) or (0 < c)
</code>```

which is almost certainly not what you want.

In languages less brain damaged than C, you can be saved by the
type system, because (a < b) returns true or false, and (false < c)
is not a valid expression.

I can't think offhand of any languages that implement this ternary operator
the way you expect, but it would be dangerous to use it if it exists, if only
because so many other languages will screw you.

Body:
In languages like C, a < b < c is compiled as

  (a<b) < c
  a<b evaluates to 0 or 1, so you end up executing
  (1 < c) or (0 < c)

which is almost certainly not what you want.

In languages less brain damaged than C, you can be saved by the
type system, because (a < b) returns true or false, and (false < c)
is not a valid expression.

I can't think offhand of any languages that implement this ternary operator
the way you expect, but it would be dangerous to use it if it exists, if only
because so many other languages will screw you.


问:
How many hours can you be really productive per day? How?
I find that I'm having a great deal of trouble staying alert 8 hours per day. I've heard of people who've negotiated work contracts of just 4 hours/day, arguing that they won't be able to do much more in eight hours.

I am often overwhelmed with drowsiness, boredom, distraction. Some days, I seem to blaze through eight hours in a furious explosion of productivity; other days, I hardly get anything done at all. Most days, it's somewhere in between, and I feel bad for wasting a lot of time because I can't muster the concentration to be my best throughout much of the day.

I'd like to hear your experiences (tell me I'm not alone!), and, if found, your solutions to this dilemma.

Are you productive 8 hours/day almost every day? How?

答:
My last Agile Scrum job used the concept of "ideal hours" for task estimation. Put simply, an "ideal hour" is an hour spent heads-down coding new things that have never existed before in the project. A non-ideal hour is time spent refactoring, debugging, on the phone, in meetings, at lunch, on break, lurking/posting to StackExchange, etc.

The typical expectation was 5 to 6 ideal hours per 8-hour workday. You simply can't expect developers to spend 8 hours a day "plugged in", and even if you do, you'll typically find that you don't get much more in those 2-3 hours than in the normal 5-6. It isn't a laziness thing, it isn't a "stuck" thing, it isn't even a lack of skill or typing speed; the simple fact of the matter is that sh*t happens. Someone will call or IM a dev asking about something from their personal life. Technical debt must be repaid by organizing and refactoring the codebase (which the clients won't see as productive because they're not working toward points, but it's critical to keep the codebase maintainable and extensible, thus keeping the pace of development). And devs need to blow off steam; we're creative knowledge workers, and from time to time the humming, productive team room will break down into a few minutes of hurling paper wads at each other (or, if the goofing off is more encouraged by management, a Nerf gun fight).

Anyway, our team's estimation worked out to about one "point" = about two developer-days (a five-pointer was one two-week developer-iteration), based on 5 hours of heads-down coding per day. So, a five-pointer would be billed to the client at a rate roughly equivalent to 50 developer-hours.


答:
Adding a service layer because you have evaluated the idea and concluded its the best approach: good

Adding a service layer because that's what all the cool kids are doing: bad

If your gut says you don't need one, then don't make one.

One of the more disappointing developments in the programming world over the past 10 years or so is that it has become annoyingly 'fashion' oriented, with people following trends and bandwagons as if they were this season's shoes.  Don't fall into that trap.  Because next season 'everybody' will be telling you that you should have designed it some other way.

There's nothing wrong or right with a service layer - it's a particular approach whose suitability should be evaluated on its technical merits for the project at hand.  Do not feel compelled to substitute other people's opinions for your own judgement.

Title: How essential is it to make a service layer?

Body:
I started building an app in 3 layers (DAL, BL, UI) [it mainly handles CRM, some sales reports and inventory].

A colleague told me that I must move to service layer pattern, that developers came to service pattern from their experience and it is the better approach to design most applications. He said it would be much easier to maintain the application in the future that way.

Personally, I get the feeling that it's just making things more complex and I couldn't see much of a benefit from it that would justify that.

This app does have an additional small partial ui that uses some (but only few) of the desktop application functions so I did find myself duplicating some code (but not much). Just because of some code duplication I wouldn't convert it to be service oriented, but he said I should use it anyway because in general it's a very good architecture, why programmers are so passionate about services??

I tried to google on it but I'm still confused and can't decide what to do.


答:
Most PLC languages include some kind of instruction that does this.  In RSLogix it's called the LIM instruction (see pg 3-5).  It takes 3 inputs: a Low Lim, Test, and High Lim value and returns a true/false output.

Note that you can provide parameters where Low Lim is higher than High Lim then it changes to an OR condition.  That is, the output is true if the input is higher than Low Lim OR lower than High Lim.  This makes sense when you consider many times you might have a 12 or 16-bit encoder on a rotary axis so the value zero is adjacent to the highest possible value.

Also, other languages, e.g. TwinCAT, have a LIMIT instruction that outputs a coerced value instead of a boolean.  That is, its purpose is to give you an output within the specified limits, or one of the limits themselves if the input is outside the specified limits.  I believe this function is similar to the saturation function in Matlab/Simulink.

In both cases you could just create your own function to do this from the available primitives, so I can see why including such an operator might be considered superfluous.

Title: What do you call "X <= $foo <= Y" comparison?

Body:
While writing a Perl statement like if ( $foo >= X && $foo <= Y ) yet again, I wondered why many programming languages do not support the more comfortable form if ( X <= $foo <= Y ) and what this is called.  I came up with "3-legged comparison" but no results when searching for it. By the way there is also the "element-of-set" form if ( $foo in X..Y ) which I only consider more readable when provided via a short keyword.

Is there a term for X <= $foo <= Y comparison?  Which languages support it?


问:
Is defining a variable to name a method argument a good practice?
For the sake of readability I often find myself defining temporary variables while calling functions, such as the following code

```<code>var preventUndo = true;
doSomething(preventUndo);
</code>```

The shorter version of this to this would be,

```<code>doSomething(true);
</code>```

But when I come back to the code I often wonder what true refers to. Is there a convention for this kind of conundrum?

答:
The focus of your question and of the other answers is improving readability where the function is called, which is a focus I agree with. Any specific guidelines, event "no boolean arguments", should always function as means to this end and not become and end themselves.

I think it's useful to note that this issue is mostly averted when the programming language supports named arguments / keyword arguments, like in C# 4 and Python, or where the method arguments are interleaved in the method name, like in Smalltalk or Objective-C.

Examples:

// C# 4
foo.doSomething(preventUndo: true);
```

<pre class="lang-py prettyprint-override"><code># Python
foo.doSomething(preventUndo=True)
</code>```

// Objective-C
[foo doSomethingWith:bar shouldPreventUndo:YES];
```

Body:
The focus of your question and of the other answers is improving readability where the function is called, which is a focus I agree with. Any specific guidelines, event "no boolean arguments", should always function as means to this end and not become and end themselves.

I think it's useful to note that this issue is mostly averted when the programming language supports named arguments / keyword arguments, like in C# 4 and Python, or where the method arguments are interleaved in the method name, like in Smalltalk or Objective-C.

Examples:

// C# 4
foo.doSomething(preventUndo: true);

# Python
foo.doSomething(preventUndo=True)

// Objective-C
[foo doSomethingWith:bar shouldPreventUndo:YES];


问:
System Analyst vs Computer Programmer?
My question here is relative to jobs.  I currently hold a System Analyst position.

What is the difference between System Analyst and Programmer/Analyst? Is this position higher than a programmer? Or how should I upgrade myself ?

答: Yes it's definitely subjective to the employer, I also hold the Systems Analyst title, and here we play the role of On Call Systems Administrators to the tech support and development groups, so that our Systems Engineers can focus proactively on projects, where our role is to be more reactive. though we also have proactive tasks towards dept projects, as well as being a 3rd tier final escalation point for tech support tickets, as well as pushing through the developers changes weekly into production.  Everyone with my title does have some coding experiencing, but some people on my team, don't know more than Batch, so it's definitely not a development-centric role, i have experience with multiple programming / scripting languages, but don't count myself as a developer.</p>

Title: System Analyst vs Computer Programmer?


答:
At 16 people + 8 QA, it's no longer a team, you have made the transition to a big "small organization". These don't work for very long. You need to transition quickly to a small "big organization". The important difference is how they are managed, reporting structures, responsibilities and authorities.

Your boss is probably still trying to manage as if it were a single team with him at the helm, when he should be managing the business and letting team leads manage the teams.

This is not a uniquely software development problem. Better places to start are books on managing (particularly growth), business schools etc. You boss is no longer in a role that is primarily technical, and if he thinks he is, the management is not being done, and if he wants to remain technical, he should recruit a manager.

Title: How to manage a growing team?

Body:
I'm the admin assistant of the CTO and our organization has recently experienced a lot of growth.  Within six months, we have merged with another organization and our Dev team has grown from 8 to 16, with another 8 people in QA.    </p>

<p>What we're dealing with now is a highly technical individual, with little patience, managing a  much larger team than he's accustomed to, 40% of which is junior as well as an increase in the number of projects.  Needless to say, my boss is being pulled in too many directions at once.  How can I help him manage his workload and his team so that the team feels they're getting enough help and support and remain effective?  Also, where can I find additional resources on managing a growing team? </p>


问:
I believe my solution is better than my boss's, so should I ignore him?
I'm working with php and sql.

I think that my method of implementing functions is better than what my boss proposes. Just now he explained me how to do a check on a list of email addresses, and I do not like his idea. I proposed mine which is better and quicker to implement, but he disagreed.

Now I think I will go ahead and implement my idea, because his idea was not clear enough to me. Do you think he will be mad?

答:
It can be either way, depending on details.

I know that I have been in a lot of situations where I have been arguing with the bosses about one thing or another. A lot of times I have proven that my idea is better, sometimes they have shown me a solution that was a lot quicker and more complete. Sometimes neither of us knew, so I had to do the research, compare the ideas, and maybe even come up with something new for the next round of decision making.

If the boss is a good boss, and you're at the senior level, he probably knows you have a lot of experience and a better/fresher view on internal problems, and he will understand why you did something if you'll explain it to him. He will also avoid micromanaging you.

And sometimes, no matter how good you are, you miss simple things, that later make you wonder how you could be so stupid to overlook a trivial solution. And the boss, with his overview from distance might spot them a lot easier.


问:
What are use cases and advantages of pointers?
I often struggle to see the advantages of pointers (except for low level programming).

Why use of char* instead of a String or char[] or what advantages pointer arithmetic brings.

So what are the pros and use cases of pointers?

答:
Pointers are necessary for dynamic memory location, many data structures, and efficient handling of large amounts of data.  Without pointers, you'd have to allocate all the program data globally or in functions or the equivalent, and you'd have no recourse if the amount of data grew beyond what you had originally allowed for.  I hesitate to use absolutes here, but as far as I know all modern computer languages have pointers in some form or other.

In most languages that use pointers, there are certain sorts of references that are pointers, and perhaps certain sorts of references that aren't, and there is no further notational difference.  A Lisp cons cell is a pair of pointers, although a fixnum is not a pointer.  In Java, the variable used for the instance of a class is a pointer, but an int isn't.  The language syntax doesn't reflect that.

C is unusual in that pointers are optional, explicit, and allow explicit pointer arithmetic.  It is perfectly possible to write struct foo bar; struct foo * baz;, and once you've allocated memory for baz you can use both bar and baz to represent struct foos.  Since pointers are optional, it is useful to have notational differences.  (It's essential in C++ for smart pointers, as given boost::shared_ptr<foo> bar;, bar.reset() has one meaning and bar->reset() is likely to have a much different one.)

(Actually, explicit pointers were often used in other languages when C was originally being developed, such as ^ in Pascal.  C is an older language than most in common use today, and it shows.)

One of C's design goals was to write Unix in, and therefore it needed to handle memory locations in a detailed manner.  (C is actually one of a family of system implementation languages common when it was being designed, another example being Cybol for Control Data computers.  C is the one that became a big hit.)  Therefore, it is possible to manipulate C pointers directly, assigning memory addresses and calculating new ones.  This also led to some design decisions in C.  C arrays are based heavily on pointer arithmetic, and indeed an array decays into a pointer in very many situations.  Passing variables to C functions by reference is done by pointer.  There was no strong need for arrays and passing variables by reference in the form that other contemporary languages had, so C didn't get those.

So, the answer is that, in most languages nowadays, you use pointers constantly without being reminded of the fact.  In C, and to a lesser extent C++, you use pointers either to do low-level things, or as accomplish higher-level things that there's no special notation for.


答:
There are many factors that go into the decision of creating a service layer. I have created service layers in the past for the following reasons.

Code that needs to be re-used by multiple clients.

Third party libraries that we have limited licenses for.

Third parties that need an integration point into our system.

Centralizing duplicated business logic.

Case 1: You are creating base functionality that needs to be used by a myriad of different clients. Service layer builds in functionality for different clients to tap into your provided functionality right out of the box.

Case 2: You normally host code in app space but you are using a third party library that you have limited licenses for. In this case you have a resource you would like to use everywhere, but only a limited number of them. If you host it behind a service then your whole organization can get usage of it from their applications without having to buy a license for each individual hosting.

Case 3: You are building functionality for third parties to communicate to you. In your example you could set up an inventory endpoint to allow vendors to pass messages to you about incoming product shipments.

Case 4: You have analyzed your code enterprise wide and found that separate teams have created the same thing (just implemented slightly differently). With a service layer you can pick the best approach(es) and now you can implement the process the same across all teams by having them call into the service. Another benefit to centralizing logic is when bugs are found. Now you can deploy the fix once and all clients enjoy the benefit at the same time.

All this being said there are potential negatives to a service layer.

Adds system complexity. Where before you only had one application to debug now you have two. Production problems require checking client app setting, service app settings, or communication problems between otherwise correctly setup client and server apps. This can be tricky if you've never done it before.

One point of failure. If you have a service outage all clients are affected. When code is not deployed in this manner the risk can be less (though there are ways to mitigate this).

Versioning can be harder to do. When you have one app using a service deploying interface changes can be done at the same time between the two. When you have multiple clients now you must manage who is on V1, who is on V2, and coordinating the removal of V1 (once you know everyone has updated to V2).

The main point is that it's not always a slam dunk to make your system service oriented. In my experience it usually is a good idea (I tend to structure applications in this way), but it's not an automatic decision. At the end of the day you need to weigh the pros and cons and make the decision that's right for your situation.


答:
In english it's called "between inclusive".

Microsoft's T-SQL gives special syntax for it

```<code>select * from User where Age between 18 and 25
</code>```

Body:
In english it's called "between inclusive".

Microsoft's T-SQL gives special syntax for it

select * from User where Age between 18 and 25


问:
What Pattern will solve this - fetching dependent record from database
I have these classes

```<code>class Match
{
  int MatchID,
  int Team1ID, //used to reference Team
  int Team2ID,
  ... other fields
}
</code>```

Note: Match actually have 2 teams which means 2 TeamID

```<code>class Team
{
   int TeamID,
   string TeamName
}
</code>```

In my view I need to display List<Match> showing the TeamName. So I added another field

```<code>class Match
{
  int MatchID,
  int TeamID, //used to reference Team
  ... other fields

  string TeamName;
}
</code>```

I can now do

```<code>Match m = getMatch(id);
m.TeamName = getTeamName(m.TeamId); //get name from database
</code>```

But for a List<Match>, getTeamName(TeamId) will go to the database to fetch TeamName for each TeamID.

For a page of 10 Matches per page, that could be (10x2Teams)=20 trip to database. Example:

```<code>for(1..10)
{
   Match m[i] = getMatch(i);

   //the team are never going to be repeated, 20 teams spread over ten matches
   m[i].Team1Name = getTeamName(m.Team2Id);
   m[i].Team2Name = getTeamName(m.Team2Id);
}
</code>```

To avoid this, I had the idea of loading everything once, store it in memory and only lookup the TeamName in memory. This made me have a rethink that what if the records are 5000 or more.

What pattern is used to solve this and how?

答:
I think your problem is not to be solved by a specific pattern, but by the the software design itself.

There are many things that can be done, if your are connecting directly to a relational database, you could fetch the data in a single query, using joins, and in code bind the data where you want. You could also do it in two trips, and look up the objects already loaded in memory. Or also use something like NHibernate, it all depends of your software design and architecture.

About the many records problem, where are you to use these data? It could probably be paged or filtered, and you could load it in chunks from the data store.

In situations like this you should look overall your project and see how situations like this were handled, and try to follow the same pattern, hence improving code maintainability


问:
Is the .NET/Microsoft technology stack a financially viable option for a startup with limited finances?
I have an unpaid internship for a very new startup company with little tech experience that's trying to be a Groupon clone. They're currently using Wordpress and I've been trying to decide what web framework to push them towards, since I'll have to learn that language and implement it as well.

Is ASP.Net MVC a realistic option for a web based startup company with little financial backing? For example, I know in the Rails hosting is slightly cheaper because of the whole free OS thing and there are free "gems" available to do things like a mailers, but how much more expensive can it get if I go with ASP.Net MVC since such add-ons stop being open source?

How much does the cost of hosting for .NET applications add to the equation?

答:
Not a whole lot. The people to program things, and the people to manage the infrastructure are a few orders of magnitude more expensive than any hosting cost issues you can run across. There are plenty of free "gems" -- check out nuget for .NET's version of that. Cloud-wise, both EC2 and Azure offer windows boxes so you aren't stuck owning hardware.

The one place it probably could get more expensive is in developer tools -- most of the OS stuff has a few FOSS tools of choice, whereas with .NET good most tools are not free. While you can get MSDN Ultimate subscriptions for all your developers, free for three years (check out bizspark), you will have to pay for that stuff after the initial three-year period. And there are some necessary ancillary tools such as resharper. TeamCity is an awesome build server but it isn't free either. You get the idea.

See StackOverflow for a huge Q&A community with lots of .NET devs. It is a very well documented, well supported platform.

Personally, I would avoid startups with shaky backing these days, but even in that case one could make headway with ASP.NET. The game is about Minimum Viable Product and .NET can get you there just as well as rails with the right team.


问:
Why aren't there native Javascript interpreters for Windows/Mac/Linux?
It seems to me it would be very useful to use Javascript for general server side scripting tasks as it has more or less the same features as Perl and Python. But AFAIK there are no generally available Javascript interpreters for the major machine architectures. I guess the other problem may be lack of libraries but surely these would come if the interpreters were there. Google's V8 maybe could be a starting point. Does anyone think we'll see this soon?</p>

答:
In addition to node.js, there is also gjs, which is a GNOME-oriented runtime giving access to GNOME, GTK, and GLib libraries, among others. I believe you can use with it any library that supports GObject introspection.

Gjs is used widely in the GNOME3 desktop.


问:
What made object oriented programming successful?
What is that feature according to you that has made object oriented programming so much successful ?

Message Passing

Inheritance

Polymorphism

Encapsulation

Or some other feature that you may like to introduce.

Also I would like to know that what is the connection between Abstract Data type and Object Oriented programming?

答:
It is somewhat successful because it encourages the use of the human mind's organization of things into objects.  People are generally good at seeing relationships of things - things like differences, similarities and behavior.  OO encourages developing software to mimic human conceptualization of the world.

Making software development similar to how we view the world makes it easier for our minds to handle the complexity.


答:
First off... this sounds like you are trying to solve a problem you dont know you'll have.  Unless you know for a fact that hitting the database 20 times per page (which is nothing) will be a problem, stick with what you have for now and address it when it actually becomes an issue.

That said... a couple of approaches:

In SQL, you can do something like this:

```<code>select name from teams where id in (10, 15,....)
</code>```

Even if you do it once per match, thats 10 trips to the db, not 20.  That just cut it in half.

Alternatively - and this is where abstractions can bite you - rethink what you are doing.  Rather than loading objects and querying their team names, make a single query that generates all/most of the information you'd need to list everything on the page you are displaying (at least as far as the match information is concerned).  With some nifty SQL, you can probably reduce the whole thing down to a single query that returns 10 rows (one per match).

Title: What Pattern will solve this - fetching dependent record from database

Body:
I have these classes

```<code>class Match
{
  int MatchID,
  int Team1ID, //used to reference Team
  int Team2ID,
  ... other fields
}
</code>```

Note: Match actually have 2 teams which means 2 TeamID

```<code>class Team
{
   int TeamID,
   string TeamName
}
</code>```

In my view I need to display List<Match> showing the TeamName. So I added another field

```<code>class Match
{
  int MatchID,
  int TeamID, //used to reference Team
  ... other fields

  string TeamName;
}
</code>```

I can now do

```<code>Match m = getMatch(id);
m.TeamName = getTeamName(m.TeamId); //get name from database
</code>```

But for a List<Match>, getTeamName(TeamId) will go to the database to fetch TeamName for each TeamID.

For a page of 10 Matches per page, that could be (10x2Teams)=20 trip to database. Example:

```<code>for(1..10)
{
   Match m[i] = getMatch(i);

   //the team are never going to be repeated, 20 teams spread over ten matches
   m[i].Team1Name = getTeamName(m.Team2Id);
   m[i].Team2Name = getTeamName(m.Team2Id);
}
</code>```

To avoid this, I had the idea of loading everything once, store it in memory and only lookup the TeamName in memory. This made me have a rethink that what if the records are 5000 or more.

What pattern is used to solve this and how?

Body:
First off... this sounds like you are trying to solve a problem you dont know you'll have.  Unless you know for a fact that hitting the database 20 times per page (which is nothing) will be a problem, stick with what you have for now and address it when it actually becomes an issue.

That said... a couple of approaches:

In SQL, you can do something like this:

select name from teams where id in (10, 15,....)

Even if you do it once per match, thats 10 trips to the db, not 20.  That just cut it in half.

Alternatively - and this is where abstractions can bite you - rethink what you are doing.  Rather than loading objects and querying their team names, make a single query that generates all/most of the information you'd need to list everything on the page you are displaying (at least as far as the match information is concerned).  With some nifty SQL, you can probably reduce the whole thing down to a single query that returns 10 rows (one per match).


答:
"ADT vs objects" has been asked a number of times here. The one-line answer is "ADTs and objects are the inverse of each other - what one abstracts neatly the other cannot; each allows flexibility in different ways."

For a longer answer, see William Cook's On Understanding Data Abstraction, Revisited. Briefly, objects allow you to easily use multiple implementations/representations of some datum (something that looks like a list could be an array, or a self-balancing tree, or...) but make it hard to add new operations (because you have to add that new operation to each of your representations), while ADTs make it easy to add new operations on your data type, but make it hard to have multiple implementations.

Edit: I'd said that message passing was what made OO successful. Based on Jonas' comment, that's not right, because most languages that people consider OO don't use message passing. Since it's not right, I culled it from my answer.

Title: What made object oriented programming successful?

Body:
What is that feature according to you that has made object oriented programming so much successful ?

Message Passing

Inheritance

Polymorphism

Encapsulation

Or some other feature that you may like to introduce.

Also I would like to know that what is the connection between Abstract Data type and Object Oriented programming?


答:
In .Net land, it is not that hard to create decent product using open source only (just browse nuget.org). Switch MsSql with Postgre, entity framework with nhibernate, unity with structuremap, mstest with xunit. You can even switch asp.net-mvc with fubumvc or even nancy if you want more lightweight option.

But I would recommend you to use ruby on rails. Ecosystem around it is much larger and I find ruby being less verbose and more pleasant to work with language than c#.

Title: Is the .NET/Microsoft technology stack a financially viable option for a startup with limited finances?

Body:
I have an unpaid internship for a very new startup company with little tech experience that's trying to be a Groupon clone. They're currently using Wordpress and I've been trying to decide what web framework to push them towards, since I'll have to learn that language and implement it as well.

Is ASP.Net MVC a realistic option for a web based startup company with little financial backing? For example, I know in the Rails hosting is slightly cheaper because of the whole free OS thing and there are free "gems" available to do things like a mailers, but how much more expensive can it get if I go with ASP.Net MVC since such add-ons stop being open source?

How much does the cost of hosting for .NET applications add to the equation?


问:
Is it possible to migrate struts/spring based application to GWT?
I am using the combination of spring, spring-security, struts and iBatis in my application. Now I am looking to migrate the struts UI to GWT.

The new combination must be spring, spring-security, GWT and iBatis.

I applied a layered approach to develop my application. In Controller/UI layer i am using Struts. I want to replace struts and use GWT in Controller/UI layer.

Is is possible to use GWT without affecting another layers DAO/BL/SL?

答:
The short answer is: Yes, you can.

The problem is how to do it, as you will probably need a rewrite of your presentation layer and I don't think there is any tool that can help you easy up the migration.


问:
Where does Java get its SOA reputation from?
I see lots of SOA books surrounding Java and have always had the subliminal notion that Java is the "right" language for robust/enterprisey SOA, even though I know what SOA involves and  that it is perfectly possible using other languages & frameworks.

What exclusive traits Java has that other languages/platforms don't, that makes it so popular for SOAs?

答:
Java was (and still is) simply the most popular language for the kind of application where the SOA concept is most attractive, i.e. heterogenous distributed and integrated systems with constantly shifting requirements aka "enterprise applications". So everyone was already using Java for such systems before SOA became a buzzword in exactly the same area.

As for the reason Java got so popular in that area, there's a lot of things that probably contributed: platform-independance, excellent cross-version compatibility, Sun's marketing budget and previous presence in the market (via Solaris and hardware), the focus on standardized APIs, being the first garbage collected and VM-based language to offer acceptable performance...


问:
Should a programmer take writing lessons to enhance code expressiveness?
Given that programmers are authors and write code to express abstract thoughts and concepts, and good code should be read by other programmers without difficulties and misunderstandings, should a programmer take writing lessons to write better code?

Abstracting concepts and real world problems/entities is an important part of writing good code, and a good mastery of the language used for coding should allow the programmer to express his thoughts more easily, or in a better way. Besides, when trying to write or rewrite some code to make it better, much time can be spent in deciding the names for functions, variables or data structures.

I think this could also help to avoid writing code with more than one meaning, often cause of misunderstanding between different programmers. Code should always express clearly its function unambiguously.

答:
I always find simply stopping after each bit of code you write and reading it again, imagining that you've never seen it before, gets me a long way with this.

Even better is to ask a friend who is familiar with programming to read your code without telling them what it does.


答:
Like writers are taught by reading world's classicals, so the programmers are educated by reading good code. But there is one little problem. While there are recognized giants in literature, there are few of them in programming. And if there are, they might "speak" a different language. (I'm not even sure that its reasonable to advise reading the Minix source code by Tanenbaum)

There are many popular ways to make code more readable (=> maintainable), like writing comments, giving meaningful names, etc. Besides, many companies establish their rules of writing code, and it makes everything much easier.

Anyway, like many excellent writers, programmers are never happy with their own code. So knowing when to stop is as important as writing quality code.

Title: Should a programmer take writing lessons to enhance code expressiveness?

Body:
Given that programmers are authors and write code to express abstract thoughts and concepts, and good code should be read by other programmers without difficulties and misunderstandings, should a programmer take writing lessons to write better code?

Abstracting concepts and real world problems/entities is an important part of writing good code, and a good mastery of the language used for coding should allow the programmer to express his thoughts more easily, or in a better way. Besides, when trying to write or rewrite some code to make it better, much time can be spent in deciding the names for functions, variables or data structures.

I think this could also help to avoid writing code with more than one meaning, often cause of misunderstanding between different programmers. Code should always express clearly its function unambiguously.


问:
Why the overhead when allocating objects/arrays in Java?
How many bytes an array occupies in Java? Assume It's a 64bit machine and also assume there are N elements in an array, so all these elements would take up 2*N, 4*N or 8*N bytes for different types of array.

And a lecture in Coursera says that it would occupy 2*N+24, 4*N+24 or 8*N+24 bytes for a N element array and the 24 bytes is called overhead, but didn't explain why the overhead is needed.

Also objects have overheads, which is 16 bytes.

What exactly are these overheads? What are these 24/16 bytes composed of?

Also, do these overheads only exist in Java? How about C, C++ and Python?

答:
Each Java object has a header that contains information important for the JVM. The most important is a reference to the object's class (one machine word), and there are some flags used by the garbage collector and to manage synchronization (since every object can be synchronized on) which takes up another machine word (using partial words would be bad for performance). So that's 2 words, which is 8 bytes on 32 bit systems, and 16 bytes on 64 bit. Arrays additionally need an int field for the array length, which is another 4 bytes, possibly 8 on 64 bit systems.

As for other languages:

C doesn't have objects, so of course it doesn't have object headers - but may have a header on each separately allocated piece of memory.

In C++, you don't have garbage collection and cannot use arbitrary objects for synchronization, but if you have classes with overridden methods, each object has a pointer to its vtable, just like the Java object's reference to its class. If you use smart pointers that do garbage collection, they need housekeeping data.

I don't know about Python, but I'm pretty sure it also needs a reference to the class, and housekeeping information for the garbage collector.