问:
Reusing the logic in another repository in ASP.NET MVC repository pattern
I have an ASP.NET MVC4 web application, with EntityFramework for data access. In the application I have two repositories as follow (this is only an example not my real code):

public class CustomerRepository
{
     ICustomerContext _db;

     public CustomerRepository(ICustomerContext db)
     {
          _db = db;
     }

     ...

     public void DeactivateCustomer(int customerId)
     {
         var customer = _db.Customers.Single(x => x.CustomerId == customerId);
         customer.IsActive = false;
         _db.SaveChanges();
     }
}
```

<p>And</p>

<pre class="lang-cs prettyprint-override"><code>public class ItemRepository
{
     IItemContext _db;

     public ItemRepository(IItemContext db)
     {
         _db = db;
     }

     ...

     public void DeactivateItem(int itemId)
     {
         var item = _db.Items.Single(x => x.ItemId == itemId);
         item.IsActive = false;

         // The problem is here
         new CustomerRepository().DeactivateCustomer(item.CustomerId);

         _db.SaveChanges();
     }
}
</code>```

The ItemRepository wants to use the logic of deactivating the Customer from the CustomerRepository without copying the code, or couple both repositories like the example above.

I also want to make both actions (deactivating the item, and deactivating the customer) execute in one transaction (maybe one call to SaveChanges())

Is there any design pattern that can achieve these requirements?

答:
The logic of deactivating a customer should exist on a Customer class. Only after pulling the customer from the database and modifying its value should you then save it back to the database. Furthermore, the logic of deactivating an item should go on the Item class. To make this happen, you need a more descriptive relationship between Item and Customer:

public class Customer
{
    public bool IsActive { get; set; }
    public long CustomerId { get; set; }

    public void Deactivate()
    {
        IsActive = false;
    }
}

public class Item
{
    public bool IsActive { get; set; }
    public long CustomerId { get; set; }
    public Customer Customer { get; set; }

    public void Deactivate()
    {
        IsActive = false;

        if (Customer != null)
        {
            Customer.Deactivate();
        }
    }
}
```

<p>Now your repository classes don't need this business logic -- in fact repositories should not have <em>any</em> business logic in them for the exact same reason that you are posting this question. It's hard to reuse business logic. The real change happens in the code <em>using</em> the repository classes:</p>

<pre class="lang-cs prettyprint-override"><code>public class ItemsController : Controller
{
    public ActionResult Deactivate(long id)
    {
        using (var db = new DbContext())
        {
            var item = db.Items.Find(id);

            item.Deactivate();

            db.SaveChanges();
        }
    }
}
</code>```

(using Entity Framework as an example)

Create the database context object inside a using block so it gets properly disposed if an exception gets thrown

Fetch the Item from the database context

Call Deactivate() on the item

The item deactivates itself, then calls Deactivate on the Customer.

End the transaction by calling db.SaveChanges() to persist any domain object changes to the database

If you aren't using Entity Framework, you might need to explicitly save the Item and Customer objects separately in the controller, but the main design pattern still applies.

Body:
The logic of deactivating a customer should exist on a Customer class. Only after pulling the customer from the database and modifying its value should you then save it back to the database. Furthermore, the logic of deactivating an item should go on the Item class. To make this happen, you need a more descriptive relationship between Item and Customer:

public class Customer
{
    public bool IsActive { get; set; }
    public long CustomerId { get; set; }

    public void Deactivate()
    {
        IsActive = false;
    }
}

public class Item
{
    public bool IsActive { get; set; }
    public long CustomerId { get; set; }
    public Customer Customer { get; set; }

    public void Deactivate()
    {
        IsActive = false;

        if (Customer != null)
        {
            Customer.Deactivate();
        }
    }
}

Now your repository classes don't need this business logic -- in fact repositories should not have any business logic in them for the exact same reason that you are posting this question. It's hard to reuse business logic. The real change happens in the code using the repository classes:

public class ItemsController : Controller
{
    public ActionResult Deactivate(long id)
    {
        using (var db = new DbContext())
        {
            var item = db.Items.Find(id);

            item.Deactivate();

            db.SaveChanges();
        }
    }
}

(using Entity Framework as an example)

Create the database context object inside a using block so it gets properly disposed if an exception gets thrown

Fetch the Item from the database context

Call Deactivate() on the item

The item deactivates itself, then calls Deactivate on the Customer.

End the transaction by calling db.SaveChanges() to persist any domain object changes to the database

If you aren't using Entity Framework, you might need to explicitly save the Item and Customer objects separately in the controller, but the main design pattern still applies.


问:
Is a function immediately impure if it takes a function as a parameter?
Since the purity of an input parameter is an unknown until runtime, is a function immediately considered impure if it takes a function as an input parameter?

Related: if a function applies a pure function that is defined outside of the function, but is not passed in as a parameter, is it still pure if it fulfills the criteria of having no side effects and output depends solely on input?

For context, I'm writing functional code in JavaScript.

答:
Since the purity of an input parameter is an unknown until runtime, is a function immediately considered impure if it takes a function as an input parameter?

No. Counterexample:

```<code>function pure(other_function) {
    return 1;
}
</code>```

It doesn't matter whether other_function is a pure function, an impure function, or not a function at all. The pure function is pure.

Other counterexample:

```<code>function identity(x) {
    return x;
}
</code>```

This function is pure, even if x is an impure function. identity(impure_function) will always return impure_function, no matter how many times you repeat the call. It doesn't matter whether identity(impure_function)() always returns the same thing; a function's return value's return value doesn't affect its purity.

In general, if a function might call a function it was passed as an argument, it's not pure. For example, a function function call(f) {f();} isn't pure, because even though it makes no mention of any global or mutable state, f might be something like alert that causes visible side effects.

If a function takes functions as arguments, but it doesn't call them or cause them to be called, then it can be pure. It might still be impure if it does some other impure thing. For example, function f(ignored_function) {alert('This isn't pure.');} is impure, even though it never calls ignored_function.

ContentLicense: CC BY-SA 3.0

Body:
Since the purity of an input parameter is an unknown until runtime, is a function immediately considered impure if it takes a function as an input parameter?

No. Counterexample:

function pure(other_function) {
    return 1;
}

It doesn't matter whether other_function is a pure function, an impure function, or not a function at all. The pure function is pure.

Other counterexample:

function identity(x) {
    return x;
}

This function is pure, even if x is an impure function. identity(impure_function) will always return impure_function, no matter how many times you repeat the call. It doesn't matter whether identity(impure_function)() always returns the same thing; a function's return value's return value doesn't affect its purity.

In general, if a function might call a function it was passed as an argument, it's not pure. For example, a function function call(f) {f();} isn't pure, because even though it makes no mention of any global or mutable state, f might be something like alert that causes visible side effects.

If a function takes functions as arguments, but it doesn't call them or cause them to be called, then it can be pure. It might still be impure if it does some other impure thing. For example, function f(ignored_function) {alert('This isn't pure.');} is impure, even though it never calls ignored_function.


问:
string.format with variables vs inline variables
What are the pros/cons (if any) to using

```<code>string output;
int i = 10;
output = string.Format("the int is {0}", i);
</code>```

versus

```<code>string output;
int i = 10;
output = "the int is " + i;
</code>```

I have always used the latter example, but it seems as though a good majority of online tutorials use the string.format example. I don't think that there are any real differences in terms of efficiency, my initial thought is so a coder doesn't have to keep breaking the string to insert variables.

答:
Ref: String output: format or concat in C#?

Consider this code.

It's a slightly modified version of your code.

I removed Console.WriteLine as it's probably few orders of magnitude slower than what I'm trying to measure.

I'm staring the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example 26.4 ticks to execute.

The way you divided result by number of iterations was wrong. See what hapens if you have 1000 milliseconds and 100 milliseconds. In both situations you will get 0 ms after dividing it by 1000000.

```<code>Stopwatch s = new Stopwatch();

var p = new { FirstName = "Bill", LastName = "Gates" };

int n = 1000000;
long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;

string result;
s.Start();
for (var i = 0; i < n; i++)
    result = (p.FirstName + " " + p.LastName);
s.Stop();
cElapsedMilliseconds = s.ElapsedMilliseconds;
cElapsedTicks = s.ElapsedTicks;
s.Reset();
s.Start();
for (var i = 0; i < n; i++)
    result = string.Format("{0} {1}", p.FirstName, p.LastName);
s.Stop();
fElapsedMilliseconds = s.ElapsedMilliseconds;
fElapsedTicks = s.ElapsedTicks;
s.Reset();

Console.Clear();
Console.WriteLine(n.ToString()+" x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks");
Console.WriteLine(n.ToString() + " x result = (p.FirstName + \" \" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks");
Thread.Sleep(4000);
</code>```

Those are my results:

