问:
Abstracted better? Data driven string creation
I am trying to post this question neutral of programming language so it helps the widest audience. But for those who must know, I am using Objective-C and iOS frameworks.

The background:

I have a format string that describes the eventual value of an attribute, which is also a string. Example: attribute name of "report1" might have format of:

```<code>"[chefName] has [totalOrders]"
</code>```

I can have several such attributes with different formats. These formats are centralized in a data file. My desire is to have future developers update this data file only to change the behavior of the code.

I hand the format to a parser which returns an array of single item dictionaries describing how to handle each element of the format. To continue the example:

```<code>[ {"chefName": "directive"},
  {" has ": "literal"},
  {"totalOrders": "directive"}]
</code>```

I then process each element of the array to compose the final value. Anything tagged "literal" is simply appended to the final string value. Anything tagged "directive" is looked up in a dispatch table (dictionary) of functions and the return value of that function is appended to the final string value.

For example: a function at the dispatch table key "totalOrders" might also be named totalOrders() and it would return "12" as a string.

More details leading to my question:

For a lot of functions in the dispatch table, they obviously know best how to calculate and return the appropriate value. However, for a few items, it is the caller of the function who best knows the value.

Continuing example: suppose collectInfo() is a function that loops thru the parsed format array of dictionaries. It might know what the return value of chefName() should actually be even though it has no idea what totalOrders() should be.

Here is how I have current solved this. Every function in the dispatch table takes an argument. Some functions merely return back the argument they are given. Before calling a function, the caller looks up the key from the dictionary in another dictionary that is has. If there is a match, it passes in that value.

Example: collectInfo() has a dictionary named "specialX" that looks like this:

```<code>{"chefName": lookupChef(c)}
</code>```

"c" is a variable local to collectInfo() that the chefName() function would not know about. So what collectInfo() does is call lookupChef(c) and hand the return value to chefName() like this:

```<code>chefName(lookupChef(c))
</code>```

And the entire code for chefName() is:

```<code>chefName(x) {
    return x
}
</code>```

Doing this allows my code to still (mostly) be data driven. I do not have to include if/then string comparisons and hard code things like "chefName" into my loop in collectInfo().

So here is my problems with this solution:

I still have that "specialX" dictionary hard coded into collectInfo(). That kills my purely data driven approach. I am having trouble abstracting it out to a data file. I'm not sure I ever can.

Is there some way I can create the chefName() function so it knows what it needs to know to calculate the answer? That is, is there some way to tell it about lookupChef(c) directly without breaking encapsulation?

After I have parsed the format, perhaps there is a better approach entirely to composing the final value?

One final note.

You might be wondering where the dispatch table and the functions within it come from. That is the other file future developers will update if a new element is added. For example, if a new format element is added "[quantityOfButtons]" then a new entry in the dispatch table and a new corresponding function would have to be added as well.

The file where collectInfo() is defined imports the file where the dispatch table and its functions are defined.

答:
It sounds like the crux of the problem is:

For a lot of functions in the dispatch table, they obviously know best
  how to calculate and return the appropriate value. However, for a few
  items, it is the caller of the function who best knows the value.

What solution you should use depends entirely on why the caller knows best, which you haven't explained. But it would probably boil down to this: Whatever special thing collectInfo() has access to, it should be giving it to the dispatch table functions. Then chefName() can access the special thing itself instead of relying on specialX to provide lookupChef().

Without knowing exactly what the special thing is and why the functions don't already have access to it, I can only suggest the obvious options like passing it to each function as a parameter (since they all seem to be 0-ary right now) or passing it to the dispatch table constructor (if it's the kind of thing that needs constructing).

Regarding question three, it sounds like what you're doing now is looking at an "element" (single-key dictionary), getting the value it refers to, then simply appending that value to the final string. This is probably fine, but if you feel the need to improve it I would suggest keeping the values in an array until you've retrieved all of them, then concatenating everything afterward.

The advantages are that the elements can be processed in any order (even in parallel), and it's very easy to do some validation or formatting logic on the values before converting them all to strings. For instance, you might check that totalOrders is a number, then add  if the number is less than 10.

Body:
It sounds like the crux of the problem is:

For a lot of functions in the dispatch table, they obviously know best
  how to calculate and return the appropriate value. However, for a few
  items, it is the caller of the function who best knows the value.

What solution you should use depends entirely on why the caller knows best, which you haven't explained. But it would probably boil down to this: Whatever special thing collectInfo() has access to, it should be giving it to the dispatch table functions. Then chefName() can access the special thing itself instead of relying on specialX to provide lookupChef().

Without knowing exactly what the special thing is and why the functions don't already have access to it, I can only suggest the obvious options like passing it to each function as a parameter (since they all seem to be 0-ary right now) or passing it to the dispatch table constructor (if it's the kind of thing that needs constructing).

Regarding question three, it sounds like what you're doing now is looking at an "element" (single-key dictionary), getting the value it refers to, then simply appending that value to the final string. This is probably fine, but if you feel the need to improve it I would suggest keeping the values in an array until you've retrieved all of them, then concatenating everything afterward.

The advantages are that the elements can be processed in any order (even in parallel), and it's very easy to do some validation or formatting logic on the values before converting them all to strings. For instance, you might check that totalOrders is a number, then add <font color="red"></font> if the number is less than 10.


问:
Are there problems with using Reflection?
I don't know why, but I always feel like I am "cheating" when I use reflection - maybe it is because of the performance hit I know I am taking.

Part of me says, if it is part of the language you are using and it can accomplish what you are trying to do, then why not use it.  The other part of me says, there has to be a way I can do this without using reflection.  I guess maybe it depends on the situation.

What are the potential issues I need to look out for when using reflection and how concerned should I be about them?  How much effort is it worth spending to try to find a more conventional solution?

答:
Reflection is the primary method of creating convention-based systems. I would not be surprised to find it is in use heavily inside most MVC frameworks. It's a major component in ORMs. Chances are, you're already using components built with it every day.

The alternative for such a use is configuration, which has its own set of drawbacks.

ContentLicense: CC BY-SA 3.0


问:
Is Emailing waste of time in Dev Teams
I know its not strictly related to what people ask here but I have to ask this anyway.

Isn't having long conversations/discussions over emails reduce one's productivity. I have joined this new company where people prefer emails alot. It's not a big company so every one is accessible to everyone and also senior techies tend to get together for a 30 mins session every day to discuss and plan things with managers and stake holders.

I think emails are great and should be used as long as they are to the point and don't waste anyone's time. In my professional experience getting or agreeing things over emails quickly becomes an endless game of ping-pong. Reaching to a conclusion often takes days just because.. oh well..not everyone has enough time to go through lengthy emails. Email subjects often become less subjective and more "re:re:re:re:fw:". After few "re:re's" and "fw:fw's" it becomes a nightmare to find what you're looking for since not every single thing in emails is a key-point so coming back to conversation after 8-9 months is like going through someone's source code writen in C.

It's also not the best approach for discussing ideas or agreeing over things as most people tend to be more reserved in email conversations than they are in real life because it's very easy to misinterpret one's tone.

Most of the times I find it much easier and quicker to send an email saying "Lets discuss thing X at xx:xx" followed by a quick call at agreed time rather than dragging the issue for days (or in some cases weeks). When needed I follow up with an email saying "well here's what we agreed on the phone".

Also people are generally more respectful to each other and open to discussions when talking face to face or over the phone.

Don't get me wrong, emails are important and should be used whenever they are absolutely necessary. But in small/medium sized teams why is this culture (of writing long stories i.e. emails) so so important ? why don't people use tools like Basecamp, redmine, wiki's instead.

How would you improve your team or company's communications so people become more productive and create a friendly environment.

Thank you for reading.

答:
There is a flip side case to be said for e-mails being advantageous in some cases:

Introverted people may tend to prefer written communications which e-mail would be one form of that.  This allows for multiple thoughts to be expressed in one message that can be sent in bulk which can be useful to record in some situations,e.g. what work was I doing, what decisions were made about this or that, etc.  While e-mail may be abused, there are times where some people that are focused a lot on precision and accuracy in conveying thoughts may prefer e-mail with its structure, archiving, etc.  Although things like Twitter and Instant Messaging have replaced some of this need and may be more effective at times.  Think of this as some people would rather relay information through written words than verbally, which can be a strength or weakness depending on how one wants to see it.

E-mails can be good for some broadcast scenarios.  A build going into test or some other environmental deployment may be worthwhile as an e-mail that can get logged for when was this done and what changes were in it.  Another scenario here is to have an agenda for a meeting sent out before the meeting while being environmentally friendly about it.

Approval and workflow management can sometimes be done through e-mail where a system will send off a notification to someone and thus a developer may know a bug was assigned to them or a manager may get an approval form to click for someone to use their vacation time, etc.  This isn't quite the broadcast case but it is the case where written records may be wanted for some situations.

ContentLicense: CC BY-SA 2.5

Title: Is Emailing waste of time in Dev Teams


问:
Leaving intentional bugs in code for testers to find
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).

答:
This isn't necessarily as crazy as it sounds. It rather depends on your motivation. If you are looking for a stick to beat your test team with, well that would be crazy. On the other hand, one of the most difficult things in software development is to know how effective your testing approach is.

