问:
asp.net mvc vs angular.js model binding
So I've noticed a trend lately of .net web developers using angular.js on the client side of applications and I've become more curious as I play around with angular and compare it to how I would do things in asp.net mvc.

I'll give a quick example of what really got me thinking.

I recently came across a situation at work (I work in a .net environment) where I needed to create a table bound to a collection of objects that had the ability to add and remove rows/items from the collection. I had an add button that created a new object and appended a row to the end of the table, and a remove button in each row to remove a particular object/row. Using asp.net mvc, I first found myself making an ajax call to the server for each operation, updating the server side model, and refreshing part of the page to show the result in the table. This worked but I didn't really like the idea of calling the server to update the model each time, so I tried to come up with a solution to do this on the client side. It turned out to be quite a task, as I had to generate the html on add with validation and all and the correct indexing for the model binding to work. It got worse on remove, as I ended up with a crazy string replace function to recreate the indexes on each item to satisfy the binding requirements (if an item other than the last is removed, the indexes are no longer correct). Now out of curiosity, I tried to recreate this at home in angular (which I had no experience with) and it took me all of about 10 minutes with simple functions to add and remove items from the client side model.

This is just one example, but it seems to me that I'm able to achieve the same results with far fewer calls to the server in angular because of the fact that it binds to a client side model.

So my question is, is this a distinct advantage of using a javascript mvc framework or am I somehow under utilizing the power of asp.net mvc and am I right in thinking that these operations should be done on the client and have no business requiring calls to the server?

答: Its absolutely the power of angularjs, when ever there is a change in the model, it will observe it and update the view. ASP.Net is all about managing data at server side, you must be basically making ajax calls and it can be any server not only an asp.net mvc application. We are using angular in one of our projects, it absolutely increased the developer productivity. Its still evolving and its great fun....</p>

Title: asp.net mvc vs angular.js model binding


答:
It seems that what you're describing is client-side data-binding, which is one small part of what AngularJS does. (It also does routing, view templating, and a ton of other stuff.)

If what you're interested in is just adding the client-side data-binding piece to your otherwise just-fine ASP.NET MVC framework, there are other options (such as knockout.js) which you should investigate before deciding what works best for you.

There is no one answer to the question of how much functionality should be client-side vs server-side.

ContentLicense: CC BY-SA 3.0

Title: asp.net mvc vs angular.js model binding

Body:
So I've noticed a trend lately of .net web developers using angular.js on the client side of applications and I've become more curious as I play around with angular and compare it to how I would do things in asp.net mvc.

I'll give a quick example of what really got me thinking.

I recently came across a situation at work (I work in a .net environment) where I needed to create a table bound to a collection of objects that had the ability to add and remove rows/items from the collection. I had an add button that created a new object and appended a row to the end of the table, and a remove button in each row to remove a particular object/row. Using asp.net mvc, I first found myself making an ajax call to the server for each operation, updating the server side model, and refreshing part of the page to show the result in the table. This worked but I didn't really like the idea of calling the server to update the model each time, so I tried to come up with a solution to do this on the client side. It turned out to be quite a task, as I had to generate the html on add with validation and all and the correct indexing for the model binding to work. It got worse on remove, as I ended up with a crazy string replace function to recreate the indexes on each item to satisfy the binding requirements (if an item other than the last is removed, the indexes are no longer correct). Now out of curiosity, I tried to recreate this at home in angular (which I had no experience with) and it took me all of about 10 minutes with simple functions to add and remove items from the client side model.

This is just one example, but it seems to me that I'm able to achieve the same results with far fewer calls to the server in angular because of the fact that it binds to a client side model.

So my question is, is this a distinct advantage of using a javascript mvc framework or am I somehow under utilizing the power of asp.net mvc and am I right in thinking that these operations should be done on the client and have no business requiring calls to the server?


问:
object model and data model
I have heard/read mixed things on whether to start with an object model or a data model. And more people say to starting with an object model as it will ease your data modelling.

My question is, Shouldn't an object model always drive the design of data model? Why and When would a data model design be different than an object model?

If we have a good object model, shouldn't the classes we come up with translate into tables? And class associations as table relationships?

答:
The question is, does your app serve the database or does the database serve the app?

If you can describe your app/website as a "skin" on a database, you can start with the database structure/schema and code the CRUD because the behavior of the app is to manage data on the disk. You may hit a few bumps in the road.

If this isn't the case, you need to address the behavior of the app besides just the CRUD. There will be information held in the app that never makes it to the database. Much of the logic can be coded without the database. This can help with unit testing or maybe as a guide to keep your code organized and separate the data storage needs.

Who knows. Your app may not need a database at all or something as simple as a text file.

Title: object model and data model


问:
Purposely raising exceptions to use catch
For a typical if...else wrapped with exception handling, is something like the following example a recommended practice to avoid code duplication?

```<code>try
{
    if (GetDataFromServer())
    {
        return ProcessData();
    }
    else
    {
        throw new Exception();
    }
catch(Exception ex)
{
    return null;
}
</code>```

instead of...

```<code>try
{
    if (GetDataFromServer())
    {
        return ProcessData();
    }
    else
    {
        return null;
    }
}
catch(Exception ex)
{
    return null;
}
</code>```

I know there is a slight performance hit, but I'm wondering if this is considered to be an acceptable practice. I currently do it the second method - especially in cases where I need to handle specific exceptions differently - but I was wondering if the first method is appropriate for simple cases.

答:
Why not the far simpler:

```<code>if (!GetDataFromServer()) return null;
ProcessData();
</code>```

If an exception handler is going to exist it should be in ProcessData()

OwnerDisplayName: grovesNL

Body:
Why not the far simpler:

if (!GetDataFromServer()) return null;
ProcessData();

If an exception handler is going to exist it should be in ProcessData()


问:
How to restrict the violation of an N-Tier Architecture
Recently we fitted a 4-Tier Architecture in our project composed by the following four main layers :

User Interface Layer.

Data Access Layer.

Domain Layer.

Business Layer.

All the layers fulfill their usual roles in 4-Tier Architecture and interact which each one in the usual way. We use SVN to maintain our CVS.

My problem is that we have many inexperienced programmers developing in a well formed architecture, and we have to be checking all the time the code to find violations of the architecture.

For example:

Sometimes include access to database in the User Interface Layer and not in the Business Layer which is where interact with the Data Access layer to read or save data in the database.

Problems like the above occurs all the time. My question is:

How to check the code before the programmers can submit his new changes to the repository and report violations of the architecture? How to avoid doing this manually?

答:
If the UI layer has no access to the assemblies or authentication information needed to access the database, it is impossible to access the database directly from that layer. If you have separated your layers into separate assemblies, and limit the public data types and members to only those needed in the higher level layer, it is easy to detect a violation, as an assembly reference will have been added.

One problem pointed out by the user Euphoric below is that the assembly restrictions do not prevent lower layers from making calls into higher layers using interfaces, events, or delegate callbacks. So education about layering is still needed.


问:
Useful design patterns for working with FragmentManager on Android
When working with fragments, I have been using a class composed of static methods that define actions on fragments. For any given project, I might have a class called FragmentActions, which contains methods similar to the following:

```<code>public static void showDeviceFragment(FragmentManager man){
    String tag = AllDevicesFragment.getFragmentTag();

    AllDevicesFragment fragment = (AllDevicesFragment)man.findFragmentByTag(tag);

    if(fragment == null){
        fragment = new AllDevicesFragment();
    }

    FragmentTransaction t = man.beginTransaction();
    t.add(R.id.main_frame, fragment, tag);

    t.commit();
}
</code>```

I'll usually have one method per application screen. I do something like this when I work with small local databases (usually SQLite) so I applied it to fragments, which seem to have a similar workflow; I'm not married to it though.

How have you organized your applications to interface with the Fragments API, and what (if any) design patterns do you think apply do this?

