问:
Should the Presenter depend on the View or the vice versa?
So far, I have used the MVP architecture pattern a few times. Every now and then, I wonder whether my Presenter should depend on my View or vice versa, that is the View depends on my Presenter.

NOTE

Though the sample code provided is in C#, I don't mind about the language. My question targets more precisely the MVP pattern. Additionally, it was provided off the top of my head solely to help illustrate my concern. It may not compile.

Here's a short sample of what I'm used to do:

```<code>public interface IHasUiHandler<H> where H : IUiHandler {
    H Handler { set; }
}

public interface IView {
    void Close();
    void Hide();
    void Show();
}

public abstract class Presenter<V> where V : IView {
    protected Presenter(V view) { this.view = view; }

    public void CloseView() { view.Close(); }
    public void HideView() { view.Hide(); }
    public void ShowView() { view.Show(); }

    private readonly V view;
}
</code>```

And let's say I'm creating a Customer Management feature.

```<code>public interface ICustomerManagementUiHandler : IUiHandler {
    Customer CreateNewCustomer();
    IList<Customer> ListCustomers();
    void RemoveCustomer(Customer customer);
    Customer UpdateCustomer(Customer customer);
}

public class CustomerManagementPresenter : Presenter<ICustomerManagementView>
                                         , ICustomerManagementUiHandler {
    public CustomerManagementPresenter(ICustomerManagementView view
        , CustomerManagementService service)
        : base(view) {
        view.Handler = this;
        customers = service;
    }

    public Customer ChangeExistingCustomer(Customer customer) { return customers.Update(customer); }
    public Customer CreateNewCustomer(Customer customer) { return customers.Add(customer); }
    public IList<Customer> ListCustomers() { return customers.List(); }
    public void RemoveCustomer(Customer customer) { customers.Remove(customer); }

    private readonly CustomerManagementService customers;
}

public interface ICustomerManagementView : IHasUiHandler<ICustomerManagementUiHandler> {
}

public class CustomerManagementForm : Form, ICustomerManagementView {
    public CustomerManagementForm() { }

    public ICustomerManagementUiHandler Handler {
        private get { return handler; }
        set { if (handler == null) handler = value; }
    }

    private void changeCustomerButton_Click(object sender, EventArgs e) {
        if (Handler == null)
            throw new InvalidOperationException("Can't change customer. No handler specified.");
        Handler.ChangeExistingCustomer(current);
    }

    private void createCustomerButton_Click(object sender, EventArgs e) {
        if (Handler == null)
            throw new InvalidOperationException("Can't add new customer. No handler specified.");
        Handler.CreateNewCustomer(); // No parameters for sample simplicity sake.
    }

    private void deleteCustomerButton_Click(object sender, EventArgs e) {
        if (Handler == null)
            throw new InvalidOperationException("Can't add new customer. No handler specified.");
        Handler.RemoveCustomer(current);
    }

    private readonly ICustomerManager manager;
    private ICustomerManagementUiHandler handler;
}
</code>```

I feel like the View should depend on the presenter, so that there would be no need for a Handler property in the View itself. Then the Presenter could depend on the data access service or the like to handle the business entities and the like.

This would wave away the Method Injection, which is a benefit, IMHO. Plus it seems to reduce complexity for waving away both the IHasUiHandler and IUiHandler interfaces. This makes it a easily testable code because the Presenter is an easily-tested class.

However, this way I'm afraid that the Presenter has no real handle over the view which it should be able to either show or hide. So this is where I'm growing confused about which shall depend on which.

答:
Truthfully, it doesn't really matter.

There isn't much difference between a presenter-first design where the presenter subscribes to events on the view (observer pattern) and a view-first design where the view calls methods on the presenter instead of raising those events (potentially using command pattern, such as in MVVM).

So long as you inject an interface of the view into the presenter or an interface of the presenter into the view, they are sufficiently de-coupled.

OwnerDisplayName: Will Marcouiller


问:
Java labels. To be or not to be
Before I start this question I know the java 'goto' is a big no go.

So I've been writing a program and I have some indented Loops and statements and I need to BREAK multiple on command. Rather than having a load of boolean variables and if(!<booleanName>) BREAK; statements throughout these loops and statements what is everyone's opinions on using labels to break them using the BREAK  statement?

e.g.

```<code> for(...) {

      indented_example_loops:     // Label name
           for(...) {
                for(...) {
                     if(match) break indented_example_loops;
                     // ^ Break statement to break the 2 for loops at once
                }
           }

 }
</code>```

Perfectly okay? Okay to do occasionally? Completely avoid? or should i go to a corner and call the Devil to take my soul?

答:
For very deeply nested loops or complex code flow, I often declare anonymous Runnables. While not directly related to the question, it is still relevant. I'm sure there is a better example than this, but it's a start.