1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 618ms - 2213706 ticks
1000000 x result = (p.FirstName + " " + p.LastName); took: 166ms - 595610 ticks
```

Body:
Ref: String output: format or concat in C#?

Consider this code.

It's a slightly modified version of your code.

I removed Console.WriteLine as it's probably few orders of magnitude slower than what I'm trying to measure.

I'm staring the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example 26.4 ticks to execute.

The way you divided result by number of iterations was wrong. See what hapens if you have 1000 milliseconds and 100 milliseconds. In both situations you will get 0 ms after dividing it by 1000000.

Stopwatch s = new Stopwatch();

var p = new { FirstName = "Bill", LastName = "Gates" };

int n = 1000000;
long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0;

string result;
s.Start();
for (var i = 0; i < n; i++)
    result = (p.FirstName + " " + p.LastName);
s.Stop();
cElapsedMilliseconds = s.ElapsedMilliseconds;
cElapsedTicks = s.ElapsedTicks;
s.Reset();
s.Start();
for (var i = 0; i < n; i++)
    result = string.Format("{0} {1}", p.FirstName, p.LastName);
s.Stop();
fElapsedMilliseconds = s.ElapsedMilliseconds;
fElapsedTicks = s.ElapsedTicks;
s.Reset();

Console.Clear();
Console.WriteLine(n.ToString()+" x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks");
Console.WriteLine(n.ToString() + " x result = (p.FirstName + \" \" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks");
Thread.Sleep(4000);

Those are my results:

1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 618ms - 2213706 ticks
1000000 x result = (p.FirstName + " " + p.LastName); took: 166ms - 595610 ticks


问:
What is the role of the public folder in MVC web applications?
Must all the controllers, models and views be placed in the private folders? If so, what are the roles of the public folder? What are the correct terminologies for such roles in computer science? How does the GUI relate with such concepts?

Otherwise, does the controllers and/or views have to be distributed across the private and public folders? In that case, the scripts that are directly invoked via POST, are just interfaces, or controller interfaces, or view interfaces?

答:
The role of the public folder is to have those views that would be publicly accessible in the application. For example, a Login page would generally be a page that anonymous users could access to then log into the site.

Some MVC web applications may not have any public pages as they may use some internal security system that checks before accessing any page such as a SharePoint site that may use Windows credentials to identify users as an example so it can exist but doesn't have to exist.

Within Computer Science this would fall under Information Security and looking at Authorization policies. Each application may use different methods for enforcing security so this could go in a bunch of different directions potentially.

GUI being the Graphical User Interface fits as part of the architecture here. Each view is a User Interface and thus a GUI may well interact with the View portion where the public and private folder concept would apply within security behind the scenes though some sites may use locks and other symbols to denote what pages require authentication and authorization to visit.

Controllers can be lumped into a folder though some may want them spread and depending on the technologies used there may be different ways to implement this. Views would likely be in folders that again depending on the technologies could have security handled in various ways.

POST requests to the server would likely go through a controller to a view in the MVC architecture since there would likely be data to process that is the role of the controller. The view is responsible for returning to the user the data of the page requested.

In response to the comment:

Controller security could be done on a file level or on a function level where the latter may make more sense in some cases as the same controller could have different functions. For example, consider the Yahoo! home page where if you aren't signed in, then the most popular stuff may be shown while if you are signed in then the personalized page would be shown that could be going through the same base controller potentially. Thus, file level permissions would be pointless here since all the controller code would likely be run under the same server account.

While there can exist some web applications that have no public views, this depends a great deal on how one wants to implement security which can be done in various ways using various technologies, not unlike how two people communicate can be done in various formats, languages and grammar. Keep in mind that by keeping this so generic, there are likely dozens of different answers depending on what implementation you choose to use, e.g. you could take ASP.Net Webforms and implement your own MVC or you could use ASP.Net MVC or you could look into PHP open source code bases that may implement the pattern, etc.


问:
Dependency Injection: Field Injection vs Constructor Injection?
I know this is a hot debate and the opinions tend to change over time as to the best approach practice.

I used to use exclusively field injection for my classes, until I started reading up on different blogs (exs: petrikainulainen and schauderhaft and fowler) about the benefits of constructor injection.  I have since switched my methodologies to use constructor injection for required dependencies and setter injection for optional dependencies.

However, I have recently gotten into a debate with the author of JMockit - a mocking framework - in which he sees constructor & setter injection as bad practice and indicates that the JEE community agrees with him.

In today's world, is there a preferred way of doing injection?  Is Field injection preferred?

Having switched to constructor inject from field injection in the last couple of years, I find it a lot clearer to use, but I am wondering if I should re-examine my viewpoint.  The author of JMockit (Rogério Liesenfeld), is clearly well versed in DI, so I feel obligated to review my approach given that he feels so strongly against constructor/setter injection.

答:
Field injection is a bit too "spooky action at a distance" for my taste.

Consider the example you provided in your Google Groups post:

```<code>public class VeracodeServiceImplTest {

    @Tested(fullyInitialized=true)
    VeracodeServiceImpl veracodeService;
    @Tested(fullyInitialized=true, availableDuringSetup=true)
    VeracodeRepositoryImpl veracodeRepository;
    @Injectable private ResultsAPIWrapper resultsApiWrapper;
    @Injectable private AdminAPIWrapper adminApiWrapper;
    @Injectable private UploadAPIWrapper uploadApiWrapper;
    @Injectable private MitigationAPIWrapper mitigationApiWrapper;

    static { VeracodeRepositoryImpl.class.getName(); }
...
}
</code>```

So basically what you are saying is that  "I have this class with private state, to which I have attached @injectable annotations, which means that the state can be automagically populated by some agent from the outside, even though my state has all been declared private."

I understand the motivations for this.  It is an attempt to avoid much of the ceremony that is inherent in setting up a class properly.  Basically, what one is saying is that "I'm tired of writing all of this boilerplate, so I'm just going to annotate all of my state, and let the DI container take care of setting it for me."

It's a perfectly valid point of view.  But it's also a workaround for language features that arguably should not be worked around.  Also, why stop there?  Traditionally, DI has relied on each class having a companion Interface.  Why not eliminate all those interfaces with annotations as well?

Consider the alternative (this is going to be C#, because I know it better, but there's probably an exact equivalent in Java):

```<code>public class VeracodeService
{
    private readonly IResultsAPIWrapper _resultsApiWrapper;
    private readonly IAdminAPIWrapper _adminApiWrapper;
    private readonly IUploadAPIWrapper _uploadApiWrapper;
    private readonly IMitigationAPIWrapper _mitigationApiWrapper;

    // Constructor
    public VeracodeService(IResultsAPIWrapper resultsApiWrapper, IAdminAPIWrapper adminApiWrapper, IUploadAPIWrapper uploadApiWrapper,         IMitigationAPIWrapper mitigationApiWrapper)
    {
         _resultsAPIWrapper = resultsAPIWrapper;
         _adminAPIWrapper = adminAPIWrapper;
         _uploadAPIWrapper = uploadAPIWrapper;
         _mitigationAPIWrapper = mitigationAPIWrapper;
    }
}
</code>```

Already I know some things about this class.  It's an immutable class; state can only be set in the constructor (references, in this particular case).  And because everything derives from an interface, I can swap out implementations in the constructor, which is where your mocks come in.

Now all my DI container has to do is reflect over the constructor to determine what objects it needs to new up.  But that reflection is being done on a public member, in a first-class way; i.e. the metadata is already part of the class, having been declared in the constructor, a method whose express purpose is to provide the class with the dependencies it needs.

Granted this is a lot of boilerplate, but this is how the language was designed.  Annotations seem like a dirty hack for something that should have been built into the language itself.

Body:
Field injection is a bit too "spooky action at a distance" for my taste.

Consider the example you provided in your Google Groups post:

public class VeracodeServiceImplTest {

    @Tested(fullyInitialized=true)
    VeracodeServiceImpl veracodeService;
    @Tested(fullyInitialized=true, availableDuringSetup=true)
    VeracodeRepositoryImpl veracodeRepository;
    @Injectable private ResultsAPIWrapper resultsApiWrapper;
    @Injectable private AdminAPIWrapper adminApiWrapper;
    @Injectable private UploadAPIWrapper uploadApiWrapper;
    @Injectable private MitigationAPIWrapper mitigationApiWrapper;

    static { VeracodeRepositoryImpl.class.getName(); }
...
}

So basically what you are saying is that  "I have this class with private state, to which I have attached @injectable annotations, which means that the state can be automagically populated by some agent from the outside, even though my state has all been declared private."

I understand the motivations for this.  It is an attempt to avoid much of the ceremony that is inherent in setting up a class properly.  Basically, what one is saying is that "I'm tired of writing all of this boilerplate, so I'm just going to annotate all of my state, and let the DI container take care of setting it for me."

It's a perfectly valid point of view.  But it's also a workaround for language features that arguably should not be worked around.  Also, why stop there?  Traditionally, DI has relied on each class having a companion Interface.  Why not eliminate all those interfaces with annotations as well?

Consider the alternative (this is going to be C#, because I know it better, but there's probably an exact equivalent in Java):

public class VeracodeService
{
    private readonly IResultsAPIWrapper _resultsApiWrapper;
    private readonly IAdminAPIWrapper _adminApiWrapper;
    private readonly IUploadAPIWrapper _uploadApiWrapper;
    private readonly IMitigationAPIWrapper _mitigationApiWrapper;

    // Constructor
    public VeracodeService(IResultsAPIWrapper resultsApiWrapper, IAdminAPIWrapper adminApiWrapper, IUploadAPIWrapper uploadApiWrapper,         IMitigationAPIWrapper mitigationApiWrapper)
    {
         _resultsAPIWrapper = resultsAPIWrapper;
         _adminAPIWrapper = adminAPIWrapper;
         _uploadAPIWrapper = uploadAPIWrapper;
         _mitigationAPIWrapper = mitigationAPIWrapper;
    }
}

Already I know some things about this class.  It's an immutable class; state can only be set in the constructor (references, in this particular case).  And because everything derives from an interface, I can swap out implementations in the constructor, which is where your mocks come in.

Now all my DI container has to do is reflect over the constructor to determine what objects it needs to new up.  But that reflection is being done on a public member, in a first-class way; i.e. the metadata is already part of the class, having been declared in the constructor, a method whose express purpose is to provide the class with the dependencies it needs.

Granted this is a lot of boilerplate, but this is how the language was designed.  Annotations seem like a dirty hack for something that should have been built into the language itself.


问:
Why aren't named switch statements a language feature?
I could imagine the below code being somewhat useful. Is there a reason this pattern hasn't made it into programming languages?

To be clear the string was just what I chose as an example you could substitute near any type you like for the input and my question would still apply.

```<code>public string switch findLastName(string firstName)
{
    case "John":
        return "Johnson";
    case "Susan":
        return "Stevens";
    case "Tyler":
        return "Gomez";
    default:
        return "Smith";
}
</code>```

Instead of:

```<code>public string findLastName(string firstName)
{
    switch(firstName)
    {
        case "John":
            return "Johnson";
        case "Susan":
            return "Stevens";
        case "Tyler":
            return "Gomez";
        default:
            return "Smith";
    }
}
</code>```

答:
You mean a String switch?

Most language constructs translate directly to a few instructions.

However deciding which string a given one matches is more complicated. The simplest method is trying each one by one. The more complicated and memory intensive but faster way is using a prefix trie or hashmap (or hashtable) out of which you can get an integer which you can switch on. However there are several implementations of both and different hash functions, each with their own trade-offs; forcing a implementation-dependent one-size-fits-all on the programmer will not be a good thing™.

Or do you mean mapping a string (or any other object) to another value?

That is solved using (again) a prefix trie or hashmap (or hashtable).

As for why that type of mapping isn't built in...

It's a single line of code that you save for an idiom that is frankly not all that common. That's not worth worrying about.


答:
Fundamentally it isn't in any language because it doesn't give you much over a function; the standard way to create a reusable "chunk" of code. For example your example can be created easily as follows

```<code>public string findId(string firstName) {
    switch(firstname) {
        case "John": return "Johnson";
        case "Susan": return "Stevens";
        case "Tyler": return "Gomez";
        default: return "Smith";
    }
}
</code>```

(This particular use of a switch statement probably isn't a good idea but I understand that this is just an example)

If we are to support named switch statements should we also support named while and for loops, named if statements etc. All these can easily be implemented already as functions but in a far more flexible way

Title: Why aren't named switch statements a language feature?

Body:
I could imagine the below code being somewhat useful. Is there a reason this pattern hasn't made it into programming languages?

To be clear the string was just what I chose as an example you could substitute near any type you like for the input and my question would still apply.

```<code>public string switch findLastName(string firstName)
{
    case "John":
        return "Johnson";
    case "Susan":
        return "Stevens";
    case "Tyler":
        return "Gomez";
    default:
        return "Smith";
}
</code>```

Instead of:

```<code>public string findLastName(string firstName)
{
    switch(firstName)
    {
        case "John":
            return "Johnson";
        case "Susan":
            return "Stevens";
        case "Tyler":
            return "Gomez";
        default:
            return "Smith";
    }
}
</code>```

Body:
Fundamentally it isn't in any language because it doesn't give you much over a function; the standard way to create a reusable "chunk" of code. For example your example can be created easily as follows

public string findId(string firstName) {
    switch(firstname) {
        case "John": return "Johnson";
        case "Susan": return "Stevens";
        case "Tyler": return "Gomez";
        default: return "Smith";
    }
}

(This particular use of a switch statement probably isn't a good idea but I understand that this is just an example)

If we are to support named switch statements should we also support named while and for loops, named if statements etc. All these can easily be implemented already as functions but in a far more flexible way


问:
How do you combine licensed data and event sourcing?
Hypothetical problem, inspired by How to query Aggregate Root to react to event from other AR  How should an event sourced application handle data, where the license to that data can expire?

Example: the model includes sensitive billing information; when an account is closed, the billing information for that client needs to be scrubbed from the system.

Example: data is licensed from a 3rd party vendor; the agreement specifies that at then end of the license period, the data needs to be removed.

答:
I suspect these are orthogonal concerns.  Removal of data when some date expires is an aging process; either the data is removed or marked deleted by some scheduled process, or it doesn't get through the security filter (which has as one of its rules to not let through resources which have expired).

That said, if you want to look at it from an event-driven perspective, you simply add a rule to the event filter that inhibits the firing of the event if the resource has expired.  Or you fire an event that puts the resource into the recycle bin instead (hypothetically speaking).


问:
Scala: DSL for repetitive algroritms
So, very often in your code you have statements/algorithms like this one:

```<code>if (!myCollection.contains(unit))
  throw new IllegalArgumentException(s"$unit is not available")