So if you structure it properly, you could use this technique to estimate how many unfound bugs remain in the product you are about to ship. So imagine that you've artificially seeded 100 bugs in your test build, and the testers find 50 of them. Then you can infer that there's a certain likelihood that if they also found 50 unseeded bugs, perhaps there are 50 left to find.

Of course, this is fraught with many problems. You could decide whether to ship based on these statistics, but in real life, you might find one very nasty issue, or a thousand minor irritations.

Still - knowledge is power, and without this technique, you have even less idea of the quality of your code base. If you can implement it respectfully and for the right reasons, I'd say "Why not?"


问:
What's the best way to avoid catastrophe caused by negligence?
I have been a programmer for almost 1 year.

As an ADHD adult, naturally I don't have the same strength of attention on ordinary stuffs as my colleagues do.

And I find the catastrophe made by me are usually caused by trivial negligence.

Like for today, I found the cron process on the server collapsed in the morning.

After half hour of debugging. I found I wrote in the cron

* 4 * * * sh daily_task.sh

instead of

0 4 * * * sh daily_task.sh

Which runs the huge shell 59 times in the morning instead of the intended 1 time.

Is there some kind of cultivatable behaviour or some tools or anything that can help me at least reduce such kind of  mistake?

How do you do to avoid such kind of mistake?

答:
I think the direct solution, especially to the sort of problem you exemplified, is to make mistakes conspicuous.

If you look at the two lines you gave, the difference is actually quite subtle. You have to have a lot of detailed, nuanced syntax "in your mind" when reading it if you want to catch the mistake. You also have to keep an eye out for hard-to-see visual features (* and 0 can be easy to confuse).

For example, in your example, if cron syntax was like the following:

```<code>minute=0 hour=4 day=every week=every month=every year=every
</code>```

You would be less likely to confuse it with:

```<code>minute=every hour=4 day=every week=every month=every year=every
</code>```

You can't really change cron's syntax, but you could write a simple CLI program for yourself that takes named arguments like above, and then pass them to the actual cron. You'd need to carefully review the code that converts from your named arguments, but you only need to do that once, so you can afford to really focus yourself and go the extra mile in error checking - print out the code, read and explain it to yourself aloud and so on.

When you have a program like this, you can also add a sanity check. After you make a new cron job, have it output:

```<code>This new job will run 1 times a day.
</code>```

(perhaps it tries to find the shortest time period that results in a whole number)

Now it will be really difficult for you to make the same mistake. Your tradeoff is:

It now takes more keystrokes to type the commands, and they look busier (this is probably why cron was given the syntax that it was in the first place).

You have spent time and effort setting up the error-resistant interface model and the sanity check (but in this case you can probably do it in an hour or two).

Now, I'm not necessarily suggesting you do this for cron. That seems like it's a bit of overkill, unless you set and edit tasks on cron very often. I just used your example to illustrate the two useful tricks: Sanity checks, and preferring syntax that makes errors very conspicuous even if you don't look for them. The idea is to make sure that mistakes smell.

With syntax, the two obvious things you can do are:

Select tools and languages that have more error-resistant syntax, for instance, C# vs. Perl. Notice again the tradeoff between catching mistakes quickly and having to do more work.

Wrap poor syntax in better syntax. For instance, make your own wrapper function for a poorly named functions with ambiguous argument names, make your own wrapper program for arcane tools, use an editor that supports color highlighting and so on.

It doesn't make sense to do these all the way all the time. You want to ask yourself, what matters more in a given task: Correctness, or your time? It's no use disputing that hacking together a quick script in Perl is going to get the job faster than writing a well-structured C# program with clear OOP hierarchy. If you're not worried about mistakes, and you're in a hurry, why bother? But keep in mind that every time you take this shortcut, you are making a gamble: You wager much frustration and gnashing of teeth on the hope that you won't have to go back and extend on your project in the far future, long after you've forgotten how it was supposed to work (or that you won't realize halfway through that your original design won't work, and now must be radically altered).

Body:
I think the direct solution, especially to the sort of problem you exemplified, is to make mistakes conspicuous.

If you look at the two lines you gave, the difference is actually quite subtle. You have to have a lot of detailed, nuanced syntax "in your mind" when reading it if you want to catch the mistake. You also have to keep an eye out for hard-to-see visual features (* and 0 can be easy to confuse).

For example, in your example, if cron syntax was like the following:

minute=0 hour=4 day=every week=every month=every year=every

You would be less likely to confuse it with:

minute=every hour=4 day=every week=every month=every year=every

You can't really change cron's syntax, but you could write a simple CLI program for yourself that takes named arguments like above, and then pass them to the actual cron. You'd need to carefully review the code that converts from your named arguments, but you only need to do that once, so you can afford to really focus yourself and go the extra mile in error checking - print out the code, read and explain it to yourself aloud and so on.

When you have a program like this, you can also add a sanity check. After you make a new cron job, have it output:

This new job will run 1 times a day.

(perhaps it tries to find the shortest time period that results in a whole number)

Now it will be really difficult for you to make the same mistake. Your tradeoff is:

It now takes more keystrokes to type the commands, and they look busier (this is probably why cron was given the syntax that it was in the first place).

You have spent time and effort setting up the error-resistant interface model and the sanity check (but in this case you can probably do it in an hour or two).

Now, I'm not necessarily suggesting you do this for cron. That seems like it's a bit of overkill, unless you set and edit tasks on cron very often. I just used your example to illustrate the two useful tricks: Sanity checks, and preferring syntax that makes errors very conspicuous even if you don't look for them. The idea is to make sure that mistakes smell.

With syntax, the two obvious things you can do are:

Select tools and languages that have more error-resistant syntax, for instance, C# vs. Perl. Notice again the tradeoff between catching mistakes quickly and having to do more work.

Wrap poor syntax in better syntax. For instance, make your own wrapper function for a poorly named functions with ambiguous argument names, make your own wrapper program for arcane tools, use an editor that supports color highlighting and so on.

It doesn't make sense to do these all the way all the time. You want to ask yourself, what matters more in a given task: Correctness, or your time? It's no use disputing that hacking together a quick script in Perl is going to get the job faster than writing a well-structured C# program with clear OOP hierarchy. If you're not worried about mistakes, and you're in a hurry, why bother? But keep in mind that every time you take this shortcut, you are making a gamble: You wager much frustration and gnashing of teeth on the hope that you won't have to go back and extend on your project in the far future, long after you've forgotten how it was supposed to work (or that you won't realize halfway through that your original design won't work, and now must be radically altered).


问:
How can I avoid tight coupling when practically every decision-logic has to check lots of distributed state?
As the senior developer in our company, I am currently starting to move our commercial php-mysql e-commerce solution (which takes data from a specific ERP-system) from procedural spaghetti-code which uses globals for pretty much everything and has very little separation of concerns to OOP.

The title describes the basic problem rather well - almost every user-interaction will have to check lots and lots of things (state), and do different things based on that. How can I avoid bloating my controllers & services or coding structural knowledge about everything into my classes (constructor over-injection, service-locator, law-of-Demeter violations etc)?

More information about the current situation:

I have already successfully developed a basic architectural style and implemented an RMA-module with this design.

A brief summary: For every basic business-entity (the rows of our mysql-tables), I have a class for data-storage and retrieval, as well as for getting NULL-versions of that object, a configuration-class that holds information about which fields are mapped from db, what a potential alternative unique key besides the db-id is, as well as the name of the table (or view) to get data from. Furthermore, I have specific collection-classes which ensure that they only contain instances of the data-classes and specific repositories also implementing the identity-map pattern which manage both basic retrieval & persistence as well as entity-specific methods. When non-persistent business-entities are needed, they can be stand-alone, in a dyad with collection or a triad with collection and repository.

On top of this, I have quasi-"front controllers" for modules which use services for processing-tasks. In case of multi-step processes (currently RMA, later also user-account, order etc), the module "front controller" checks the current step (action) & user-input (delegate validation to services where sensible).

If multiple actions are possible on a view, and an action only changes data within the view, and has no potential to change which view has to be chosen - the "front-controller" will pass that action to a presenter for the view. If the action can change what page is displayed (re-routing on validation error, progressing to different view on successful input-validation), the business-logic is done by the module "front-controller" itself with the help of a service or services.

As a rather standard php-application, the application is created with user input via URL, POST & GET, has this input from the beginning, constructs a response, outputs it and then is destroyed. New user input will create the entire application anew - with the exception of one or two places where Ajax-code is put into the site by the application, which is basically just creating a mini-application and integrating its output into the browser-window, and isn't an interaction with the application-instance that created the page. So the application cannot update views during its lifetime - actually creating a view in the UI is the end of the application lifetime, meaning actual MVC / MVVM / MVP implementations as originally conceived are not strictly possible... only partial mappings are. I have tried a modest implementation as described above.

RMA is working nicely, and has already achieved huge increase in separation of concerns and thus "debuggability". Using traits for fields and field-related methods that different classes need to fulfill common interfaces (the business-entity specific collections, configs, data-objects and repositories/identity-maps), I was able to avoid code duplication quite neatly.

After many months of reading all about best practices, patterns and anti-patterns, architectural styles etc and trying out different things - I'm still left with some rather pressing problems.