```<code>public int ComplexFunction() {
    final Integer value = new Integer();
    final Boolean quit = new Boolean(false);

    final Runnable doTest = new Runnable() {
        public void run() {
            if (value.intVal() > 100) {
                quit = new Boolean(true);
            }
        }
    }

    while (true) {
        value = new Integer(value.intVal() + 5);
        doTest.run();
        if (quit.booleanVal() == true) {
            return 1;
        }
    }
    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Java labels. To be or not to be

Body:
For very deeply nested loops or complex code flow, I often declare anonymous Runnables. While not directly related to the question, it is still relevant. I'm sure there is a better example than this, but it's a start.

public int ComplexFunction() {
    final Integer value = new Integer();
    final Boolean quit = new Boolean(false);

    final Runnable doTest = new Runnable() {
        public void run() {
            if (value.intVal() > 100) {
                quit = new Boolean(true);
            }
        }
    }

    while (true) {
        value = new Integer(value.intVal() + 5);
        doTest.run();
        if (quit.booleanVal() == true) {
            return 1;
        }
    }
    return 0;
}


问:
What is the purpose of a Code Review
I am in the process of trying to sell my organisation on the value of code reviews.  I have worked at several places where they were employed.  I have seen them used to nitpick styling choices, and functional decisions, and I have seen them used as nothing more than a gut check to make sure nothing dangerous is being implemented.  My gut feeling is that the most effective purpose is somewhere between the two options.

So, what is the purpose of a Code Review?

答:
There are multiple reasons why you would want to conduct a code review:

Education of other developers. Ensure that everyone sees the modification associated with a defect fix or enhancement so that they can understand the rest of the software. This is especially useful when people are working on components that need to be integrated or on complex systems where one person may go for long periods without looking at certain modules.

Finding defects or opportunities for improvement. Both the deliverable code as well as test code and data can be examined to find weaknesses. This ensures that the test code is robust and valid and that the design and implementation is consistent across the application. If there needs to be additional changes made, it catches the opportunity closer to the point of entry.

There are several business cases for conducting reviews:

Finding defects or issues that would need to be reworked closer to their injection. This is cheaper.

Shared understanding of the system and cross-training. Less time for a developer to come up to speed to make changes.

Identification of possible enhancements to the system.

Opening up the implementation to ensure that testers are providing adequate coverage. Turning a black box into a grey box or white box from a testing perspective.

If you're looking for a comprehensive discussion on the benefits of and implementation strategies for peer reviews, I'd recommend checking out Peer Reviews in Software: A Practical Guide by Karl Wiegers.

Title: What is the purpose of a Code Review


答:
Code Reviews are a tool for knowledge transfer.

When developers review each other's code, they gain familiarity across all areas of the system. This reduces a project's bus factor, and makes developers more efficient when having to do maintenance on a part of the system they didn't write.

When a junior programmer reviews a senior's code, the junior programmer can pick up tricks otherwise only learned through experience. This can also work as a corrective against overly complicated code.

A thorough code review will require frequent checks against various documentation. It's a great way to learn a language or API.

When a senior programmer reviews a junior's code, this is an opportunity to iron out issues before they translate into technical debt. A code review can be a good setting for mentoring junior programmers.

Code reviews are not about:

… finding bugs. That's what tests are for. It will still frequently happen that a code review finds some problem.

… nitpicking on style issues – settle for one style, and use automated formatters to enforce it. But there are many things which an automated tool cannot check. Code reviews are a good place to make sure the code is sufficiently documented or self-documenting.

Title: What is the purpose of a Code Review

Body:
I am in the process of trying to sell my organisation on the value of code reviews.  I have worked at several places where they were employed.  I have seen them used to nitpick styling choices, and functional decisions, and I have seen them used as nothing more than a gut check to make sure nothing dangerous is being implemented.  My gut feeling is that the most effective purpose is somewhere between the two options.

So, what is the purpose of a Code Review?


问:
Is this a good Visual Studio solution structure for a domain driven design RESTful web service?
I am building a .NET 4.5 C# Web API RESTful solution and I would like someone to tell me if my project solution is correct and/or wise(-enough?) for a solution designed using Domain Driven Design, please.

The solution has been split into 6 projects:

/Base

(Not referenced by anything)

The web project and forms the interface between the solution and the outside world. Contains the Web API controllers. Contains almost no logic beyond gathering values from request objects and asking the BizApi layer for work.

/Biz.Api

(Referenced by Base])

Provides the domain services and allows the /Base interface project to have access to the domain business logic objects in the /Biz.Domain project.

/Biz.Domain

(Referenced by Biz.Api)

Provides the domain classes for the Biz.Api layer. These provide methods to manipulate the data of the business in memory.

/Dal.Db

(Referenced by Biz.Api)

The database repository layer. Accesses the databases and maps returned data into internal DTO's defined in the /Interfaces layer.

/Dal.Services

(Referenced by Biz.Api)

Provides a proxy layer to external dependencies like web services and maps their returned data to internal DTOs defined in the /Interfaces project.

/Interfaces

(Referenced by most projects above)

Contains the DTO classes for passing data around the solution and the C# interfaces to define contracts for things like IoC.

答:
This folder structure is inspired by the famous Implementing domain driven design book by Vaugh Vernon.

Solution:

├ WebService (REST Services reside here)

├ WebServiceTests

├ Application (Application services reside here)

├ ApplicationTests

├ Domain (Entities, VO, Domain services, domain factories, specifications, domain events, Repositories interfaces, infrastructures services interfaces)

├ DomainTests

├ Infrastructure (Repositories, Infrastructure services impl., Adapters to external services)

└ InfrastructureTests

I start with a Solution then create four projects for each layer in my application then another four projects for each layer tests.

Don't create a folder interfaces or services in your domain layer instead related classes should be grouped by functionality in modules.


问:
Using a zLib like icensed library which has dependencies on LGPL or GPL libs; what license am I able to release my project under?
If I use an Open Source library which is released under a zLib like license, but it has dependencies on libraries that are using LGPL or GPL; what license am I able to release my project under?

If I read things I find on the net it sounds like I can sell my project but I can't stop people from distributing it freely as per GPL?

答:
If libX has hard dependencies on a GPL library, then it cannot be distributed under a permissive/non-copyleft license like zLib.  Better check that the library in question has their licensing in order.

Either way, if your code depends (transitively) on GPL, you have to abide by those terms.  Selling is allowed, but the user must be provided source and allowed to redistribute, etc.


问:
What is the largest size a HashSet or TreeSet be?
So I am working on a solo project that involves a lot of strings. In one of my smaller test cases there will be at least 70 million elements. So my question is, what is the largest possible size a TreeSet or a HashSet can reach until it can no longer grow OR until it reaches a size that it can no longer be feasible to use in terms of efficiency.

答:
If just allocating objects for your smaller test cases are using several GB of RAM, and many small objects, you are right to worry about your larger cases.

I would sit down and think carefully about your data needs for a larger test case.  If it is pushing what you are comfortable with, I would radically restructure your program.  For inspiration, read http://research.google.com/archive/mapreduce.html and think through how to implement a toy version using the standard Unix sort utility.  (Warning, you need to set the locale to C for it to Do The Right Thing.)

I have personally written programs that used "toy" versions like that to process billions of data points on a single machine in a matter of hours.  If you have a real cluster available to you with something like Hadoop, then the only limit is the size of your cluster.  (With AWS available to you, that is entirely a question of how much you want to spend.)

If you wind up "at internet scale", remember that the key to scalability is to do a map-reduce to map data from one distributed data store to another.  That way there is fault-tolerance everywhere (in your data store and in your map-reduce framework) and no bottlenecks.  What you never, ever, want to do is collect data on a single machine.

Admittedly this involves completely rethinking your program.  But if you'll need to EVENTUALLY, might as well do it now when that is less work!


问:
Anonymous access to api REST, protection
I have a public website that does not require authentication. It's a lighting calculator  for indoor cultivation. Anyone can enter and complete the process and ultimately save your settings for future use sharing it on Facebook or twitter.

The configuration is saved as a document in a database, using a REST api. At this time nothing prevents someone make a bot and fill my hard disk in a few hours.

What steps can I take to give protection to my service?

答:
Add a limit per ip / browser as a start and also a slowdown for the whole site. So if you get more > 150% of the normale amount of requests (in total) add a time limit which stops the requests. Let the user wait until the next minute for example. That will stop it.

https://stackoverflow.com/questions/12449538/http-response-code-for-please-wait-a-little-bit

So if you are over the limit send a 503 error. That saves your server. Then in javascript get the response code, understand it, and show the user a timer.

If others use it at their website you can also get a get from your rest api and include it in the page. Like a session id. That way you can block everyone who did not come from the website at first. Making it more complex because they need to do 2 requests.


问:
Is it ever OK for a conditional to have side effects?
I'm taking intermediate data structures course as a prereq for entry into the CS MS program at a University everyone in America has heard of. One line of code that was written in class caught my eye:

if (a > 33 | b++ < 54) {...}

This would not pass a code review at my workplace. If you wrote code like this in an interview, this would be a significant strike against you. (In addition to being a conditional with side effects, it's being clever at the expense of clarity.)

In fact, I've never seen a conditional with side effects, and Googling doesn't turn up much, either. Another student stayed behind after class to ask about it, too, so I'm not the only one who thought this was weird. But the professor was pretty adamant that this was acceptable code, and that he would write something like that at work. (His FT job is as a Principal SWE at a company you've all heard of.)

I cannot imagine a world in which this line of code would ever be acceptable, let alone desirable. Am I wrong? Is this OK? What about the more general case: conditionals with side effects? Are those ever OK?

答:
Though really smelly code, it has the advantage of being simpler (and maybe faster if you don't have a good optimizing compiler) than the equivalent
if (a > 33 | b < 54) {b++; ...} else b++;

but of course it is possible to optimize it to the following (but watch out! this one has different behavior in case of overflow!):
b++; if (a > 33 | b < 53) {...}


问:
C++ : Association, Aggregation and Composition
I'm beginning to study OOAD and I'm having difficulty finding a C++ code example that'd illustrate how Association, Aggregation and Composition are implemented programmatically. (There are several posts everywhere but they relate to C# or java). I did find an example or two, but they all conflict with my instructor's instructions and I'm confused.

My understanding is that in:

Association: Foo has a pointer to Bar object as a data member

Aggregation: Foo has a pointer to Bar object and data of Bar is deep copied in that pointer.

Composition: Foo has a Bar object as data member.

And this is how I've implemented it:

```<code>//ASSOCIATION
class Bar
{
    Baz baz;
};
class Foo
{
    Bar* bar;
    void setBar(Bar* _bar)
    {
        bar=_bar;
    }
};

//AGGREGATION
class Bar
{
    Baz baz;
};
class Foo
{
    Bar* bar;
    void setBar(Bar* _bar)
    {
        bar = new Bar;
        bar->baz=_bar->baz;
    }
};