</code>```

The issue which I have with this approach that it clutters you source-code - this is especially true if you need extensive checks.

I was thinking if such repetitive algorithms, checks etc. are more elegant solvable in scala, e.g. by a DSL ?

答:
While you can use certain abstractions like a DSL to simplify things like argument checking, in functional programming, that sort of error handling by side effect is usually avoided altogether by the way you structure your program.

For example, an availability check might look something like this:

```<code>def firstAvailableUnit(): Option[Unit] = {
  val available = units filter {_.available == true }
                        filter {_.occupancy == 4 }
                        filter {_.haunted   == false }

  available.headOption
}

// The calling code:
println(firstAvailableUnit() map {_.name} getOrElse "No units available")
</code>```

OOP uses a sort of blunt-instrument approach to validation.  Once you get the hang of the idiomatic FP way, it feels a little like your arguments are almost already magically validated for you.

Title: Scala: DSL for repetitive algroritms

Body:
While you can use certain abstractions like a DSL to simplify things like argument checking, in functional programming, that sort of error handling by side effect is usually avoided altogether by the way you structure your program.

For example, an availability check might look something like this:

def firstAvailableUnit(): Option[Unit] = {
  val available = units filter {_.available == true }
                        filter {_.occupancy == 4 }
                        filter {_.haunted   == false }

  available.headOption
}

// The calling code:
println(firstAvailableUnit() map {_.name} getOrElse "No units available")

OOP uses a sort of blunt-instrument approach to validation.  Once you get the hang of the idiomatic FP way, it feels a little like your arguments are almost already magically validated for you.


答:
In many MVC frameworks (e.g. Rails), the public folder is used to serve static files. So for example, you often see 404.html, 500.html and favicon.ico files in there when creating the project through the "usual" means provided by such frameworks. These are "dumb" files that don't interact w/the backend. The assumption is that these don't require a context generated by your controllers to render them; for example the 404.html might just express that nothing exists at this URL, where the URL is something that isn't matched by the framework's routing system.

You may also see compiled assets placed there (e.g. a framework's asset pipeline combining multiple CSS files into one to reduce # of connections required to render a page).

Additionally, when deployed to a non-development webserver, the webroot is often set to the public directory.

Re: how a GUI relates to this concept... well it's a stretch to associate these things, but assuming you are using an IDE that has source control features (e.g. git integration) it might be automatically detected as containing directories to exclude from version control. For instance, you probably do not want your compiled assets showing up in your repository since they can be generated by the committed pipeline config combined w/the dev files.

Title: What is the role of the public folder in MVC web applications?

Body:
Must all the controllers, models and views be placed in the private folders? If so, what are the roles of the public folder? What are the correct terminologies for such roles in computer science? How does the GUI relate with such concepts?

Otherwise, does the controllers and/or views have to be distributed across the private and public folders? In that case, the scripts that are directly invoked via POST, are just interfaces, or controller interfaces, or view interfaces?


问:
Understaing the "fillable" in Laravel migration
Using models is one the best facts in Laravel, but when using a model, it is not like my "native" environment (J2EE, models declare all DB table colums), it has three variable, and which of them is "fillable". When seeing the tutorials online, the fillable hold some specific data like in a table :

```<code>Table : Users
Fields : Name, Email, Id, Password
</code>```

They put protected $fillable = ['nom', 'email', 'password']; which means we've got rid of the id .. But the word fillable means something we can fill and it makes sense hince the ID is auto-incremented, but let's say I want to execute some update to JUST the name field, will that return an error cause the fillable instruction contain 2 additional fields ? As in their documentation :

 You may also use the create method to save a new model in a single line.
The inserted model instance will be returned to you from the method.
However, before doing so, you will need to specify either a fillable or
guarded attribute on the model, as all Eloquent models protect against
mass-assignment.

  A mass-assignment vulnerability occurs when a user passes an unexpected
 HTTP parameter through a request, and that parameter changes a column in
your database you did not expect. For example, a malicious user might send
an is_admin parameter through an HTTP request, which is then mapped onto
 your model's create method, allowing the user to escalate themselves to an
 administrator.
```

From which I resume : If a single input is sent in a HTTP request WITHOUT other inputs (mass), it will stopped ? Or that the user have to enter each of them in inputs to get them inserted ? In that case what happens if a value isn't set (null) ? It will be considered as not filled ?

答: Say we want to protect the role field from being mass-assignment, so, there are two ways to do this in the User model. We can either specify a $guarded property to specify a list of fields that we want to exclude from mass-assignment, or we can specify a $fillable property to specify a list of fields that we want to allow for mass-assignment


问:
Best way to develop new features as well as fix any bugs for a web system on Windows
I'm a one-man band and I have a contract with a client to develop and maintain a web-based system that is relied upon. This is the first project of this size and type that I have done for anyone else so I'm still finding my feet a bit in that respect and I'm not sure on any standard practices.

The current situation is that the live system is hosted on a VPS and I have a copy of the system on my local Windows machine with MySQL and PHP installed so that I can develop new features locally and then sync the files with the VPS once I have finished them. This works great, however the complications come when there are any bugs in the system - at which point I'm not sure what to do?