The coupling between the classes related to a single business-entity (data-object, config, collection and repository) is acceptable, in fact quite beneficial: in virtue of this tetrad-pattern and the use of traits, new business-entities are added (and provide extremely powerful methods for handling them) in a matter of minutes. Schema-modifications merely necessitate changing the respective fields in the data-object and their description in the config (two lines of code for every field, plus a potential further two if the non-id unique-key changes... which does't happen).

What's bothering me mostly is that I have found no way to avoid falling prey to at least one of the set of bad practices related to constructor over-injection, service locator plus law-of-Demeter violation and tight coupling (too much knowledge) in general for the controllers and services.

That's mainly because pretty much every single controller will have to check with huge amounts of distributed state... mainly, what should be done and displayed on a certain URL with a certain set of POST & GET data depends on a so many things: Is the shop b2c, b2b or salesperson? Is the visitor logged in? Does the form-data identifying a record to act upon match the records company-code, shop-code, shop-language-code? If we are in b2b, does the user have permission for the module? Does the user have permission for the record? What is the content of the text-snippet with the given code in the local language?

All this information is distributed in different model-entities. Wherever a procedure concerns only the data of the object itself, it is in the data-class or (when meta-information is needed) in a service that knows about the data-class and its config. When it contains nothing but operations on a given collection/aggregate of a business-entity, it's in the collection-class, if it concerns retrieval, it's in the repository/identity-map.

But since practically every module and nearly every action the user can perform with respect to a module is dependent upon so many different things, I currently can't seem to find a way to avoid either bloating objects and their constructors beyond the pale, or using (as I do now with the RMA-module) Configuration-Objects such as "CurrShopConfiguration" which contain the current shop, shop-language, a provider of local text-constants, the current visitor, user and customer and a "god"-like helper-service for a controller which has the CurrConfig-Object and implements all procedures the "front-controller" needs to perform beyond choosing actions, models, views and linking them.

I would very much like to write more SOLID code - yet can't see how, since the essential decision-logic of the modules and actions have so many necessary dependencies.

Perhaps you have some ideas on how to approach this issue?

Here is some example code - the part of the RMA-"Front Controller" that is executed when the 'save' action on a a form with a returnable shipment is called:

```<code>//Check for existence of shipment-id in input
if (!($this->inputHeaderID > 0)) {
    //add user-faced error-message for view-models
    $this->errors[] = $this->templateEngine->getText('record_not_set');
    //go to search-view (where errors are displayed)
    $this->_showSearchPage();
} else {
    //Try to get shipment from Repository (extracted from helper), get either target shipment or NULL-object (unset fields)
    $shipment = $this->retShipmentRepository->findByID($this->inputHeaderID);
    //Check for NULL-Object
    if (!((int)$shipment->id) > 0) {
        $this->errors[] = $this->templateEngine->getText('record_not_set');
        $this->_showSearchPage();
    } else {
        //We have valid shipment. Check for user permission on shipment
        if (!$this->helper->checkUserShipmentPermission($this->user,$shipment,$this->inputEMail,$this->inputPostCode)) {
            $this->errors[] = $this->templateEngine->getText('record_not_permitted');
            $this->_showSearchPage();
        } else {
            //We have permission, attempt saving (shop-context based switching and further validation inside service)
            if(!($this->helper->saveReturnOrder($shipment,$this->inputReference,$this->inputLines))) {
                $this->errors = $this->helper->getErrors();
                $this->_showShipmentPage($shipment);
            } else {
                //The Shipment could be appended with the return order information and saved.
                //Check if it was deemed to require verification via link with token in email to owner of shipment
                //Show either success view or confirmation-required view based
                $saveStatus = $this->helper->getSaveStatus($shipment->id);
                if($saveStatus == RMAOrderHelper::SAVE_STATUS_WITHOUT_TOKEN) {
                    $this->_showSuccessPage();
                } elseif($saveStatus == RMAOrderHelper::SAVE_STATUS_WITH_TOKEN) {
                    $this->_requestTokenConfirmation($shipment);
                }
            }
        }
    }
}
</code>```

The user-input variables are stored on __construct of the controller (which is injected with the helper - it accesses the helper's "CurrShopConfig" and extracts information it needs directly) via filter_var.

The above code smells pretty badly to me ... but there's far more to the decision-logic, which is is in the helper-service and accesses the current shop-configuration, user, visitor etc to perform the tasks of its public methods.

Here are the first 2/3rds of the helper-services saveReturnOrder-Method

```<code>public function saveReturnOrder( RetShipmentDocument $shipment, $yourReference, $inputLines ) {
        //Check if document isn't already marked with a return order request
        //that hasn't been synchronized with the ERP-System (and thus cleared) yet
        if (!$shipment->isReturnOrderSettable()) {
            $this->errors[] = $this->templateEngine->getText('internal_error');
            return FALSE;
        }
        //Check if the input for the shipment-lines (id, return quantity and return-reason code)
        //belong to the shipment and are valid (e.g. return quantity <= un-returned quantity)
        if (!$this->_validateReturnOrderLineInput($shipment, $inputLines)) {
            $this->errors[] = $this->templateEngine->getText('internal_error');
            return FALSE;
        }

        //ValidatedLineRequests are stored for the shipment by the _validateReturnOrderLineInput-Method
        //that has just been executed
        $requestLines  = $this->validatedLineRequests[$shipment->id];
        $shipmentLines = $shipment->getLines();

        $token  = '';
        $markAsConfirmed = TRUE;

        //If visitor is not logged in and we have a content for a confirmation-request mail
        //we must not mark it as confirmed and generate a token
        if (!$this->shopConfiguration->visitorLoggedIn() && ($this->getConfirmMailTextModule()->id > 0)) {
            $token  = md5(uniqid(mt_rand(), TRUE));
            $markAsConfirmed = FALSE;
        //Otherwise if visitor is not logged in and there is no such mail-content
        //we have an error and cannot proceed
        } elseif (!$this->shopConfiguration->visitorLoggedIn() && !($this->getConfirmMailTextModule()->id > 0)) {
            $this->errors[] = $this->templateEngine->getText('internal_error');
            return FALSE;
        }
        $lineRepository = $this->shipmentRepository->getLineRepository();
        $committedLineRequests = 0;
        foreach ($requestLines as $lineRequest) {
            $lineID           = $lineRequest['line_id'];
            $returnQuantity   = $lineRequest['return_quantity'];
            $returnReasonCode = $lineRequest['return_reason_code'];
            foreach ($shipmentLines as $shipmentLine) {
                if ($shipmentLine->id == $lineID) {
                    //The shipment has a line matching the request, attempt setting the return-order data
                    if (!$shipmentLine->setReturnOrder($markAsConfirmed, $returnQuantity, $returnReasonCode)) {
                        $this->errors[] = $this->templateEngine->getText('internal_error');
                        $this->_unsetReturnOrder($shipment);
                        return FALSE;
                    }
                    //Data could be set in object - now try persisting it
                    if (!$lineRepository->updateSingle($shipmentLine)) {
                        $this->errors[] = $this->templateEngine->getText('internal_error');
                        $this->_unsetReturnOrder($shipment);
                        return FALSE;
                    }
                    //Persistence succeeded, increment counter
                    ++$committedLineRequests;
                }
            }
        }
</code>```

As you can see... I've already made many discrete sub-processes into methods and located them with objects to which they belong, but I'm still left with huge ugly nested conditionals and an explosion of dependencies. Splitting up every part (or even most parts) of such nested conditionals into different objects is unfeasible... and unhelpful, since practically every conditional already uses methods that are with objects where they belong, and since such a splitting would likely increase re-usability very little and would have to be done for many dozens such situations, resulting in a class- and file-explosion.

答:
If you have too many dependencies being passed around, the general technique is to eliminate those dependencies higher up in the call stack, by changing the order decisions are made.  This is easiest to explain with an example:

```<code>getPath(config, user) {
  if (config.isB2B())
    return b2bpath(config, user);
  else
    return b2cpath(config, user);
}

b2bpath(config, user) {
  if (!config.allowedToAccessPath(user))
    return accessDeniedPage();
  else
    return "My fancy b2b page";
}

b2cpath(config, user) {
  if (!config.allowedToAccessPath(user))
    return accessDeniedPage();
  else
    return "My fancy b2c page";
}
</code>```

You are repeating the authorization check down at the lowest levels of the call stack, so move it up:

```<code>getPath(config, user) {
  if (!config.allowedToAccessPath(user))
    return accessDeniedPage();

  if (config.isB2B())
    return b2bpath();
  else
    return b2cpath();
}

b2bpath() {
    return "My fancy b2b page";
}

b2cpath() {
    return "My fancy b2c page";
}
</code>```

Then repeat to see if you can move some of the decisions into the code that calls getPath.  This is a simple example, but I see the former kind of code all over the place with more layers.  Start with decisions at your lowest layers, and try to figure out ways to move them up.  Sometimes this requires judicious use of inheritance, like:

```<code>getPath(config, user) {
  module = config.isB2B() ? B2BModule() : B2CModule()
  if (!config.allowedToAccessPath(user))
    return module.accessDeniedPage();

  return module.getPath();
}
</code>```

It's very rare not to be able to simplify dependencies this way.  It's a matter of trying different arrangements until you find one that works.

If you have workflow-type dependencies, not just data dependencies, as in your first example, you can separate them out using something like this:

```<code>step1 = new ValidateHeaderId(inputHeaderId);
step2 = new FindShipment(retShipmentRepository);
step3 = new ValidateUserPermission(user, inputPostCode, inputEmail);
step4 = new SaveReturnOrder(inputLines, inputReference);
step5 = new CheckSaveStatus();
notSet = new NotSetPage(templateEngine, searchPage);
notPermitted = new NotPermittedPage(templateEngine, searchPage);
saveErrors = new SaveErrorsPage();
success = new SuccessPage();
requestTokenConfirmation = new RequestTokenConfirmation();

steps = [step1, [notSet, step2], [notSet, step3], [notPermitted, step4],
         [saveErrors, step5], [success, requestTokenConfirmation]];
executeSteps(steps);
</code>```

This recognizes you have a series of steps which each produce some sort of result and choose the next step.  executeSteps abstracts away the repetition of calling run() on each step, and passing the output from the previous step into the next step.  This allows the steps to be stored in a data structure instead of a function, which can then be built up in several different ways, including by some sort of registration process or config file.  Once each step object has been created, its dependencies no longer need to be tracked outside it.  I believe the rules engines from BobDalgleish's answer are basically pre-existing libraries to help you do this more easily.

Body:
If you have too many dependencies being passed around, the general technique is to eliminate those dependencies higher up in the call stack, by changing the order decisions are made.  This is easiest to explain with an example:

getPath(config, user) {
  if (config.isB2B())
    return b2bpath(config, user);
  else
    return b2cpath(config, user);
}

b2bpath(config, user) {
  if (!config.allowedToAccessPath(user))
    return accessDeniedPage();
  else
    return "My fancy b2b page";
}

b2cpath(config, user) {
  if (!config.allowedToAccessPath(user))
    return accessDeniedPage();
  else
    return "My fancy b2c page";
}

You are repeating the authorization check down at the lowest levels of the call stack, so move it up:

getPath(config, user) {
  if (!config.allowedToAccessPath(user))
    return accessDeniedPage();

  if (config.isB2B())
    return b2bpath();
  else
    return b2cpath();
}

b2bpath() {
    return "My fancy b2b page";
}

b2cpath() {
    return "My fancy b2c page";
}

Then repeat to see if you can move some of the decisions into the code that calls getPath.  This is a simple example, but I see the former kind of code all over the place with more layers.  Start with decisions at your lowest layers, and try to figure out ways to move them up.  Sometimes this requires judicious use of inheritance, like:

getPath(config, user) {
  module = config.isB2B() ? B2BModule() : B2CModule()
  if (!config.allowedToAccessPath(user))
    return module.accessDeniedPage();

  return module.getPath();
}

It's very rare not to be able to simplify dependencies this way.  It's a matter of trying different arrangements until you find one that works.

If you have workflow-type dependencies, not just data dependencies, as in your first example, you can separate them out using something like this:

step1 = new ValidateHeaderId(inputHeaderId);
step2 = new FindShipment(retShipmentRepository);
step3 = new ValidateUserPermission(user, inputPostCode, inputEmail);
step4 = new SaveReturnOrder(inputLines, inputReference);
step5 = new CheckSaveStatus();
notSet = new NotSetPage(templateEngine, searchPage);
notPermitted = new NotPermittedPage(templateEngine, searchPage);
saveErrors = new SaveErrorsPage();
success = new SuccessPage();
requestTokenConfirmation = new RequestTokenConfirmation();

steps = [step1, [notSet, step2], [notSet, step3], [notPermitted, step4],
         [saveErrors, step5], [success, requestTokenConfirmation]];
executeSteps(steps);

This recognizes you have a series of steps which each produce some sort of result and choose the next step.  executeSteps abstracts away the repetition of calling run() on each step, and passing the output from the previous step into the next step.  This allows the steps to be stored in a data structure instead of a function, which can then be built up in several different ways, including by some sort of registration process or config file.  Once each step object has been created, its dependencies no longer need to be tracked outside it.  I believe the rules engines from BobDalgleish's answer are basically pre-existing libraries to help you do this more easily.


问:
Exception handling scope when dealing with nested exceptions
Assume you have one object that has two methods which both throw different exceptions. These methods must be used together. For instance:

```<code>SqlCon{
  static SqlCon connect(string user, string pass) throws UnableToConnect;
  string[] query(string query) throws BadQueryExcep;
}
</code>```

Options
1.

```<code>try{
   SqlCon s = connect("user", "pass");
   s.query("myquery");

}catch(UnableToConnect e || BadQueryExcep b){
  //do something with error
}
</code>```

Option 2.

```<code> try{
       SqlCon s = connect("user", "pass");
       try{
         s.query("myquery");
       }catch(BadQueryExcep b){
        //do something with different error
       }

    }catch(UnableToConnect u){
      //do something with error
    }
</code>```

Option 3.

```<code>SqlCon s;

try{
   s = connect("user", "pass");

}catch(UnableToConnect e){
  //do something with error
  return;
}
try{
   s.query("myquery");
}catch(BadQueryExcep b){
  //do something with different error
}
</code>```

Options
4.

```<code>try{
   SqlCon s = connect("user", "pass");
   s.query("myquery");

}catch(UnableToConnect e){
  //do something with e
}catch(BadQueryExcep b){
 //do something with b
}
</code>```

Option 4 seems the cleanest to me but if there were a lot of statements within the try{..} block, you would be hiding where the exception occurred.

Which option would you choose and why? Which option would you not choose and why? Is there better options available (operating within the constraints of the question...don't just say 'You should throw the exception')?

答:
Option 1 or 4. The others add a lot of visual confusion without improving the behavior in any way.

Assuming these exceptions have reasonably descriptive error messages (eg, "Could not connect to database", "Syntax error in query after 'SELECT' token", etc) which you can access via the usual e.what(), then Option 1 is probably the best because you'll likely use the exact same code to handle both types of exceptions. If for some reason you need to handle the two exception types differently, then Option 4 is better.

Note that "hiding where the exception occurred" is not an issue at all as long as the error messages are reasonably descriptive (and if they aren't, that's the first problem to tackle). Especially in the context of databases, the error message probably tells you far more than which line of code threw it.

In addition to the readability problem, with Options 2 and 3 the first/inner try-catch block is probably using exceptions as control flow, which we all know is an anti-pattern for plenty of other reasons.


答:
The general rule in complicated programs is

Separation of Data and Control

The more that you can keep these two aspects separate, the easier the software will be to maintain. This what you are trying to do in your refactoring.

I would suggest that you take a more drastic step and use a "business rules engine" to drive your program. I don't mean one of those fancy tools designed for non-programmers, but something that quite clearly separates out the decision making process from the actual collection or transformation of data.

I often recommend JBoss Drools for applications that are Java-based. I see that there is a similar type of engine available for PHP. Looking over it, it accomplishes many of the things you are trying to do. -> Ruler.

Title: How can I avoid tight coupling when practically every decision-logic has to check lots of distributed state?

Body:
As the senior developer in our company, I am currently starting to move our commercial php-mysql e-commerce solution (which takes data from a specific ERP-system) from procedural spaghetti-code which uses globals for pretty much everything and has very little separation of concerns to OOP.

The title describes the basic problem rather well - almost every user-interaction will have to check lots and lots of things (state), and do different things based on that. How can I avoid bloating my controllers & services or coding structural knowledge about everything into my classes (constructor over-injection, service-locator, law-of-Demeter violations etc)?

More information about the current situation:

I have already successfully developed a basic architectural style and implemented an RMA-module with this design.

A brief summary: For every basic business-entity (the rows of our mysql-tables), I have a class for data-storage and retrieval, as well as for getting NULL-versions of that object, a configuration-class that holds information about which fields are mapped from db, what a potential alternative unique key besides the db-id is, as well as the name of the table (or view) to get data from. Furthermore, I have specific collection-classes which ensure that they only contain instances of the data-classes and specific repositories also implementing the identity-map pattern which manage both basic retrieval & persistence as well as entity-specific methods. When non-persistent business-entities are needed, they can be stand-alone, in a dyad with collection or a triad with collection and repository.

On top of this, I have quasi-"front controllers" for modules which use services for processing-tasks. In case of multi-step processes (currently RMA, later also user-account, order etc), the module "front controller" checks the current step (action) & user-input (delegate validation to services where sensible).

If multiple actions are possible on a view, and an action only changes data within the view, and has no potential to change which view has to be chosen - the "front-controller" will pass that action to a presenter for the view. If the action can change what page is displayed (re-routing on validation error, progressing to different view on successful input-validation), the business-logic is done by the module "front-controller" itself with the help of a service or services.

As a rather standard php-application, the application is created with user input via URL, POST & GET, has this input from the beginning, constructs a response, outputs it and then is destroyed. New user input will create the entire application anew - with the exception of one or two places where Ajax-code is put into the site by the application, which is basically just creating a mini-application and integrating its output into the browser-window, and isn't an interaction with the application-instance that created the page. So the application cannot update views during its lifetime - actually creating a view in the UI is the end of the application lifetime, meaning actual MVC / MVVM / MVP implementations as originally conceived are not strictly possible... only partial mappings are. I have tried a modest implementation as described above.

RMA is working nicely, and has already achieved huge increase in separation of concerns and thus "debuggability". Using traits for fields and field-related methods that different classes need to fulfill common interfaces (the business-entity specific collections, configs, data-objects and repositories/identity-maps), I was able to avoid code duplication quite neatly.

After many months of reading all about best practices, patterns and anti-patterns, architectural styles etc and trying out different things - I'm still left with some rather pressing problems.

The coupling between the classes related to a single business-entity (data-object, config, collection and repository) is acceptable, in fact quite beneficial: in virtue of this tetrad-pattern and the use of traits, new business-entities are added (and provide extremely powerful methods for handling them) in a matter of minutes. Schema-modifications merely necessitate changing the respective fields in the data-object and their description in the config (two lines of code for every field, plus a potential further two if the non-id unique-key changes... which does't happen).

What's bothering me mostly is that I have found no way to avoid falling prey to at least one of the set of bad practices related to constructor over-injection, service locator plus law-of-Demeter violation and tight coupling (too much knowledge) in general for the controllers and services.

That's mainly because pretty much every single controller will have to check with huge amounts of distributed state... mainly, what should be done and displayed on a certain URL with a certain set of POST & GET data depends on a so many things: Is the shop b2c, b2b or salesperson? Is the visitor logged in? Does the form-data identifying a record to act upon match the records company-code, shop-code, shop-language-code? If we are in b2b, does the user have permission for the module? Does the user have permission for the record? What is the content of the text-snippet with the given code in the local language?

All this information is distributed in different model-entities. Wherever a procedure concerns only the data of the object itself, it is in the data-class or (when meta-information is needed) in a service that knows about the data-class and its config. When it contains nothing but operations on a given collection/aggregate of a business-entity, it's in the collection-class, if it concerns retrieval, it's in the repository/identity-map.

But since practically every module and nearly every action the user can perform with respect to a module is dependent upon so many different things, I currently can't seem to find a way to avoid either bloating objects and their constructors beyond the pale, or using (as I do now with the RMA-module) Configuration-Objects such as "CurrShopConfiguration" which contain the current shop, shop-language, a provider of local text-constants, the current visitor, user and customer and a "god"-like helper-service for a controller which has the CurrConfig-Object and implements all procedures the "front-controller" needs to perform beyond choosing actions, models, views and linking them.

I would very much like to write more SOLID code - yet can't see how, since the essential decision-logic of the modules and actions have so many necessary dependencies.

Perhaps you have some ideas on how to approach this issue?

Here is some example code - the part of the RMA-"Front Controller" that is executed when the 'save' action on a a form with a returnable shipment is called:

```<code>//Check for existence of shipment-id in input
if (!($this->inputHeaderID > 0)) {
    //add user-faced error-message for view-models
    $this->errors[] = $this->templateEngine->getText('record_not_set');
    //go to search-view (where errors are displayed)
    $this->_showSearchPage();
} else {
    //Try to get shipment from Repository (extracted from helper), get either target shipment or NULL-object (unset fields)
    $shipment = $this->retShipmentRepository->findByID($this->inputHeaderID);
    //Check for NULL-Object
    if (!((int)$shipment->id) > 0) {
        $this->errors[] = $this->templateEngine->getText('record_not_set');
        $this->_showSearchPage();
    } else {
        //We have valid shipment. Check for user permission on shipment
        if (!$this->helper->checkUserShipmentPermission($this->user,$shipment,$this->inputEMail,$this->inputPostCode)) {
            $this->errors[] = $this->templateEngine->getText('record_not_permitted');
            $this->_showSearchPage();
        } else {
            //We have permission, attempt saving (shop-context based switching and further validation inside service)
            if(!($this->helper->saveReturnOrder($shipment,$this->inputReference,$this->inputLines))) {
                $this->errors = $this->helper->getErrors();
                $this->_showShipmentPage($shipment);
            } else {
                //The Shipment could be appended with the return order information and saved.
                //Check if it was deemed to require verification via link with token in email to owner of shipment
                //Show either success view or confirmation-required view based
                $saveStatus = $this->helper->getSaveStatus($shipment->id);
                if($saveStatus == RMAOrderHelper::SAVE_STATUS_WITHOUT_TOKEN) {
                    $this->_showSuccessPage();
                } elseif($saveStatus == RMAOrderHelper::SAVE_STATUS_WITH_TOKEN) {
                    $this->_requestTokenConfirmation($shipment);
                }
            }
        }
    }
}
</code>```

The user-input variables are stored on __construct of the controller (which is injected with the helper - it accesses the helper's "CurrShopConfig" and extracts information it needs directly) via filter_var.

The above code smells pretty badly to me ... but there's far more to the decision-logic, which is is in the helper-service and accesses the current shop-configuration, user, visitor etc to perform the tasks of its public methods.

Here are the first 2/3rds of the helper-services saveReturnOrder-Method

```<code>public function saveReturnOrder( RetShipmentDocument $shipment, $yourReference, $inputLines ) {
        //Check if document isn't already marked with a return order request
        //that hasn't been synchronized with the ERP-System (and thus cleared) yet
        if (!$shipment->isReturnOrderSettable()) {
            $this->errors[] = $this->templateEngine->getText('internal_error');
            return FALSE;
        }
        //Check if the input for the shipment-lines (id, return quantity and return-reason code)
        //belong to the shipment and are valid (e.g. return quantity <= un-returned quantity)
        if (!$this->_validateReturnOrderLineInput($shipment, $inputLines)) {
            $this->errors[] = $this->templateEngine->getText('internal_error');
            return FALSE;
        }

        //ValidatedLineRequests are stored for the shipment by the _validateReturnOrderLineInput-Method
        //that has just been executed
        $requestLines  = $this->validatedLineRequests[$shipment->id];
        $shipmentLines = $shipment->getLines();

        $token  = '';
        $markAsConfirmed = TRUE;

        //If visitor is not logged in and we have a content for a confirmation-request mail
        //we must not mark it as confirmed and generate a token
        if (!$this->shopConfiguration->visitorLoggedIn() && ($this->getConfirmMailTextModule()->id > 0)) {
            $token  = md5(uniqid(mt_rand(), TRUE));
            $markAsConfirmed = FALSE;
        //Otherwise if visitor is not logged in and there is no such mail-content
        //we have an error and cannot proceed
        } elseif (!$this->shopConfiguration->visitorLoggedIn() && !($this->getConfirmMailTextModule()->id > 0)) {
            $this->errors[] = $this->templateEngine->getText('internal_error');
            return FALSE;
        }
        $lineRepository = $this->shipmentRepository->getLineRepository();
        $committedLineRequests = 0;
        foreach ($requestLines as $lineRequest) {
            $lineID           = $lineRequest['line_id'];
            $returnQuantity   = $lineRequest['return_quantity'];
            $returnReasonCode = $lineRequest['return_reason_code'];
            foreach ($shipmentLines as $shipmentLine) {
                if ($shipmentLine->id == $lineID) {
                    //The shipment has a line matching the request, attempt setting the return-order data
                    if (!$shipmentLine->setReturnOrder($markAsConfirmed, $returnQuantity, $returnReasonCode)) {
                        $this->errors[] = $this->templateEngine->getText('internal_error');
                        $this->_unsetReturnOrder($shipment);
                        return FALSE;
                    }
                    //Data could be set in object - now try persisting it
                    if (!$lineRepository->updateSingle($shipmentLine)) {
                        $this->errors[] = $this->templateEngine->getText('internal_error');
                        $this->_unsetReturnOrder($shipment);
                        return FALSE;
                    }
                    //Persistence succeeded, increment counter
                    ++$committedLineRequests;
                }
            }
        }
</code>```

As you can see... I've already made many discrete sub-processes into methods and located them with objects to which they belong, but I'm still left with huge ugly nested conditionals and an explosion of dependencies. Splitting up every part (or even most parts) of such nested conditionals into different objects is unfeasible... and unhelpful, since practically every conditional already uses methods that are with objects where they belong, and since such a splitting would likely increase re-usability very little and would have to be done for many dozens such situations, resulting in a class- and file-explosion.


问:
pixel perfect apps techniques
While doing your iOS app development, do you try to achieve pixel perfect similarity? Is your app identical to provided photoshop designs?

If yes, what techniques are you using to speed this process up? I find it really time-consuming, since:

I'm using a lot of custom component which aren't displayed in interface builder.

Text field boundaries size are different in XCode and Photoshop. So I can't just copy position.

Some of the properties are not easily modify-able. I've got a lot of custom-sized buttons, and changing text baseline is difficult

etc...

I'm aware about tools like Reveal or SparkInspector - they speed things up, but it's not a dramatic boost for me. I know also that with XCode 6 you can use IBDesignable. I'm stucked with 32bit app right now, so I can't use it yet (and not sure how useful is it).

So, is it really so time consuming? If you're trying to achieve pixel-perfection in your projects, how much time do you usually spend on this? (E.g. on average per screen?)

答:
Know UIKit classes intimately. If you know the classes in that framework well, you do not spend almost any time researching how to customise them in unusual manner.

Master CoreGraphics/Quartz2D. This will help you to deal with unusual or dynamically changing shapes.

Work purely in vector domain, no bitmaps. 2) helps with that a lot. With all the form factors for iOS nowadays (and iPad Pro 12inch is coming, you can't afford to work with bitmaps anymore..)

Master custom control design patterns. Sometimes it's better to implement a custom UI control than fighting UIKit stuff.

Learn the fundamentals of UI/UX design. If you know them, you can easily identify whether the designer made an honest mistake (not paying attention, mouse click error,..etc.) or he/she had a horrible idea that must avoided at all cost :), or he/she is doing a sloppy job and yours is to smooth things out as it is the path of least resistance.

Educate your designer about limitations of iOS platform that have some consequence on design approach, tell him/her to throw Photoshop to the bin and start using Sketch and PaintCode. Teach him/her to prototype so that you guys do not have a long feedback cycle. Teach him/her to internalise the concept of points. Print out a big wallpaper with screen sizes (in points) for all iOS devices. Make him/her promise to never position anything in between points.

Debug Views in runtime, commercial solutions are still a bit better than XC6 view debugging.

Use Xscope to measure visual elements on your simulator screen in many different ways (distance, size, ratios, alignments..etc..)

Save time be being a really good developer when working on business logic and use that saved time to polish things on presentation layer.

Identify stakeholders (managers, product owners, customer representatives) who understand why a finished product means a product with no visual deficiencies. When there is time squeeze, they will protect you.

Do not optimise for iPhone6+; it is impossible. Hopefully Iphone6S+ will get rid of that hardware downsampling and will have physical pixels matching 3x logical points. (In the meantime you can envy Metal/OpenGL developers as they have access to physical pixels on screen.)

Find an employer that values pixel-perfect. They will allocate more time to that officially.

Pixel-perfect takes time. There is a dominant public opinion trend in programming circles lately that uses terms like "lean", fail quickly, you are "paid for features". etc..etc..for people that value the aesthetic aspect of product, it is pain and suffering. Often delivering a pixel-perfect level of polish to the product borders on semi-illegality and you will sacrifice some overtime for the cause as a last resort.

So to sum this up, the solution is not to be able to click with mouse more quickly doing all the things you did until today, but to apply qualitative improvements in your tooling & work processes and programming know-how.

Title: pixel perfect apps techniques

ContentLicense: CC BY-SA 4.0


答:
Building Pixel Perfect UI is both an Art and Science. Having the right tools makes the science part easy.

Take a look at QuickLens, a Mac App to help UI Designers/Developers to be true to the Visual Design. It provides a Modern, feature-rich interface, at a very affordable price. Use QuickLens to magnify an area, sample colors, export to Photoshop/Html, measure distances, angles, check alignments and much more.

In addition to visual crispness, you also have to care about the overall User Experience.
It takes lot of patience and tireless iteration to achieve that.

Take inspiration from well-designed apps

Here is a nice article about the rules of good App Design

Read blogs, newsletters such as objc.io which cover the technical aspects of App Design

Experiment a lot

Fail early, Fail often

Take feedback from potential users. It will help shape your app.

Most importantly: Have Fun building your App

Title: pixel perfect apps techniques

Body:
While doing your iOS app development, do you try to achieve pixel perfect similarity? Is your app identical to provided photoshop designs?

If yes, what techniques are you using to speed this process up? I find it really time-consuming, since:

I'm using a lot of custom component which aren't displayed in interface builder.

Text field boundaries size are different in XCode and Photoshop. So I can't just copy position.

Some of the properties are not easily modify-able. I've got a lot of custom-sized buttons, and changing text baseline is difficult

etc...

I'm aware about tools like Reveal or SparkInspector - they speed things up, but it's not a dramatic boost for me. I know also that with XCode 6 you can use IBDesignable. I'm stucked with 32bit app right now, so I can't use it yet (and not sure how useful is it).

So, is it really so time consuming? If you're trying to achieve pixel-perfection in your projects, how much time do you usually spend on this? (E.g. on average per screen?)


问:
Are there any benefits of using this extra variable in the for loop annotation?
I have found the following loop annotation in a big project I am working on (pseudocode):

```<code>var someOtherArray = [];
for (var i = 0, n = array.length; i < n; i++) {
    someOtherArray[i] = modifyObjetFromArray(array[i]);
}
</code>```

What brought my attention is this extra "n" variable. I have never seen a for lop written in this way before.

Obviously in this scenario there is no reason why this code couldn't be written in the following way (which I'm very much used to):

```<code>var someOtherArray = [];
for (var i = 0; i < array.length; i++) {
    someOtherArray[i] = modifyObjetFromArray(array[i]);
}
</code>```

But it got me thinking.

Is there a scenario when writing such a for loop would make sense? The idea comes to mind that "array" length may change during the for loop execution, but we don't want to loop further than the original size, but I can't imagine such a scenario.

Shrinking the array inside the loop does not make much sense either, because we are likely to get OutOfBoundsException.

Is there a known design pattern where this annotation is useful?

Edit
As noted by @Jerry101 the reason is performance.
Here is a link to the performance test I have created: http://jsperf.com/ninforloop. In my opinion difference is not big enough unless you are iterating though a very huge array. The code I copied it from only had up to 20 elements, so I think readability in this case outweighs the performance consideration.

答:
The variable n ensures the generated code doesn't fetch the array length for every iteration.

It's an optimization that might make a difference in run time depending on the language used, whether the array is actually a collection object or a JavaScript "array", and other optimization details.


问:
Why is the Document Object Model the view?
I was told by a Javascript programmer not to do DOM manipulation in model code.

I also remember hearing a snazzy tune for a JS framework (I forget which one): "Get your models out of the DOM".

This is confusing to me. The DOM is the Document Object Model. To me it sounds like "get your model out of the model".

Should my JS model really not touch the DOM? Can someone set me straight on model v. model?

答:
There are a lot of overloaded terms in programming. The "model" in Model-View-Controller has nothing to do with the "model" in Document Object Model.

Arguably the DOM should have been called something like the Document Manipulation Interface, since that's what it actually is: an interface. More importantly, it's an interface for manipulating the content that gets shown directly to the user. In MVC, any code that shows things to the user should be in a View.

It's entirely correct to say that your MVC model should not be manipulating the DOM, for the same reason it shouldn't be generating popups or playing sounds: We want to keep the business entities (models) decoupled from the presentation logic.


答:
The fetching of the length of the array can easily be "more expensive" then the actual action you iterate over.

So if the set doesn't change, only query the length once.

Not with arrays, but with record-sets coming from an sql server I've seen dramatic improvements by not querying the record-count every iteration. (of-course do this only if you can guarantee you array or record-set doesn't get changed during this process).

Title: Are there any benefits of using this extra variable in the for loop annotation?

Body:
I have found the following loop annotation in a big project I am working on (pseudocode):

```<code>var someOtherArray = [];
for (var i = 0, n = array.length; i < n; i++) {
    someOtherArray[i] = modifyObjetFromArray(array[i]);
}
</code>```

What brought my attention is this extra "n" variable. I have never seen a for lop written in this way before.

Obviously in this scenario there is no reason why this code couldn't be written in the following way (which I'm very much used to):

```<code>var someOtherArray = [];
for (var i = 0; i < array.length; i++) {
    someOtherArray[i] = modifyObjetFromArray(array[i]);
}
</code>```

But it got me thinking.

Is there a scenario when writing such a for loop would make sense? The idea comes to mind that "array" length may change during the for loop execution, but we don't want to loop further than the original size, but I can't imagine such a scenario.

Shrinking the array inside the loop does not make much sense either, because we are likely to get OutOfBoundsException.

Is there a known design pattern where this annotation is useful?

Edit
As noted by @Jerry101 the reason is performance.
Here is a link to the performance test I have created: http://jsperf.com/ninforloop. In my opinion difference is not big enough unless you are iterating though a very huge array. The code I copied it from only had up to 20 elements, so I think readability in this case outweighs the performance consideration.


问:
Git, semantic versioning and how it fits into (my) a typical development timeline?
I'm working on a Q&A system and about to tag my current application with "1.0.0" for it's first official version/tag. It's about to be rolled out for beta testing to a limited test audience next. Is "1.0.0" correct at this stage?

Also, no doubt there will be many bugs found at that stage. Do I keep it as "1.0.0" but forcefully moving the tag until it's release. Or upon fixing the bugs, would I give it a new tag "1.0.1". Then after another round of testing perhaps "1.0.2"

So when working on enhancements (e.g. new features such as a new menu, new search input field) would these be minor changes as in from "1.0.0" to "1.1.0"?

答:
Yes, update the version number all the time it moves out of your control and into someone else's.

the reason is you need ot know what they were working with. When test comes back and says"we found a bug in version 1.0.0", the last thing you want is to say "which version 1.0.0, the one we gave you on Monday or the updated one I gave you on Friday?"

Updating the 3rd number is really designed for this, the functional difference between 1.0.0 and 1.0.999 should be limited, when you add big new features, then you update the 2nd number. Though, adding a new search input field doesn't really count as a big enough change to warrant a 2nd number update, but YMMV.

Personally, I tend to use the 2nd number not so much for feature updates but to mark a "full release", ie one that has been through test and passed. Then I update that value and repeat the back-and-forth between dev and test, incrementing the 3rd number each time until it all passes.


问:
How do I organizing 2 different projects with shared code
I know there have been same question asked multiple times on the programmers stackexchange. I think my question is more specific and hence decided to start a new question.
My current a project which has models, views and libraries (front-end and back-end both). My project directory structure looks something like:

```<code>/php/libs/emailLib
/php/libs/serviceLib
/php/libs/databaseLib
/php/services/Service1
/php/services/Service2
/php/services/Service3
/php/services/Service4
/js/module2
/js/module1
/models/Model1
/models/Model2
/models/Model3
</code>```

I have been using git to source control the current project. Now I'm about to start a new project which is independent of the current one but lot of code is which can be shared between new and the current project. I'm creating another repository for the new project. For libraries I can create a git submodule for libraries /php/libs. But the services are like few of them can be only be shared like service for translation can be shared but service for service for generating categories can't be shared (because my new project does not have anything to do with categories).

How do I share the services? And there are few other such folders/programs(where only few of them shared among all).

答: Have you considered to use branches? It sounds like you are not going to work on both projects at the same time. You can branch out the second project from the first one and if there is anything you'd like to move to your first project, then you can merge your changes.</p>


问:
REST request of different length
When a client requests my .../resources/user URL with a HTTP GET I get the following response:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<collection>
    <User id="5">
        <Password>DC647EB65E6711E155375218212B3964</Password>
        <FirstName>Super</FirstName>
        <LastName>Admin</LastName>
        <Role id="4">
            <Description>Default Guest Role</Description>
            <Group id="2">
                <Description>Default Guest Group</Description>
                <Name>GuestGroup</Name>
            </Group>
            <Name>Guest</Name>
        </Role>
        <Role id="3">
            <Description>Default Super Admin Role</Description>
            <Group id="1">
                <Description>Default Admin Group</Description>
                <Name>AdminGroup</Name>
            </Group>
            <Name>SuperAdmin</Name>
        </Role>
        <Username>superadmin</Username>
    </User>
    <User id="6">
        <Password>DC647EB65E6711E155375218212B3964</Password>
        <FirstName/>
        <LastName>Guest</LastName>
        <Role id="4">
            <Description>Default Guest Role</Description>
            <Group id="2">
                <Description>Default Guest Group</Description>
                <Name>GuestGroup</Name>
            </Group>
            <Name>Guest</Name>
        </Role>
        <Username>guest</Username>
    </User>
</collection>
</code>```

For data transport efficiency purposes I would also like the client to be able to request a short version of this response. Something like:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<collection>
    <User id="5">
        <Password>DC647EB65E6711E155375218212B3964</Password>
        <FirstName>Super</FirstName>
        <LastName>Admin</LastName>
        <Role id="4" />
        <Role id="3" />
        <Username>superadmin</Username>
    </User>
    <User id="6">
        <Password>DC647EB65E6711E155375218212B3964</Password>
        <FirstName/>
        <LastName>Guest</LastName>
        <Role id="4" />
        <Username>guest</Username>
    </User>
</collection>
</code>```

What is the best way to identify a full and a short request from the client and why? Client technology should be agnostic. Server technology is Java EE 7

A few options I thought of myself:

Sub level webservices like .../resources/user/short

Different webservices like .../resources/user2

Use a custom HTTP parameter lik Accept-Length : Short

Use the HTTP request field Expect : Short

答:
My view is that the client is requesting a different representation of the resource i.e. a short one.

When you request a different representation (like json or xml) this normally gets tagged at the end of the resource e.g. /some/resource.json, /some/resource.xml

So you could take the same logic and do something like /some/resource.short.json

Title: REST request of different length


问:
Tips for understanding big project fast?
I've got a job and many new things to be learned. The first thing is to understand big project, writtened mostly in C++, using Visual Studio. So, I see a statement, and I want to find its definition. Using Ctr+F to search through entire solution, and if multiple libraries have different function but same name, I would have many result that I don't know which one is the definition of the statement. And vice versal, I see a definition, but I don't know which statements are its invoker.

Is there any tips for my issue? Any suggestion is very appreciated. Thanks (And please, I don't want to go to debug mode, since It takes lot of time to build, and I'm lazy rofl).

答:
You could try with a tool like doxygen.

I find it useful when I start to work on a new codebase.

Just tweak some parameter in the configuration file and run doxygen against your code. For your needs you could change:

CALL_GRAPH = YES. A graphical call graph is drawn for each function showing the functions that the function directly or indirectly calls

CALLER_GRAPH = YES. A graphical caller graph is drawn for each function showing the functions that the function is directly or indirectly called by

Probably also:

EXTRACT_ALL = YES, HAVE_DOT = YES, UML_LOOK = YES to generate a class diagram (see Graphviz + doxygen to generate UML class diagrams).

The nice things is that even if the documentation isn't already available, you can extract a lot of useful information (and while learning you could start documenting the code).

Anyway it takes time.


问:
How to implement the repository pattern for an app that will change its database from sql to nosql on in couple of years?
I have been reading a lot about repository implementation. I am confused about which way to implement it for a project I am sure would change its data layer methods because of db migration from MS Sql Server to NoSQL in a couple of years.

Imp #1

Implement Rep layer as a completely separate layer. This will have
its own interface and conversion methods here. This rep layer has a
dependency on DAL and in turn BLL will have a dependency on this
layer

Imp#2

Implement Repository not as a separate layer but have its interfaces
in Business Logic Layer and the methods in DAL.

I am leaning more towards imp #1 since it looks cleaner. However some explanations of experts I have read use imp#2. I think there must be a clear reason to use one over another according to the situation. I would ideally want our switch to a different database be as painless as possible.

答:
Sticking to option 1 will allow you to change the least amount of things when you switch from one database to another, thus the change should have the least impact on your application since only the files concerned with the database will need to be changed.

The business layer and any other layer which does not deal with the database should not care, nor know any implementation details. Thus, when you mention that ...and in turn BLL will have a dependency on this layer I am assuming that you would have a series of interfaces, such as IUserRepository or something like that which will define methods such as GetUserByName(string name), etc.

Layers on top of the repository will then consume these interfaces to suit their data needs, this would allow the business layer to know what the repository layer provides, but it will not include any implementation details. Thus, when you make the change, as far as the business layer is concerned, nothing is changed (assuming that you do not make any changes in the functionality provided by the repository layer).


答:
Maybe you could create a third project on your source control, which contains only the shared libraries. So in short, your other two projects will reference this shared group of source files.

This would allow you to have a group of shared libraries which are self contained, and are not stored within the context of another project. This assumes that you want to propagate any changes you make in the shared services of one application to another.

If the above is not the case (you might want to do per project customizations), you could still create the third project as a shared structure, but once that you will have checked out your shared code, you would then include it with the current project and check it into its own repository. This would disconnect the shared code from its repository and would allow you to make per project customizations.

If you see that certain features are being inserted into multiple projects, you could then edit your Vanilla shared folder structure and add the new files. This way, any new project which you will create will now have access to the new functionality without affecting your older project.

Title: How do I organizing 2 different projects with shared code

Body:
I know there have been same question asked multiple times on the programmers stackexchange. I think my question is more specific and hence decided to start a new question.
My current a project which has models, views and libraries (front-end and back-end both). My project directory structure looks something like:

```<code>/php/libs/emailLib
/php/libs/serviceLib
/php/libs/databaseLib
/php/services/Service1
/php/services/Service2
/php/services/Service3
/php/services/Service4
/js/module2
/js/module1
/models/Model1
/models/Model2
/models/Model3
</code>```

I have been using git to source control the current project. Now I'm about to start a new project which is independent of the current one but lot of code is which can be shared between new and the current project. I'm creating another repository for the new project. For libraries I can create a git submodule for libraries /php/libs. But the services are like few of them can be only be shared like service for translation can be shared but service for service for generating categories can't be shared (because my new project does not have anything to do with categories).

How do I share the services? And there are few other such folders/programs(where only few of them shared among all).


答:
The main reason you would have the interfaces for your repositories in your BLL is to avoid having hard references to the separate DAL but instead have your changing DAL reference the stable BLL.

To be able to swap out implementations without changing the stable BLL

On the internet this might not be the main reason in general, but this would be a compelling reason for me to prefer option 2 in your situation.

Let's assume that you are using a DI (dependency injection) container. If you configure this using a configuration file, for example, you would tell the container that the implementations for the repository-interfaces in the BLL can be found in the DAL.Sql project. Once you switch over to a NoSQL solution you would create the DAL.NoSQL project, deploy it and change the DI container configuration to resolve the implementations of the repository from the new project. Your new DAL depends on the stable BLL that does not need to change.

However, if you go with option 1, you might not be able to hot-swap the DAL project. If you use .NET for example you could run into issues where the BLL project depends on a certain version of the DAL dll and you would not be able to swap out the DAL without changing the BLL as well.

Because the repository interface is part of the BLL

A repository is merely a gateway that defines how your application will retrieve data. In that sense it is as much a part of the business logic as your domain objects. The concrete implementations can change, but the interfaces themselves are part of your business logic.

Because it isolates the BLL

Having the interfaces and implementations in the DAL means bringing all of the DAL into the BLL. There is nothing preventing developers from using objects from the DAL project in ways that they shouldn't be used. Having the DAL depend on the BLL means the BLL can only contain the interfaces that it needs.

To avoid a separate project with the domain objects

Your DAL and BLL both depend on your domain objects. If your BLL has a class that uses a repository and a domain object, you cannot put your repository interfaces into the DAL as that creates a circular reference (BLL needs interface for repository in DAL, DAL needs domain objects in BLL). So you would have to split the BLL and the domain objects into two projects so your BLL can reference the domain and the DAL and the DAL can also reference the domain.

Title: How to implement the repository pattern for an app that will change its database from sql to nosql on in couple of years?

Body:
I have been reading a lot about repository implementation. I am confused about which way to implement it for a project I am sure would change its data layer methods because of db migration from MS Sql Server to NoSQL in a couple of years.

Imp #1

Implement Rep layer as a completely separate layer. This will have
its own interface and conversion methods here. This rep layer has a
dependency on DAL and in turn BLL will have a dependency on this
layer

Imp#2

Implement Repository not as a separate layer but have its interfaces
in Business Logic Layer and the methods in DAL.

I am leaning more towards imp #1 since it looks cleaner. However some explanations of experts I have read use imp#2. I think there must be a clear reason to use one over another according to the situation. I would ideally want our switch to a different database be as painless as possible.


问:
RESTful Api: Send email with links to client URL
A client can call the following REST api URI to send an enquiry

```<code>POST /v1/businesses/{business_name}/enquiries
</code>```

The enquiry can then be viewed through the following call:

```<code>GET /v1/businesses/{business_name}/enquiries/{enquiry_id}
</code>```

When a new enquiry is posted, the business is informed via email. The email includes a link to the enquiry. The issue I have is that the API will add the following link to email:

```<code>http://api.com/v1/businesses/{business_name}/enquiries/{enquiry_id}
</code>```

When a user clicks the link in the email, they will be incorrectly taken to the API resource instead of the client page. So I need the email to contain the following link:

```<code>http://client.com/dashboard/{business_name}/enquiries/{enquiry_id}
</code>```

Noted: Above client URL is an example. Clients can implement their own routing however they want, a single page client app URL could also be used. The point is, the client URL must be exposed in the email, not the API URL.

I'm not quite sure how to get client URLs into the email.

One option would be to provide a client URL in the original POST request. Problem with this is that the client won't know the URL to use until after the POST, at which point the email has already been added to the queue.

Another option is to pull out the queueing of emails from the API and make the clients responsible for it. I don't really like this idea as client implementers will not be too happy that they purchased the API, only to then find out they then have to decide when to queue emails.

答:
Terms:

```<code>USER = end user of your client
CLIENT = your client
API = your server
</code>```

Your example urls:

POST /v1/public/{business_name}/enquiries
  GET /v1/businesses/{business_name}/enquiries/{enquiry_id}

Don't do access control in your urls. One resource one url is most simple for your customers to understand.

Also:

A client can call the following REST api URI to allow an unauthenticated user

The fact that the end user is unauthenticated does not mean the client is unauthenticated.

So let's say that your enquiry gets posted:

```<code>USER sends post to: client.com/some/custom/path/enquiries
CLIENT receives the post post
CLIENT authenticates to the API
CLIENT sends post data to your API
  OR CLIENT sends post data + path to your API (path could be: client.com/some/custom/path/enqueries/{id} as an url template)
API receives the post
  IF no url is supplied lookup the client url in the database)
API inserts in database
API returns to CLIENT: {success: 1, url: 'http://api.com/enquiries/123'}
  OR API returns to CLIENT: {success: 1, url: 'http://api.com/enquiries/123', clientUrl: 'http://client.com/enqueries/123'}
CLIENT RECEIVES the response
CLIENT sends response back to USER ("Thanks for your enquiry" OR "You did not fill out a required field")
API adds e-mail to the queue, it knows the url from the post OR from the settings in the database for this client.
</code>```

This way you can also customise the e-mails more because they can contain a logo, business name of your client etcetera.

EDIT
Good to see the question improved!

After reading your question again here you seem to get stuck:

One option would be to provide a client URL in the original POST request. Problem with this is that the client won't know the URL to use until after the POST, at which point the email has already been added to the queue.

I thought this maybe needs a bit more clarification.

First rule in your business case is:

You want to send a link via e-mail to the client domain. Only the client knows the domain.

That explicitly requires the the client let's the API know the domain, otherwise it cannot perform the send e-mail action. Agree on that?

I am not sure whether you are known with URL templates, an example is this:

```<code>https://client.com/some/custom/path/enqueries/{id}
</code>```

Example here: https://github.com/mikekelly/hal_specification/blob/master/hal_specification.md#applicationhaljson

So the client does not give you the full URL but a template which you parse in your API. You agree upfront on the variables which can be used.

That means you have 2 options:

Client sends you the domain upfront. For example at the moments:

When the client signs up for your API service
You can do this via your registration form or configuration panel for example.

When the client logs in

Just in a separate request

Client sends you the domain with the request.

JSON
{
  urlTemplate: 'https://client.com/some/custom/path/enqueries/{id}',
  enquery: {
    name: 'test',
  }
}

You have to accept that the client needs to let you know the url if it's custom. You cannot magically find it.

You have multiple options to receive it, just select what's best for you.

Body:
Terms:

USER = end user of your client
CLIENT = your client
API = your server

Your example urls:

POST /v1/public/{business_name}/enquiries
  GET /v1/businesses/{business_name}/enquiries/{enquiry_id}

Don't do access control in your urls. One resource one url is most simple for your customers to understand.

Also:

A client can call the following REST api URI to allow an unauthenticated user

The fact that the end user is unauthenticated does not mean the client is unauthenticated.

So let's say that your enquiry gets posted:

USER sends post to: client.com/some/custom/path/enquiries
CLIENT receives the post post
CLIENT authenticates to the API
CLIENT sends post data to your API
  OR CLIENT sends post data + path to your API (path could be: client.com/some/custom/path/enqueries/{id} as an url template)
API receives the post
  IF no url is supplied lookup the client url in the database)