//COMPOSTION
class Bar
{
    Baz baz;
};
class Foo
{
    Bar bar;
    Foo(Baz baz)
    {
        bar.baz=baz;
    }
};
</code>```

Is this correct? If not, then how should it be done instead? It'd be appreciated if you also give me a reference of a code from a book (so that I can discuss with my instructor)

答:
There are multiple ways to map the OO concepts of association, aggregation and composition to C++ code. This is especially true for aggregation, because there is not even a consensus what it exactly means.

Your mapping suggests the following semantics, which are not wrong:

Association: Foo has a pointer to Bar object as a data member, without managing the Bar object -> Foo knows about Bar

Composition: Foo has a Bar object as data member -> Foo contains a Bar. It can't exist without it.

Aggregation: Foo has a pointer to Bar object and manages the lifetime of that object -> Foo contains a Bar, but can also exist without it.

As stated, aggregation is the difficult one here because, even within UML, the meaning of aggregation is not crystal clear. Another possible meaning of aggregation is "Foo contains a Bar object that is shared with other objects." This would typically be represented in C++ code by means of a std::shared_pointer or boost::shared_pointer.

Which meaning your instructor attaches to aggregation must be discussed with him.


问:
Entity design for a blackjack game - should I make Card an entity?
I am creating a simple blackjack game backed by database

In my Card is

```<code>public class Card{
 private Face face;
 private Suit suit;

 //setters.. getters
}
</code>```

where face and suit are enums

I have an entity Bet with the following

```<code>@Entity
public class Bet{
   private Player player;
   private String cards;
   //...
}
</code>```

Currently when I'm dealing cards I parse the suit and face to string and concatenate them in the cards field and then parse the cards if I want to calculate the score. I find this cumbersome so I want to change my field "cards" to List in the Bet Entity.

Now, if that's the case I would have to make the Card class an entity as well. But my cardService, which is where I get my cards, does not rely on the database, it just creates random cards so it does not make sense to make card an entity - am I right?

答:
A card is a value, not an entity.

Cards do not have identity -- if the pack contains two cards with the same value it is of no interest to identify them separately. They only have value.

Programming languages tend to provide values like integer, string and struct. You need to pick one of those to represent the value of a card. I would suggest using integer for the value, and write a class that can convert that integer to and from string or image representation, and to return the rank, suit and order (which may not be the same as the integer order).

Then your generator simply generates integers within a specified range.

The usual deck of cards contains 53 distinct cards, including a Joker. There are games (500) that have up to 63 distinct cards but the principle is the same, and an integer is a perfectly convenient way to encode the value. I would use that in the database too.

For a hand or a deal you have multiple cards, up to 13 in Bridge or 52 if you want to keep a complete deal. You could encode that as a space-separated list of integers or some other way, depending on what you need. That's getting off the original point.

For clarity, I do not suggest for a moment that one should use actual integers in the code to represent cards. In Java or JavaScript I would use a class, in C# or C++ a struct. The problem is that an object has identity but we want to deal with values. We want two different card objects that have the same value to compare equal. The simplest way (but not the only way) to do that is for the card object to contain an integer so that two cards with the same integer value are the same value. This is done by implementing a 'Compare Equal' operator in the class that compares the integer value.

This is a subtle issue, the representation of value types, and not easily addressed with an audience of widely different skills.


问:
How do you make sure a .net client application is not being hacked to bypass authorization claims?
We wrote a simple .NET (C#) desktop application in Wpf. We also used WIF (Windows Identity Framework) to get a list of claims for the authenticated user. Some examples are:

CanOverrideSalesAmount

CanAddContact

etc.

This works fine and all, the client seems very protected. But, when I was debugging the application it occurred to me that all of the authorization is happening on the client side. A devious person could use a tool such as Snoop to hook into the application and make changes to the domain model that s/he isn't supposed to do.

We thought about moving the authorization checks on the property setters, but even that isn't good enough because when we serialize the object graph to send over the wire, the serialized data can be altered (far fetched, but still possible).

It seems to me that the only true way to protect my object graph is to have it only reside on the server and to have the client make calls to update it, but that seems like such an overkill. Is there a better way to handle this situation? I want our application to be as secure as possible.

答:
Firstly, you should sign the assembly so users cannot tamper with it - Microsoft signs and secures its assemblies in the GAC to prevent hackers tampering with them. You should do the same.

That prevents someone from modifying your assembly using some binary editor, though you will also have to cater for them replacing your assembly completely. Ensure you obfuscate your assembly to make decompliation harder.

You also have to secure the communications channel to the server, or anyone could install wireshark to inspect the packets being sent and then replicate the auth sequence with their own, slight, modifications. You see this occurring all the time on naively written game servers, some people suddenly acquire more game resources because they've spoofed the network messages to tell the server they've "paid" for a massive boost, honest. (and such flash-style games tend not to be written by people familiar with enterprise security).

Network security is quite simple in this day of SSL comms.

You can also improve your communications by using a secure token system (eg Kerberos or similar - do not try to roll your own) that is sent with each message to the server to ensure the message is coming from a properly authenticated user. This stops any user from simply replaying messages outside your application.

Its still possible to be hacked after this, but these steps make you reasonably secure.


答:
As far as the structure, it seems OK to me although I would have come up with different, more self-descriptive names, such as "YourProjectWebApi" instead of "Base", "Dal.External" instead of "Dal.Services" and so on.

There might be a smell in the "internal DTO" part though, as you're supposed to get entities out of repositories and be able to take domain (business) actions directly on them. Entities are not just DTO's.

I kind of gather from the fact that Dal.Db has no dependency to Biz.Domain, that the Domain layer is doing some mapping between DTO's from the Interfaces project (returned by Repositories ?) and its own Domain objects. This wouldn't be correct in a typical state-of-the-art (== "onion" or "hexagonal") DDD architecture -- the Domain layer shouldn't reference other projects. For the same reason, Repository interfaces should be declared in the Domain and not in Interfaces as I guess they are.

Title: Is this a good Visual Studio solution structure for a domain driven design RESTful web service?

Body:
I am building a .NET 4.5 C# Web API RESTful solution and I would like someone to tell me if my project solution is correct and/or wise(-enough?) for a solution designed using Domain Driven Design, please.

The solution has been split into 6 projects:

/Base

(Not referenced by anything)

The web project and forms the interface between the solution and the outside world. Contains the Web API controllers. Contains almost no logic beyond gathering values from request objects and asking the BizApi layer for work.

/Biz.Api

(Referenced by Base])

Provides the domain services and allows the /Base interface project to have access to the domain business logic objects in the /Biz.Domain project.

/Biz.Domain

(Referenced by Biz.Api)

Provides the domain classes for the Biz.Api layer. These provide methods to manipulate the data of the business in memory.

/Dal.Db

(Referenced by Biz.Api)

The database repository layer. Accesses the databases and maps returned data into internal DTO's defined in the /Interfaces layer.

/Dal.Services

(Referenced by Biz.Api)

Provides a proxy layer to external dependencies like web services and maps their returned data to internal DTOs defined in the /Interfaces project.

/Interfaces

(Referenced by most projects above)

Contains the DTO classes for passing data around the solution and the C# interfaces to define contracts for things like IoC.


问:
What do Java developers think of Scala?
I've noted that IDE support is nowhere near as good, but the language itself supports functional programming idioms much more cleanly.</p>

答:
About one year ago, as I became more and more frustrated about the future of my startup's products if I continued to use Java, I decided to give Scala a try. I was already programming in JavaScript and Python at the time, Ruby was also a good alternative, but I was looking for a statically typed language, preferably one that could run on the JVM.

I really tried to like Scala, I really did, but I found it's code utterly ugly and hard to understand. I dramatically wondered that if Scala was our best answer to Java, then I was surely screwed and sentenced to continue working with a language I didn't liked after all...

Fortunately, not too long afterwards, I found out about Fantom. Oh man, did I loved it! To me, it was like american's splendor answer to german bureaucracy! It matched the requirements I was looking for in Scala, but much more elegantly. It had Vim, Eclipse and Netbeans integration, a nice web framework, mature products running with it, a small but incredibly helpful community... Dynamic and Static typing! I rejoiced!

(I could continue but this post is meant to be about Scala, not Fantom, so I stop here. My preference is clear, nevertheless there's this post comparing the two. I never could understand why Fantom gets so little attention when compared to Scala. But apparently I'm not the only one, if you listen to this podcast [mp3] until the end.)

ContentLicense: CC BY-SA 2.5

Title: What do Java developers think of Scala?


问:
Is there any logical reason to auto-generate code documentation?
Automatic documentation generation can be done with a variety of tools, GhostDoc being one of the more prominent.  However, by definition, everything it generates is redundant.  It takes a look at names of methods, classes, etc. and outputs English that might explain them more verbosely.  In the best case, it does what the reader could already do in their head (examples taken from here):

```<code>/// <summary>
/// Initializes a new instance of the <see cref="Person"/> class.
/// </summary>
public Person() ...
</code>```

In the worst, it can actually end up generating bizarre documentation that is actually misleading in its attempt to heuristically figure out the meaning of names:

```<code>/// <summary>
/// Riches the text selection changed.
/// </summary>
/// <param name="richTextBox">The rich text box.</param>
private void RichTextSelection_Changed(System.Windows.Controls.RichTextBox richTextBox) ...
</code>```

It seems that the attitude with GhostDoc is, "it's intrinsically better to have some kind of formal XML documentation", but when that documentation is 100% redundant, why?  Isn't it just wasting a ton of space at best?

At my workplace, we have to document everything, and almost always with GhostDoc's auto-generated docs.  Do you do this, and are there any rational reasons not to simply leave code undocumented if you aren't going to actually write the documentation yourself?

答:
the simple answer to "why generate docs" can be simply answered by showing MSDN.

Imagine trying to write a program that uses any library where there is no API documentation. It'd be a nightmare. MSDN is a great example of the the kind of doc that can be generated from source code and comments and form an essential resource to developers.

If you're writing an application (ie not a library to be consumed by others) then maybe there is a case for not bothered - but even then, how much of a large, internal-only, application doesn't contain bunch of libraries anyway? When you join such a team, having some browsable API doc is going to be helpful.

No tool is going to write your documentation for you, but they do give you the boilerplate that you'd have to write out manually anyway, some tools (like doxygen) will also generate diagrams and reference lists (of called and calling functions for example) that would not be easily discovered even by looking at source code.

Obviously pragmatic common sense should be applied to what gets documented, properties and minor functions can be ignored (and skipped from generation even in the tools), but at no point should anyone say "there's the source code, that's documentation enough" at any time.


问:
How does the Common Language Runtime improve performance?
I read on the wikipedia article for Common Language Runtime that one of the benefits that the runtime provides is "Performance improvements".

Executing managed code (Or bytecode) must surely always be slower due to additional overhead for JIT compilation than executing native code. How then is it possible that the CLR causes "Performance improvements"?

Update:

I have looked at the question and answers to What backs up the claim that C++ can be faster than a JVM or CLR with JIT?, but it has not been helful as that question is actually asking why C++ would be faster rather than slower. What I am interested in is how it is possible, from an architectural point of view, that managed code could lead to performance improvements

答:
Improve performance compared to what exactly?

Compared to most compiled executables, a JIT compiler has the advantage of knowing exactly what environment it's running in. It can use the latest instruction set extensions and apply optimizations that work only on that specific CPU.

Compared to code that does manual memory management that isn't optimized very carefully, a modern generational garbage collector is very efficient, especially if you have lots of very short-lived objects. Allocation is basically free.


问:
dealing with a very large state machine in a class
I am currently implementing a class for a network protocol. The protocol uses a quite complex and extensive finite state machine. A pair of an event plus a state is mapped to a function, which does some work and sets the new state.

As there are about 150 valid state/event combinations and 28 distinct functions to be called, I refactored the whole state machine logic away from the associating/sending/receiving/... (let's call it service class)  into a separate statemachine class.  The problem is, that some of these 28 functions need access to the service class, for example to reset a deadline timer.

What I could do is befriend the statemachine class and the service class, so they can access each other's internals. This would introduce a very tight coupling (albeit natural, as they belong together). I could also just leave both these classes in one, but this would result in a huge class.

But since I doubt that I am the first one running into this problem, I assume that there exists a more or less canned solution to this I haven't found yet.

答:
I think the problem is that your state machine class is too specific for the protocol. If it was generic, the table of actions would be provided by the protocol class to the state machine class. Those actions would just be std::function<void(ServiceClass*).

Clearly the protocol class has access to the service class, as the protocol defines which service functions are called when.


问:
Should I use expect or should when writing RSpec specs?
Please can someone explain to me how I should go about deciding whether to use expect or should syntax for my rspec examples.

From my understanding we should no longer be using the 'should' syntax.

The replacement is to use expect().to or is_expected.to

Is this correct?

On some really good references, it seems to be common practice to still use should. And these references are being updated consistently.

Any help in the correct direction would be appreciated.

References (+ others, but excluded)

https://github.com/thoughtbot/shoulda-matchers

https://www.railstutorial.org/book

答:
Yes you should use expect().to

.should is the original format but had some issues in certain circumstances

expect().to overcomes these issues

I have worked on several large github open source projects that have made the change over the past couple of years.

You may also find https://stackoverflow.com/a/19570645/631619 helpful


问:
How best to handle database refactoring within a team?
We are currently usign a roll-forward approach to DB changes, akin to Migrations, where each developer creates and checks in a script that promotes the latest version of the DB to a new state. Problems arise when multiple developers concurrently work on non-trivial tasks and end up making changes to the DB that interfere with each other. The 'non-trivial' bit is significant because if the tasks take long enough, and if DB changes occurr early enough in the cycle, neither dev ends up being aware of the other's changes, and we end up with either a DB merge nightmare (preferred case) or an inadvertently broken database.

Can these situations be easily avoided? Are there database refactoring strategies that effectively handle the scenario of multiple developers actively changing the schema?

If it matters, we use SQL Server.

答:
The only solution I've found is to have a functional layer between the DB and the application. Data needs in the application require abstraction from the DB schema and vice versa, lest a change of schema become massive project surgery. This is not the same thing as using an ORM.

If the DB schema should be changed then the change must be accompanied by changes in the functional request layer that pulls/pushes data. Likewise, changes in the data representation within the application must be accompanied by changes in the data layer that pulls/pushes data.

What this approach adds in terms of coding requirements in data abstraction call code it saves in massive, rewrite-the-world project-shaking changes. In particular, it prevents those project-wide changes from turning into feature/mission creep and putting your team in an impossible situation.

An additional benefit to this approach is that you can implement such a layer now and in increments without getting too wild up front. For example, you can write a 1-for-1 table query layer that separates the calling code from the DB query, and replace the previous in-code queries (or ORM or DB framework calls) with calls to these new functions that accept and return exactly whatever you are dealing with right now. This is easy. Now if you need a DB change, do it with an accompanying change to the data layer code so it accepts and returns whatever it does now but deals with the DB change gracefully. You can then change the calling code itself if this makes sense.

Sometimes you discover something interesting about non-trivial data in this process -- namely that object-to-table translations are not 1-for-1 and that the shape of the data in code can never match its shape in a relational DB, but that a relational DB is the most reasonable way (sometimes the only way) to store the data if it might ever directly serve more than a single application.


答:
When I initially dabbled with Scala 2 years ago, it looked alien and intimidating to me. At some point I discovered that the core language is actually much simpler than Java, but its syntax and semantics are so flexible that you can create new language constructs like it, even without a macro feature. I have since completely switched to Scala for all my Java projects, because it lets me write without too much boilerplate code.

I like Clojure, but there are situations, where the platform needs you to compile to static bytecode (Android, applets, ...) and while you can do that, in Scala, it's just there.

While Scala lets you solve many problems in a functional way, I often find problems where using classes feels more natural. That makes things a bit more complex, but nowhere near the complexities and pains of C++.

The biggest takeaway for me when I really started learning the language was that I could program just I did in Java, just without the noise (a little bit like when you start Groovy), but eventually you want to try to dive deeper into the power of the language - it grows with you.

About the IDE question: After using Emacs for everything, all my IDE issues went away :-)

Title: What do Java developers think of Scala?

Body: I've noted that IDE support is nowhere near as good, but the language itself supports functional programming idioms much more cleanly.</p>


答:
The classic approach for decoupling two components is by defining a clear interface between them and let them communicate only by this interface (opposed to giving direct access to any internals).

So in your case: create an interface class (in C++ typically an abstract base class) for your service class, defining the interface you want to make public. Any access by the state machine or the 28 functions should be done only through this interface. So the state machine and the service class become decoupled, you now can easily replace it by a mock implementation for testing purposes, if you like.

This works the other way round as well: if your service class needs to access the state machine, define a public interface for your state machine, and access the state machine from outside only through this interface.

Title: dealing with a very large state machine in a class

Body:
I am currently implementing a class for a network protocol. The protocol uses a quite complex and extensive finite state machine. A pair of an event plus a state is mapped to a function, which does some work and sets the new state.

As there are about 150 valid state/event combinations and 28 distinct functions to be called, I refactored the whole state machine logic away from the associating/sending/receiving/... (let's call it service class)  into a separate statemachine class.  The problem is, that some of these 28 functions need access to the service class, for example to reset a deadline timer.

What I could do is befriend the statemachine class and the service class, so they can access each other's internals. This would introduce a very tight coupling (albeit natural, as they belong together). I could also just leave both these classes in one, but this would result in a huge class.

But since I doubt that I am the first one running into this problem, I assume that there exists a more or less canned solution to this I haven't found yet.


答:
Consider using a distributed version control system like git.

Create one repository for the database change scripts and use a workflow such as 'you must fetch the latest, merge your changes in, commit and push and only after pushing and seeing no rejection (because others pushed) should you run your script on the actual shared db server.  Until then each developer can have a local copy, usually pared down to some test data.

Title: How best to handle database refactoring within a team?

Body:
We are currently usign a roll-forward approach to DB changes, akin to Migrations, where each developer creates and checks in a script that promotes the latest version of the DB to a new state. Problems arise when multiple developers concurrently work on non-trivial tasks and end up making changes to the DB that interfere with each other. The 'non-trivial' bit is significant because if the tasks take long enough, and if DB changes occurr early enough in the cycle, neither dev ends up being aware of the other's changes, and we end up with either a DB merge nightmare (preferred case) or an inadvertently broken database.

Can these situations be easily avoided? Are there database refactoring strategies that effectively handle the scenario of multiple developers actively changing the schema?

If it matters, we use SQL Server.


问:
How accurate is "Business logic should be in a service, not in a model"?
Situation

Earlier this evening I gave an answer to a question on StackOverflow.

The question:

Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}
```