At the minute, I've created another local copy of the system for the purposes of fixing bugs but whilst this enables to sync to the VPS without also syncing any incomplete features, that means that the version of the system which I develop features on still contains the bugs that I have fixed. The only thing I can think of to solve this is to manually copy any changes I made in the bug fixing version, but this seems quite inefficient and impractical once more than one person starts working on a project (which I hope will be the case soon).

I would appreciate if people could share their solutions to situations that may be similar to mine, as I appreciate that no situation is identical and that people may have different solutions to the same problem. For your information as well, I prioritise the fixing of bugs over the implementation of new features.

答:
My suggestion would be to get a version control system that would allow for branching, e.g. Subversion and Git would both be free ones that can be used, so that you can have branches for features, bugs and releases so that you can revert your code to various states easily.

Here are some links to help with the basics:

Subversion link about branching: http://svnbook.red-bean.com/en/1.7/svn.branchmerge.html

Git link about branching: http://pcottle.github.io/learnGitBranching/

I'd put this in place ASAP as this allows for rolling back changes as well as being a reasonable way to move forward knowing which version has had which bug and what patches are applied for which branches, etc.


答:
As Telastyn said: Technically, yes, unless there is some way in your language to guarantee that the input function is also pure.

That's not hypothetical, there are indeed good ways to guarantee this. At least in a strongly typed language.

Such a pure~ function you'd write in JavaScript as

```<code>function foo(f) {
   return f(1) + 2;
}
</code>```

can be translated directly to Haskell:

```<code>foo :: (Int -> Int) -> Int
foo f = f 1 + 2
</code>```

Now, in JavaScript you can do evil stuff like

```<code>js> foo (function(x) {console.log("muharhar"); return 0})
muharhar
2
</code>```

This is not possible in Haskell. The reason being, something side-effect-ful like console.log() must always have a result type IO something, not just something alone.

```<code>GHCi> foo (\x -> print "muarhar" >> return 0)

<interactive>:7:12:
    Couldn't match expected type ‘Int’ with actual type ‘IO b0’
    In the expression: print "muarhar" >> return 0
    In the first argument of ‘foo’, namely
      ‘(\ x -> print "muarhar" >> return 0)’
    In the expression: foo (\ x -> print "muarhar" >> return 0)
</code>```

For this expression to typecheck, we would need to give foo the type signature

```<code>foo :: (Int -> IO Int) -> Int
</code>```

But it turns out I cannot implement it anymore then: because the argument function has IO in its result, I can not use it within foo.

```<code><interactive>:8:44:
    Couldn't match expected type ‘Int’ with actual type ‘IO Int’
    In the first argument of ‘(+)’, namely ‘f 1’
    In the expression: f 1 + 2
</code>```

The only way I could use an IO action in foo is if the result of foo has type IO Int itself:

```<code>foo :: (Int -> IO Int) -> IO Int
foo f = do
   f1 <- f 1
   return (f1 + 2)
</code>```

But at this point it's clear from the signature of foo that it is not a pure function, either.

Title: Is a function immediately impure if it takes a function as a parameter?

Body:
Since the purity of an input parameter is an unknown until runtime, is a function immediately considered impure if it takes a function as an input parameter?

Related: if a function applies a pure function that is defined outside of the function, but is not passed in as a parameter, is it still pure if it fulfills the criteria of having no side effects and output depends solely on input?

For context, I'm writing functional code in JavaScript.

Body:
As Telastyn said: Technically, yes, unless there is some way in your language to guarantee that the input function is also pure.

That's not hypothetical, there are indeed good ways to guarantee this. At least in a strongly typed language.

Such a pure~ function you'd write in JavaScript as

function foo(f) {
   return f(1) + 2;
}

can be translated directly to Haskell:

foo :: (Int -> Int) -> Int
foo f = f 1 + 2

Now, in JavaScript you can do evil stuff like

js> foo (function(x) {console.log("muharhar"); return 0})
muharhar
2

This is not possible in Haskell. The reason being, something side-effect-ful like console.log() must always have a result type IO something, not just something alone.

GHCi> foo (\x -> print "muarhar" >> return 0)

<interactive>:7:12:
    Couldn't match expected type ‘Int’ with actual type ‘IO b0’
    In the expression: print "muarhar" >> return 0
    In the first argument of ‘foo’, namely
      ‘(\ x -> print "muarhar" >> return 0)’
    In the expression: foo (\ x -> print "muarhar" >> return 0)

For this expression to typecheck, we would need to give foo the type signature

foo :: (Int -> IO Int) -> Int

But it turns out I cannot implement it anymore then: because the argument function has IO in its result, I can not use it within foo.

<interactive>:8:44:
    Couldn't match expected type ‘Int’ with actual type ‘IO Int’
    In the first argument of ‘(+)’, namely ‘f 1’
    In the expression: f 1 + 2

The only way I could use an IO action in foo is if the result of foo has type IO Int itself:

foo :: (Int -> IO Int) -> IO Int
foo f = do
   f1 <- f 1
   return (f1 + 2)

But at this point it's clear from the signature of foo that it is not a pure function, either.


问:
What's the REAL benefit of using CDECL? (more specifically pushing instead of reg-ing)
So, I'm learning assembly, and I've come to know the ABIs and i got some basics tests working using the cdecl calling convention to use the c's stdlib under nasm.
But I've seen other Calling Conventions (like topspeed/Clarion/JPI/watcom/borland register(delphi), fastcall, etc).
And I wonder, what are the REAL benefits of using cdecl instead of Clarion.
More specifically Pushing instead of using the registers.

This are some of the benefits i imagined please let me know which of these apply.

I've read that cdecl is important because it allows to use variable parameters, but as I see it, I can do the same using registers.
The problems are to know the count, type and order of the params, but that problem exists on cdecl too. It can be inferred from the format string (in printf) or from the function signature. And if I run out of registers I can push the rest of the params.

I imagine that performance shouldn't be a big thing because cpus manufactures might have optimized everything that they could regardless of the calling convention of mayor use (and this time is cdecl?¿?).
But if I think of raw operations (and disregard caches and writeback buffers) I think it should be faster to use registers instead of the stack (which should be located in ram right?). I mean, is like "inc eax" vs "add eax, 1" (am I right?).

By pushing i create a memory space that goes off when I ret (just like creating a local variable).
That might seem handy (to have a local var just by the time of being called).

But, as most params (in my experience) are used as a read value, and very few times we need them as a variable, to store mutated values, and when you do you are actually dealing with complex structures that are passed as pointers anyway.

So I don't really see the value on creating a memory space BEFORE actually needing it.

As I see, if I do need a variable is better to have the option to create it (like in clarion), but if I don't it would be nice to be able to not create it (like you can't in cdecl).

You preserve the registers.

I can't even think of a positive side. AFAIK the registers are used for intermediary calculations, and as such are volatile in nature. If I think of them as volatile I could push/pop/mov them whenever i need to "hold" the value and only in such cases.
In that sense I see it as the most efficient use (I only access the ram when i need it).

But if I don't do that, and try to "preserve the registers":

callee: I have no certainty whatsoever what the callee code will do with a register (unless is being documented or they adhere to the same calling convention). By hoping it will preserve them, it imposes an artificial constraint on the callee. As the callee has no idea which registers need to be really preserved they'll tend to overpreserve unnecessary registers. (like pusha/popa in x86?) Which sounds really inefficient to me.

caller: the caller have no idea what registers will the callee [s]taint?[/s] use, so it'll just preserve all of them. It'll end up with the same inefficient result as before.

I noticed that linux syscalls as well as 8086 (from my old classes) use registers instead of stack to pass parameters. What happened there?

So those are my thoughts, thanks for all the clarification possible.

Notes:

I am learning, most of this are assumptions based on what i've readed/tried so far. i'll be glad if you correct me as needed (just be nice).