答:
The accepted pattern is to have a factory method inside your custom fragment class (typically called newInstance() but hey dealer's choice).  So your fragment class should look something like this:

```<code>public class MyFragment extends Fragment
{
    public static MyFragment newInstance()
    {
        MyFragment newFragment = new MyFragment();
        // add any bundle arguments here if needed
        return newFragment;
    }
    // rest of fragment class...
}
</code>```

Then, when you create a fragment and add it to the backstack, instead of saying:

MyFragment fragment = new MyFragment();

You can use the factory method instead of the 'new' keyword.

Body:
The accepted pattern is to have a factory method inside your custom fragment class (typically called newInstance() but hey dealer's choice).  So your fragment class should look something like this:

public class MyFragment extends Fragment
{
    public static MyFragment newInstance()
    {
        MyFragment newFragment = new MyFragment();
        // add any bundle arguments here if needed
        return newFragment;
    }
    // rest of fragment class...
}

Then, when you create a fragment and add it to the backstack, instead of saying:

MyFragment fragment = new MyFragment();

You can use the factory method instead of the 'new' keyword.


问:
Push-Based Events in a Services Oriented Architecture
I have come to a point, in building a services oriented architecture (on top of Thrift), that I need to expose events and allow listeners.

My initial thought was, "create an EventService" to handle publishing and subscribing to events. That EventService can use whatever implementation it desires to actually distribute the events. My client automatically round-robins service requests to available service hosts which are determined using Zookeeper-based service discovery. So, I'd probably use JMS inside of EventService mainly for the purpose of persisting messages (in the event that a service host for EventService goes down before it can distribute the message to all of the available listeners).

When I started considering this, I began looking into the differences between Queues and Topics. Topics unfortunately won't work for me, because (at least for now), all listeners must receive the message (even if they were down at the time the event was pushed, or hadn't made a subscription yet because they haven't completed startup (during deployment, for example) - messages should be queued until the service is available).

However, I don't want EventService to be responsible for handling all of the events. I don't think it should have the code to react to events inside of it. Each of the services should do what it needs with a given event. This would indicate that each service would need a JMS connection, which questions the value of having EventService at all (as the services could individually publish and subscribe to JMS directly). However, it also couples all of the services to JMS (when I'd rather that there be a single service that's responsible for determining how to distribute events).

What I had thought was to publish an event to EventService, which pulls a configuration of listeners from some configuration source (database, flat file, irrelevant for now). It replicates the message and pushes each one back into a queue with information specific to that listener (so, if there are 3 listeners, 1 event would become 3 events in JMS). Then, another thread in EventService (which is replicated, running on multiple hots) would be pulling from the queue, attempting to make the service call to the "listener", and returning the message to the queue (if the service is down), or discarding the message (if the listener completed successfully).

tl;dr

If I have an EventService that is responsible for receiving events and delegating service calls to "event listeners," (which are really just endpoints on other services), how should it know how to craft the service call? Should I create a generic "Event" object that is shared among all services? Then, the EventService can just construct this object and pass it to the service call. Or is there a better answer to this problem entirely?

答:
If the service must receive the message, even though it is unaware of its existence, then the publish/subscribe pattern is not the answer. Publishers are not supposed to know about their subscribers. The subscriber is supposed to care, not the publisher.

If the "publisher" is responsible for maintaining messages, then what you want is polling.


答:
Perhaps what you're attempting is possible with Layer Diagrams.

See MSDN: Validate Code with Layer Diagrams

To make sure that code doesn't conflict with its design, validate your code with layer diagrams in Visual Studio Ultimate and Visual Studio Premium. This can help you:

Find conflicts between dependencies in your code and dependencies on    the layer diagram.

Find dependencies that might be affected by    proposed changes. For example, you can edit the layer diagram to show    potential
  architecture changes and then validate the code to see the    affected
  dependencies.

Refactor or migrate code to a different    design.

Find code or dependencies that require work when you move the    code to a different architecture.

You can validate code manually from an open layer diagram in Visual
  Studio or from a command prompt. You can also validate code
  automatically when running local builds or Team Foundation Build.

or Channel 9: Using layer diagrams to design and validate your architecture

This short video shows how to design architectural layers in your
  product, and then validate them to ensure that components implement
  the intended architecture.

Title: How to restrict the violation of an N-Tier Architecture

Body:
Recently we fitted a 4-Tier Architecture in our project composed by the following four main layers :

User Interface Layer.

Data Access Layer.

Domain Layer.

Business Layer.

All the layers fulfill their usual roles in 4-Tier Architecture and interact which each one in the usual way. We use SVN to maintain our CVS.

My problem is that we have many inexperienced programmers developing in a well formed architecture, and we have to be checking all the time the code to find violations of the architecture.

For example:

Sometimes include access to database in the User Interface Layer and not in the Business Layer which is where interact with the Data Access layer to read or save data in the database.

Problems like the above occurs all the time. My question is:

How to check the code before the programmers can submit his new changes to the repository and report violations of the architecture? How to avoid doing this manually?


答: There is only way to solve this problem: tutoring and core reviews. It is no-brainer that inexperienced developer's code is first reviewed by more experienced one before it is checked in. The reviewer then provides feedback, so the developer can fix the code and learn not to do same mistake again. And if said developer repeat same mistakes all the time, then it is time to look for a new developer.</p>


问:
Is it good practice to declare and set properties in abstract classes?
I am using PHP and designing some abstract classes.

I can declare properties with constant values within my abstract class and access/overwrite them from any class which extends this without re declaring them within any of the extending classes.

A benefit to this is less repetitive typing but the downside that overtime the original structure/layout of these abstract properties is forgotten and could be left at there default static values or even forgotten(not used) completely.

How is this handled in professional environments? I assume this has been thought out before and is either favored or isn't?

I am trying to adhere to good OOP principles/rules such as SOLID, DRY and KISS but I haven't seen this specific issue talked about in these. (perhaps I missed it when researching?)

答:
To answer your question, yes. If the abstract class is the logical place for the property then put it there. Use the tools that classes and OOP gives you.

"overtime the original structure/layout of these abstract properties is forgotten and could be left at there default static values or even forgotten(not used) completely."

This implies to me that developers using/creating the abstract class or child classes are required to do something with these properties. If that is true, try to come up with a class design that forces a developer to deal with this. That's better then to trust everyone to always do it correctly.

You mention changing static values. Static properties are shared between all class instances, so by changing their value in one object you change it for all. Multiple objects changing global state is something you want to avoid, because it is difficult to keep all changes in the correct order.


答:
Some reasons the two models may differ:

you have to use an existing database

a data model directly modeled like the object model may not give the required performance

not all classes end up in storage

as @CodeART commented, you may need to use a different storage technology then a relational database

Title: object model and data model

Body:
I have heard/read mixed things on whether to start with an object model or a data model. And more people say to starting with an object model as it will ease your data modelling.

My question is, Shouldn't an object model always drive the design of data model? Why and When would a data model design be different than an object model?

If we have a good object model, shouldn't the classes we come up with translate into tables? And class associations as table relationships?


问:
Why is there a new() constraint in C# but no other similar constraint?
In C# generics, we can declare a constraint for a type parameter T to have a default constructor, by saying where T : new(). However, no other kinds of constraints like this are valid - new(string) for example, etc.

From a language design and/or implementation perspective, what is the reason for this?

Is there something in the way constructors work or in the way the type system is implemented that forbids this (or at least makes it harder)? If so, what is it? I recall reading somewhere that default(T) actually compiles to new T() for T : struct. Is it related to this, maybe?

Or is it simply a design decision made in order to avoid making the language too complicated?

答:
For an authoritative answer, I would refer you to Eric Lippert's answer to that question on StackOverflow a few years ago, a snippet of which is briefly quoted below.

However, in this specific case I can certainly give you some reasons
why I would push back on the feature if it came up in a design meeting
as a possible feature for a future version of the language.

...

I say that we should either do the whole feature or don't do it at
all. If it is important to be able to restrict types to have
particular constructors, then let's do the whole feature and restrict
types on the basis of members in general and not just constructors.


答:
Decompiling (as per Robert Harvey's suggestion) yielded the following, for anyone interested. This method:

```<code>static T GenericMake<T>()
    where T : new()
{
    return new T();
}
</code>```

Apparently, when compiled, becomes this:

```<code>private static T GenericMake<T>()
    where T : new()
{
    T t;
    T t1 = default(T);
    if (t1 == null)
    {
        t = Activator.CreateInstance<T>();
    }
    else
    {
        t1 = default(T);
        t = t1;
    }
    return t;
}
</code>```

If T is a value type, new() becomes default(T).

If T is a reference type, new() works using reflection. Activator.CreateInstance() internally calls RuntimeType.CreateInstanceDefaultCtor().

So there it is - internally, default constructors really are special to C# in relation to the CLR. Giving other constructors the same treatment would have been costly, even if there are some valid use cases for more complicated constraints in generics.

Title: Why is there a new() constraint in C# but no other similar constraint?

Body:
In C# generics, we can declare a constraint for a type parameter T to have a default constructor, by saying where T : new(). However, no other kinds of constraints like this are valid - new(string) for example, etc.

From a language design and/or implementation perspective, what is the reason for this?

Is there something in the way constructors work or in the way the type system is implemented that forbids this (or at least makes it harder)? If so, what is it? I recall reading somewhere that default(T) actually compiles to new T() for T : struct. Is it related to this, maybe?

Or is it simply a design decision made in order to avoid making the language too complicated?

Body:
Decompiling (as per Robert Harvey's suggestion) yielded the following, for anyone interested. This method:

static T GenericMake<T>()
    where T : new()
{
    return new T();
}

Apparently, when compiled, becomes this:

private static T GenericMake<T>()
    where T : new()
{
    T t;
    T t1 = default(T);
    if (t1 == null)
    {
        t = Activator.CreateInstance<T>();
    }
    else
    {
        t1 = default(T);
        t = t1;
    }
    return t;
}

If T is a value type, new() becomes default(T).

If T is a reference type, new() works using reflection. Activator.CreateInstance() internally calls RuntimeType.CreateInstanceDefaultCtor().

So there it is - internally, default constructors really are special to C# in relation to the CLR. Giving other constructors the same treatment would have been costly, even if there are some valid use cases for more complicated constraints in generics.


问:
Ensuring non conflicting components in a modular system
So lets say we are creating a simple "modular system" framework.

The bare bones might be the user management. But we want things like the Page Manager, the Blog, the Image Gallery to all be "optional" components.

So a developer could install the Page Manager to allow their client to add a static home page and about page with content they can easily edit with a wysiwyg editor.

The developer could then also install the Blog component to allow the client to add blog entries.

The developer could then also install the Gallery component to allow the client to show off a bunch of images.

The thing is, all these components are designed to be independent, so how do we go about ensuring they don't clash? E.g. ensuring the client doesn't create a /gallery page with the Page Manager and then wonder why the gallery stopped working, or the same issue with the Blog component, assuming we allow the users to customize the URL structure of the blog (because remember, the Page Manager doesn't necessarily have to be there, so we might not wan't our blog posts to be Date/Title formatted), likewise our clients aren't always going to be happy to have their pages under pages/title formatting.

My core question here is, when building a modular system how to we ensure that the modules don't conflict without restricting functionality?

Do we just leave it up to the clients/developer using the modules to ensure they get setup in a way that does not conflict?

答:
namespaces are the usual response to this. A namespace limits the scope of the components internals (objects, methods and variables).

Different languages implement namespaces to a greater or lesser extent

php:
http://www.sitepoint.com/php-53-namespaces-basics/

javascript:
http://www.kenneth-truyers.net/2013/04/27/javascript-namespaces-and-modules/

Usually you can specify which component you mean by specifying the namespace, e.g.
mycomponents.mylistcomponent specifies the mylistcomponent in mycomponents namespace. Most languages provide a way of skipping specifying the namespace all the time e.g.

in c#:

```<code>using System.Objects
</code>```

will look in the System.Objects namespace for any objects you declare

Body:
namespaces are the usual response to this. A namespace limits the scope of the components internals (objects, methods and variables).

Different languages implement namespaces to a greater or lesser extent

php:
http://www.sitepoint.com/php-53-namespaces-basics/

javascript:
http://www.kenneth-truyers.net/2013/04/27/javascript-namespaces-and-modules/

Usually you can specify which component you mean by specifying the namespace, e.g.
mycomponents.mylistcomponent specifies the mylistcomponent in mycomponents namespace. Most languages provide a way of skipping specifying the namespace all the time e.g.

in c#:

using System.Objects

will look in the System.Objects namespace for any objects you declare


问:
How to deal with interactions between many objects
I've been working on a game in my spare time. I'm pretty much done defining the primitives and until today everything was pretty well segmented and encapsulated but now it's come time to implement path finding (and other ways for the objects to interact with each other). Here path finding requires at minimum a knowledge of the map, a knowledge of where units are in the map and which types of terrain are passable by the unit whose path is being found.

There are three ways I've thought to implement this

Implement it in some high level class that knows about all of these things already (i.e. a game state object)

Implement it in some specific method inside one of the "involved" classes (like unit or map) and pass in all relevant state

Implement it in some function which is completely separate (because no state needs to be retained) and again pass in all of the relevant data

I want to get your opinion on which of these makes sense (or if  there are others I haven't thought of). I like The first one the most because it only couples the objects at a high level and doesn't require exposing objects to state they don't (otherwise) need to know about. I don't like number 2 because it doesn't do those things and number 3 I'm neutral on at this point; it doesn't seem necessarily better or worse than number 1.

If number 2 is in fact the winner I have concerns about how much complexity will be propagated up to this high level game class.

答:
I would go for #3 in an ideal world, simply due to Single Responsibility Principle. One class does pathfinding, not pathfinding and game state. This keeps it easy to change the path finding strategy as well as testing it in isolation (and in an ideal world, reuse it for different games).

That said, the interface you expose to work with game state (and map info, unit info, etc.) tends to be very query based. Ask for something, get something. Pathfinding tends to need to have everything and then manipulate it to some degree. In the real world, you may need a back door interface to get the pathfinder what it needs or to go with #1.

Remember, a done game is always better than a non-functioning well-designed game.


答:
I've found it best to always start by sketching out a logical domain model.  This sort of model is independent of the implementation and focuses on identifying key concepts and their relationships.  Eric Evan's "Domain Driven Design" is a great reference for this.

The next step is to design the implementation model.  For this, a good rule of thumb is to determine the interface that clients will be using to interact with your model and start there.

For example, if you're building a new OLTP system using an ORM-based framework (such as Rails or Grails), your services and controllers will interact with the model using the ORM interface.  Because of this, you'll want to start with designing the object model and let the data model follow from that. ORM frameworks each have their own preferred ways to model object-oriented concepts at the database level and following the framework's preferred way will be faster and less buggy.  If you design the data model first and then map it to the ORM framework, you may end up having to jump through hoops to get it to work properly.

On the other hand, if you're building an OLAP system backed by a Kimball-style data warehouse, there will likely be a variety of clients accessing it, such as custom apps and BI tools.  A common interface to use in this case is direct SQL access.  It provides great flexibility and allows clients to leverage the full power of the database.  So in this case, you'd want to focus on the database design first.

Title: object model and data model


问:
Best way to indicate more results available
We have a service to return messages. We want to limit the number returned, either allowing the caller to specify the max number to return, or else to use an internal hard limit. We also have thought it would be nice to include in the response whether more messages are available. The "best" way to go about this is not clear.

Here are some ideas so far:

Only set the "more messages" indicator if the user did not specify a max limit, and the internal max limit was hit.

Same as #1 except that "more messages" indicator set regardless of whether the internal hard limit is hit, or the user-specified limit is hit.

Same as #1 (or #2) except that we internally read limit + 1 records, but only return limit records, so we know "for sure" there is at least one additional message rather than "maybe" there are additional messages.

Do away with the "more messages" flag, as it is confusing and unnecessary. Instead force the user to keep calling the API until it returns no messages.

Change "more messages" indicator to something more akin to an EOF indicator, only set when the last message is known to have been retrieved and returned.

What do you think is the best solution? (Doesn't have to be one of the above choices.) I searched and couldn't find a similar question already asked. Hopefully this is not "too subjective".

答: As a consumer of API's, my preference would be 3 or 5.  While it makes coding easy to just go until you get nothing, API requests can be costly.  The choice between 3 or 5 I think would really come down to the penalty for retrieving limit + 1 items.  If there is very little overhead to the backend to check, then it is a very friendly thing to let the user know before they make one more needless request.</p>


问:
Relevance of HTML5: Is now the time?
It seems like most of the jobs I'm receiving, and most of the Internet, is still using standard HTML (HTML 4, let's say) + CSS + JS. Does anyone have any vision on where HTML5 is as a standard, particularly regarding acceptance and diffusion? It's easy to find information about inconsistencies between implementations of HTML5 and so forth. What I want to know about is relevance of HTML5.

答: HTML4 is 13 years old, and still not universally/consistently supported. HTML5 is only about 2 years old, so I'd give it another decade.

ContentLicense: CC BY-SA 2.5

Title: Relevance of HTML5: Is now the time?


问:
Using a closure to avoid code duplication in Python
Sometimes I find myself wanting to run the same code from a few different spots in the same function. Say I have some function func1, and I want to do the same thing from a few different spots in func1. Normally the way to do this would be to write another function, call it "func2", and call func2 from several different places in func1. But what about when it's convenient to have func2 access variables that are local to func1? I find myself writing a closure. Here's a contrived example:

```<code>import random
import string

def func1 (param1, param2):
    def func2(foo, bar):
        print "{0} {1} {2:0.2f} {3} {4} {0}".format('*'*a, b, c, foo, bar)

    a = random.randrange(10)
    b = ''.join(random.choice(string.letters) for i in xrange(10))
    c = random.gauss(0, 1)
    if param1:
        func2(a*c, param1)
    else:
        if param2 > 0:
            func2(param2, param2)
</code>```

Is this the Pythonic way to handle this problem? A closure feels like pretty heavy machinery to be rolling out here, especially given that I have to construct a new function every time func1 is called, even though that function is going to be basically the same every time. But it does avoid the duplicated code and in practice the overhead of repeatedly creating func2 doesn't matter to me.

答:
TL;DR: Create function (ideally at import time, not execution time) unless you need to save state

A closure is so named because you "close over" a lexical variable in the enclosing scope.  This allows you to save state.  That is why you use closures.

If a, b, and c represent variables declared in func1 you have a closure.  If they do not represent captured variables from the enclosing scope the you just have a function declared inside a function.

If you want to capture values, but aren't going to modify them I would use functools.partial  instead of a closure or a dynamically defined function. ie.

```<code>from functools import partial

def func1(a, b):
  print a, b

def func2(i, j ,k):
  fn = partial(func1, i)
  fn(j)
  fn(k)
</code>```

I would still make func1 a regular helper function declared outside of func2.  Then possibly use partial to save on passing arguments on subsequent calls.

Body:
TL;DR: Create function (ideally at import time, not execution time) unless you need to save state

A closure is so named because you "close over" a lexical variable in the enclosing scope.  This allows you to save state.  That is why you use closures.

If a, b, and c represent variables declared in func1 you have a closure.  If they do not represent captured variables from the enclosing scope the you just have a function declared inside a function.

If you want to capture values, but aren't going to modify them I would use functools.partial  instead of a closure or a dynamically defined function. ie.

from functools import partial

def func1(a, b):
  print a, b

def func2(i, j ,k):
  fn = partial(func1, i)
  fn(j)
  fn(k)

I would still make func1 a regular helper function declared outside of func2.  Then possibly use partial to save on passing arguments on subsequent calls.


答:
It is a an acceptable form. As @Giorgio said, I would put the closure after the captured variable definition to ease the flow of reading.

The alternative form would be to define another function, taking a, b, c as parameters. That is 5 parameters which is a lot. The closure allows you avoid repeating yourself in a very simple way. This is a big win for your version.

You can use the timeit module to compare the performances of simple snippets. You should check yourself that a closure is not a heavy machinery. The only problem I see is that it creates more nested elements. So if you find yourself writing a big closure, you should try to extract the complex part outside. But in this case I don't think it is an issue.

```<code>import timeit
import random
import string

def func1 (param1, param2):
    def func2(foo, bar):
        return "{0} {1} {2:0.2f} {3} {4} {0}".format('*'*a, b, c, foo, bar)

    a = random.randrange(10)
    b = ''.join(random.choice(string.letters) for i in xrange(10))
    c = random.gauss(0, 1)
    if param1:
        func2(a*c, param1)
    else:
        if param2 > 0:
            func2(param2, param2)

def func4(foo, bar, a, b, c):
    return "{0} {1} {2:0.2f} {3} {4} {0}".format('*'*a, b, c, foo, bar)

def func3 (param1, param2):

    a = random.randrange(10)
    b = ''.join(random.choice(string.letters) for i in xrange(10))
    c = random.gauss(0, 1)
    if param1:
        func4(a*c, param1, a, b, c)
    else:
        if param2 > 0:
            func4(param2, param2, a, b, c)

print timeit.timeit('func1("tets", "")',
 number=100000,
 setup="from __main__ import func1")

print timeit.timeit('func3("tets", "")',
 number=100000,
 setup="from __main__ import func3")
</code>```

Title: Using a closure to avoid code duplication in Python

Body:
Sometimes I find myself wanting to run the same code from a few different spots in the same function. Say I have some function func1, and I want to do the same thing from a few different spots in func1. Normally the way to do this would be to write another function, call it "func2", and call func2 from several different places in func1. But what about when it's convenient to have func2 access variables that are local to func1? I find myself writing a closure. Here's a contrived example:

```<code>import random
import string

def func1 (param1, param2):
    def func2(foo, bar):
        print "{0} {1} {2:0.2f} {3} {4} {0}".format('*'*a, b, c, foo, bar)

    a = random.randrange(10)
    b = ''.join(random.choice(string.letters) for i in xrange(10))
    c = random.gauss(0, 1)
    if param1:
        func2(a*c, param1)
    else:
        if param2 > 0:
            func2(param2, param2)
</code>```

Is this the Pythonic way to handle this problem? A closure feels like pretty heavy machinery to be rolling out here, especially given that I have to construct a new function every time func1 is called, even though that function is going to be basically the same every time. But it does avoid the duplicated code and in practice the overhead of repeatedly creating func2 doesn't matter to me.

Body:
It is a an acceptable form. As @Giorgio said, I would put the closure after the captured variable definition to ease the flow of reading.

The alternative form would be to define another function, taking a, b, c as parameters. That is 5 parameters which is a lot. The closure allows you avoid repeating yourself in a very simple way. This is a big win for your version.

You can use the timeit module to compare the performances of simple snippets. You should check yourself that a closure is not a heavy machinery. The only problem I see is that it creates more nested elements. So if you find yourself writing a big closure, you should try to extract the complex part outside. But in this case I don't think it is an issue.

import timeit
import random
import string

def func1 (param1, param2):
    def func2(foo, bar):
        return "{0} {1} {2:0.2f} {3} {4} {0}".format('*'*a, b, c, foo, bar)

    a = random.randrange(10)
    b = ''.join(random.choice(string.letters) for i in xrange(10))
    c = random.gauss(0, 1)
    if param1:
        func2(a*c, param1)
    else:
        if param2 > 0:
            func2(param2, param2)

def func4(foo, bar, a, b, c):
    return "{0} {1} {2:0.2f} {3} {4} {0}".format('*'*a, b, c, foo, bar)

def func3 (param1, param2):

    a = random.randrange(10)
    b = ''.join(random.choice(string.letters) for i in xrange(10))
    c = random.gauss(0, 1)
    if param1:
        func4(a*c, param1, a, b, c)
    else:
        if param2 > 0:
            func4(param2, param2, a, b, c)

print timeit.timeit('func1("tets", "")',
 number=100000,
 setup="from __main__ import func1")

print timeit.timeit('func3("tets", "")',
 number=100000,
 setup="from __main__ import func3")


问:
What is a good algorithm for tracing around the edge of a 2D polyline
If I have a polyline made up of any number of vertexes, what is an efficient algorithm for tracing around the boundary of this polyline?

There are 4 situations to consider:

The polyline does not intersect itself and has no colinear edges.

The polyline does not intersect itself but has an interior or exterior loop.

The polyline has self intersections in a bowtie shape.

The polyline has self intersections which form interior loops.

An example of each (all are closed):

Vertex List = (5,3) (10,3) (10,7) (5,7)

Vertex list = (0,0) (3,0) (3,3) (1,3) (1,2) (2,2) (2,3) (0,3)

Vertex list = (5,3) (10,7) (10,3) (5,7)

Vertex list = (0,0) (3,0) (3,4) (1,4) (1,2) (2,2) (2,3) (0,3)

Visually:

In this case a convex hulling algorithm really is not appropriate, because I wish to preserve any concavities in the shape.

Results:

To clarify, the bow tie shape should not be crossed over, and a simple area calculation should yield an area for this shape (i.e. the two triangles end up logically wound in the same direction).

Not only does this algorithm have to work (which is the first priority) it should be fast enough to run on hundreds of thousands of polylines in a few seconds.

In addition, the algorithm has to be able to handle any combination of the four cases.

答:
Here is a rough outline of an algorithm which might probably solve your problem:

dissolve the polygon into non-intersecting lines, forming a planar graph

once you have the planar graph, construct the outer hull by adapting the classic gift wrapping algorithm to this graph

Step 1 could be implemented in a simple, but not very efficient manner, by making a intersection test for each pair of edges (giving a running time of O(#Edges²)). A more sophisticated implementation could utilize a sweep line approach. You have to be careful to move your sweep line not just to the coordinates of the existing vertices, but also take care for intersecting points, parallel lines etc. and split the existing lines accordingly. After this step, there should be no crossing or overlaying lines any more.

Step 2 is a simple modification of the classic "convex hull" algorithm: just start with an outer vertice of your graph, move from one vertice to the next adjacent vertice picking the connecting edge with the "smallest angle". Make sure that step 1 passes you the planar graph in a data structure which will allow you to pick all edges connected to a given vertice very quickly.

Hope this helps.


问:
How do I explain to non-programers what .NET is?
I don't work at a software company, and I'm one of a small handful of people in the company that know anything about programming. I spend a lot of time automating other programs that are used in the office through public APIs, and I've also created a few stand alone applications. I work almost entirely in C#.NET as every application we seem to use in the office seems to have some form of .NET API.

I've had a few people here ask me about learning "how to program", and where they should start. I think it makes a lot more sense to learn a .NET language as nearly all the programs they would want to automate have a .NET API, and it sounds like VBA is on it's way out and being replaced by VSTA.

However, I'm trying to figure out how to explain what .NET is and why they should learn it to a someone that doesn't know anything about programming. It's not really a language, as there are a number of languages that are considered .NET languages. Plus I think there is a distinction between ".NET" and "The .NET framework" as the latter is more about the libraries provided by Microsoft.

答:
Don't

Tell them "C#" and if they follow through they'll figure it out. There's no point in explaining it in a vacuum.

[or tell them "Java" so they won't come to you for help!]


问:
Is it possible to implement a native compiler for a 'managed language' such as Java?
In most cases, it is possible to create both a native compiler and an interpreter for a programming language. The compiler would simply convert the source code to machine code, and the interpreter would simply execute the source code (or some IL produced by a compiler).

However, I'm not sure about languages with garbage collection. Let's take Java for example.

When Java was designed, it was clear that Java programs were always going to be run on the JVM. And the JVM was supposed to feature a garbage collection mechanism. So while designing the Java language itself, there was no need for destructors and such.

If one was going to implement a native Java compiler, that would mean the Java source code would be compiled to machine code to be run on the machine itself, not on a VM. And the machine itself doesn't feature a mechanism for garbage collection.

How would someone implementing a native Java compiler deal with this situation? Is it possible to create a native compiler for Java, since the Java design 'counts' on automatic garbage collection? (And possibly on some additional things the VM does for the program?)

答:
Sure, it's possible. It just means that to keep the full semantics of java as it is specified, you have to include part of the code that constitutes the JVM into each binary you create.

In particular, the reference-counting, the garbage collecting, the run-time type information code etc. have to be included (unless maybe you have a very smart compiler that can prove certain features aren't going to be used by this program). Overall you save some of the JIT and byte code interpretation code in the JVM, but you pay for that by increasing the size of each natively compiled program.

This is usually not a good trade-off, which is why it's rarely done, but there is no fundamental technical reason why things the JVM does for you can't be done by a standalone application for itself. It's no different from bundling e.g. a Perl interpreter with a cool script to spare people the necessity of installing Perl itself.


答:
Since native compilers for Java, C# etc. exist, it is obviously possible.

Whether or not a language is "managed" is a question of language semantics, not the implementation. It doesn't matter whether it's a compiler, an interpreter or a mixed-mode implementation. Every language can be implemented with a compiler and every language can be implemented with an interpreter. After all, most real-world implementations of Java are static compilers anyway.

Even C and C++ need a runtime library. For a Java-to-x86 compiler, that runtime library would need to include a little bit more than it would for a C-to-x86 compiler (the GC, reflection system, but also the dynamic linker and dynamic loader because Java code can be added to the program at any time), but the principle is the same.

By the way, you should be careful with terms like "native code" or "native compiler": there are CPUs that execute JVM byte code, and there are x86 interpreters for the JVM. So, imagine a JVM program running on a JVM CPU, and an x86 program running on an interpreter running on a JVM running on a Sparc CPU emulated via QEmu running on a PowerPC. Which one is "native"?

Title: Is it possible to implement a native compiler for a 'managed language' such as Java?

Body:
In most cases, it is possible to create both a native compiler and an interpreter for a programming language. The compiler would simply convert the source code to machine code, and the interpreter would simply execute the source code (or some IL produced by a compiler).

However, I'm not sure about languages with garbage collection. Let's take Java for example.

When Java was designed, it was clear that Java programs were always going to be run on the JVM. And the JVM was supposed to feature a garbage collection mechanism. So while designing the Java language itself, there was no need for destructors and such.

If one was going to implement a native Java compiler, that would mean the Java source code would be compiled to machine code to be run on the machine itself, not on a VM. And the machine itself doesn't feature a mechanism for garbage collection.

How would someone implementing a native Java compiler deal with this situation? Is it possible to create a native compiler for Java, since the Java design 'counts' on automatic garbage collection? (And possibly on some additional things the VM does for the program?)


问:
Collecting user information for debugging and support
I have a Java application that I need to support. I'd like it to collect user information, such as system information: OS and hardware for easier diagnostics and support.

Are there any security & privacy regulations I need to follow?

Do I specifically need consent from the user to do this?

答:
Need: depends on the country you and your users are in. Ask a lawyer.

Should you explicitly gain consent to avoid pissing off users who will think you are scum when they find out you've been doing it without permisssion: Yes. Absolutely. Essential. Oh dear $diety yes. What, are you crazy? Just do it. And so on, you get the idea.


问:
Term for accidental features
Despite the best intentions of programmers; oftentimes, in the real world, software systems contain "accidental features" that are accepted as part of a working system.

For example, there may be some process that runs out of memory and crashes before the process exceeds its quota for calls to an external system (which will cost the company money). Though the software team acknowledges that this is an issue, there is simply not enough perceived business value to fix the problem.

Advantageous accidental behavior like this is often lost in any type of significant technical migration.

My question: Is there a term for this type of "feature" that can serve to differentiate it from a run-of-the-mill bug?

答:
"Emergent properties" is a correct term. We went over this at university - example was a 4x4 car. Its main purpose is off-road. However, many families decide to buy such a car because it provides safety to their kids (passengers).

Another emergent property of that car is the fact is when you drop your kids off at school, they tend to open a door in a rush. This has caused separate problem where small kids on the pavement were hit by the car door as you couldn't really see them in a window.

The point is that the term applies to both good and not so good features. It's also used in a range of industries, not just the IT.

Title: Term for accidental features


问:
What is the role of the lead developer in an agile team?
In a non-agile development team a lead developer generally:

Sets the standard (coding and otherwise)

Researches new technologies for the team

Sets the technical direction for the team

Has the final say on matters

Designs the architecture of a system

However an agile team works differently:

An agile team will rely on emergent design, rather than up front

An agile team designs together, rather than design being dictated by one person

An agile team decides on their own technical direction, which is best to deliver a project

Where does this leave a lead developer in an agile team? Is it possible to have a lead developer in an agile team? Does a agile team demand different responsibilities from a lead?

答:
In an agile team everyone is supposed to put their egos aside.

If one member of an agile team has more experience than the others what will likely happen is that the experienced member will be involved in most code reviews and people will often defer to that person's experience when making team decisions.

So, a "lead" developer will continue "leading," but as a natural consequence of their experience and not as a mandated function of their title.

That's in an ideal world where people can put their egos aside.  Good luck!


答:
Nothing in agile changes how the lead developer should function.  They should be involving the rest of the team with system architecture decisions, and technical direction no matter what development model is being followed.

Handing out decisions by edict is a terrible way for any development team to run. Agile just makes getting buy in from the rest of the team a more explicit process, and a lead developer should have been doing that anyway.

Just because there isn't a set lead developer role in a scrum methodology doesn't mean the more experienced programmers opinions aren't the most respected. Agile is not letting everyone go wild on their own thing and then trying to stick it all together, there is still a unified vision and direction that needs to be set.

Title: What is the role of the lead developer in an agile team?

Body:
In a non-agile development team a lead developer generally:

Sets the standard (coding and otherwise)

Researches new technologies for the team

Sets the technical direction for the team

Has the final say on matters

Designs the architecture of a system

However an agile team works differently:

An agile team will rely on emergent design, rather than up front

An agile team designs together, rather than design being dictated by one person

An agile team decides on their own technical direction, which is best to deliver a project

Where does this leave a lead developer in an agile team? Is it possible to have a lead developer in an agile team? Does a agile team demand different responsibilities from a lead?


答:
In addition to Ryathal's answer:

You talk about emergent design and team direction as though they flow from the team in perfect unison and harmony. Groups of people, groups of programmers especially have conflict. As the team lead, your job in an agile team is more of a referee or catalyst than in waterfall. When the team has conflict about what design to use for example, you'll make sure that people have equal say and stick to arguing over merits. And you end up being the arbiter to which proposed solution the team will go with when the path is not clear.

This is one of the most important responsibilities of the lead, but plenty of other things are needed to make a bunch of people into a team. You still need to set an example as far as good coding goes, and often enforce that (either directly or by creating a culture to do it). You need to facilitate communication between all of your team members, because once a day at standup isn't going to cut it.

The other important thing you've overlooked is meetings. It's impractical to bring the entire team to every meeting where the team needs to interact with business people, other technical teams, etc. As the team lead, you're the team's representative. You go to the meetings so that they can stay at their desks and get stuff done. You're the point of contact so that they're not interrupted by people stopping by directly. And you work to take information from the outside world (what other teams are working on, what the agile teams look like next sprint, what's the status of that open req, etc), boil it down for them and communicate it.

In short, you're the lubricant to make sure that they can run smoothly.


问:
How can I handle Bots in a site that creates a database item every page
I have an eCommerce platform that creates a basket as soon as the user lands on the site if they don't already have one (from session or cookies). It then stores the basket information in session and in cookies to remember what the user has added to their basket for a month.

The problem is if they aren't capable of having a session or cookies, such as a bot, then it creates a basket every time they visit a page. This means a bot crawling through the website can easily create hundreds of baskets.

One of the options we're exploring is changing our code so that a basket is only created when a user adds an item, and so far it seems the best option, but it's also the most time consuming option as a lot of the code base assumes a basket exists at all times. That would need to be changed so that it checks for a basket and handles a basket not existing. We'd like to find a less intensive solution if possible.

Another option we've explored is periodically clearing out the table in the database of all old baskets to help mitigate the issue. However this is just mitigating, and not solving the issue. I'd like to solve the problem if I can.

How can I identify if the user is incapable of having a session and cookies so that I can stop the basket from being created? Or is there a better way of dealing with bots in this instance?

答:
Any agent that isn't capable of handling cookies or even sessions will probably also be unable to tell you reliably that it doesn't handle them correctly.

However, indexing bots that crawl arbitrary pages will usually specify a characteristic user-agent string and/or obey your robots.txt rules, so you should deal with them via one of those two well-established bot-handling protocols.


答: I would recommend doing some detection based on the users user-agent. You can use a library like UA Detector to identify users as bots and trigger different backend behavior. You will likely need to also take the approach recommended by Mike in the comments to your question as your traffic continues to grow and you start getting hit by unidentified bots.</p>

Title: How can I handle Bots in a site that creates a database item every page

Body:
I have an eCommerce platform that creates a basket as soon as the user lands on the site if they don't already have one (from session or cookies). It then stores the basket information in session and in cookies to remember what the user has added to their basket for a month.

The problem is if they aren't capable of having a session or cookies, such as a bot, then it creates a basket every time they visit a page. This means a bot crawling through the website can easily create hundreds of baskets.

One of the options we're exploring is changing our code so that a basket is only created when a user adds an item, and so far it seems the best option, but it's also the most time consuming option as a lot of the code base assumes a basket exists at all times. That would need to be changed so that it checks for a basket and handles a basket not existing. We'd like to find a less intensive solution if possible.

Another option we've explored is periodically clearing out the table in the database of all old baskets to help mitigate the issue. However this is just mitigating, and not solving the issue. I'd like to solve the problem if I can.

How can I identify if the user is incapable of having a session and cookies so that I can stop the basket from being created? Or is there a better way of dealing with bots in this instance?


问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
Miss Understood, this isn't really an answer to your question, but some advice for the future.

You may have just paid £800 for a course in dishonest business practices. It's cheaper than it might have been, and it's up to you to make the most of that fee.

We all "know" that if we go into business, we might run into dishonest people. But if you're like me, you don't take it seriously until it happens to you.

Even when you're on guard, there are many ways for people to be dishonest, and many dishonest people are very good at seeming honest. So you may get "taken" several times in the course of a career. I certainly have - since I began freelance programming in 1990, I can total up $40,000 in direct cash losses due to dishonest clients, $5,000 paid to a subcontractor who didn't deliver, thousands more I only received due to legal arm-twisting, and a $400,000 contract lost because a multi-billion dollar company gave my proposal to a competitor to undercut.

Here are a few things I've learned from all this:

Always have a contract. Honest clients don't mind them, and dishonest ones need them. Especially the ones blather about "handshake deals".

If the client provides a contract, and you don't like it, demand changes. If you can't get a contract that suits you, don't do the project. Remarks about "standard contracts we have to use" are just hot air.

Get everything important in writing. Summarize verbal conversations in a confirming email. If you have to go to court, it's really useful. People who might be inclined toward dishonesty are often aware of that, so it can prevent problems.

Always have a way out, and be willing to use it. The first rule of business deals is: the person who can afford to walk away from the table first wins.

Structure your payments so that you don't deliver final work until all your costs have been covered. That way, if they take your work and stiff you on the final payment, it's just profit and you haven't lost money.

As soon as there's a payment problem, stop work and don't deliver anything.

If your customer is a pain, sack them. Life is short, stress and worry suck, and there are other customers out there.

I've quit doing fixed-price projects because they're too prone to problems. Many clients who want fixed-price also want free changes, and I hate arguing about that. Even if the client is great, it's far too easy to underestimate a project and lose money. My income and profitability have skyrocketed since I went to hourly-only work.

My final advice is, don't be afraid to publicize the fact that your client stiffed you. If you can back it up with evidence, it's wonderful leverage. Why should you worry about damaging the business of some scumbag who stole from you?

I just went through that myself. I'm doing a programming project through an agency that started talking about paying me late. I sent them a stiff email this morning, and was just talking to my wife about calling the principal and telling them I was stopping work, when the agency said I'd have a wire transfer in a few days.

Title: How to get money from reluctant client?


问:
When to start thinking about scalability?
I'm having a funny but also terrible problem. I'm about to launch a new (iPhone) app. It's a turn-based multiplayer game running on my own custom backend. But I'm afraid to launch.

For some reason, I think it might become something big and that its popularity will kill my poor lonely single server + MySQL database.

On one hand I'm thinking that if it's growing, I'd better be prepared and have a scalable infrastructure already in place.

On the other hand I just feel like getting it out into the world and see what happens.

I often read stuff like "premature optimization is the root of all evil" or people saying that you should just build your killer game now, with the tools at hand, and worry about other stuff like scalability later.

I'd love to hear some opinions on this from experts or people with experience with this. Thanks!

答:
At the business requirements stage, which then is used to establish a common understanding for performance for all elements downstream such as architecture, ops, development, QA and monitoring in prod.   If you don't establish a common understanding for what is required up front then you will have each of the parts of the organization making assumptions about performance (or not thinking about them at all) when engaging in particular tasks across the life cycle of the application.    This is true whether you are engaged in waterfall, short waterfall, agile or whatever the development methodology of the moment is hot on the resume keyword list.

Performance and scalability is hard.  Functionality is easy.   Poor scaling code will grow to fill whatever resource pool you provide to it, so shifting the cost bubble by purchasing larger hardware only takes you so far before you have to either fix the inefficient code or purchase ever more hardware.   Leaving this to last in priority is also very costly.  There are architecture and design decisions which are made early in the life cycle of the application which may have to be completely reversed in order to hit a late arriving requirement related to performance - Think of a high performance sports car manufacturere having to switch from aluminum to carbon fiber late in the design cycle to hit a power/weight ratio related to performance and how this impacts tooling, training, the construction of the car, etc...

Ask the architects, developers and ops people in your organization what are the performance requirements for the application.   If these are not captured from the business then don't be surprised if you receive different answers (or no answers) from different individuals even within the same group.   Those "assumptions" always come back to smack the organization in deployment.


问:
Eventual consistency in Banking systems
I keep hearing people say Banking systems like ATM use Eventual consistency model for data synchronization, but I am wondering if it is true.

Definitely the amount you withdraw might be delayed showing in your banking statement, but I assume  they won't let the amount of your banking account inconsistent at any given time, right?

Anyone working in the industry can confirm this?

答:
You must distinguish technical correctness criteria from real-world systems requirements.

Certainly banks must be able to account for every withdrawal and deposit, and more generally for every in and out on their balance sheets. That's what regulators are for. But no regulator will ever hold a bank to prove that the accounts were completely "consistent" at any given point in time, particularly if it's long in the past. That's why banks can get away with deducting sums from your account while not crediting the recipient until days later, as long as they keep track of where everything has to go eventually.

In their own trades, modern banks are capable of millisecond-accurate accounting, so obviously this is not a technical limitation. The simple truth is that there is an incentive for the bank to execute deductions as early as possible, and credits as late as possible, because that earns them more fees that doing the opposite, and as long as there is no legislation which forbids this, they have no reason to improve. So 'eventual consistency' in banking is not a technical compromise for lack of a better alternative, as with huge NoSQL data stores - it is plain and simple good business for the money handlers.

Title: Eventual consistency in Banking systems


答:
Your non-agile description doesn't invalidate your agile description.

An agile team will rely on emergent design, rather than up front.

Nothing about your definition of a lead developer says design must be had up front. He may set the direction, and he may still lay out an initial design.  That design is definitely emergent.

An agile team designs together, rather than design being dictated by one person

Nothing about your definition of a lead developer says that he dictates design.  Although he may have final say, only a poor lead would fully disregard the thoughts of his majority teammates. On the flip side, only a poor team would fully disregard the thoughts of the lead developer.

An agile team decides on their own technical direction, which is best to deliver a project

Again, this doesn't mean that the lead does not initially set this direction.  The lead is part of this agile team.  Even in a non-agile environment, only a poor lead would continue to march a team in said direction when it has becoming knowingly unfeasible, or when new information has been presented to invalidate this direction.


问:
Why did Microsoft dropped the RESX model for RESW in Windows Store applications?
Why did Microsoft choose to change the resources management system from .NET's RESX files?

RESX had useful code generation, providing developers auto-completion for resources names and outputting IMHO very readable code.

The new RESW format is as far as I know, the same bare XML files, but without any code generation, forcing developers to write more code, and depriving them of compile time error detection.

答:
While this article on MSDN doesn't go much into detail as to the "why", it rather explicitly states the "what."

In Windows Store apps, you use .resw files to create resources. Despite the difference of file extension, the .resw file format is identical to the .resx file format, except that .resw files may contain only strings and file paths.

While answering the "why" requires speculation or inside knowledge (my guess is "to save on file writes in the final App"), the fact that the syntax is idental means that you should be able to use whatever tooling you had to create resx files to produce Windows 8 compatible resw files.  (in fact, you may be compiling the resx into resm, similar to how LESS or DART are processed into CSS or JavaScript.)


问:
Improving ZooKeeper to increase availability
Running Apache ZooKeeper (this applies to PAXOS style system just as well) with 2 members - which is not recommended - does not make sense, because if either

member1 goes down

member2 goes down

there's a network partition between member1 and member2

, ZooKeeper will declare business hours to be over, as there's no single sub cluster with a clear majority of members (in this case: > 1). So running ZooKeeper on 2 members makes it less available than running a single member.

Why can't the majority constraint be relaxed so that when the there's a sub cluster of exactly 50% of members, it is considered the active sub cluster if it contains the eldest member? (Eldest as of the just before the partition happened, i.e. when the cluster was member-complete) Who's eldest is information ZooKeeper already keeps track of, so implementation looks easy.

That way, we don't run into the dreaded split-brain scenario, and the ZooKeeper cluster could stay up in 2 of the 3 cases above, improving availability, especially when running 2 members only.

Anything speaking against this?

答:
It just occurred to me that although the 2 member scenario could indeed be made more available than it is right now, it would still not be more available than the 1 member scenario, and writing is in fact slower for 2 members, because every change needs to be propagated to another member. Only reads from ZooKeeper will improve under heavy load (assuming the members are on different machines), because you can read from any of two machines, rather than just one.

So this change might still be implemented, but choosing 2 members over just 1 member would turn from a no-brainer to a trade-off decision: having to maintain another process, worse write performance in general, with better read scalability for the improved 2 member case. This isn't necessarily bad though, especially if ZooKeeper is used for what it was designed for: scenarios with an overwhelming proportion of reads.

And to address the question: Although it would increase availability, it would increase the 2 member availability only to that of the 1 member case.


问:
object model and data model
I have heard/read mixed things on whether to start with an object model or a data model. And more people say to starting with an object model as it will ease your data modelling.

My question is, Shouldn't an object model always drive the design of data model? Why and When would a data model design be different than an object model?

If we have a good object model, shouldn't the classes we come up with translate into tables? And class associations as table relationships?

答:
Or you may want to start with a behavior model. It depends on the problem at hand. One of the key goals of modeling is to assist the discussions with your nontechnical stakeholders. From this point if view it is useful to frame the model in the context that us most intuitive to those stakeholders. If those stakeholders are deeply immersed in process flows, it might be better to start there, figure out what data is needed to support the behavior and think about how to group behaviors and data into objects a bit later. Admittedly heresy in the "Objects are the Answer to Every Problem" world...but it might get you a better level of communication with your stakeholders, and hence a product with a higher level of user satisfaction.

David Hetherington

Title: object model and data model


问:
Implementation difference between Lombok & AutoValue
I thought both Project Lombok & AutoValue used compiler annotation processors, but from this slide presentation and this stackoverflow answer it seems that Lombok doesn't... or at least not annotation processors alone.  What is the difference in the way that Lombok & AutoValue use annotation processors?

答:
AutoValue is a standard Java annotation processor, meaning that it uses only the javax.* interfaces for annotation processing. Lombok is also an annotation processor, but it references implementation-specific classes in order to do things that standard processors cannot. Most notably, it changes the code being generated for source classes, for example by inserting getter and setter methods. The standard for annotation processors very deliberately did not allow that because it was felt to violate Java's WYSIWYG qualities.

Because Lombok references nonstandard classes it is much more fragile, in that those classes may change between releases. It's also obliged to have two parallel implementations for the two main Java compilers (JDK and Eclipse).


问:
How can I promote software reuse in a large company?
Take a large company, formed through many iterations of mergers and reorganizations. This company produces lots of different products that are all targeted to a specific industry. Most products share similar characteristics, such as communication standards and certification and safety requirements. But there is no unified development platform or model for the company. Each product has its own distinct hardware, and software is created in any number of languages. Most new products will be updates to older versions or target the same industry. What strategies would you use to promote software reuse?</p>

答:
A few years ago I actually was able to start a team that did this within the organization I was working for at the time. It was a great experience and I'd do it again in a heart-beat. The most difficult people to sell on the idea were the other developers, not the management. I had a good reputation with the different development groups so that was very helpful and we were very careful to keep that reputation as our team grew. By the time I left the company the project had been alive for two years and had around 8 full time developers.

Advise I could pass on:

Have a team that is responsible for nothing other than this

Get your requirements from representatives of each development group so that they have buy-in

Start with something that developers on a couple teams already want to share

Document you code as well as you would expect a language to be documented


问:
Testing in procedural programming code
I have designed and implemented, for my final year in college, an autonomous robot with Arduino board microcontroller. The robot wanders around an area, avoids obstacles and tries to detect intruders.

I have to do some testing for this project . Could anyone help me by telling what test procedures I can perform in procedural code?

Observation of the behavior of robot could be one of them?

```<code>Servo servoLeft;          // Define left servo
Servo servoRight;         // Define right servo
const int trigPin = 5;
const int echoPin = 2;
int buzzerPin = 6;               // choose the pin for the LED //buzzer
int inputPin = 9;              // choose the input pin (for PIR sensor)

int val = 0;
Timer t;
boolean pirSense = false;
long xronos=0;

void setup() {
Serial.begin(9600);
 servoLeft.attach(4);      // Set left servo to digital pin 10
 servoRight.attach(3);     // Set right servo to digital pin 9

 pinMode(buzzerPin, OUTPUT);      // declare LED as output
 pinMode(inputPin, INPUT);     // declare sensor as input

 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 t.every(30000,monitoring);
  }

  void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  distance = microsecondsToCentimeters(duration);
   delay(100);
   Serial.println(distance);
   if (distance >= 40){
       moveForward();
     }
      else {

    stopMove();
    int x = random(0,2);
    if(x == 0 ){
    turnRight();
    delay(500);
   }
   else{
     turnLeft();
    delay(500);
   }
  }
 t.update();
 }

 void monitoring(){
  xronos = now();
 while( xronos+5 >now() ){
  stopMove();
 delay(1000);
 pirSensor();
 }

}

  // Motion routines for forward, reverse, turns, and stop
  void reverse() {
  servoLeft.write(0);
 servoRight.write(180);
 }

 void moveForward() {
 servoLeft.write(180);
 servoRight.write(0);
 }

  void turnRight() {
 servoLeft.write(180);
 servoRight.write(180);
  }
 void turnLeft() {
  servoLeft.write(0);
  servoRight.write(0);
  }

 void stopMove() {
 servoLeft.write(90);
 servoRight.write(90);
  }

 long microsecondsToCentimeters(long microseconds)
 {
 // The speed of sound is 340 m/s or 29 microseconds per centimeter.
 // The ping travels out and back, so to find the distance of the
 // object we take half of the distance travelled.
 return microseconds / 29 / 2;
 }
</code>```

答:
Observation of the robot is probably the most important test you can run. Don't let anyone tell you that anything short of a full integration test (which is what your observation is) is fully testing.

However, there are also unit testing frameworks for Arduino.

There are also Pseudo-Arduino boards.

And there are also ways to do pseudo-object-oriented C, to allow you to test your objects independently.

All of these will probably serve you well in a variety of contexts. Understand your options and pick the best tool for the job; that's the skill of programming.

But never forget that there's no better testing than watching the totality of your code work as it's intended. That applies as much to writing a web page, or a game or a robot controller.

Title: Testing in procedural programming code


问:
How to provide a service with RESTful API?
Generally speaking, RESTful API's are very good for representing resources and collections of resources.

http://example.com/resources

http://example.com/resources/item17

And we are good, if we work with resource.

However, what should be done, when you need to expose API which does an action which doesn't create/update or delete a resource.

Couple of examples:

You have an algorithm (as example add two numbers)

You have an action which uses external system (as example send an email).

I saw two approaches:

Represent an action as a subresource

POST http://example.com/resource/item17/sendemail

On one hand, it's straightforward. On other hand, it start smelling SOAPy (read RPC calls).

Represent an action as a standalone resource

POST http://example.com/emailsender

This looks more RESTful. However, it doesn't feel right too (only one of CRUD actions is implemented). This resource actually doesn't have a representation.

I am not sure, may be there are other methods which I have missed.

The question is - "Is there a consensus on this subject? What is the preferred way to do it?"

答:
Since verbs in REST under HTTP are restricted to the HTTP verbs, everything in the URI should be name a noun. So the common trick is to do what you say -- convert the custom verb (sendemail) to a processor noun (emailsender) instead.

At first that seems like a word trick, but it does have some merit. You can then use the "data processing" provision of the POST verb to post commands to your processor. It opens the door to responses like a 202 Accepted if you want to do asynchronous processing.

One thing to watch out for is namespace collision; the processor noun can collide with your identifier namespace. For example:

```<code>http://some/site/users/SomeCoolDude

http://some/site/users/emailprocessor
</code>```

...now you can't have a user named "emailprocessor" because it collides with the processor noun. That may not be a problem if the IDs are ints or UUIDs, but it's something to bear in mind.

...

(And the strict answer is that all the URIs the client uses should come from hypermedia, so the design of the URI should be opaque to the user anyway.)

Body:
Since verbs in REST under HTTP are restricted to the HTTP verbs, everything in the URI should be name a noun. So the common trick is to do what you say -- convert the custom verb (sendemail) to a processor noun (emailsender) instead.

At first that seems like a word trick, but it does have some merit. You can then use the "data processing" provision of the POST verb to post commands to your processor. It opens the door to responses like a 202 Accepted if you want to do asynchronous processing.

One thing to watch out for is namespace collision; the processor noun can collide with your identifier namespace. For example:

http://some/site/users/SomeCoolDude

http://some/site/users/emailprocessor

...now you can't have a user named "emailprocessor" because it collides with the processor noun. That may not be a problem if the IDs are ints or UUIDs, but it's something to bear in mind.

...

(And the strict answer is that all the URIs the client uses should come from hypermedia, so the design of the URI should be opaque to the user anyway.)


问:
What is "condition testing" (as defined by the ISTQB Syllabus) actually good for?
I am currently checking through the syllabus for the ISTQB "Technical Test Analyst" certification. This syllabus (henceforth called "TTA syllabus") contains a chapter dedicated to "condition testing" (apparently this is also called "condition coverage" or "condition coverage testing".)

Condition testing as defined in the TTA syllabus strikes me as an exceedingly strange and possibly anachronistic thing that has more to do with Grandma's Ham Story than with software testing. Let me explain...

What is "condition testing" according to the TTA syllabus?

Referring to the "Advanced Level Syllabus - Technical Test Analyst, Version 2012" of the ISTQB, available here, "condition testing" is defined as follows on page 12:

Compared to decision (branch) testing, which considers the entire
  decision as a whole and evaluates the TRUE and FALSE outcomes in
  separate test cases, condition testing considers how a decision is
  made. Each decision predicate is made up of one or more simple
  “atomic” conditions, each of which evaluates to a discrete Boolean
  value. These are logically combined to determine the final outcome of
  the decision. Each atomic condition must be evaluated both ways by the
  test cases to achieve this level of coverage.

Applicability

Condition testing is probably interesting only in the abstract because
  of the difficulties noted below. Understanding it, however, is
  necessary to achieving greater levels of coverage that build upon it.

So let's clarify the words

Suppose we have some software-under-test on which we want to do whitebox testing (i.e. we have the source code). The code naturally contains many of those decision predicates that we all know and love and that show up after strings like if, while, until etc.

An example of the decision predicate might be:

((x>y+z) AND (y<-3)) OR ((z²+x²<4) AND (z≤y))

This decision predicate accepts a triple (x,y,z) of integer values (say) and outputs a boolean, b_out.

The first-level functions which map (x,y,z) to {TRUE,FALSE} are called conditions (also atomic conditions) in the TTA syllabus.

Condition testing coverage

One attains "condition testing coverage" by running test cases until all the conditions found in the decision yielded at least once true and at least once false.

One can thus achieve condition testing coverage by running the following five test cases (for example):

Each of the the b0, b1, b2, b3 shows up at least once with true and at least once with false. In some test cases, we do not care about a given value as it has no influence on the condition whose output we want to get right.

Addendum: Decision coverage

Incidentally, the truth table shows also that "decision coverage" has been attained for this decision, as b_out shows up at least once with true and at least once with false, so both branches of any code would be covered.

And now the question

What is "condition testing" as defined above actually good for?

It won't help you ascertain the correctness of the decision predicate at all.

That is best done by a code inspection, letting a second team write the same expression and comparing outputs or running test cases at "boundary values" (e.g. here, for y = -4, -3, -2).

Checking the individual conditions strikes me to be more about testing the CPU's ALU or maybe testing the compiler output. It is certainly suitable for checking manually written assembler code or verifying manually assembled logic.

And this makes me think that "condition testing" could well be a leftover from the days where conditions were actually wired up on panels  (for example in the ENIAC) and might thus be subject to wiring bugs. These days, the condition is written in high-level code and is exactly the one you conceptually want. While review might be useful, a testing of the condition is just a waste of time.

Or am I missing something?

Addendum: Literature Search

A search of the IEEE Xplore library for "condition testing" yields only two papers relevant to software (all the others seem relevant to hardware only), both by K.C. Tai of the Department of Computer Science of North Carolina State University.

Checking one of those, Condition-based software testing strategies reveals that the author uses the term condition in the sense of decision above, i.e. in this paper "condition testing" is actually "decision testing". The condition as used in the TTA syllabus is called simple condition. It seems the TTA syllabus definitions are not widely used.

From the abstract:

A computer program consist of statements, such as IF and WHILE statements, that contain conditions, which are combinations of Boolean and relational expressions. A testing approach, referred to as condition testing, is to test a program by focusing on testing the conditions in this program. A number of condition testing strategies have been developed, but they are not effective for detecting errors in complicated conditions. In this paper, we define two condition testing strategies, based on the detection of Boolean and relational expression [i.e. expression of the form E1 op E2, where E1 and E2 are arithmetic expressions and op is one of six possible relational operators: < <=, =, !=, >, >=] errors in a condition. For these two condition testing strategies, we show some theoretical properties and explain why they are practical and effective for testing programs containing complicated conditions.

答:
The best answer I could find (and which also applies to statement coverage testing and other types of coverage testing) is given by this page from atollic.com "Why code coverage analysis?"

More technically, code coverage analysis finds areas in your program
  that is not covered by your test cases, enabling you to create
  additional tests that cover otherwise untested parts of your program.
  It is thus important to understand that code coverage helps you
  understand the quality of your test procedures, not the quality of the
  code itself.

And this seems to be quite relevant here. If you have a test case set that manages to set the individual conditions of any decision to TRUE or FALSE, then you are quite likely invoking the code under test with a rather exhaustive set of input values!

Good condition coverage does not tell you much about the code under test (unless the code blows up or generates detectable faults) but gives you confidence in your test case set.

Addendum:

This is interpretation is correct. In the paper The effect of program and model structure on MC/DC test adequacy coverage (Ajitha Rajan and Mats Heimdahl, University of Minnesota, ICSE, 2008), which is about the related "Modified Condition/Decision Coverage" (MC/DC), one reads:

Adequacy of test suites is currently measured using the MC/DC metric on source code (or on a model in model-based development) ...
  Test adequacy metrics defined over the structure of a program, such as
  statement coverage, branch coverage, and decision coverage, have been
  used for decades to assess the adequacy of test suites. Such criteria
  can be useful tools when evaluating a testing effort.

The paper also concludes that MC/DC coverage is highly sensitive to the structure of the SUT. Purely syntactic rearrangements can change MC/DC coverage dramatically. This is of course because MC/DC just works on the syntax, not on the data flow, and is therefore a rather suspicious measure in any case. But that is another problem entirely.

OwnerDisplayName: David Tonhofer


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

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

答:
I have been asking myself this question for some time now in relation to "condition coverage". So how about this page from atollic.com "Why code coverage analysis?"

More technically, code coverage analysis finds areas in your program
  that is not covered by your test cases, enabling you to create
  additional tests that cover otherwise untested parts of your program.
  It is thus important to understand that code coverage helps you
  understand the quality of your test procedures, not the quality of the
  code itself.

This seems to be quite relevant here. If you have a test case set that manages to attain a certain level of (code or otherwise) coverage, then you are quite likely invoking the code under test with a rather exhaustive set of input values! This will not tell you much about the code under test (unless the code blows up or generates detectable faults) but gives you confidence in your test case set.

In an interesting Necker Cube change-of-view, the test code is now being tested by the code under test!


答:
There are many ways to guarantee that a program does what you intend, and to ensure that modifications will carry no unintended effects.

Testing is one. Avoiding mutation of data is another one. So is a type system. Or formal verification.

So, while I agree that testing is generally a good thing, a given percent of testing might not mean much. I would rather rely on something written in Haskell with no tests than on a well tested PHP library

Title: Is test coverage an adequate measure of code quality?

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

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


问:
What are the downsides of implementing a singleton with Java's enum?
Traditionally, a singleton is usually implemented as

```<code>public class Foo1
{
    private static final Foo1 INSTANCE = new Foo1();

    public static Foo1 getInstance(){ return INSTANCE; }

    private Foo1(){}

    public void doo(){ ... }
}
</code>```

With Java's enum, we can implement a singleton as

```<code>public enum Foo2
{
    INSTANCE;

    public void doo(){ ... }
}
</code>```

As awesome as the 2nd version is, are there any downsides to it?

(I gave it some thoughts and I'll answer my own question; hopefully you have better answers)

答:
enum pattern can't be used for any Class that would throw an exception in the constructor. If this is required, use a factory:</p>

```<code>class Elvis {
    private static Elvis self = null;
    private int age;

    private Elvis() throws Exception {
        ...
    }

    public synchronized Elvis getInstance() throws Exception {
        return self != null ? self : (self = new Elvis());
    }

    public int getAge() {
        return age;
    }
}
</code>```

Body:
enum pattern can't be used for any Class that would throw an exception in the constructor. If this is required, use a factory:

class Elvis {
    private static Elvis self = null;
    private int age;

    private Elvis() throws Exception {
        ...
    }

    public synchronized Elvis getInstance() throws Exception {
        return self != null ? self : (self = new Elvis());
    }

    public int getAge() {
        return age;
    }
}