<p><em>A comment I received:</em></p>

<blockquote>
  <p>Business logic should really be in a service. Not in a model.</p>
</blockquote>

<p><strong>What does the internet say?</strong></p>

<p>So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.</p>

<p>Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:</p>

<blockquote>
  <p>There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>

  <p>(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.</p>
</blockquote>

<p>To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).</p>

<p>I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.</p>

<blockquote>
  <p>Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.</p>
</blockquote>

<p>Which is reinforced here:</p>

<blockquote>
  <p>Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.</p>
</blockquote>

<p>And here:</p>

<blockquote>
  <p>The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.</p>
</blockquote>

<p>This is a serious contrast to other resources that talk about the Service Layer:</p>

<blockquote>
  <p>The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.</p>
</blockquote>

<p>Or the second answer to a question I've already linked:</p>

<blockquote>
  <p>At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.</p>
</blockquote>

<p><strong>"Solution"?</strong></p>

<p>Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:</p>

<pre class="lang-cs prettyprint-override"><code>class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}
</code>```

Conclusion

All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.

I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?

Is it supposed to form a contract between the controller and the domain?

Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?

答:
For the record.

SRP:

Model = Data, here goes the setter and getters.

Logic/Services = here goes the decisions.

Repository/DAO = here we permantenty store or retrieve the information.

In this case, is OK to do the next steps:

If the debt will not require some calculation:

```<code>userObject.Debt = 9999;
</code>```

However, if it requires some calculation then:

```<code>userObject.Debt= UserService.CalculateDebt(userObject)
</code>```

or also

```<code>UserService.UpdateDebt(userObject)
</code>```

But also, if the calculation is done in the persistence layer, such a store procedure then

```<code>UserRepository.UpdateDebt(userObject)
</code>```

In this case, i we want to retrieve the user from the database and to update the debt then, we should do it in several step (in fact, two) and it's not requires to wrap/encapsulate it in a service's function.

```<code>User userObject=UserRepository.GetUserByName(somename);
UserService.UpdateDebt(userObject)
</code>```

And if it requires to store it then, we can add a third step

```<code>User userObject=UserRepository.GetUserByName(somename);
UserService.UpdateDebt(userObject)
UserRepository.Save(userobject);
</code>```

About the solution proposed

a) We shouldn't be afraid to left the end-developer to write a couple of instead of encapsulate it in a function.

b) And about Interface, some developers love interface and they are fine but in several cases, they aren't need at all.

c) The goal of a service is to create one without attributes, mainly because we can use Shared/Static functions. It's also easy to unit test.

ContentLicense: CC BY-SA 4.0

Body:
For the record.

SRP:

Model = Data, here goes the setter and getters.

Logic/Services = here goes the decisions.

Repository/DAO = here we permantenty store or retrieve the information.

In this case, is OK to do the next steps:

If the debt will not require some calculation:

userObject.Debt = 9999;

However, if it requires some calculation then:

userObject.Debt= UserService.CalculateDebt(userObject)

or also

UserService.UpdateDebt(userObject)

But also, if the calculation is done in the persistence layer, such a store procedure then

UserRepository.UpdateDebt(userObject)

In this case, i we want to retrieve the user from the database and to update the debt then, we should do it in several step (in fact, two) and it's not requires to wrap/encapsulate it in a service's function.

User userObject=UserRepository.GetUserByName(somename);
UserService.UpdateDebt(userObject)

And if it requires to store it then, we can add a third step

User userObject=UserRepository.GetUserByName(somename);
UserService.UpdateDebt(userObject)
UserRepository.Save(userobject);

About the solution proposed

a) We shouldn't be afraid to left the end-developer to write a couple of instead of encapsulate it in a function.

b) And about Interface, some developers love interface and they are fine but in several cases, they aren't need at all.

c) The goal of a service is to create one without attributes, mainly because we can use Shared/Static functions. It's also easy to unit test.


答: The most valuable thing I personally get from a code review is confidence that the code is clear to another person.  Are variables clearly named?  Is the purpose of each chunk of code reasonably obvious?  Is anything ambiguous clarified with a comment?  Are edge cases and valid values for parameters outlined in comments and checked-for in code?

Title: What is the purpose of a Code Review


问:
Adding to the System namespace in C#
Would it be acceptable for some very generic utilities or classes to be added in the System namespace?

I'm thinking of really basic stuff like a generic EventArgs (EventArgs<T>),

Use case: would be shared in a company's core library (so that it can be recompiled in a new project as-is, without changing the namespace);

答:
Yes, you can do it. VS might report various false errors, like classes it doesn't find but when compiled everything will work ok. It is generally NOT recommended for already mentioned reasons BUT, I think you can do it in some situations.

In my case I did it for a shared code base which is compiled as libraries for 6 different .net based platforms (.NET basic, Xamarin, Window 8.1, Mac etc, each api having its own small differences). The compiled lib is then used by projects targeting each platform. For the Windows Store 8.1 Apps and Windows Phone 8.1 platforms the System.Collections had a whole bunch of classes missing from it: ArrayList, Hashtable, SortedList etc, all kinds of comparers, enumerables etc etc. While I am aware of the fact that these classes are not recommended and one should use generic alternatives (which are available for the Win 8.1 platforms), it is a HUGE task in our case to make such changes on the shared code, PLUS on the code of the consumer projects of the resulting libraries. Non generic classes are used all over the place, the dev started in 2002. And we are talking about tens of thousands of lines of code now...
So in this case, I think it is ok to inject a few missing classes in System namespace.

Title: Adding to the System namespace in C#


问:
Is test coverage an adequate measure of code quality?
If I have some code that has 80% test coverage (all tests pass), is it fair to say that it's of higher quality than code with no test coverage?

Or is it fair to say it's more maintainable?

答:
I would agree about the maintainable part. Michael Feathers recently posted a video of an excellent talk of his called "The deep synergy between testability and good design" in which he discusses this topic. In the talk he says that the relationship is one way, that is, code that is well designed is testable, but testable code is not necessarily well designed.

It's worth noting that the video streaming is not great in the video, so it might be worth downloading if you want to watch in full.


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

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

答:
1) Use an Object Database in an ERP system

2) Use an EVA Database in an ERP system

3) Craziest: Build a visual-based business rules system (a la Outlook Rules) to hand to our users (without a test harness to test the rules) and "throw it over the wall" at them. So instead of us writing programs for our users, we could just write a dumbed-down programming language for them and let them write their own apps.


答:
The problem with authorization checks only on the client side is that ultimately an attacker can mimick the behaviour of your application. Robert Harvey argues that it's unlikely for your users to debug the compiled application or to look at the network traffic. It very well may be.

The problem is that it's not rocket science to find out what's going on. And if somebody breaches the security, you may never know, because to the server, everything looks like the regular traffic.

So, the answer is you may try to protect your application by obfuscating it and by encrypting the traffic to the server, but this just raises the bar for a successful breach. Videogame and movie producing companies invest serious effort into developing protection for the software or the content on an untrusted device, but you can see these protections being circumvented quite soon. Running the security-critical part on a trusted computer (like a server) scales much better in terms of effort vs. security.

Title: How do you make sure a .net client application is not being hacked to bypass authorization claims?

Body:
We wrote a simple .NET (C#) desktop application in Wpf. We also used WIF (Windows Identity Framework) to get a list of claims for the authenticated user. Some examples are:

CanOverrideSalesAmount

CanAddContact

etc.

This works fine and all, the client seems very protected. But, when I was debugging the application it occurred to me that all of the authorization is happening on the client side. A devious person could use a tool such as Snoop to hook into the application and make changes to the domain model that s/he isn't supposed to do.

We thought about moving the authorization checks on the property setters, but even that isn't good enough because when we serialize the object graph to send over the wire, the serialized data can be altered (far fetched, but still possible).

It seems to me that the only true way to protect my object graph is to have it only reside on the server and to have the client make calls to update it, but that seems like such an overkill. Is there a better way to handle this situation? I want our application to be as secure as possible.


答:
The easiest way to illustrate why programmers shy away from putting domain logic in the domain objects is that they're usually faced with a situation of "where do I put the validation logic?"  Take this domain object for instance:

```<code>public class MyEntity
{
    private int someProperty = 0;

    public int SomeProperty
    {
        get { return this.someProperty; }
        set
        {
            if(value < 0) throw new ArgumentOutOfRangeException("value");
            this.someProperty = value;
        }
    }
}
</code>```

So we have some basic validation logic in the setter (cannot be negative).  The problem is that you can't really re-use this logic.  Somewhere there's a screen or a ViewModel or a Controller that needs to do validation before it actually commits the change to the domain object, because it needs to inform the user either before or when they click the Save button that they can't do that, and why.  Testing for an exception when you call the setter is an ugly hack because you really should have done all the validation before you even started the transaction.

That's why people move the validation logic some kind of service, such as MyEntityValidator.  Then the entity and the calling logic can both get a reference to the validation service and re-use it.

If you don't do that and you still want to re-use validation logic, you end up putting it in static methods of the entity class:

```<code>public class MyEntity
{
    private int someProperty = 0;

    public int SomeProperty
    {
        get { return this.someProperty; }
        set
        {
            string message;
            if(!TryValidateSomeProperty(value, out message))
            {
                throw new ArgumentOutOfRangeException("value", message);
            }
            this.someProperty = value;
        }
    }

    public static bool TryValidateSomeProperty(int value, out string message)
    {
        if(value < 0)
        {
            message = "Some Property cannot be negative.";
            return false;
        }
        message = string.Empty;
        return true;
    }
}
</code>```

This would make your domain model less "anemic", and keep the validation logic next to the property, which is great, but I don't think anyone really likes the static methods.

Title: How accurate is "Business logic should be in a service, not in a model"?

Body:
Situation

Earlier this evening I gave an answer to a question on StackOverflow.

The question:

Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}
```