I do understand this are all x86 CC, and in 64 there is another (which i'm not familiar with).

I am not asking which is the "best", i just want to understand more and clarify my assumptions.

I am looking for benefits of the calling convention by itself (by contrasting with others). not by it's side-effects (like compilers and cpus being optimized or its ubiquity)

Basically a theoretical question to understand more of why that way was chosen

答:
Raymond Chen put together a history of calling conventions here. While he doesn't touch on Clarion, he does touch on Fastcall, which while not the same as Clarion does use more of a register-based approach.

He has this to say:

Fastcall (__fastcall)

The Fastcall calling convention passes the first parameter in the DX register and the second in the CX register (I think). Whether this was actually faster depended on your call usage. It was generally faster since parameters passed in registers do not need to be spilled to the stack, then reloaded by the callee. On the other hand, if significant computation occurs between the computation of the first and second parameters, the caller has to spill it anyway. To add insult to injury, the called function often spilled the register into memory because it needed to spare the register for something else, which in the "significant computation between the first two parameters" case means that you get a double-spill. Ouch!

Consequently, __fastcall was typically faster only for short leaf functions, and even then it might not be.

I believe the criticism applied here is still relevant - Clarion is likely faster for certain types of calls, but not others.

That being said, your points about the register usage are quite valid. While you did not want to consider x64 in the scope of your question, the pattern discussed later in that series for Itanium might interest you!

ContentLicense: CC BY-SA 4.0


问:
Should I document expected call-sequences when call-order matters?
In dynamically and weakly-typed languages*, I often find myself with structures like the following pseudocode:

```<code>class Stateful:

    # [ various datamembers / attributes / properties / fields / etc. ]

    define constructor(arguments):
        configureA(arguments)
        # [ maybe set a variable or two here ]
        configureB()

    define configureA():
    ## configures the most important parts of Stateful state
    ## throws some exceptions if these basic changes cannot be made
        # [ code goes here ]

    define configureB():
    ## handles a little bit of bookkeeping. Usually called after configureA().
    ## expects the following variables to be set: <list of vars>
        # [ code goes here ]
    #
    # ...
</code>```

Though there may be a better way to do this such as providing a single block that describes the call-sequence and notes consequences all in once place, is it a good idea in general to document expected call-sequences? If it is a good idea to "just document" this sort of thing when it comes up, are there established best-practices?  Or is doing so perhaps a sign of a deeper problem?

* Answers to this question suggest that configureA() return a type which is required by configureB(), then have configureB() return a type which is required by configureC(), etc. I'm asking here about languages which are weakly and/or dynamically typed, or in instances wherein adding extra classes for each configuration-step would just yield a bunch of smallish classes with low to no reusability and poor maintainability given a need for even more classes if config gains steps.

My mixed thoughts about this follow below the line:

Reasons to document expected call-sequences (in some form or other):

Such comments often help me track down would-be mysterious errors in my code, by leading me to re-examine call-sequences after periods of being focused on other implementation-details.

If code for stateful classes needs to be updated, this should help other programmers avoid such mysterious errors as well.

Especially for private functions, describing functions' "contracts" in comments allows me to focus on essential functionality in and less on throw new DescriptiveErrorMessage("Let's talk for a while, shall me? ..."). Even in the case where exceptions should ultimately be thrown, I find it easier to go back and examine exception-cases after I've been apart from the real "working" part of the code for a while.

Not other all programmers will be using IDEs capable of generating information about standing call-sequences for them, and even if they did, an IDE may not be able to tell a programmer whether a certain sequence of initialization-calls is necessary or just a de-facto "it's in that order because that's how it was written"

Reasons not to do this:

Comments like these are implementation-specific and may not have a lot of usefulness after a class is stabilized.

Comments like these increase code's maintenance-burden because they need to be kept up-to-date in addition to the code itself.

The code should speak for itself and good programmers should use introspection instead of reading my drivel.

Comments specifying these kinds of sequential preconditions may just be a crutch for bad code.

答:
Consider the following "what-if" thought exercise:

Suppose you modify configureA and configureB, so that instead of actually doing the work that is order dependent, the two methods merely save a copy of the parameters that were passed in.

Then, write another method, realConfigureA_and_B which takes those saved parameters, and do the actual work that is order dependent.

The question to ask is: if you split the functions this way, will the clients of this class fail? Will the clients need to do things with this class while the class has already configured A but not B (being in a state of partially initialized)?

If the clients don't actually care, then it might be the case that the order dependency could be removed in some way by rearranging code, or by merging code from some functions into a single function.

If the clients can't tolerate this, then in other programming languages it would be a sign that the class is doing too much work, and needs to be split up into several classes.

Other options. In some other programming paradigms, ...

The class may require the clients to provide already-initialized instances of A and B, instead of doing it inside the class.

The class may implement lazy-initialization for A and B, that is, it postpones the initialization until it cannot do that anymore, then it will initialize what is needed.

The class may require its clients to provide some callbacks, whose job is to help initialize those things. The class is in control of the order of initialization, and the clients are required to follow the class's choice of ordering, and to provide the initialization info upon request.


问:
Is it a reasonable task to automatically convert ANTLR grammars to my own format?
I was working on my own parser generator tool in Clojure and then I realised I want to test it with some real programming languages.
I can find a lot of existing language grammars only in antlr v4 format.

That means if I can automatically translate antlr grammars to my own format, I can get them all. Is that a reasonable task(because I haven't noticed other parser generators with antlr-converters, so there must be something hard)

答:
Is translating ANTLR grammars to my own format a reasonable task?

That depends on your definition of reasonable. If you mean "achievable" or "worthwhile given the time and effort required", that is only something you can answer. Presumably, if you have written your own parser, this should not be too difficult.

If you mean "legal" (e.g. violating copyrights or patents), that depends on the individual or organization that created the ANTLR grammar. Some grammars may be licensed or have other legal protections. For example, a grammar licensed under GPL may require any works based on this (such as your own grammars or code generated to parse it) to also be licensed under GPL. If in doubt, talk to a legal professional or the person or organization that created or is responsible for the grammar.

If you mean "looked down upon", "cutting corners" or "being lazy", all grammars have been derived from something. Once you have written a few grammars, there are diminishing returns for doing everything from scratch. I would talk to other members of the parser/lexer community and see what they do.

If you mean "best practice", as @RubberDuck has said, some published grammars may have errors or omissions. Carefully check any third party grammars before copying them. You may want to derive your own then use other grammars as a reference or test data.


答:
The argument of less test initialization boiletplate is valid, but there are other concerns that must be taken into account. First of all, you have to answer a question:

Do I want my class to be instantiable only with reflection?

Using field injections means narrowing down compatibility of a class to dependency injection environments that instantiate objects using reflection and support these particular injection annotations. Some platforms based on Java language do not even support reflection (GWT), so field‑injected class will not be compatible with them.

Second issue is performance. A constructor call (direct or by reflection) is always faster than a bunch of reflection field assignments. Dependency injection frameworks must use reflection analysis to build dependency tree and create reflection constructors. This process causes additional performance hit.

Performance affects maintainability. If each test suite must be run in some sort of dependency injection container, a test run of few thousands unit tests may last tens of minutes. Depending of size of a code base, this may be an issue.

This all rises many new questions:

What is the probability of using parts of the code on another platform?

How many unit tests will be written?

How fast do I need to prepare each new release?

...

Generally, the bigger and more important a project is, the more significant these factors are. Also, Quality-wise, we would generally like to the keep the code high on compatiblity, testability and maintainability. From the philosophical point of view, field injection breaks encapsulation, which is one of four fundamentals of object-oriented programming, which is the main paradigm of Java.

Many, many arguments against field injection.

Title: Dependency Injection: Field Injection vs Constructor Injection?

Body:
I know this is a hot debate and the opinions tend to change over time as to the best approach practice.

I used to use exclusively field injection for my classes, until I started reading up on different blogs (exs: petrikainulainen and schauderhaft and fowler) about the benefits of constructor injection.  I have since switched my methodologies to use constructor injection for required dependencies and setter injection for optional dependencies.

However, I have recently gotten into a debate with the author of JMockit - a mocking framework - in which he sees constructor & setter injection as bad practice and indicates that the JEE community agrees with him.

In today's world, is there a preferred way of doing injection?  Is Field injection preferred?

Having switched to constructor inject from field injection in the last couple of years, I find it a lot clearer to use, but I am wondering if I should re-examine my viewpoint.  The author of JMockit (Rogério Liesenfeld), is clearly well versed in DI, so I feel obligated to review my approach given that he feels so strongly against constructor/setter injection.


问:
How to use DAO effectively in my MMO server
I am working on a small multi player game for my final year project and currently working on the server. It's a Tank Battle game and have two main entities which I will use on the server side which are

Player (Player details like username, password, currentTank, statistics)

Tank (Details of a tank like velocity, rotationVelocity, Turret)

Turret(Details of turret like rotation velocity, fireRate, etc)

Statistics(stats like totalKills, total deaths, total shots etc)

I have recently read about DAO and how they separate out the database concerns and thought to use it in my project because my project does have good amount of data to persist and also due to the fact that I want to learn this technique.

After reading about DAO I realised there will be need to map the DTO to Domain Objects for business logic. As I am going to have quite a bit of logic on these object as well methods which are not really needed on DTO's.

So for example I map :

PlayerDTO -> PlayerObject

Whenever there is a request from player to move his tank, I queue the direction in a queue contained in player's tank. (This shows the need for having Domain Object as I don't need movement queue on the database but I need it on the tank objects to queue movements)

Now let's say in my MovementService of my server, I loop through the PlayerObject list (the logged in players) and update player's tank position in by calling the player.moveTank() which will update his positions according to the movement queued in the movement queue inside the TankObject contained in PlayerObject. I understand it till this point what I need to do.

Now my question is how will I save PlayerObject back to Database? Do I need to map it back to PlayerDTO? What is the most effective way to do it?

For now I have thought that when the player logs out,In my LogoutService I will use the PlayerDAO service and get the PlayerDTO using PlayerObject ID and update the object details and save him back to the database but I feel that I will be making extra database calls just to get the object (An extra select call) and to save it back rather than just updating the object using update query.

I also feel that just for updating let's say his position on the database I will have to use a query which will overwrite everything. Is there any better way of doing it or I am doing it right?

Note: I won't be using any ORM in my project.

P.S. I searched a lot but couldn't find any similar question. I know I haven't put any code and it's a long question but if anything is not clear let me know.

答:
Instead of mapping the two, you could have the PlayerObject constructed around a PlayerDTO, and just keep the player info there. When it's time to save, ask it back from the Object.

AFAIK this would work also with ORMs, and one like Hibernate would worry about partial updates (efficiency considerations apart). Another path could be to remember "manually" (say in the object) if only the position has changed, and in that case use a particular DAO method that takes only the position from the DTO. But if you're saving just at the logout, overwrite everything.


问:
Entity Framework in n-tier application confusion
I'm building a rather large (web) application where I'm using Entity Framework to communicate with the database.

My solution is set up in layers like so:

Client

Website (MVC web application)

Server

BusinessLogic (contains, well, business logic. There's a lot of business rules involved in this project)

Repository (contains repository classes for querying the database using EF)

Interfaces (interfaces for defining the repository classes, i.e. IFirmRepository)

Model (contains my edmx file, view models, enums etc)

So, the client/UI knows about the business logic layer where the business classes needed for a given view is injected into the MVC controllers. The business logic layer knows about interfaces and model and the repository implements the interfaces.

Been developing for the last week using this approach, I have a feeling that it's not quite "correct" since:

The repository classes becomes bloated with a lot of methods where I need to use the Include()method to be able to work with the disconnected entities in my business logic layer

For every query, I'm using a new context: using(var ctx = new MyContext()) and a single business logic method might be calling more than one repository method which makes for N number of new MyContext() which isn't ideal, I guess?

Relating to the above: I've read about having one context per http request is the way to go when it comes to websites, which my approach seems to "violate"?

Out of curiousity, I tried to simply make use of the MyContextdirectly in a business logic class, making the query for the object(s) needed and then performing business logic. Doing this felt very smooth/easy and made the repository seem like a lot more work than needed and almost redundant.

So, I guess different projects needs different approaches when it comes to the architecture, but before I scratch my repository completely and making use of the entity framework context directly in my business logic classes, I'd like your opinion on this. It kinda feels wrong (in the sense that I'm violating something) to scratch the repository, but on the other hand, it's so easy to simply do the magic without first defining the method in an interface, then implementing it as a repository and then make use of it in a business logic class.

So, what is your opinion on this? :-) Am I completely off the record here, or?