API inserts in database
API returns to CLIENT: {success: 1, url: 'http://api.com/enquiries/123'}
  OR API returns to CLIENT: {success: 1, url: 'http://api.com/enquiries/123', clientUrl: 'http://client.com/enqueries/123'}
CLIENT RECEIVES the response
CLIENT sends response back to USER ("Thanks for your enquiry" OR "You did not fill out a required field")
API adds e-mail to the queue, it knows the url from the post OR from the settings in the database for this client.

This way you can also customise the e-mails more because they can contain a logo, business name of your client etcetera.

EDIT
Good to see the question improved!

After reading your question again here you seem to get stuck:

One option would be to provide a client URL in the original POST request. Problem with this is that the client won't know the URL to use until after the POST, at which point the email has already been added to the queue.

I thought this maybe needs a bit more clarification.

First rule in your business case is:

You want to send a link via e-mail to the client domain. Only the client knows the domain.

That explicitly requires the the client let's the API know the domain, otherwise it cannot perform the send e-mail action. Agree on that?

I am not sure whether you are known with URL templates, an example is this:

https://client.com/some/custom/path/enqueries/{id}

Example here: https://github.com/mikekelly/hal_specification/blob/master/hal_specification.md#applicationhaljson

So the client does not give you the full URL but a template which you parse in your API. You agree upfront on the variables which can be used.