<p><em>A comment I received:</em></p>

<blockquote>
  <p>Business logic should really be in a service. Not in a model.</p>
</blockquote>

<p><strong>What does the internet say?</strong></p>

<p>So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.</p>

<p>Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:</p>

<blockquote>
  <p>There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>

  <p>(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.</p>
</blockquote>

<p>To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).</p>

<p>I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.</p>

<blockquote>
  <p>Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.</p>
</blockquote>

<p>Which is reinforced here:</p>

<blockquote>
  <p>Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.</p>
</blockquote>

<p>And here:</p>

<blockquote>
  <p>The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.</p>
</blockquote>

<p>This is a serious contrast to other resources that talk about the Service Layer:</p>

<blockquote>
  <p>The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.</p>
</blockquote>

<p>Or the second answer to a question I've already linked:</p>

<blockquote>
  <p>At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.</p>
</blockquote>

<p><strong>"Solution"?</strong></p>

<p>Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:</p>

<pre class="lang-cs prettyprint-override"><code>class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}
</code>```

Conclusion

All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.

I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?

Is it supposed to form a contract between the controller and the domain?

Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?

Body:
The easiest way to illustrate why programmers shy away from putting domain logic in the domain objects is that they're usually faced with a situation of "where do I put the validation logic?"  Take this domain object for instance:

public class MyEntity
{
    private int someProperty = 0;

    public int SomeProperty
    {
        get { return this.someProperty; }
        set
        {
            if(value < 0) throw new ArgumentOutOfRangeException("value");
            this.someProperty = value;
        }
    }
}

So we have some basic validation logic in the setter (cannot be negative).  The problem is that you can't really re-use this logic.  Somewhere there's a screen or a ViewModel or a Controller that needs to do validation before it actually commits the change to the domain object, because it needs to inform the user either before or when they click the Save button that they can't do that, and why.  Testing for an exception when you call the setter is an ugly hack because you really should have done all the validation before you even started the transaction.

That's why people move the validation logic some kind of service, such as MyEntityValidator.  Then the entity and the calling logic can both get a reference to the validation service and re-use it.

If you don't do that and you still want to re-use validation logic, you end up putting it in static methods of the entity class:

public class MyEntity
{
    private int someProperty = 0;

    public int SomeProperty
    {
        get { return this.someProperty; }
        set
        {
            string message;
            if(!TryValidateSomeProperty(value, out message))
            {
                throw new ArgumentOutOfRangeException("value", message);
            }
            this.someProperty = value;
        }
    }

    public static bool TryValidateSomeProperty(int value, out string message)
    {
        if(value < 0)
        {
            message = "Some Property cannot be negative.";
            return false;
        }
        message = string.Empty;
        return true;
    }
}

This would make your domain model less "anemic", and keep the validation logic next to the property, which is great, but I don't think anyone really likes the static methods.


问:
What effect does using multiple childViewControllers views inside a ContainerViewController have on memory?
I have three childViewController views inside my ContainerViewController and these three views are inside a horizontal scroll view. My intention is to build an app that has a custom camera on one ChildViewController view, a tableView which will display JSON data on another view, and a page which will show a list of the users friends.

The reason I am building it this way is to achieve a dragging/sliding effect between the three different child views. Although I get the result I want from a UI/UX perspective, i'm not sure how this will effect memory and performance. If i'm not mistaken my containerViewController will be handling a lot of activity.

Would there be an alternative way to architect this type of application? I understand I could have three separate view controllers using a Navigation Controller but than I wouldn't achieve the UI/UX experience I want. I'm really after the dragging/sliding between different pages experience, similar if not the same as Snapchat/Tinder

答:
There's no real way to know based on the description you gave. And I know that's sort of a vague answer, but it depends on a whole bunch of other things. Are you using the standard UIImagePickerController to take photos, or rolling your own using AVFoundation? If you're rolling your own, you could be leaking or misusing memory such that your UIViewController architecture doesn't matter. Are you fetching your JSON data synchronously or asynchronously? How are you fetching the user's friends? Are you showing their profile pictures, if applicable? How are you fetching those? You could have slow HTTP requests or slow CoreData queries that are entirely separate from your front end architecture.

The other consideration is which device and minimum version of iOS are you using? An iPhone 4 obviously has much higher memory constraints than an iPhone 5S (or an iPhone 6 PLUS!).

At the end of the day, this is what Instruments is for. Build your application the way you want it to be, and profile it. If there are memory or performance issues, Instruments will identify them and you can look into them.


问:
Managing code changes in this coding environment
I have the following coding environment:

Three Developers

Source code resides in Team Foundation Server (2010)

Development Environment

Stage Environment

Production Environment

As the Senior Developer, I need to review code before its pushed to the Staging Environment. Once I review the code, it is pushed to Stage where it gets tested by our (small) test team. Once changes are tested and accepted, I move to production.

Suppose the following:

Developer A submits a change, I review it and push to stage.
Developer B submits a change, I review it and push to stage.

During the testing, a user says the change Developer A made has bugs and needs to be fixed. But the changes Developer B made need to go to production.

This happens more than not. Currently, I need to wait for Developer A to fix the bugs and test again or have Developer A disable their changes.

How to solve this dilemma?

答:
One strategy, which can be established with any decent VCS, is to open a parallel maintenance branch in such a situation (based on the latest stable production release) and merge only the immediate bugfixes or other urgent changes for production into it (for example, the changes of your developer B). Typically, you can create a maintenance release from this branch for production much quicker, with only a low risk introducing new bugs and with less testing effort than from your current development branch.

Your "staging branch" will still contain all new features (including the changes from A and B), and you can deploy it later when it is "ready".

This model can be supported by your version numbering scheme: for example, when you release your version 1.2 into production it is actually version 1.2.0. Whenever you deliver a maintenance release, you increase the last digit: 1.2.1, 1.2.2, 1.2.3. These numbers tell anyone that your application contains no real new features within the 1.2 line, only urgent fixes. When you deliver a release with new-features, you increase the first digits: 1.3, 1.4 or 2.0.

In fact, in our team we make sometimes use of this technique for our main product, but only when we cannot easily hide the changes "of dev A" behind a "feature toggle". The latter will typically cause less branching/merging effort than a maintenance branch, so if you can avoid the changes in dev A's code influencing production by simply setting a runtime switch, then this maybe the better alternative.


答:
Many correct answers already. But I want to add another perspective:

Using the System namespace tells the developer to look at MSDN, using the company's namespace tells the developer to look at internal resources for documentation.

It also makes the dependency on the company's library clear, which might be relevant when moving code around between different modules.

Title: Adding to the System namespace in C#

Body:
Would it be acceptable for some very generic utilities or classes to be added in the System namespace?

I'm thinking of really basic stuff like a generic EventArgs (EventArgs<T>),

Use case: would be shared in a company's core library (so that it can be recompiled in a new project as-is, without changing the namespace);


问:
When should you call yourself a senior developer?

Possible Duplicate:

  Whats the difference between Entry Level/Jr/Sr developers?

I'm curious what senior developer means because apparently the definition doesn't mean what I thought it would. I keep seeing these teens at 22-23 years old who call themselves senior X developer or senior Y developer. To me, a senior must have 10 years or so experience in programming to call himself 'senior'. I've seen a lot of these teens here (hence the question). Am I wrong? Why?

答:
When other call you senior developer. There is no one definition. Its changes from company to company. In a well settled company freshers are given less work, and their learning curve is slow. In the startup company a fresher can take many responsibilities and learns many things in less time. I have experienced this first hand. Unfortunately it's only the other experienced people which can calculate the depth of your knowledge, by looking at the quality of your code or work. And I am sure everyone gets their title when the their time is up.

And if you don't you change the company. :-)


答:
It's a design decision.  You can make Card an entity, with attributes like rank, suit, blackjack value (1..11), etc. and drive the game play from the data.  That would let you modify the game play by changing data, and allow you to produce a useful report on the game play from the database alone.

Or you could make Card a value class (enum or whatever), and specify how it will be translated to/from a numeric or string value in the database.  Depending on how you represent the cards in the database, it could be more difficult to generate a report independent of the application code.

Title: Entity design for a blackjack game - should I make Card an entity?

Body:
I am creating a simple blackjack game backed by database

In my Card is

```<code>public class Card{
 private Face face;
 private Suit suit;

 //setters.. getters
}
</code>```

where face and suit are enums

I have an entity Bet with the following

```<code>@Entity
public class Bet{
   private Player player;
   private String cards;
   //...
}
</code>```

Currently when I'm dealing cards I parse the suit and face to string and concatenate them in the cards field and then parse the cards if I want to calculate the score. I find this cumbersome so I want to change my field "cards" to List in the Bet Entity.

Now, if that's the case I would have to make the Card class an entity as well. But my cardService, which is where I get my cards, does not rely on the database, it just creates random cards so it does not make sense to make card an entity - am I right?


问:
Workflow for obfuscated PHP code with PHP protect
Let's say I have a database-driven web application written in PHP.

After obfuscating the code with PHP protect it will
be copied to a web hosting server.

And here is the question.

What is the workflow of a programmer when there is a bug in an application
and he needs to edit the PHP code to repair it?
It's clear, that he can't debug (and edit) directly the obfuscated code.

答: Maintain two identical hardware/software platforms: a production platform and a test platform.  When an error occurs, reproduce it on the test platform.  Then, upload the unobfuscated code to the test platform and reproduce the bug again.  Perform the usual troubleshooting, fix the bug, obfuscate the new code, and upload it to the production server.</p>


问:
Is $.proxy a code smell?
I've been writing most of my javascript applications in an OO style close to what I would use for most other languages. However, this means that most callbacks need to have a reference to an object, and I generally handle that by using $.proxy (or dojo.hitch, or whatever the framework's tool for this is) to be sure that the callbacks are operating in the context of my object, rather than the tag they were attached to.

Very quickly, this seems to lead to using proxied calls for almost everything, and can look like I'm fighting against the tool, particularly if the tool is jQuery.

Do you have a policy on how to handle javascript function binding in your work? Do you try fit your design to how the tool binds it's functions, or do you force the bindings to work according to your design?

答:
If the function to which you're binding is simple (no return value, no arguments), $.proxy seems like the simplest option (plus, it has other functionality).

However, since you mentioned that you've "been writing most of my javascript applications in an OO style close to what I would use for most other languages", I highly recommend TypeScript and its lambda syntax.  I've provided a relevant example below, but first, an intro:

CoffeeScript, Google Dart, and other more mature languages have similar goals, but I'm not familiar with those--what you use will depend on the development tools and languages with which you're most comfortable.  If you use Microsoft languages and development tools, TypeScript is probably the best option (JetBrains IDEs have strong TypeScript support, as well).

I recently started implementing TypeScript in my projects because it brings object orientation to JavaScript and works well with .NET server-side languages (the open-source TypeLite makes it easy to automatically generate TypeScript interfaces from .NET classes: http://type.litesolutions.net/).  Although TypeScript is a Microsoft-initiated product, it's an open-source language.  For example, JetBrains' WebStorm IDE supports TypeScript more thoroughly than Visual Studio at this point; I use WebStorm along with Visual Studio for that reason.

I just realized that the OO-specific problem with $.proxy is that you can't enforce strongly-typed method arguments and return values.  But if you use lambdas in TypeScript (syntax that will be available in ECMAScript 6), you can enforce that without writing all the extra code required in ECMAScript 5.  Here's a working TypeScript example:

```<code>interface ICallbackData{
Value1: boolean;
Value2: string;
}