Thanks in advance.

答:
I think your question is something similar to whether to use repository pattern over Entity framework which I was also researching recently. Here is one link I found with good answers.

The Entity Framework DBContext class already implements Repository pattern. Now, if we should abstract the Entity Framework itself depends on, if this provider (EF) itself is going to change to something like web service, xml etc. In other cases better to go without custom Repository classes.


答:
Many languages support a construct called pattern matching, and this can be used as a fairly close approximation to what you're doing there. For example, in Haskell (and the Haskell experts will have to forgive my syntax, because it's been a while since I did any work with it) your code looks like this:</p>

```<code>findLastName :: string -> string
findLastName "John" = "Johnson"
findLastName "Susan" = "Stevens"
findLastName "Tyler" = "Gomez"
findLastName x = "Smith"
</code>```

Body:
Many languages support a construct called pattern matching, and this can be used as a fairly close approximation to what you're doing there. For example, in Haskell (and the Haskell experts will have to forgive my syntax, because it's been a while since I did any work with it) your code looks like this:

findLastName :: string -> string
findLastName "John" = "Johnson"
findLastName "Susan" = "Stevens"
findLastName "Tyler" = "Gomez"
findLastName x = "Smith"


答:
A version control system is surely what you need, but don't expect it to solve your problems automatically. You need to work with feature branches, and that can be additional effort, especially when merging bugfixes and new features. So I recommend also to learn how feature toggles work. That is an alternative approach (which works without version control), which sometimes causes less efforts, especially when you are developing a new feature with a small "entry point".

Note that feature branches and feature toggles both have some advantages and disadvantages, sometimes the former works better, sometimes the latter.

Title: Best way to develop new features as well as fix any bugs for a web system on Windows

Body:
I'm a one-man band and I have a contract with a client to develop and maintain a web-based system that is relied upon. This is the first project of this size and type that I have done for anyone else so I'm still finding my feet a bit in that respect and I'm not sure on any standard practices.

The current situation is that the live system is hosted on a VPS and I have a copy of the system on my local Windows machine with MySQL and PHP installed so that I can develop new features locally and then sync the files with the VPS once I have finished them. This works great, however the complications come when there are any bugs in the system - at which point I'm not sure what to do?

At the minute, I've created another local copy of the system for the purposes of fixing bugs but whilst this enables to sync to the VPS without also syncing any incomplete features, that means that the version of the system which I develop features on still contains the bugs that I have fixed. The only thing I can think of to solve this is to manually copy any changes I made in the bug fixing version, but this seems quite inefficient and impractical once more than one person starts working on a project (which I hope will be the case soon).

I would appreciate if people could share their solutions to situations that may be similar to mine, as I appreciate that no situation is identical and that people may have different solutions to the same problem. For your information as well, I prioritise the fixing of bugs over the implementation of new features.


问:
If it's a static object is using ref as method argument better?
I have an object 'connection' which holds the path/credentials to a SQL DB.

When calling methods; we usually do this:

```<code>Connection con = new Connection();

GetSalesData(con);

public static void (Connection con)
{
   // Run code

}
</code>```

As I understand, we just created two instance of connection, so that means two memory allocations. Is it better to do this:

```<code>Connection con = new Connection();

GetSalesData(ref con);

public static void (ref Connection con)
{
   // Run code

}
</code>```

答:
As I understand, we just created two instance of connection

No, we did not. Passing a variable automatically works as pass-by-reference for reference types and pass-by-value for value types. As your connection is a class, this means it is a reference type and only a reference will be passed to the method. You never created a second instance of your connection.

This has nothing to do with the static modifier, neither on the variable, nor on the method.

I suggest you spent a little while reading the MSDN on this topic, especially the two links called Passing Reference-Type Parameters and Passing Value-Type Parameters.

In addition, as another commenter remarked, you may want to read the excellent Jon Skeet on parameters.


答:
When you use:

```<code>public static void GetSalesData (Connection con)
</code>```

you are passing a reference to the Connection object as a value. As such, you can access that object via con. You aren't creating a second copy of the Connection object.

Use:

```<code>public static void GetSalesData (ref Connection con)
</code>```

you are now passing a reference to the memory location that in turn references the Connection object. This lets you change what's in that memory location, ie you can change what con in the code snippet:

```<code>Connection con = new Connection();
GetSalesData(con);
</code>```

refers to. It is extremely unlikely that you want to do this.

Title: If it's a static object is using ref as method argument better?

Body:
I have an object 'connection' which holds the path/credentials to a SQL DB.

When calling methods; we usually do this:

```<code>Connection con = new Connection();

GetSalesData(con);

public static void (Connection con)
{
   // Run code

}
</code>```

As I understand, we just created two instance of connection, so that means two memory allocations. Is it better to do this:

```<code>Connection con = new Connection();

GetSalesData(ref con);

public static void (ref Connection con)
{
   // Run code

}
</code>```

Body:
When you use:

public static void GetSalesData (Connection con)

you are passing a reference to the Connection object as a value. As such, you can access that object via con. You aren't creating a second copy of the Connection object.

Use:

public static void GetSalesData (ref Connection con)

you are now passing a reference to the memory location that in turn references the Connection object. This lets you change what's in that memory location, ie you can change what con in the code snippet:

Connection con = new Connection();
GetSalesData(con);

refers to. It is extremely unlikely that you want to do this.


问:
Questions about compiler/interpreter design
I am implementing a programming language, for fun, in C. I have most of the parsing code done and also the AST ready. I once did write a runtime for this language some time ago, but I had some trouble with the garbage collector. I then realized i needed to study a little more and that my previous AST walker implementation was really poor.

Now I'm restarting it, and I choosed to compile the AST to bytecode and then run it on a pretty basic stack-based VM. I have looked at others languages compilers and VMs and I learned a lot, but my research wasn't still enough to answer me somethings.

When compiling, should I maintain an array for each type of "basic" constants like strings, numbers, booleans, etc... And then compile that to bytecode as well, or a single array of constants but already wrapped by a custom struct? And if I do this, how should I pass this objects to the VM? Compile it's address in memory as void * or create the VM's own reference to this array of objects and pass the indices as an instruction argument? Also, should the Garbage Collector know about this objects immediately or just when they get pushed to the stack? It seems wrong to me the later approach because if I have a big program, it would allocate a very large amount of memory before even executing anything. However, that's the way I saw some languages implementations doing it.

To sum up, should I compile "raw" values, or keep a reference to language Objects through the Compiling-Executing process?

答:
There are a lot of design tradeoffs to weigh. Factors that might influence the best design include whether or not you want to persist bytecode to a file, whether your vm has primitive types that it operates on directly or if you've gone with a pure object-oriented approach and the bytecode doesn't operate at an integer/float/etc level. Also, much depends on the type of gc you are using. With a copying collector, having live objects in the constant pool makes less sense than it does with mark &  sweep, for example.

The best approach is probably to look at a few systems that have similar designs to your own, and look at what they have done, and why.


答:
It's not in the C language. One of the reasons is that in C, switch cases are compared for equality, and strings are pointers, so unless you introduce weird rules, strings would be compared with pointer comparison which would be absolutely useless ("John" == "John" can be either true or false in C, depending on the implementation). </p>

<p>For just one example of a much more powerful switch / case statement, you can download the Swift language book; there are many other languages with similar features. So your assumption that this hasn't made it into programming languages is totally wrong. </p>

Body:
It's not in the C language. One of the reasons is that in C, switch cases are compared for equality, and strings are pointers, so unless you introduce weird rules, strings would be compared with pointer comparison which would be absolutely useless ("John" == "John" can be either true or false in C, depending on the implementation).

For just one example of a much more powerful switch / case statement, you can download the Swift language book; there are many other languages with similar features. So your assumption that this hasn't made it into programming languages is totally wrong.


答:
There is no way to delete data from an event driven system so the only way is to store the sensitive data in another data store and link to it somehow. </p>

<p>For example you could just store it a different table if you are using sql. Choose to store in some immutable way and just refer to it by row id. Then you are free to delete from the sensitive table. </p>

Title: How do you combine licensed data and event sourcing?

Body:
Hypothetical problem, inspired by How to query Aggregate Root to react to event from other AR  How should an event sourced application handle data, where the license to that data can expire?

Example: the model includes sensitive billing information; when an account is closed, the billing information for that client needs to be scrubbed from the system.

Example: data is licensed from a 3rd party vendor; the agreement specifies that at then end of the license period, the data needs to be removed.