That means you have 2 options:

Client sends you the domain upfront. For example at the moments:

When the client signs up for your API service
You can do this via your registration form or configuration panel for example.

When the client logs in

Just in a separate request

Client sends you the domain with the request.

JSON
{
  urlTemplate: 'https://client.com/some/custom/path/enqueries/{id}',
  enquery: {
    name: 'test',
  }
}

You have to accept that the client needs to let you know the url if it's custom. You cannot magically find it.

You have multiple options to receive it, just select what's best for you.


答:
I recommend against deliberately injecting bugs into EVERY build you send to QA.

You could, from time to time, let's say once a year, do a covert "QA audit". Take a "tested and working" codebase, and as many small new features from your Todo list as possible. Implement them "a bit more sloppily" than you usually do. Think of the edge cases, write them down, but don't fix your code to take them into account. Send it off to QA.

If they find more non-working edge case bugs than you wrote down, it's certainly not your QA that needs supervision... ;-)

Title: Leaving intentional bugs in code for testers to find

Body:
We don't do this at our firm, but one of my friends says that his project manager asked every developer to add intentional bugs just before the product goes to QA. This is how it works:

Just before the product goes to QA, the development team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.

Testers are also informed about this. So they will test hard,
because they know there are bugs present and that not finding them might
be considered as a sign of incompetence.

If a bug (intentional or otherwise) has been found, they will be reported for the development team to fix. The development team then adds another intentional bug in a related section of the code just before the product goes to the second-level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.

Well, this is how it goes. They say that this approach has following advantages.

Testers will be always on their toes and they will test like crazy.
That helps them to also find hidden (unintentional) bugs so developers
can fix them.

Testers feed on bugs. Not finding any bugs will affect their morale.
So giving them an easy one to find will help their morale.

If you ignore the scenario where one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?

Some clarifications:

They properly backup the original code in source control.

When a tester finds the intentional bug, the development team just ignores it. If tester finds out an unintentional (original) bug, the development team first checks whether it is caused by any of the intentional bugs. That is, the development team first tries to reproduce that on the original working code and tries to fix it if they can.

Just ignore the relationship issues between QA and development team. I specifically asked this question on Programmers, not on The Workplace. Consider that there is good rapport between QA and the development team, and they party together after working hours. The project manager is a nice, old gentleman who is always ready to support both teams (Godsend).