class Manager{
    private _CallbackProxy: (CallbackData: ICallbackData)=>string;
    constructor(){
        this._CallbackProxy = (CallbackData)=>this.CallbackHandler(CallbackData);
    }
    CallbackHandler(CallbackData: ICallbackData): string{
        if (CallbackData.Value1){
            return CallbackData.Value2;
        }
        return "Other String";
    }

    Value: number;
    PerformActionThenCallback(){
        this.Value += 1;
        this._CallbackProxy(<ICallbackData>{Value1: true, Value2: "Callback String, Value: " + this.Value.toString()});
    }
}
</code>```

You can see the JavaScript to which that code will compile by plugging it in here: http://www.typescriptlang.org/Playground

TypeScript will be ready for the future of ECMAScript, so you won't have to rewrite or upgrade your code.  For example, lambda functions written in TypeScript currently compile similar to what Esailija wrote (the alternative to $.proxy):

```<code>var self = this;
$().click( function(e) {
    self.doit(e);
});
</code>```

It compiles to that because it is trying to be compatible with as many browsers' ECMAScript 5 implementations (it can currently compile to be compatible with ECMAScript 3 or 5; I'm not sure why it doesn't compile using .bind() for ECMAScript 5--that's a different topic).  But when ECMAScript 6 is widespread, TypeScript lambdas will compile directly as lambdas without generating all that extra code.  For now, though, at least there are robust OO languages that compile to JavaScript and simplify OO requirements, while eliminating the need to wait for ECMAScript 6 and beyond.

Title: Is $.proxy a code smell?

Body:
If the function to which you're binding is simple (no return value, no arguments), $.proxy seems like the simplest option (plus, it has other functionality).

However, since you mentioned that you've "been writing most of my javascript applications in an OO style close to what I would use for most other languages", I highly recommend TypeScript and its lambda syntax.  I've provided a relevant example below, but first, an intro:

CoffeeScript, Google Dart, and other more mature languages have similar goals, but I'm not familiar with those--what you use will depend on the development tools and languages with which you're most comfortable.  If you use Microsoft languages and development tools, TypeScript is probably the best option (JetBrains IDEs have strong TypeScript support, as well).

I recently started implementing TypeScript in my projects because it brings object orientation to JavaScript and works well with .NET server-side languages (the open-source TypeLite makes it easy to automatically generate TypeScript interfaces from .NET classes: http://type.litesolutions.net/).  Although TypeScript is a Microsoft-initiated product, it's an open-source language.  For example, JetBrains' WebStorm IDE supports TypeScript more thoroughly than Visual Studio at this point; I use WebStorm along with Visual Studio for that reason.

I just realized that the OO-specific problem with $.proxy is that you can't enforce strongly-typed method arguments and return values.  But if you use lambdas in TypeScript (syntax that will be available in ECMAScript 6), you can enforce that without writing all the extra code required in ECMAScript 5.  Here's a working TypeScript example:

interface ICallbackData{
Value1: boolean;
Value2: string;
}

class Manager{
    private _CallbackProxy: (CallbackData: ICallbackData)=>string;
    constructor(){
        this._CallbackProxy = (CallbackData)=>this.CallbackHandler(CallbackData);
    }
    CallbackHandler(CallbackData: ICallbackData): string{
        if (CallbackData.Value1){
            return CallbackData.Value2;
        }
        return "Other String";
    }

    Value: number;
    PerformActionThenCallback(){
        this.Value += 1;
        this._CallbackProxy(<ICallbackData>{Value1: true, Value2: "Callback String, Value: " + this.Value.toString()});
    }
}

You can see the JavaScript to which that code will compile by plugging it in here: http://www.typescriptlang.org/Playground

TypeScript will be ready for the future of ECMAScript, so you won't have to rewrite or upgrade your code.  For example, lambda functions written in TypeScript currently compile similar to what Esailija wrote (the alternative to $.proxy):

var self = this;
$().click( function(e) {
    self.doit(e);
});

It compiles to that because it is trying to be compatible with as many browsers' ECMAScript 5 implementations (it can currently compile to be compatible with ECMAScript 3 or 5; I'm not sure why it doesn't compile using .bind() for ECMAScript 5--that's a different topic).  But when ECMAScript 6 is widespread, TypeScript lambdas will compile directly as lambdas without generating all that extra code.  For now, though, at least there are robust OO languages that compile to JavaScript and simplify OO requirements, while eliminating the need to wait for ECMAScript 6 and beyond.


问:
how to manage a release of both sw and config data
in my repository I've got a sw and a cfg(config) folder under trunk, I'm thinking that when I release I'll branch both of these to the releases folder e.g. v1 of my app, with London config data. If I want to release v1 of my app to NewYork too then I'm thinking I'll branch my config data off of main and adjust it in the release folder. Does this sound ok? have I missed something? I want to be able to tell 12 months from now which city has which version of the app, and be able to support their config data too. Cheers

```<code>Trunk
  sw
    qweqwe.cs, asdasd.cs etc.
  cfg
    setupData.inixmlwhatever