Body:
There is no way to delete data from an event driven system so the only way is to store the sensitive data in another data store and link to it somehow.

For example you could just store it a different table if you are using sql. Choose to store in some immutable way and just refer to it by row id. Then you are free to delete from the sensitive table.


问:
Should I create Use Cases or create Class Diagrams first?
So I'm designing an Education Management System and I'm wondering if I should be creating the Use Cases or the Class Diagrams first?</p>

答:
You should be first defining how the tool you are creating is going to look, feel, and be used by your users/customers. That is what dictates how your software will be architected.

People use your software, not computers, so design how people will interact with it first. If you design around how software components should fit together, your user interface will be made for robots, not human beings.

ContentLicense: CC BY-SA 2.5


问:
What to do when hydrating whole domain model is unnecessary for concrete operation?
If some model can only exist if set of values are passed to it and validation on them are performed, then how to load such a model if only one of those values is needed for some action?

It seems a little overhead to do hydration of model all over again if only one value for action on that model is needed. That can be expensive.

I have an auction model. It has title, description, owner, current value, dates and bids. For particular operation like bid I only need current value and bids in this model to be populated. However, model, theoretically, cannot exist if other values are not received and validated (in constructor).

What to do? How to do separation? Is that normal/common for DDD and there is just some trade offs you cannot avoid?

答:
When you realize that most of the data an AR carries is not needed at all to fulfill some of it's commands then you are on the urge of discovering a new domain concept. Another analysis that may help the discovery process is doing a concurrency conflict analysis to see if your design introduces unnecessary concurrency conflicts.

e.g. Should changing the title of the auction conflict with someone who's trying to bid?

The fact that you are asking this question is a strong indicator that your aggregate boundaries are wrong and that your Auction concept is currently not very cohesive.

Most people will solve the data-loading part of this problem by introducing lazy-loading, but that's a code smell and doesn't address the heart of the problem.

I can't tell if that really fits with your domain, but what about having a Listing aggregate as well as an Auction aggregate. A Listing is sold through an Auction.

The Listing would handle the descriptive part of what's being sold while the Auction will handle the bidding process.

Both ARs can be created in the same transaction: the creation of the Auction is an immediate side-effect of the creation of a Listing.

"But there's a rule stating that one should not modify more than a
  single AR in a transaction".

Yes and it's very important to respect that rule, but here we aren't modifying ARs we are creating them and that's very different because no contention can exist during the creation process. Those ARs aren't shared resources yet.


答:
How about this:

When the expiry event occurs the object is loaded via event state, but then copied or serialized to a new expired/archived object which doesn't not contain the sensitive information.

This can then be stored, either using the event sourcing pattern, but with the archive at the new first event, Or in some other non event sourcing method.


问:
OO Design: Reading/Writing object with multiple formats
I have a class Song, which has the following public methods:

```<code>String getSong();
void setSong(String);
int getId();
void setId(int);
</code>```

Now I have two different ways I might want to store these songs in a database:

just two columns; one for ID, one for the whole text of the song

three columns; one for ID, one for line number, and one for that line

[Please ignore DB design issues; it's only important the two schema are different.]

So I need a way of swapping out how songs are written/read from/to the database.  That might even mean making a runtime decision on which schema I use. What is the proper OO way of doing this? I feel like the Strategy pattern would work here, but I can't connect it all together. Some questions I've been struggling with over this:

Should there be a separate object for each read and each write? Or should one class implement both a read and a write?

How do I avoid duplicated logic? For example, method (2) means the write method splits the song on newlines, while the read method joins them.  Is there a way to combine the similar logic here?

What if Song didn't have public setters? How does the design change?

I've been really having difficulty with solving this cleanly and in a flexible object-oriented way, so any help would be great.

答:
Perhaps, this isn't the answer you expect, but I believe strongly, that you should put more effort in your design decisions, than making bad decisions and invest most of the time in thinking about how to implement this bad design.

Now I have two different ways I might want to store these songs in a database:

1) just two columns; one for ID, one for the whole text of the song

2) three columns; one for ID, one for line number, and one for that line

Yes. These are the possibilities. But two questions coming to my mind:

1) Why do you want 2 different formats (at the same time)?

2) Does the second design even make sense?

What would be the advantage of storing the line number and the content of that line? The only case, when it might eventually somehow would make sense is, when you oftentimes have queries get me exactly line n from the song x and even then I see no justification to store text line by line as column rows. Put the text as TEXT in the DB and do whatever magic you want to do on that in-memory after you retrieved it from the DB

So I need a way of swapping out how songs are written/read from/to the database. That might even mean making a runtime decision on which schema I use. What is the proper OO way of doing this? I feel like the Strategy pattern would work here, but I can't connect it all together. Some questions I've been struggling with over this

The strategy would be a good fit for that; so you could change the strategy how to store or retrieve data at will.

Should there be a separate object for each read and each write? Or should one class implement both a read and a write?

The typical pattern for persistence is the repository. The job of the repository is to abstract away details of persitence. And it would be the repository, which would use the strategy.

How do I avoid duplicated logic? For example, method (2) means the write method splits the song on newlines, while the read method joins them. Is there a way to combine the similar logic here?

It depends on your implementation. Sure, there are ways to prevent duplication.

What if Song didn't have public setters? How does the design change?

You have to implement some way, how your song represents state.

Since you need it to set at least at object creation, you would write a constructor such, that your object is initialized in the desired way.

Letting out (public) setters, you make the object immutable which could be what you wanted. The advantage of immutable objects is simple: they are astoundingly boring; they have always the same state - which is nice in multithreaded context. There are no surprises, that state was altered unintentionally.


问:
What is the difference between proxy class and delegation in Python?
Wiki:

A proxy, in its most general form, is a class functioning as an interface to something else. The proxy could interface to anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. In short, a proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes

Hmm!, what would this look like in terms of code ?

Wiki

delegation refers to one object relying upon another to provide a specified set of functionalities

This class for example delegates its functionalities to another object:

```<code>class CustomInt:

    def __init__(self):
        self.obj = int()

    def __getattr__(self, attr):
        return getattr(self.obj, attr)   # Delegation
</code>```

Since it's a class functioning as an interface for something else, can I consider it as a proxy class ?

答: Yes. Your class is a proxy, and this is the typical pattern used to implement a proxy in a dynamic language (in static languages, each method must typically be forwarded individually). Proxies also usually change the behaviour of the object they proxy on a subtle way (e.g. preventing access to certain methods, hosting the target object in a separate process or on another machine, etc.).</p>


答: Always create Use Cases first. However the detail with which use-cases are worked out depends on your familiarity/comfort with the domain, if you have worked within the domain before initially you can keep your use-cases brief and expand it later on along with the development.</p>

Title: Should I create Use Cases or create Class Diagrams first?

Body: So I'm designing an Education Management System and I'm wondering if I should be creating the Use Cases or the Class Diagrams first?</p>


问:
Why doesn't Java implement a better way of handling getters and setters?
Getters and setters are everywhere in Java, but they are managed in a horribly outdated way.

Simply put: Why doesn't a newer version of Java enable a simpler syntax for managing it? Even if this syntax is converted to the old one by the compiler for compatibility, at least it would be good to let people write code without putting boilerplate getters everywhere.

For example instead of:

```<code>private String id;

public String getId() {
    return id;
}
</code>```

We could just have:

```<code>public readonly String id;
</code>```

And then, in the "client" code, instead of having to call getId everywhere, the compiler could detect if you are reading the variable id, and automatically match it at compilation by a getId call.

Example:

```<code>String userId = user.getId();
</code>```

Becomes:

```<code>String userId = user.id: // Compiler automatically manages the call to getId
</code>```

This post is not here for ranting, I'm just curious if there is a reason for not doing that, because it feels like Java could really use an update on that point.

答:
Java is generally light on syntactic sugar. The only things that spring to mind are String concatenation with + and enhanced for loops. It seems the Java designers prefer to only add syntax for genuinely new semantics.

However, the only people who can definitely answer this question, are the designers of Java.

A tip: try to write up a JSR for your proposed change, and implement it in one of the open source Java compilers (e.g. OpenJDK javac, Eclipse ecj, etc.). Either you will run into problems (say, an ambiguity in the grammar, an ambiguity in the semantics of fields vs. methods, unsoundness of the overload resolution rules, whatever …), in which case you know the answer to your question, or you don't run into problems, in which case you can propose your change to the JCP, and maybe it will get accepted.

I can already sense that there will be ambiguities in the resolution of fields vs. methods, and I'm curious as to how you are going to handle that.


答:
There are many reasons why a particular language feature in a language might not be implemented.

In Java, data binding in Java Beans relies on the traditional arrangement of getter and setter methods, so it wouldn't work with first-class properties unless you rewrote the binder.  Because you still have to support the old way, you now have two different ways of doing the same thing.

Adding language features is expensive, and the more widespread and popular the language is, the more expensive it is to add the feature.  Every language feature that you add has to justify the expense; that is, it has to add more value than the time and effort required to implement it.  Every language feature addition has an opportunity cost; time, money and programmer resources are not unlimited, so implementing one feature sometimes requires giving up another.

Eric Lippert describes the process better than anyone.  He says that

Just being a good feature is not enough. Features have to be so
compelling that they are worth the enormous dollar costs of designing,
implementing, testing, documenting and shipping the feature. They have
to be worth the cost of complicating the language and making it more
difficult to design other features in the future.

A good example of this process is extension properties in C#.  Extension properties seem like a natural addition to C#.  But they weren't essential like Extension Methods were.  As Eric explains:

It was of course immediately obvious that the natural companion to
extension methods is extension properties. It's less obvious, for some
reason, that extension events, extension operators, extension
constructors (also known as "the factory pattern"), and so on, are
also natural companions. But we didn't even consider designing
extension properties for C# 3; we knew that they were not necessary
and would add risk to an already-risky schedule for no compelling
gain.

So they didn't get into C# 3, which would have been the natural place to put them.  Now we'll probably never get them, because they're really not compelling enough as a standalone feature to justify the expense.

Further Reading

How Many Microsoft Employees does it Take to Screw In a Light Bulb?

Title: Why doesn't Java implement a better way of handling getters and setters?

Body:
Getters and setters are everywhere in Java, but they are managed in a horribly outdated way.

Simply put: Why doesn't a newer version of Java enable a simpler syntax for managing it? Even if this syntax is converted to the old one by the compiler for compatibility, at least it would be good to let people write code without putting boilerplate getters everywhere.

For example instead of:

```<code>private String id;

public String getId() {
    return id;
}
</code>```

We could just have:

```<code>public readonly String id;
</code>```

And then, in the "client" code, instead of having to call getId everywhere, the compiler could detect if you are reading the variable id, and automatically match it at compilation by a getId call.

Example:

```<code>String userId = user.getId();
</code>```

Becomes:

```<code>String userId = user.id: // Compiler automatically manages the call to getId
</code>```

This post is not here for ranting, I'm just curious if there is a reason for not doing that, because it feels like Java could really use an update on that point.


问:
Login using email or username?
Is registration login using email a better idea than username to identify the user?</p>

答:
Does the site allow social interaction with others who will see the name? If so, let the user chose a username. </p>

<p>Otherwise, use the email address. It will be one less thing for the user to remember.  </p>

Title: Login using email or username?

Body:
Does the site allow social interaction with others who will see the name? If so, let the user chose a username.

Otherwise, use the email address. It will be one less thing for the user to remember.


问:
Why do negative numbers evaluate to true in PHP?
```<code>function haha($lol)
{
   if($lol) { echo "plus"; }
   else { echo "minus"; }
}
</code>```

haha(-1) echoes plus.

Is it because PHP uses twos complement? Google search wasn't really helpful.

答:
I don't know about PHP specifically, (ew,) but in all languages that I know of which allow implicit (ew,) or explicit conversions between numbers and booleans, the following holds true:

zero evaluates to false

everything non-zero evaluates to true.

And negative numbers are non-zero.

This does not really have anything to do with two's complement.

I am not sure of the precise reason why this is so, but if you think about it, if it was not to be so, then what would you rather have it be?  Positive numbers vs. non-positive numbers? That would require treating -1 the same as 0, (since 0 would of course still have to mean false,) and this is asymmetric; it feels blasphemous; wicked.

I suppose there are other reasons that have to do with the simplicity which is inherent in symmetry.  For example, if you compute the difference between two numbers A and B, this will be a negative number if A < B, zero if A == B, and a positive number if A > B.  But if you view the difference as a boolean, then automatically you have the value of the expression A != B, irrespective of > or <.  That's kind of a useful thing to have.


问:
Drawing the Line between Coding Style and Algorithm
Formatting with Indentations, White spaces, and New Lines obviously fit into the coding style category.

```<code>if (a == b) {
    foo();
}

// vs

if (a == b)
{
    foo();
}
</code>```

On the other hand, something that changes the run time of a program is no longer a matter of coding style, and becomes a matter of algorithm.

```<code>for (var i = 0; i < a.length; i++) {
    // Remove first element of the array.
    a.shift();
}

// vs

for (var i = 0; i < a.length; i++) {
    // Remove last element of the array.
    a.pop();
}
</code>```

However, at what point does a matter of coding style turn into a matter of algorithm?

In other words, when comparing two possible methods to write the same program, when can we objectively determine whether the choice between the two methods is a preference in coding style or a difference in algorithm?

Is comparing to true a matter of coding style or algorithm?

```<code>if (a == true) {
    // a is true.
}

// vs

if (a) {
    // a is true.
}
</code>```

Is returning true a matter of coding style or algorithm?

```<code>function isA(b) {
    return this.a == b;
}

// vs

function isA(b) {
    if (this.a == b) {
        return true;
    }
    return false;
}
</code>```

What about merging conditions into one if statement?

```<code>if (a > 0) {
    return foo();
}

if (b == 0) {
    return foo();
}

// vs

if (a > 0 || b == 0) {
    return foo();
}
</code>```

Loop conditions?

```<code>// Loop 10 times.
for (var i = 0; i < 10; i++);

// vs

// Loop 10 times.
for (var i = 1; i <= 10; i++);
</code>```

Nested if statements?

```<code>function foobar() {
    if (a) {
        return foo();
    }

    if (b) {
        return bar();
    }

    return barfoo();
}

// vs

function foobar() {
    if (a) {
        return foo();
    } else {
        if (b) {
            return bar();
        } else {
            return barfoo();
        }
    }
}
</code>```

These examples don't exactly change the run time of a program, yet isn't exactly just indentations, white spaces, or new line changes either. They are also typically not mentioned in coding style guides for most languages.

Given these examples above and other similar examples, is the difference a matter coding style or algorithm? Or is there a completely different term for it?

For example, if I am someone who uses for (var i = 0; i < 10; i++), do I simply have a different preference for coding style compared to someone who uses for (var i = 1; i <= 10; i++)? Or is there something more to it besides just coding style? At what point is it no longer just coding style and start becoming part of the algorithm?

答:
Short answer:

Are the two versions of code capable of producing different outcomes when executed? If so, they are probably different algorithms.

The kinds of outcomes we're concerned with:

Results of the execution. For example, shift and pop modifies the array in different ways, so the content of the array is different. Any other code that has access to the array needs to be aware of how it was intended to be modified.

Differences in qualities, or "non-functional requirements". For example, if the time taken by the operation "grows linearly (proportional) to the current size of the array", its performance is different from another which "grows quadratically to (proportional to the square of) the current size of the array", then it is likely that the two code implements two different algorithms.

There are many other outcomes we might be concerned with, depending on the nature of the software projects.

Longer answer:

To be able to reason about whether some code changes will result in a change in the algorithm, one needs to:

Reason logically. Article: boolean algebra.

Understand the rules of the language very well.

Have a simplified mental model of how the code would be executed, step-by-step, by a computer (or computer program / virtual machine).

Understand possible ways in which the compiler or the execution program may diverge from your simplified mental model.

Code transformations that might be done by an optimizing compiler. Article: optimizing compiler

Effects of caching. Article: cache (computing)

Race condition. Article: race condition (software)

Transient network failures


答:
I think you should allow both user name and email for login (I think this is the system they have with disqus), of course you should only display user name to others as pointed out by Matthew.

Added. Or you can go for OpenID (highly recommended), which is emerging as a sort of internet driver's license.

Title: Login using email or username?

Body: Is registration login using email a better idea than username to identify the user?</p>


问:
Testing of a layered software architecture
I am currently building an application with a layered architecture in C. Currently, I have built and tested the bottom layer, which is a networking module, providing functionality such as connecting/disconnecting, sending messages, etc.

On top of it, I am building another layer, that implements a communication protocol. It has functionality such as connect, which calls network_connect internally to create the actual connection and does some protocol related business, such as registering on a server.

Now, the problem is how should I test the second layer? The original approach was to create 2 threads, open a server on one of them, connect to it and monitor the traffic (basically check if the required protocol-related data has been transferred). However, I do not need to test the actual network connection, since that is already tested in the tests for the networking module and I feel this approach is too complicated.

One approach I could think of was to expose the internal socket file descriptor from the networking module through getters/setters (which I needed anyway) and replace the network connection with a pipe. This approach works for most of the operations, except for the actual connection, where the network connect routine is called internally. Also, the connection in this case is made to a server whose ip/port is not exposed outside of this module (it is currently defined as a constant and will soon be moved into a config file).

How should I approach the testing of this module?

答:
A solution would be to provide fake implementation of the bottom layer (implementation that simulates network traffic). Tests of the second layer  linked with fake implementation of bottom layer.

More About Fakes


问:
success:/failure: blocks vs completion: block
I see two common patterns for blocks in Objective-C. One is a pair of success:/failure: blocks, the other is a single completion: block.

For example, lets say I have a task that will return an object asynchronously and that task might fail. The first pattern is -taskWithSuccess:(void (^)(id object))success failure:(void (^)(NSError *error))failure. The second pattern is -taskWithCompletion:(void (^)(id object, NSError *error))completion.

success:/failure:

```<code>[target taskWithSuccess:^(id object) {
    // W00t! I've got my object
} failure:^(NSError *error) {
    // Oh noes! report the failure.
}];
</code>```

completion:

```<code>[target taskWithCompletion:^(id object, NSError *error) {
    if (object) {
        // W00t! I've got my object
    } else {
        // Oh noes! report the failure.
    }
}];
</code>```

Which is the preferred pattern? What are the strengths and weaknesses? When would you use one over the other?

答:
I realize this is an old question but I have to answer it because my answer is different than the others.

For those that say it's a matter of personal preference, I have to disagree. There is a good, logical, reason to prefer one over the other...

In the completion case, your block is handed two objects, one represents success while the other represents failure... So what do you do if both are nil? What do you do if both have a value? These are questions that can be avoided at compile time and as such they should be. You avoid these questions by having two separate blocks.

Having separate success and failure blocks makes your code statically verifiable.

Note that things change with Swift. In it, we can implement the notion of an Either enum so that the single completion block is guaranteed to have either an object or an error, and must have exactly one of them. So for Swift, a single block is better.