Releases
  London
    sw@v1
    cfg - London config data

  NewYork... app at v1, NewYork cfg
  Milan... app at v2, cfg data the same as London's but called milan.cfg
  Tokyo... app at v2 but with a Tokyo specific patch, with cfg data the same as Milan
</code>```

of should I go:

```<code>Trunk
    sw
    cfg

Releases
    swV1
    swV2
    cfgTokyo
    cfgLondon
    cfgMilan
</code>```

With this latter one, I don't know what version of the app's installed in London etc? I could use tags to get round this, but then someone might shift the tag. With the former, I've got loads of appV1's kicking about (which I'm ok with, branches are cheap etc. but it looks less organised).

Cheers

答:
If at one point in time you have 3 cities, there exists 3 different config folders, each one in "production" and under maintenance. And when your product evolves, and you change something in the configs, you will have to adapt all three configs in parallel. Both of this means, you will need a working copy of each cities config in parallel. So you need them all in your trunk, not in different branches. This model will reflect this:

```<code>Trunk
    sw
    cfgTokyo
    cfgLondon
    cfgMilan
</code>```

When creating release v1 now, you have

```<code> Releases
     v1
        sw
        cfgTokyo
        cfgLondon
        cfgMilan
</code>```

And you know exactly, that you have provided v1 for these 3 different cities (if the software is actually installed and used in production is a completely different question).

After that, you add New York, but only at v2. So your next release might look like this:

```<code> Releases
     v2
        sw
        cfgTokyo
        cfgLondon
        cfgMilan
        cfgNewYork
</code>```

Again, now you see exactly which city is assciated with version 2. If you need to add a new city to an older version (lets say, you want to add Berlin to v1), you can create a "maintenance branch" based on v1, add the "cfgBerlin" there and when you deploy it, you put it under Release/v1.1.

Do yourself a favor and don't make city-specific patches in different "sw" branches, only delivered to that certain city - put city specific things  exclusively into your config files. If you need such a kind of patch, change your code below sw in your trunk in a way it checks some in the config to activate the specific behaviour - so "sw" wont't be branched, you still keep one main development line for all of your cities . Otherwise you will end in configuration management hell.

Body:
If at one point in time you have 3 cities, there exists 3 different config folders, each one in "production" and under maintenance. And when your product evolves, and you change something in the configs, you will have to adapt all three configs in parallel. Both of this means, you will need a working copy of each cities config in parallel. So you need them all in your trunk, not in different branches. This model will reflect this:

Trunk
    sw
    cfgTokyo
    cfgLondon
    cfgMilan

When creating release v1 now, you have

 Releases
     v1
        sw
        cfgTokyo
        cfgLondon
        cfgMilan

And you know exactly, that you have provided v1 for these 3 different cities (if the software is actually installed and used in production is a completely different question).

After that, you add New York, but only at v2. So your next release might look like this:

 Releases
     v2
        sw
        cfgTokyo
        cfgLondon
        cfgMilan
        cfgNewYork

Again, now you see exactly which city is assciated with version 2. If you need to add a new city to an older version (lets say, you want to add Berlin to v1), you can create a "maintenance branch" based on v1, add the "cfgBerlin" there and when you deploy it, you put it under Release/v1.1.

Do yourself a favor and don't make city-specific patches in different "sw" branches, only delivered to that certain city - put city specific things  exclusively into your config files. If you need such a kind of patch, change your code below sw in your trunk in a way it checks some in the config to activate the specific behaviour - so "sw" wont't be branched, you still keep one main development line for all of your cities . Otherwise you will end in configuration management hell.


问:
Why doesn't Google use Courgette for Android updates?
Google has an advanced diff tool specifically designed for compiled binaries called Courgette.

Is there any reason why they wouldn't use this in Android and the Google Play Store to download updates? In my basic understanding of Java, it seems like it shouldn't be any more difficult (perhaps even easier?) to create 'diffs' like this because of Java's "bytecode" nature.  Am I wrong? Are there any security reasons?

Note: I know that unless someone from Google responds, we won't know for sure. But I'm asking for any obvious reasons - I'm an Android developer and sometimes get notes from people complaining about frequent updates, so it is somewhat relevant to me. :)

答:
Simplicity.

Incremental updates have the same problems as incremental backups; you must apply all of the increments in order from the last complete installation.  It becomes impractical to do this forever; eventually everyone will have to get a complete update.  Otherwise, you wind up selling a program that requires n incremental updates to get it current (where n is some arbitrarily large number, say, more than five).

From the store's point of view, it's easier just to transport the entire updated installation to the device than it is to track incremental revisions.

Remember, there are folks at the stores that vet these applications (especially at Apple); they must also apply all of the incremental updates before they can validate, and that's a pain in the ass.  One installation, one thing to evaluate and keep track of.


答: I highly recommend avoiding branches for this (As someone who has worked with both branch- and trunk-based development, the latter is very much to be preferred). You'll be copying commits forever between them, with very little possibility for an overview or a quick fix across the board when needed. Version control isn't configuration management; for that there's Puppet, Chef and a host of other solutions much better suited for just this kind of situation. And you should not rely on a source tree to know what's installed where - how do you know if version X for site Y has actually been deployed there? By inspecting what's on site Y, running my_software --version, cat /usr/local/share/my_software/version or something similar. If you don't even have read access there the deployment process should take care of updating some central service where you can find out what each site thinks it's got.

Title: how to manage a release of both sw and config data

Body:
in my repository I've got a sw and a cfg(config) folder under trunk, I'm thinking that when I release I'll branch both of these to the releases folder e.g. v1 of my app, with London config data. If I want to release v1 of my app to NewYork too then I'm thinking I'll branch my config data off of main and adjust it in the release folder. Does this sound ok? have I missed something? I want to be able to tell 12 months from now which city has which version of the app, and be able to support their config data too. Cheers

```<code>Trunk
  sw
    qweqwe.cs, asdasd.cs etc.
  cfg
    setupData.inixmlwhatever

Releases
  London
    sw@v1
    cfg - London config data

  NewYork... app at v1, NewYork cfg
  Milan... app at v2, cfg data the same as London's but called milan.cfg
  Tokyo... app at v2 but with a Tokyo specific patch, with cfg data the same as Milan
</code>```

of should I go:

```<code>Trunk
    sw
    cfg

Releases
    swV1
    swV2
    cfgTokyo
    cfgLondon
    cfgMilan
</code>```

With this latter one, I don't know what version of the app's installed in London etc? I could use tags to get round this, but then someone might shift the tag. With the former, I've got loads of appV1's kicking about (which I'm ok with, branches are cheap etc. but it looks less organised).

Cheers


答:
Good obfuscators will store the mapping between original names and obfuscated names, and provide a tool for reversing this obfuscation in stack trace dumps which appear in your logs.  The mapping won't ever go on the server, so no one but the owner of the code can perform the deobfuscation.  This is similar to the debug symbols which compiled languages use to map instruction addresses back to source code.

Documentation of the "PHP protect" tool you linked doesn't look like it obfuscates function names at all, only variables, so this shouldn't be a major issue for you.

Title: Workflow for obfuscated PHP code with PHP protect

Body:
Let's say I have a database-driven web application written in PHP.

After obfuscating the code with PHP protect it will
be copied to a web hosting server.

And here is the question.

What is the workflow of a programmer when there is a bug in an application
and he needs to edit the PHP code to repair it?
It's clear, that he can't debug (and edit) directly the obfuscated code.