问:
How can I explain object-oriented programming to someone who's only coded in Fortran 77?
My mother did her college thesis in Fortran, and now (over a decade later) needs to learn c++ for fluids simulations. She is able to understand all of the procedural programming, but no matter how hard I try to explain objects to her, it doesn't stick. (I do a lot of work with Java, so I know how objects work) I think I might be explaining it in too high-level ways, so it isn't really making sense to someone who's never worked with them at all and grew up in the age of purely procedural programming.

Is there any simple way I can explain them to her that will help her understand?

答:
Short answer: no.

Long answer: There's no "simple way" because OOP is far from simple. Procedural programming is all about "variables" and "if then goto". Everything else is syntactic sugar, but those four things are all of what procedural programming is about. Once you get them nothing can stop you.

OOP is a way to organize variables and pieces of code. How many patterns are there to define OOP? 25? 30? Even teachers who learned OOP from different languages and backgrounds don't agree on its own definition, so ... how can it be simple?

I don't know how you came to that, but since your mother has a similar experience to mine, I can tell you how I came to that.

I was programming in C in a very large project. It was 1988. Many programmers organizing modules and libraries, with the difficulty of avoiding interference in other jobs and keeping a good segregation of duties.

We came to a "solution" that was to put all interrelated global data into structs, placing in those struct some function pointers where callbacks were required. We generalized in that way what we called io_mask (sort of textual mode dialog boxes) and graphic_manager etc. etc.

In 1996 It was very easy to discover that those structs were named "classes" and those function pointers replaced by member function and virtual functions, or with links to other objects (called behaviors) by other programmers who renewed that old project.

I started to understand OOP when I started to feel the need for it: segregation, polymorphism, and runtime defined behaviors.

Today I work with OOP, but I don't think of it as a doctrine to serve: just a "common idiom" (set of ...) that let us speak together without the need to provide long explanations and descriptions all the time. In fact, more a "convention" than anything else. After all, all OOP does is -again- "if then goto": it just does it "multilayered". Hence abstraction and idioms over idioms.

Ignore them. Until she doesn't feel the need for them don't even try to explain: she will feel them just as a complicated way to do simple things. And she is right... until what she does is -in fact- simple.

No one will think to "organize a desk" if there're just four things on top. It make sense when the things on top start to interfere each other. That's the time for OOP to come in.

You don't need OOP to work with C++. The entire C++ standard library is not designed in terms of OOP (although it can cooperate with it), and C++ is not Java.

In all my experience the worst C++ teachers and C++ programmers are the ones who come from Java, teaching all their prejudice about everything is not OOP, denaturating a language like C++ that is not (just) for OOP.

Let me suggest a good book for those who want to approach C++: Accelerated C++: it will bring you into C++ idioms without pretending to follow a predefined doctrine.


问:
Dropbox as a Version Control tool
I have some friends telling me that Dropbox can be used as a  version control tool. I have always used SVN or Git. I was looking around Dropbox and couldn't find anything that tells me about is characteristics as Merging, Fork and other characteristics for a complete VCS.

Can someone point me what I'm missing.

答:
As Thomas pointed out, you would lose some features that are relied on heavily in team environments. If your goal is to have a file share that is super-simple, it would work. If your goal is to avoid a real version control system at all costs, it would work.

You could use them together. Have the functionality of version control that utilizes the file sharing (price and privacy, sharing may cost more?) across multiple devices of DropBox. I've never done it, but here is a link:  http://rogerstringer.com/2012/04/16/using-dropbox-as-a-git-repository.

ContentLicense: CC BY-SA 3.0

Title: Dropbox as a Version Control tool


答:
You're not missing anything about Dropbox. It's great for sharing files, and occasionally useful to recover a file that someone has deleted or updated by accident. But it shouldn't ever be relied on as a source control application. Never.

At best, when you're working alone and you want your files available everywhere, it's still not as good as a Git/Mercurial repository, because you can't batch changes and publish them with a single comment (so you can figure out later what you were doing).

What you're missing is BitBucket, where you can have free private Git/Mercurial repositories with up to 5 collaborators. Once you're above that number of developers, you need to think about whether to pay for an IT department or pay for BitBucket's extended service, but by that point you're WAY beyond being able to get away with DropBox.

Setting up your repository is about as complicated as sharing a DropBox folder.

Title: Dropbox as a Version Control tool

Body:
I have some friends telling me that Dropbox can be used as a  version control tool. I have always used SVN or Git. I was looking around Dropbox and couldn't find anything that tells me about is characteristics as Merging, Fork and other characteristics for a complete VCS.

Can someone point me what I'm missing.


问:
How does Google store search trends in backend?
Google trends shows what query has been searched how many times and some other properties of the said query. But how is this data stored in a database?

Storing a new row for every search does not seem right. They also tell the query on a time graph, so they must have some way to look for individual searches made by users, but the number of queries they get every day, it does not feel right that they would store every search in a database row along with a time-stamp.

This does not apply to just Google trends or Google in general but any other big site that gets awful number of queries and then has tools to see them in depth. I am not an expert on this but I am interested to know some high level structure of how things work behind the scenes.

答:
To be able to do the time graph they would need to store each search, or at least the timestamps linked to the search entry.  This is likely stored in a distributed sharded database.  There are different approaches to how the data could be shared, but that is likely a trade secret along with much of their search engine design.

From their terms of service and the delay in finalizing ad revenues, it appears they do much the same thing every time they display an ad.

EDIT: By sharding the data by query (storing all data for a particular set of queries on one datastore, and those for other queries on different datastores) it is quite easy to scale.  Each datastore can have a reasonable size, and can be queried and update quickly.  Part of the trick is how to decide which data store gets what queries.  This can be adjusted over time.  In this case if you loose a datastore, you only loose a vertical slice (set of queries in this case) of data, not the whole database.

Data may be stored in a traditional relational model, in which case the primary key index of the query event table would provide the timestamp for the queries.  Depending on their needs it might be possible to use one of the newer noSQL databases, or another non-relational store.


问:
Forking an open source project using Git
There is an open source project that I want to fork for my own reasons. It currently has a Git mirror of its main SVN repository which I can use.

What are the best techniques for forking a project whilst still maintaining the ability to merge future changes from the original project into your own forked repository using Git?

Please note I will not be using Github at all for development so using any features from that is out of the question. The project will be hosted on a private VPS.

答:
Your fork is simply a branch which will be never re-merged into the main trunk. I guess the maintainers of the project don't know about your branch and will never pay any attention to the changes you made to the original code base. So if you change parts of the original code where the maintainers apply also apply changes in the future, expect getting merge collisions. This may be acceptable or not, depending of the frequency of "pulls" from the original code base, and the nature and size of your changes.

Best approach to deal with this is IMHO to keep those changes as small as possible - for example, put most of your code into different files. This will make the chances of merge collisions smaller whenever you "pull" future changes into your branch.


问:
How to structure an application that combines WCF and WPF
I'm in the process of learning how to use WCF (Windows Communication Foundation) to allow a client/server desktop application to communicate. The application's UI will be implemented using WPF, and we will probably use SQL Server for our database.

What I'm struggling with, is understanding how to structure such an application.

From what I've read, there are three components of a WCF application (which in the examples I've seen have existed as separate projects):

A WCF service

A WCF service host

A WCF service client

My question then, is - should these projects solely implement the functionality of sending/receiving data from the client/server? Would it make better sense this way?

Would it make sense to create a separate WPF (Windows Presentation Foundation) project to implement the UI for the application?

And so, when I need to send/receive data from the client/server, I could simply invoke the operations provided in the WCF projects that I have created?

For anyone who has built similar applications previously, perhaps you could explain what worked best for you in terms of structuring your application?

For example, if I create a user registration page. When the user clicks the 'Register' button, the client application will need to send the data to the server. In this case, could I just invoke the methods provided in the WCF projects to send the data?

Also, what data structures worked best for you when sending/receiving data? My initial thought is sending/receiving XML containing the data. Is this an option that is easy to implement?

I realise that answers to this question may well be a matter of opinion - unless there are specific best practices that I'm not aware of.

Thank you

答:
Your server solution should contain:

The database layer.

The WCF server.

Your client solution should contain:

The WPF UI.

The WCF client.

Anything else it needs.

Each of these would be a separate project within the single solution. The WPF UI would be the main application with all the other projects defining assemblies. The WPF would then call the WCF client to request data from the server and send data back to the server. It might also listen to events raised from the WCF client.

However, this is just a theoretical structure. You might find that you have to tweak things when you come to implement it.


答:
I would explain it in two steps, or maybe four, depending on how much you like to split your concepts.

Step 1: Introduce her to structures.  It's a fairly small step from Fortran data types
to structures.  Step 1a: make sure she understandard dynamic memory allocation and pointers.

Step 2: add procedures associated only with those structures.  Step 2a: add inheritance based on building larger structures which "wrap" smaller structures.

To a Fortran programmer, the "wow" factor will be that it's a lot for the compiler
to keep track of.  Yup.  That's what compilers are for...

Title: How can I explain object-oriented programming to someone who's only coded in Fortran 77?

Body:
My mother did her college thesis in Fortran, and now (over a decade later) needs to learn c++ for fluids simulations. She is able to understand all of the procedural programming, but no matter how hard I try to explain objects to her, it doesn't stick. (I do a lot of work with Java, so I know how objects work) I think I might be explaining it in too high-level ways, so it isn't really making sense to someone who's never worked with them at all and grew up in the age of purely procedural programming.

Is there any simple way I can explain them to her that will help her understand?


问:
Do stored procedures violate three-tier separation?
Some colleagues of mine have told me that having business logic in stored procedures in the database violates the three-tier separation architecture, since the database belongs to the data layer whereas stored procedures are business logic.

I think the world would be a very grim place without stored procedures.

Do they really violate the three-tier separation ?

答:
Stored procedures are powerful enough to let you code a violation of three-tier separation by bringing business logic into the RDBMS layer. However, this is your decision, not an inherent flaw of stored procedures. You can limit your SPs to servicing the needs of your data layer, while keeping your application logic in the application layer of your architecture.

There is a rare but important exception to the rule of separation, when you need stored procedures (specifically, a group of triggers) to contain business logic. This happens when your application needs to produce a lot of on-the-fly data aggregations that touch millions of rows. In cases like that, triggers can be set up to maintain pre-aggregated data for use of the business layer. This should be done only in situations when without pre-aggregation your application would be unacceptably slow.


问:
Audiobooks for programmers?
I'm a programmer with a two-hour round trip commute to work each day.  I'd like to fill some of that time with audiobooks about software development.  Any audiobooks that would help me become a better programmer would be appreciated.  I'm thinking that books about design patterns and non-fiction about computing history might be good here, but I'm open to anything.

Keeping in mind that I will be listening to this in a car, what are the best audiobooks that I can listen to?

EDIT:  Many people have also suggested podcasts.  This is appreciated, but since podcasts arrive in a constantly arriving stream of data rather than as a finite amount of data, ways to juggle all of these different content streams would also be appreciated.

To be more specific to my situation, my commuting vehicle has an MP3 CD player, USB input for MP3 files, and AUX input.  I own Android and webOS devices that can be plugged into the AUX input.

答:
For all developers

Kevin Mitnick - The Art of Deception

Kevin Mitnick - Ghost in the Wires

Richard Dawkins - The Magic of Reality

Stephen Hawking - The Grand Design

Jonah Lehrer - How We Decide

For OSX/iOS developers

Walter Isaacson - Steve Jobs

Title: Audiobooks for programmers?


答:
I'll go against the trend and argue that it can prove useful in certain cases.

While I fully agree that Dropbox is in no way a substitute for a proper VCS, it can come in handy when it comes to sharing binary files with others on the team.

The most obvious case is images. The guys whose task is to come up with several different designs for, say, a button on a webapp, will want to share a few psd files, which will then be reviewed by the one who's going to make the call.

Now, while committing assets such as images to source control is definitely worthwhile, throwing in all the intermediate versions isn't going to buy you anything, all the while making your repository bloated (which is especially true if you're using a DVCS). Nevertheless, Dropbox having some sort of rudimentary source control capability, you can still see the history of a file.

So yeah, I think that Dropbox (or Google Drive or whatever) can find its place in a team.

Title: Dropbox as a Version Control tool


答:
Tell her to think of objects like objects in the real world. For example the whole world can be a mix of object oriented programming(in C++) with some sort of functional programming(probably done in god's language, Lisp).

Take an object, for example the lawn mower, it has a certain attributes, and it can do a certain thing. (object and class)

Then tell her about a better lawn mower which is an extension of the lawn mower you already have. Tell her its better but still builds on the same mechanism(inheritance).

Then tell her about yourself. Tell her you can sometimes become a lawn mowing expert but you're actually a programmer and do it for a living. This is like you acting as two different entities at the same time. This is polymorphism.

By the time she gets this, tell her about how to implement these things in the language she has to learn(C++).

Then tell her, if she has to write a simulation of this world in the computer world, she will have to learn how to do it.

When she knows how to convert her thoughts of real world into program code. she would have learnt how to program in object oriented programming language.

OwnerDisplayName: Prototype Stark


问:
How can I distribute a unique database already in production?
Let's assume a successful web Spring application running on a MySQL or PostgreSQL database. The traffic is becoming so high and the amount of data is becoming so big that a distributed database solution needs to be implemented to address scalability issue. Let's also assume this application is using Hibernate and the data access layer is cleanly separated with DAOs.

Ideally, one should be able to add or remove databases easily. A failback solution is welcome too.

What would be the best strategy to scale this database? Is it possible to minimize sharding code (Shard) in the application?

答:
Firstly, I'd look at whether there was write-intensive data that could be moved out of the relational database altogether. In a system I currently work on, we have identified quite a lot of pointless write load from writes to tables which record user activity; we use that data for analytics and user support, so it doesn't really need to be in the main OLTPish database; it could be in a flat file, a NoSQL store, etc. I suspect that this is true of quite a lot of user-centric data in many applications - user preferences, profile, history, etc. If it's a structured dataset which is only ever stored and retrieved by key, rather than being searched by value, then it could go in some simpler, cheaper, more write-scalable, store, like Riak or something.

With that done, I'd look at what fraction of the load was reads. If it's at all significant (even 20%), move that to a read-only slave. MySQL and PostgreSQL both make it fairly straightforward to have one or more read-only slaves following a read-write master, and to use them as hot standbys for the master too.

However, splitting reads like this might be tricky; if you're doing things properly, then you will wrap every unit of work in a transaction, even if it's read-only, to guarantee a consistent view of data. Since you can't (AFAIK!) have a single transaction efficiently use two different databases (XA is not efficient), that means you have to be able to identify read-only transactions when they start, so you can send their queries to the read-only database. That will very likely require logic in the application code that isn't currently there, and might not be simple to retrofit. In our case, it was relatively simple: we send transactions from interactive user sessions to the read-write master, and transactions from our read-only REST API to the read-only slave. We could probably do a better job, by identifying read-only user requests, and sending those to the slave as well, but we haven't had to do that yet.

If you're not doing things properly, and are using no transactions, or implicit or explicit transactions around each query, then this is much simpler. A load-balancer between the app and the database can route the queries.

If segregating reads doesn't do the job, then it's time to look at having several machines handling writes. I have never done this, but we are talking about this a lot at my place of work, so I can give you my impressions. There are two ways to split writes: sharding, and multi-master replication of a shared database (I don't really consider sharding to be multi-master, because any item of data belongs to a single master). Neither of these are easy, which is why this is a step of last resort.

Multi-master is simpler from the application's point of view, because it doesn't care which master it talks to, but is less likely to help performance, because any write to one master still has to be applied by the others. It's only useful if the write traffic involves a lot of read work (eg inserts from selects, or you are using transactions and have units of work which do a lot of reading and a small amount of writing - which is not uncommon), and your multi-mastering operates at the row rather than the statement level.

Sharding is more complex. You will inevitably have to change your application code; you might even have to change it a lot. For example, if you split user profile data across multiple shards, you flat out lose the ability to do queries like "find me all the users with a Z in their name", because that crosses multiple shards. You have to do either some sort of map-reduce across the shards, or have a separate index for that field off to one side. You should be able to encapsulate this in your DAOs; where you might not is if some kinds of queries become so slow that you just can't afford to do them any more, and have to find different ways to solve the problems they solve. If your ORM has support for sharding (apparently Hibernate does), then that might help a lot, but it won't fundamentally change the problem.

Just how much of a problem this is will depend very sensitively on your access patterns. For a classic e-commerce system, for example, users make read-only access to catalogue data, which could therefore go in a single-master, many-slave database, and read-write access to their own order data, with no online access across multiple orders, which should shard very nicely. For a crowdsourced e-commerce system (like, famously, Etsy, or eBay), you have some users (shopkeepers) writing to the catalogue while others are reading from it. That makes sharding harder. For a social network application, where users are sharing content with others in a random meshwork, you will end up needing to do huge amounts of cross-shard work. Sadly, where I work, although our application is a financial system, it has many of the data characteristics of a social network; I'm not sure there is a productive way to shard it.

The good news about sharding is that if you can make it work, then it does offer a good shot at a linear speedup. To be honest, though, I suspect that the workloads that allow linear sharding are also the ones that would fit a NoSQL store well, because of that defining characteristic of not depending on cross-shard queries, so if you're going to do the work to do sharding, you might as well go the whole hog and put everything in whatever the hot NoSQL store today is.

Plus, I suspect that for an application of any complexity, the cost of the programmer and sysadmin time to introduce sharding may add up to more than the cost of simply buying some bigger iron.

So, yeah, if you can, don't shard. Stretch your existing model to see if you can get some more performance out of it first.


答:
An old friend claimed I had the shortest definition he knew of OO programming, and I've found that it works for some people (and not for others):

Object-oriented programming is data with an opinion.
You don't move the chair, you ask the chair to move itself. You don't sort the list, you ask it to sort itself (perhaps with a hint). Etc.

The idea is to get the person thinking differently about how things get done inside their program.


问:
Protobuf design patterns
I am evaluating Google Protocol Buffers for a Java based service (but am expecting language agnostic patterns). I have two questions:

The first is a broad general question:

What patterns are we seeing people use? Said patterns being related to class organization (e.g., messages per .proto file, packaging, and distribution) and message definition (e.g., repeated fields vs. repeated encapsulated fields*) etc.

There is very little information of this sort on the Google Protobuf Help pages and public blogs while there is a ton of information for established protocols such as XML.

I also have specific questions over the following two different patterns:

Represent messages in .proto files, package them as a separate jar, and ship it to target consumers of the service --which is basically the default approach I guess.

Do the same but also include hand crafted wrappers (not sub-classes!) around each message that implement a contract supporting at least these two methods (T is the wrapper class, V is the message class (using generics but simplified syntax for brevity):

```<code>public V toProtobufMessage() {
    V.Builder builder = V.newBuilder();
    for (Item item : getItemList()) {
        builder.addItem(item);
    }
    return builder.setAmountPayable(getAmountPayable()).
                   setShippingAddress(getShippingAddress()).
                   build();
}

public static T fromProtobufMessage(V message_) {
    return new T(message_.getShippingAddress(),
                 message_.getItemList(),
                 message_.getAmountPayable());
}
</code>```

One advantage I see with (2) is that I can hide away the complexities introduced by V.newBuilder().addField().build() and add some meaningful methods such as isOpenForTrade() or isAddressInFreeDeliveryZone() etc. in my wrappers. The second advantage I see with (2) is that my clients deal with immutable objects (something I can enforce in the wrapper class).

One disadvantage I see with (2) is that I duplicate code and have to sync up my wrapper classes with .proto files.

Does anyone have better techniques or further critiques on any of the two approaches?

*By encapsulating a repeated field I mean messages such as this one:

```<code>message ItemList {
    repeated item = 1;
}

message CustomerInvoice {
    required ShippingAddress address = 1;
    required ItemList = 2;
    required double amountPayable = 3;
}
</code>```

instead of messages such as this one:

```<code>message CustomerInvoice {
    required ShippingAddress address = 1;
    repeated Item item = 2;
    required double amountPayable = 3;
}
</code>```

I like the latter but am happy to hear arguments against it.

答:
Where I work, the decision was taken to conceal the use of protobuf. We don't distribute the .proto files between applications, but rather, any application that exposes a protobuf interface exports a client library which can talk to it.

I have only worked on one of these protobuf-exposing applications, but in that, each protobuf message corresponds to some concept in the domain. For each concept, there is a normal Java interface. There is then a converter class, which can take an instance of an implementation and construct an appropriate message object, and take a message object and construct an instance of an implementation of the interface (as it happens, usually a simple anonymous or local class defined inside the converter). The protobuf-generated message classes and converters together form a library which is used by both the application and the client library; the client library adds a small amount of code for setting up connections and sending and receiving messages.

Client applications then import the client library, and provide implementations of any interfaces they wish to send. Indeed, both sides do the latter thing.

To clarify, that means that if you have a request-response cycle where the client is sending a party invitation, and the server is responding with an RSVP, then the things involved are:

PartyInvitation message, written in the .proto file

PartyInvitationMessage class, generated by protoc

PartyInvitation interface, defined in the shared library

ActualPartyInvitation, a concrete implementation of PartyInvitation defined by the client app (not actually called that!)

StubPartyInvitation, a simple implementation of PartyInvitation defined by the shared library

PartyInvitationConverter, which can convert a PartyInvitation to a PartyInvitationMessage, and a PartyInvitationMessage to a StubPartyInvitation

RSVP message, written in the .proto file

RSVPMessage class, generated by protoc

RSVP interface, defined in the shared library

ActualRSVP, a concrete implementation of RSVP defined by the server app (also not actually called that!)

StubRSVP, a simple implementation of RSVP defined by the shared library

RSVPConverter, which can convert an RSVP to an RSVPMessage, and an RSVPMessage to a StubRSVP

The reason we have separate actual and stub implementations is that the actual implementations are generally JPA-mapped entity classes; the server either creates and persists them, or queries them up from the database, then hands them off to the protobuf layer to be transmitted. It wasn't felt that it was appropriate to be creating instances of those classes on the receiving side of the connection, because they wouldn't be tied to a persistence context. Furthermore, the entities often contain rather more data than is transmitted over the wire, so it wouldn't even be possible to create intact objects on the receiving side. I am not entirely convinced that this was the right move, because it has left us with one more class per message than we would otherwise have.

Indeed, I am not entirely convinced that using protobuf at all was a good idea; if we'd stuck with plain old RMI and serialization, we wouldn't have had to create nearly as many objects. In many cases, we could just have marked our entity classes as serializable and got on with it.

Now, having said all that, I have a friend who works at Google, on a codebase that makes heavy use of protobuf for communication between modules. They take a completely different approach: they don't wrap the generated message classes at all, and enthusiastically pass them deep(ish) into their code. This is seen as a good thing, because it's a simple of way of keeping interfaces flexible. There is no scaffolding code to keep in sync when messages evolve, and the generated classes provide all the necessary hasFoo() methods needed for receiving code to detect the presence or absence of fields that have been added over time. Bear in mind, though, that people who work at Google tend to be (a) rather clever and (b) a bit nuts.

Title: Protobuf design patterns


答: Keeping the original project in a branch called upstream or vendor (which I prefer) helps to separate your changes from the changes to the original. I also write the reasons for the fork to the README.md, or even create FORK.md for that reason. Storing that information especially helps if the changes compared to the original are small (and won't get integrated upstream).

Title: Forking an open source project using Git

Body:
There is an open source project that I want to fork for my own reasons. It currently has a Git mirror of its main SVN repository which I can use.

What are the best techniques for forking a project whilst still maintaining the ability to merge future changes from the original project into your own forked repository using Git?

Please note I will not be using Github at all for development so using any features from that is out of the question. The project will be hosted on a private VPS.


答:
If she did her thesis a decade ago, she probably used Fortan 90 or 95, in which case the thing to is talk about it in relationship to derived data types.  If it was long enough ago that she used Fortran 77, then introduce her to derived data types in Fortran 90 and then talk about it...

I wouldn't go into polymorphism and inheritance, until after she has grasped encapsulation, as they can be viewed as special cases and extensions of encapsulation. I would probably start her on a language that either allows free functions or static classes.


答:
It can be technically used as version control, similar to making a tar.gz/zip file after every change can be used as version control.  Which is probably not the best method to go about doing things, even if you include a changelog with every change and zipfile.

It won't include support for things like comparing and diff'ing two different versions, merging different versions, having multiple concurrent branches that you can work on with a simple "git branch" to choose between them, and a list of other features that I am not immediately thinking of.  I've done the "zipfile at the end of every feature change" method before and it's clearly better than nothing, but personally I recommend using a proper tool for the job.

Title: Dropbox as a Version Control tool


答:
Brief Summary: It really depends on your usage of stored procedures and business requirements.

There are a number of projects that do use a three-tier architecture and depending on the nature of business requirements there might be need to shift some operations to a data tier.

Speaking about terminology, in general words these tiers described as:

The presentation tier, or user services layer - gives a user access to the application.

The middle tier, or business services layer - consists of business and data rules.

The data tier, or data services layer - interacts with persistent data usually stored in a database or in permanent storage.

Usually for the given architecture, the middle tier or business services layer, consists of business and data rules. However, sometimes it makes big difference to shift heavy set base operations and/or data rules to be done in data tier - through set of stored procedures.

The benefits of three-tier designs are:

During an application's life cycle, the three-tier approach provides benefits such as reusability, flexibility, manageability, maintainability, and scalability. You can share and reuse the components and services you create, and you can distribute them across a network of computers as needed. You can divide large and complex projects into simpler projects and assign them to different programmers or programming teams. You can also deploy components and services on a server to help keep up with changes, and you can redeploy them as growth of the application's user base, data, and transaction volume increases.

Thus, it is really a case-base approach which has trade-offs in itself. However, Microsoft design guidelines of Three-Tier Architecture Model recommends to keep your business logic in middle-tier.

Title: Do stored procedures violate three-tier separation?

Body:
Some colleagues of mine have told me that having business logic in stored procedures in the database violates the three-tier separation architecture, since the database belongs to the data layer whereas stored procedures are business logic.

I think the world would be a very grim place without stored procedures.

Do they really violate the three-tier separation ?


问:
Distinguishing repetitive code with the same implementation
Given this  sample code

```<code>import java.util.ArrayList;
import blackjack.model.items.Card;

public class BlackJackPlayer extends Player {

    private double bet;

    private Hand hand01 = new Hand();
    private Hand hand02 = new Hand();

    public void addCardToHand01(Card c) {
        hand01.addCard(c);
    }

    public void addCardToHand02(Card c) {
        hand02.addCard(c);
    }

    public void bustHand01() {
        hand01.setBust(true);
    }

    public void bustHand02() {
        hand02.setBust(true);
    }

    public void standHand01() {
        hand01.setStand(true);
    }

    public void standHand02() {
        hand02.setStand(true);
    }

    public boolean isHand01Bust() {
        return hand01.isBust();
    }

    public boolean isHand02Bust() {
        return hand02.isBust();
    }

    public boolean isHand01Standing() {
        return hand01.isStanding();
    }

    public boolean isHand02Standing() {
        return hand02.isStanding();
    }

    public int  getHand01Score(){ return hand01.getCardScore(); }

    public int  getHand02Score(){ return hand02.getCardScore(); }

}
</code>```

Is this considered as a repetitive code? providing that each method is operating a seperate field but doing the same implementation ? Note that hand01 and hand02 should be distinct.

if this is considered as repetitive code, how would I address this? providing that each hand is a seperate entity

答:
Your mixing the game code with the player class. You should have a class for the player and one for the game(BlackJack). You need to start with something like this:

```<code>public class Player
{
    private double bet;
    private string name;

    public Hand hand = new Hand();

    public Player(string name)
    {
         this.name = name'
    }

    public Hand getHand(){
        return hand;
    }

}

public class BlackJack
{
     private List<Player> players = new ArrayList<Player>(); ;

     public BlackJack(Player player1, Player player2)
     {
         players.add(player1);
         players.add(player2);
     }

     public void bustHand(int playerNum) throws IndexOutOfBoundsException
     {
         players.get(playerNum).getHand().setBust(true);
     }

}
</code>```

I am coding on the spot so it will not working 100% but should give you an idea

Body:
Your mixing the game code with the player class. You should have a class for the player and one for the game(BlackJack). You need to start with something like this:

public class Player
{
    private double bet;
    private string name;

    public Hand hand = new Hand();

    public Player(string name)
    {
         this.name = name'
    }

    public Hand getHand(){
        return hand;
    }

}

public class BlackJack
{
     private List<Player> players = new ArrayList<Player>(); ;

     public BlackJack(Player player1, Player player2)
     {
         players.add(player1);
         players.add(player2);
     }

     public void bustHand(int playerNum) throws IndexOutOfBoundsException
     {
         players.get(playerNum).getHand().setBust(true);
     }

}

I am coding on the spot so it will not working 100% but should give you an idea


问:
Is a simple iPhone app more appealing to users than a mobile website?
My client wants to do an iPhone app because she's found that people are significantly more likely to use the iPhone app over a mobile optimized site. The iPhone app is very simple - it just displays a couple images and some text. As a programmer I'd much rather do a mobile site given the simple nature of the content. From a technical perspective I feel that it's overkill to use an iPhone app in this situation.

Does it make sense to build an iPhone app when a mobile site would suffice, simply because your users would much rather it be an iPhone app? Is there anyway to easily convince users that a mobile site is just as easy to use?

答:
The simple answer is to develop a website but build it as a mobile web app. If you are more comfortable with building a web site, or feel it will be faster, then this is the way to go.

Users can still 'install' it (create an icon on their home screen, where you specify the png to use for the icon), you hide the Safari toolbar, and it functions just like an app.

Here's the Apple page on creating web apps

The benefits of this are

cross platform - the web app will work on Android, WP, even Blackberry!

you can update content - e.g. text, images without updating the app

cheaper and quicker to develop

I don't know if you can put these type of web apps into the iTunes store or not.


答:
Your colleagues are conflating architecture with implementation.

The idea behind a multi-tiered application is simply that it's broken up into parts that encapsulate certain kinds of processing (storage, business logic, presentation) and communicate with each other using well-defined interfaces.  Just as it's possible to successfully do things that resemble object-oriented programming in non-object-oriented languages, it's possible to do the same with multiple tiers within one environment, such as a database server.  What doing either of those successfully have in common is a need for care, discipline and an understanding of the compromises involved.

Let's look at a three-tiered application where two of the tiers have been implemented on a database:

Data Tier:  Consists of database tables accessed using the four standard table operations (INSERT, UPDATE, DELETE and SELECT).

Logic Tier: Consists of stored procedures that implement only business logic and access the data tier using only the methods outlined above.

Presentation Tier:  Consists of a web server running code that accesses the logic tier by making only stored procedure calls.

This is a perfectly-acceptable model, but it comes with some tradeoffs.  The business logic is implemented in a way that gives it fast, easy access to the data tier and may allow doing things that would have to be done "the hard way" by a logic tier outside the database.  What you give up are the ability to easily move either tier to some other bit of technology and carefree implementation (i.e., you have to be extra careful that the tiers don't use facilities that are available in the database but outside their defined interfaces).

Whether or not this kind of thing and the tradeoffs it brings are acceptable in a given situation is something you and your colleagues have to determine using your judgment.


答:
I feel your pain, many apps should be part of the web, and developed with web technologies.

But that's a technological stance, your client probably doesn't care.

My guess is this kind of client aren't really going for the app as much as they're going for the appstore.

You might be underestimating the visibility the appstores may confer to a client's publication, here.

"Free Advertising!!!1!" might be all your client sees.

Still, they, the client, might be underestimating the actual costs implied. But in their mindscape those new costs will be balanced by the "new" monetization mechanisms appstores allow.

Then they are almost certainly overestimating the actual monetization an appstore can raise for their (editorial, I suppose) product in the current moment. They're not sporting Angry Birds, after all.

Also they're probably delaying their time to market quite a lot, by going for an app solution.

Unfortunately this kind business plan:

Build App

???

PROFIT

Seems to be all the rage nowadays.

Title: Is a simple iPhone app more appealing to users than a mobile website?

Body:
My client wants to do an iPhone app because she's found that people are significantly more likely to use the iPhone app over a mobile optimized site. The iPhone app is very simple - it just displays a couple images and some text. As a programmer I'd much rather do a mobile site given the simple nature of the content. From a technical perspective I feel that it's overkill to use an iPhone app in this situation.

Does it make sense to build an iPhone app when a mobile site would suffice, simply because your users would much rather it be an iPhone app? Is there anyway to easily convince users that a mobile site is just as easy to use?


问:
What should be done with class names that conflict (common) framework names
What should be done exactly when the most obvious class name for a component is taken by a framework? In my case, I need to make a class that describes an HTTP request. Of course, the most common name is "taken" as System.Web.HttpRequest. What should I do? This project will be used in a web context, so I'd really rather not force people to not import the System.Web namespace, or type out all of my class names manually.

What is the usual way of dealing with this? I can come up with this:

Prefix class name with a project shortname

Try to come up with a different name that means the same thing(I've tried and can't come up with anything)

Force users to choose between namespaces

答:
You can use the using alias directive to avoid having to disambiguate everywhere, e.g.

```<code>using HttpRequest = MyCompany.MyProject.HttpRequest;
</code>```

Body:
You can use the using alias directive to avoid having to disambiguate everywhere, e.g.

using HttpRequest = MyCompany.MyProject.HttpRequest;


问:
Use Android NDK for portability with iOS?
I am currently planning to implement a little painting app using OpenGL ES 1.1.  I believe this question applies to any OpenGL ES project.  I am starting development on Android and I would like to know if you would recommend writing the drawing logic (using OpenGL) in C++ with the NDK so it will easier to port to iOS, or to use the Java API and being locked on Android.

The reason I am asking that is because I have seen mixed opinions on the Web about using the NDK (some people say it is an added level of complexity).  From what I have already seen, I believe that I should go with the Java API since I am starting on Android and then, if I decide to go on iOS, to rewrite the OpenGL logic in Objective-C or C++.  This should be pretty straightforward since the calls appear to be the same in both languages.  What do you think?  Am I right?

答:
Yes, NDK will add a layer of complexity. But it will probably be worth it.

If your drawing is done in c++, then you better implement your model in C++ too. That gives you less code to rewrite for iOS and less code to maintain.

Luckily (in this case) OpenGL is state machine, so it is fairly simple to set up the rendering context in java (being close to the GUI code) and then pass control to C++ for the actual OpenGL drawing calls.

Implementing an NDK (JNI) interface is quite repetitive. It might feel ugly to set up your first three classes or so. After that you'll get the hang of it and it is just interface desig and typing code.


答:
Given your problem description I'd go for a mobile site masked as an app.
In general, many mobile apps are just HTML5 sites that may or may not run locally. This can be a great start to quickly develop a multi platform app which will work reasonably OK on many types of mobile devices without having to rework much of the code. Having said this, there is one caveat: HTML5 isn't the king of speed when doing heavy duty stuff. When it is time to do some processing intensive code which isn't available as some piece of middleware for the platform(s) you're developing for, the code can run rather slow if you depend solely on JavaScript to do the processing and you should consider taking it to the next level (Native app).</p>


问:
Does putting types/functions inside namespace make compiler's parsing work easy?
Retaining the names inside namespace will make compiler work less stressful!?

For example:

```<code>// test.cpp
#include</*iostream,vector,string,map*/>
class vec { /* ... */ };
</code>```

Take 2 scenarios of main():

```<code>// scenario-1
using namespace std;  // comment this line for scenario-2
int main ()
{
  vec obj;
}
</code>```

For scenario-1 where using namespace std;, several type names from namespace std will come into global scope. Thus compiler will have to check against vec if any of the type is colliding with it. If it does then generate error.

In scenario-2 where there is no using namespace, compiler just have to check vec with std, because that's the only symbol in global scope.

I am interested to know that, shouldn't it make the compiler little faster ?

答:
It depends on how the compiler is designed.

It can make all symbols represented with their own full-qualified names into a binary-search tree, with a another set of "visibility scope" and a coverage table telling what is visible from where (hence the entire name structures is flattened) or it can somehow cope with your name structures or cope with your code block and scopes.

You can easily understand that the compiler performances differ a lot if the compiler developer did an orthogonal choice respect to the compiler user.

However the purpose of the code (apart the obvious doing what is required to do) is to be readable and maintainable, not to be easily compilable. If you plan to optimize compiling, you are focusing on the wrong side of software development, risking to find yourself in 5 years with a code that compiles fast, but you cannot touch anymore since you are anymore able to understand it.


问:
Should we have a database independent SQL like query language in Django?
Note :

I know we have Django ORM already that keeps things database independent and converts to the database specific SQL queries.

Once things starts getting complicated it is preferred to write raw SQL queries for better efficiency.

When you write raw sql queries your code gets trapped with the database you are using.

I also understand its important to use the full power of your database that can-not be achieved with the django orm alone.

My Question :

Until I use any database specific feature, why should one be trapped with the database.

For instance :

We have a query with multiple joins and we decided to write a raw sql
  query. Now, that makes my website postgres specific. Even when I
  have not used any postgres specific feature.

I feel there should be some fake sql language which can translate to any database's sql query. Even Django's ORM can be built over it. So, that if you go out of ORM but not database specific - you can still remain database independent.

I asked the same question to Jacob Kaplan Moss (In person) :

He advised me to stay with the database that I like and endure its whole power, to which I agree. But my point was not that we should be database independent.

My point is we should be database independent until we use a database specific feature.

Please explain, why should be there a fake sql layer over the actual sql ?

================================

Update:

================================

My suggestion:

Solve the independence of the database on a fake sql level and then build ORM over that fake sql. So, if I have to write a sql query - I will use fake sql that would work on all databases yet raw SQL. That way, I will remain database independent unless I use a feature very specific to my database.

Therefore, a query like select * from table limit 10; will work on both postgres and 'MS-SQL Server'.

Is that sensible ?

Note:

I am not talking about ANSI SQL, I am suggesting a fake sql to make all databases work with 1 standard sql. [ Which may not cover db specific features ]

答:
Python database API use a common convention, that is pretty much the same across different databases (but not quite!). You can read the MySQLdb documentation here.

There is also a more feature-rich interface to mysql, called oursql. It has real parametrization (not just glorified string interpolation), server-side cursors, data streaming and so on.


答:
Just last week I published apps to both Google Play and App Store that were a little more than dedicated browsers (WebView) for a responsive web site and some sugar on top of it.

This gives you:

HTML5-based fast development of majority of the app as web page

Presence in the respective App Store of the device

Users can install the app in regular ways (no complicated instructions to get the icon to home screen)

But you still retain the benefits of native app:

You can always move more code to the native side later

Make use of APIs that are off limits to browser based webpages, e.g

advertise the app as routing app in the new iOS Maps

let the Passbook open the ticket in your app, etc

I'm sure that Android too has multitude of APIs that are forbidden to webapps.

BTW. From my own experience - stay clear of cross-platform frameworks. Even for such a simple task I got my ass bitten by one of those and I ended up rewriting the whole thing in native language.


答:
I think you're looking for the SQL ANSI standard.

This standard is implemented in most RDBMS for the biggest part.

However, every RDBMS decided to do some things their way. (Simply because the standard didn't have the feature or another reason. LIMIT has an equivalent since SQL:2008 only for example.)

Listing these differences from the SQL standard would take a whole webpage to do it. Oh wait, it was done!

So to answer you, for this very reason, you can't be independant from RDBMS without losing performance (i.e. building a layer). The differences in the SQL standard implementations are what brought people to build ORMs.

Title: Should we have a database independent SQL like query language in Django?

Body:
Note :

I know we have Django ORM already that keeps things database independent and converts to the database specific SQL queries.

Once things starts getting complicated it is preferred to write raw SQL queries for better efficiency.

When you write raw sql queries your code gets trapped with the database you are using.

I also understand its important to use the full power of your database that can-not be achieved with the django orm alone.

My Question :

Until I use any database specific feature, why should one be trapped with the database.

For instance :

We have a query with multiple joins and we decided to write a raw sql
  query. Now, that makes my website postgres specific. Even when I
  have not used any postgres specific feature.

I feel there should be some fake sql language which can translate to any database's sql query. Even Django's ORM can be built over it. So, that if you go out of ORM but not database specific - you can still remain database independent.

I asked the same question to Jacob Kaplan Moss (In person) :

He advised me to stay with the database that I like and endure its whole power, to which I agree. But my point was not that we should be database independent.

My point is we should be database independent until we use a database specific feature.

Please explain, why should be there a fake sql layer over the actual sql ?

================================

Update:

================================

My suggestion:

Solve the independence of the database on a fake sql level and then build ORM over that fake sql. So, if I have to write a sql query - I will use fake sql that would work on all databases yet raw SQL. That way, I will remain database independent unless I use a feature very specific to my database.

Therefore, a query like select * from table limit 10; will work on both postgres and 'MS-SQL Server'.

Is that sensible ?

Note:

I am not talking about ANSI SQL, I am suggesting a fake sql to make all databases work with 1 standard sql. [ Which may not cover db specific features ]


问:
Is it a good idea to appoint one of the scrum team member or scrum master as Product Owner?
Lately we had a project, in which client was busy touring. As usual scrum team was formed, management decided to appoint our analyst as Product owner since Client won’t be able to participate actively. Analyst was the one who worked closely with client for requirement analysis and specification drafting.

Client doesn’t have the time to review first two releases. Everything went smoothly until, client saw third release; he wasn’t satisfied with some functionalities, and those was introduced by make shift Product Owner (our analyst).

We were told to wait till design team finished mock-up of all pages and client checked each one and approved to continue working. Scrum team is there, but no sprints – we finished work almost like classic waterfall method.

Is it a good idea to appoint scrum team member or master as product owner? Do we need to follow scrum in the absence of client/product owner participation?

答:
Your process seems fine to me. You did not describe it in details, but a least, roles are respected (this is important).

However, with the few details I have, I can see some problem at the product owner level.

He/she should ensure that the customer is properly notified of the progress. Looks like he is doing "waterfall" externally with the customer and "scrum" internally with you.

Result: waterfall wins since customer is king. Even if in this case, the customer has his responsability...

Your current team (including Scrum Master), should focus on delivering the sprint backlog. However the product owner (analyst) should ensure that what is in his/her backlog reflects what the customer want. She/he should also ensure that the communication is good and that the customer participate.

Possible solution: send your product owner (analyst) to a Scrum Product Owner course, or make him/her read (and understand) this book: Agile Product Management with Scrum.

ContentLicense: CC BY-SA 2.5


问:
Delphi vs C# for GUI programming
I'm coming from PHP and Python background with little knowledge of C, I have done many web based application now I'm thinking of Desktop application for windows platform.

A friend told me to go for Delphi and others are saying C# is the best, well, what I'm looking for is

Simplicity

Productivity

Good API documentation

Speed

Drag and Drop

Multi threading & Good Network API

Thanks

答:
Both have all 6 points you want but I feel C# has the edge on most if not all.

To go through the points:

Delphi requires memory management, so you could argue that alone makes C# simpler. Accepted answer mentions syntax here, well C# syntax is similar to both PHP and Java, so if you want to get up and running quicker from either of those backgrounds, then C# has the edge.

Productivity, I think you get more done quicker in C#. The .net library gives you so much that in the bad old days, I'd have to look to 3rd party delphi components to provide.

Documentation, Delphi's was always good, MSDN is better, plus you will find a larger community for support, see my Stack Overflow anaylsis below.

Speed, Delphi might have the edge on this, but assembly trumps all so that's not usually a good reason to pick a language. One thing I would point out is that I've heard people cite that C# is interpretted. It is not, it never has been, it has always had a JIT.

Drag and drop, available on both.

Multithreading, Delphi is good but C# is excellent with build in constructs like lock(){} parallel extensions, and the new await.

Extra point, the question title is GUI programming, for this I am a big fan of .nets WPF, which, the only thing Delphi had that was half way close was Bold, which was a pain to tame and now dead.

Community size, comparing the number of questions on this and Stack Overflow on both the Delphi and C# tags you will see that the size of the C# community is much larger.

Stack Overflow:

Delphi 17K

C# 367K

Java 312K

c 73K

I've added c, to show that's not a problem with the languages age and Java just for comparison.

I'm not a C# or Java fan boy, I was a big Delphi fan, professional pure Delphi developer for 7 years, but they really screwed it up from 2005 onwards with thier ill faited foray into .net which screwed up the stability of the IDE for even native 32 bit compilation. Delphi 7 was peak of the language in my view.

Title: Delphi vs C# for GUI programming


问:
Library Organization in .NET
I've written a .NET bitwise operations library as part of my projects (stuff ranging from get MSB set to some more complicated bitwise transformations) and I mean to release it as free software. I'm a bit confused about a design aspect of the library, though.

Many of the methods/transformations in the library come with different endianness. A simple example is a getBitAt method that regards index 0 as the least significant bit, or the most significant bit, depending on the version used.

In practice, I've found that using separate functions for different endianness results in much more comprehensible and reusable code than assuming all operations are little-endian or something.

I'm really stumped regarding how best to package the library.

Should I have methods that have LE and BE versions take an enum
parameter in their signature, e.g. Endianness.Little,
Endianness.Big?

Should I have different static classes with
identically named methods? such as MSB.GetBit and LSB.GetBit

On a much wider note, is there a standard I could use in cases like this? Some guide? Is my design issue trivial? I have a perfectionist bent, and I sometimes get stuck on tricky design issues like this...

Note: I've sort of realized I'm using endianness somewhat colloquially to refer to the order/place value of digital component parts (be they bits, bytes, or words) in a larger whole, in any setting. I'm not talking about machine-level endianness or serial transmission endianness. Just about place-value semantics in general. So there isn't a context of targeting different machines/transmission techniques or something.

答:
As in most instances of the design problem, the solution should be based on intended usage and context, instead of any alleged absolute.

You need to establish your requirements. What do you use the library for? What is your target audience for this library?

If the intended usage is to mix little-endian logic together with big-endian logic, then it's beneficial to add an extra argument for each method, such as Endianness.Little, just like you suggested.
I wouldn't suggest a clone for each method, as that would grow rather quickly, and with today's IDEs and auto-completion it would be a visual disturbance, and also would have a (probably negligible) impact on compile time.

However, if you intend to use the library for different platforms, but on each one pick one scheme, then you're probably better off with passing an Endianness strategy to the constructor of a class that has higher level methods.

If you want to get the best of both worlds, at the expense of simplicity, you can pass a strategy in a constructor, and accept an optional strategy in each method, which defaults to the one provided in the constructor.

Title: Library Organization in .NET


答:
The YAGNI principle is important in this case.

When deciding on the topic, you should consider the advantages and disadvantages of being tied to a specific database.

It's not like there are 1000s of different databases out there. For relational databases, popular choices are Postgres and Mysql. And their differences and distinct characteristics are well known, so it's easy to compare them beforehand for the problem you are going to solve.

If you are in control of the production environment, study the differences between them and choose one.

If you are not in the control of the production environment, like if you are going to distribute the software to end users, and they will install them on their own platforms, then you should aim for the database independence.

Unless you really have a compelling reason to be database independent, it will be a hassle and bite you in the long term if you aim to do so. General advice for this kind of situations is don't do things just for the sake of doing it.


问:
Why JSP over Servlets for view?
Although servlets does the task of sending the HTML code to the client programmers weight JSP over servlets for that. Even a JSP code is compiled into servlet before giving the response to the browser then why is JSP preferred? If servlet is used then a lot of computation work can be saved.</p>

答:
why do programmers weight JSP over servlets for that?

You can look at JSP as just another more friendly syntax for writing servlets. So, it's not so much a choice between JSP and servlets: the choice is between writing servlets in JSP syntax and writing them in raw Java. As to why would someone prefer the first over the latter, for many (not all) situations raw Java syntax is very inconvenient since:

entire page is inside the out.println() calls

usually means lots of markup within strings

for non trivial pages this is insanely difficult to read not to mention debug

the increased development cost is much much greater than the lowered performance cost (which isn't lowered at all, see the next point)

If servlet is used then a lot of computation work can be saved.

No, not really. Well, only computation at deploy time, when servlets are generated from the JSPs, but during run time it's the same (assuming you disable the option to generate servlets in every request).

Title: Why JSP over Servlets for view?


答:
I agree Yam that it depends on your usage of the library. Another interesting arrangement, if you're not going for insane levels of performance could be to create a class that holds both answers. GetBit will then return an instance of this class, with two properties presenting the results.

```<code>public class BitWiseResult
{
  public <type-goes-here> MSB { get; set; }
  public <type-goes-here> LSB { get; set; }
}

public BitWiseResult GetBit() ...
</code>```

This arrangement will be best used if you need to use both results interchangeably. It has the advantage of giving you the right result in the exact place where you need it, as opposed to changing a possibly distant function call or class instantiation.

Title: Library Organization in .NET

Body:
I've written a .NET bitwise operations library as part of my projects (stuff ranging from get MSB set to some more complicated bitwise transformations) and I mean to release it as free software. I'm a bit confused about a design aspect of the library, though.

Many of the methods/transformations in the library come with different endianness. A simple example is a getBitAt method that regards index 0 as the least significant bit, or the most significant bit, depending on the version used.

In practice, I've found that using separate functions for different endianness results in much more comprehensible and reusable code than assuming all operations are little-endian or something.

I'm really stumped regarding how best to package the library.

Should I have methods that have LE and BE versions take an enum
parameter in their signature, e.g. Endianness.Little,
Endianness.Big?

Should I have different static classes with
identically named methods? such as MSB.GetBit and LSB.GetBit

On a much wider note, is there a standard I could use in cases like this? Some guide? Is my design issue trivial? I have a perfectionist bent, and I sometimes get stuck on tricky design issues like this...

Note: I've sort of realized I'm using endianness somewhat colloquially to refer to the order/place value of digital component parts (be they bits, bytes, or words) in a larger whole, in any setting. I'm not talking about machine-level endianness or serial transmission endianness. Just about place-value semantics in general. So there isn't a context of targeting different machines/transmission techniques or something.

Body:
I agree Yam that it depends on your usage of the library. Another interesting arrangement, if you're not going for insane levels of performance could be to create a class that holds both answers. GetBit will then return an instance of this class, with two properties presenting the results.

public class BitWiseResult
{
  public <type-goes-here> MSB { get; set; }
  public <type-goes-here> LSB { get; set; }
}

public BitWiseResult GetBit() ...

This arrangement will be best used if you need to use both results interchangeably. It has the advantage of giving you the right result in the exact place where you need it, as opposed to changing a possibly distant function call or class instantiation.


答:
If the webpage is really that simple, you shouldn't make it into an app.
I can give you one reason, but it's a very good one:

Simple applications usually don't pass through appstore reviewers.

From https://developer.apple.com/appstore/resources/approval/guidelines.html

2.12 Apps that are not very useful, unique, are simply web sites bundled as Apps, or do not provide any lasting entertainment value may be rejected

If you try to upload such an app, you will probably get a rejection stating "the app does not use native iOS functions" or something similar.

If you want to create a simple iOS app, you have to think what functionality will be added against a web page.


答:
Just because a JSP is compiled into a servlet doesn't mean there is no difference between these two. Actually, there might be someone out there who wrote a JSP interpreter that doesn't translate a JSP into a servlet but performs any other kind of execution.

Think about the concept of servlets and JSP and compare these concepts against each other - not the actual implementations.

Title: Why JSP over Servlets for view?

Body: Although servlets does the task of sending the HTML code to the client programmers weight JSP over servlets for that. Even a JSP code is compiled into servlet before giving the response to the browser then why is JSP preferred? If servlet is used then a lot of computation work can be saved.</p>


答:
In General, it would be harder to code complex Java code and put it inside a JSP, next is, It would be a really really messy code if you are going to combine complex java code inside a JSP.

Just my two cents.

Title: Why JSP over Servlets for view?


答:
Admittedly, I have a personal bias toward native apps, but I think there's really no black-and-white answer to this. Here are a couple thoughts on web apps vs. native apps:

Web apps are nice if you want to avoid the hassle of becoming a member of the Apple Developer Program. Without this, you cannot install apps on devices or publish them to the App Store.

Then, of course, there's the effort of learning XCode and Objective-C (if you don't already know them).

On the other hand, native apps tend to be more responsive (my own subjective experience).

If the app must be able to run "offline" (when no Internet connection is available), then a native app is really your only realistic option.

In your case, I'd weigh your client's requirements against the pros-and-cons of web and native apps.

I'd also add that writing and deploying a native iPhone App doesn't NECESSARILY require a presence in the App Store. So-called "In-House Apps" can be written and deployed in an enterprise setting. Consider this: http://help.apple.com/iosdeployment-apps/mac/1.1/#app43ad6a6a


问:
Debug multiprocessing in Python
What are some good practices in debugging multiprocessing programs in Python?</p>

答:
One thing that I find very helpful, is to use the existing logger in the multiprocessing module. Try this in your main code:

```<code>import multiprocessing, logging
mpl = multiprocessing.log_to_stderr()
mpl.setLevel(logging.INFO)
</code>```

See also: http://docs.python.org/library/multiprocessing.html#logging

Additionally, you can access the current process name using:

```<code>cpname = multiprocessing.current_process().name
# print cpname
mylogger.info("{0} is currently doing...".format(cpname))
</code>```

See: http://docs.python.org/library/multiprocessing.html#multiprocessing.current_process

Apart from that I don't know of anything else except the standard debugging methods like pdb & co.

Title: Debug multiprocessing in Python

Body:
One thing that I find very helpful, is to use the existing logger in the multiprocessing module. Try this in your main code:

import multiprocessing, logging
mpl = multiprocessing.log_to_stderr()
mpl.setLevel(logging.INFO)

See also: http://docs.python.org/library/multiprocessing.html#logging

Additionally, you can access the current process name using:

cpname = multiprocessing.current_process().name
# print cpname
mylogger.info("{0} is currently doing...".format(cpname))

See: http://docs.python.org/library/multiprocessing.html#multiprocessing.current_process

Apart from that I don't know of anything else except the standard debugging methods like pdb & co.


问:
How to handle multi-processing of libraries which already spawn sub-processes?
I am having some trouble coming up with a good solution to limit sub-processes in a script which uses a multi-processed library and the script itself is also multi-processed.

Both, the library and script are modifiable by us.

I believe the question is more about design than actual code, but for what it's worth, it's written in Python.

The goal of the library is to hide implementation details of various internet routers. For that reason, the library has a "Proxy" factory method which takes the IP of a router as parameter. The factory then probes the device using a set of possible proxies. Usually, there is one proxy which immediately knows that is is able to send commands to this device. All others usually take some time to return (given a timeout).

One thought was already to simply query the device for an identifier, and then select the proper proxy using that, but in order to do so, you would already need to know how to query the device. Abstracting this knowledge is one of the main purposes of the library, so that becomes a little bit of a "circular-requirement"/deadlock: To connect to a device, you need to know what proxy to use, and to know what proxy to create, you need to connect to a device.

So probing the device is - as we can see - the best solution so far, apart from keeping a lookup-table somewhere.

The library currently kills all remaining processes once a valid proxy has been found. And yes, there is always only one good proxy per device.

Currently there are about 12 proxies. So if one create a proxy instance using the factory, 12 sub-processes are spawned.

So far, this has been really useful and worked very well. But recently someone else wanted to use this library to "broadcast" a command to all devices. So he took the library, and wrote his own multi-processed script. This obviously spawned 12 * n processes where n  is the number of IPs to which he broadcasted.

This has given us two problems:

The host on which the command was executed slowed down to a near halt.

Aborting the script with CTRL+C ground the system to a total halt. Not even the hardware console responded anymore! This may be due to some Python strangeness which still needs to be investigated. Maybe related to http://bugs.python.org/issue8296

The big underlying question, is how to design a library which does multi-processing, so other applications which use this library and want to be multi-processed themselves do not run into system limitations.

My first thought was to require a pool to be passed to the library, and execute all tasks in that pool. In that way, the person using the library has control over the usage of system resources. But my gut tells me that there must be a better solution.

Disclaimer: My experience with multiprocessing is fairly limited. I have implemented a few straightforward which did not require access control to resources. So I have not yet any practical experience with semaphores or mutexes.

p.s.: In the future, we may have enough information to do this without the probing. But the database which would contain the proper information is not yet operational. Also, the design about multiprocessing a multiprocessed library intrigues me :)

答:
There are many ways to approach this problem; one of them being not to abstract the nature of the problem from its solution. However, let me suggest something else.

Caching

Using your current method, you need to (at least once) probe each proxy for each device. However, it might be the case that you also need at most one; meaning that once you detect a valid proxy, it's not going to change in runtime (and even this is fixable by some additional complexity which checks for this case specifically).

So then, right on startup (or whenever else applicable), you validate all proxies, and cache the results. Then, the broadcast (or any other request for that matter) looks up the proxy in the cache.

Obviously, to overcome the fact that you're exhausting the system, you need to make sure that probing and caching is done in a realistic fashion.


答:
Scrum works best with a real client in place.  There are a couple real challenges in dealing with clients who aren't used to iterative product design.

The blank sheet syndrome

Scared client syndrome

Design stages with a blank sheet tend to go pie in the sky really quickly, and typically go into great depth on a couple side issues and not enough depth on the core functionality needed.  You really need a straw man for the client to pick apart for the design meetings to go successfully.  By focusing on just one aspect at a time, you are helping your client learn iterative design.

Scared clients (like you had with your experience) don't realize that agile projects anticipate a certain (controlled) amount of rework as part of the process.  What they have a hard time grasping is that as the product development moves forward, there will be fewer "Oh my god" moments.  More importantly, the part most clients have a hard time with is that the "Oh my god" moments don't require butt-loads of money to fix because of the short time between review/planning cycles.

Managing client expectations is very difficult.  Its a fine balance of customer education, placating, and even learning to say "no".  The client can't always come weekly or biweekly.  Sometimes they can only come once a month.  That's OK.  As long as you show them what you did to address their concerns the previous month, then focus on this month's work, it will go a long way to making the project go more smoothly.  Bottom line is, in the customer's absence you do have someone who can make reasonable recommendations for some questions.  It does need to be someone familiar with the goals the client is trying to achieve.

Title: Is it a good idea to appoint one of the scrum team member or scrum master as Product Owner?

Body:
Lately we had a project, in which client was busy touring. As usual scrum team was formed, management decided to appoint our analyst as Product owner since Client won’t be able to participate actively. Analyst was the one who worked closely with client for requirement analysis and specification drafting.

Client doesn’t have the time to review first two releases. Everything went smoothly until, client saw third release; he wasn’t satisfied with some functionalities, and those was introduced by make shift Product Owner (our analyst).

We were told to wait till design team finished mock-up of all pages and client checked each one and approved to continue working. Scrum team is there, but no sprints – we finished work almost like classic waterfall method.

Is it a good idea to appoint scrum team member or master as product owner? Do we need to follow scrum in the absence of client/product owner participation?


答:
If your library users will stick with one Endianness in their application I would use an abstract factory.

```<code>// setup
var factory = new LittleEndiannessFactory();

// usage
var algo = factory.CreateSomeAlgo();
</code>```

Else you'll probably want them to specify the endianness in each method call.

Title: Library Organization in .NET

Body:
If your library users will stick with one Endianness in their application I would use an abstract factory.

// setup
var factory = new LittleEndiannessFactory();

// usage
var algo = factory.CreateSomeAlgo();

Else you'll probably want them to specify the endianness in each method call.


问:
Is server validation necessary with client-side validators?
I recently created a .net web app that used over 200 custom validators on one page. I wrote code for both ClientValidationFunction and OnServerValidate which results in a ton of repetitive code.

My sql statements are parameterized, I have functions that pull data from input fields and validates them before passing to the sql statements or stored procedures. And the javascript validates the fields before the page submits. So essentially the data is clean and valid before it even hits the OnServerValidate and clean after it anyways due to the aforementioned steps.

This makes me question, is OnServerValidate really needed when I validate on the clientside?

Edit:

My OnServerValidates do simple things like making sure a skip pattern is enforced or that a short appears in a text (which is enforced anyways with my code that pulls data from text fields into parameters i.e. GetShort()). And these are being place in patient surveys, which most of the time are filled out by staff members.

So it seems like if I didn't have the OnServerValidate for these basic checks and just client side the following situations are:

A user turns off javascript and cannot submit the form, which is
expected as buttons are javascript driven for postbacks.

A user forces a post. Which if this occurs my OnServerValidate
would do jack to stop whatever they are trying to do since it is
just looking at skip patterns, or would it?

Situation 2 is where I am getting lost. It seems like the user forcing a post is more than likely not to be caught by these simple OnServerValidates

答:
You do need them as the client can decide to allow javascript in their browsers. You also should consider those people who want to break your software. There are plenty of tools out there that can manufacture posts and submit them to your website without having used your front end.

Client side validation is nice for the user, but the server should never ever trust data that is sent to it.

--Update--

If I'm reading your edit properly, it sounds like the OnServerValidates are duplicating validation functionality that is already present on the server. Since that's the case, then you shouldn't need the OnServerValidates.

Furthermore, you are correct that if a user manufactures a post to your service, it will not trigger the OnServerValidates so you are better off keeping that type of validation where you have it currently on the server.


问:
How to turn on/off code modules?
I am trying to run multiple sites using single code base and code base consist of the following module (i.e. classes)

User module

Q & A module

Faq module

and each class works on MVC pattern i.e. it consist of

Entity class

Helper class (i.e. static class)

View (i.e. pages and controls)

and let's say I have 2 sites site1.com and site2.com. And I am trying to achieve following functionality

site1.com can have User, Q & A and Faq module up and running

site2.com can have User and Q & A module live while Faq module is switched off but it can be turned-on if needed, so my query here is what is the best way to achieve such functionality

Do I introduce a flag bit that I check on every page and control belonging to that module? It's more like CMS where you can turn on/off different features. I am trying to get my head around it, please provide me with an example or point out if I am taking the wrong approach.

答:
Well. All modules are loaded at all times. There is no way around that (if your application is a web app).

Hence you do have to check a flag wether it's active or not.

If you are using ASP.NET MVC it can be done by using an action filter which you tag each controller with ( + a session variable). something like

```<code>[AuthorizeModule(1)] //<-- 1 = module id
public class MyController : Controller
{
}
</code>```

Title: How to turn on/off code modules?

Body:
Well. All modules are loaded at all times. There is no way around that (if your application is a web app).

Hence you do have to check a flag wether it's active or not.

If you are using ASP.NET MVC it can be done by using an action filter which you tag each controller with ( + a session variable). something like

[AuthorizeModule(1)] //<-- 1 = module id
public class MyController : Controller
{
}


答:
This is actually the reason that frameworks like the Managed Extensibility Framework (MEF) were built.

Using MEF, each optional module resides in its own DLL, and your main program loads the applicable DLLs at runtime.  You only need to include the ones for each particular site.  You can then have a different user module from one site to the next.

Title: How to turn on/off code modules?

Body:
I am trying to run multiple sites using single code base and code base consist of the following module (i.e. classes)

User module

Q & A module

Faq module

and each class works on MVC pattern i.e. it consist of

Entity class

Helper class (i.e. static class)

View (i.e. pages and controls)

and let's say I have 2 sites site1.com and site2.com. And I am trying to achieve following functionality

site1.com can have User, Q & A and Faq module up and running

site2.com can have User and Q & A module live while Faq module is switched off but it can be turned-on if needed, so my query here is what is the best way to achieve such functionality

Do I introduce a flag bit that I check on every page and control belonging to that module? It's more like CMS where you can turn on/off different features. I am trying to get my head around it, please provide me with an example or point out if I am taking the wrong approach.


问:
help for choosing an encryption method for a database column
I'm storing some phone numbers in the database which should kept totally secret (they're supposed to access via web). BTW, because of the position of these people, I need to prevent any chance for leak of their numbers. So, the only solution I could thinking of is Encryption.

As the database could contains bunch of data, I won't encrypt the database entirely. Also, I actually prefer to use different key for each person to encrypt their phone numbers, so in the case of leaking one key, the other phone numbers should be safe at least. The problem is that other people also need to send SMS messages via the application through a web-interface and also some more privileged persons need to see these numbers, so I also need to make these numbers visible to the other privileged persons by the way.

I'm wondering of something like a public-key/private-key structure, but it's too much for just encrypting a phone number per person, and also there would be a problem for new users, because the previous numbers didn't encrypted with their public-keys.

So, is there any solution you might recommend to me? maybe I should to revise or update the structure of how I'm trying to do that, huh?

答:
So, you have a database backing a web application.  The web application (and other side applications) need to have access to a phone number.

I am assuming that you have sufficient security in the web application side to prevent people from getting data they shouldn't have.

Your concern is that if someone with sufficient access (either proper access or ill gotten) looks at the database, you don't want that person to be able to see the phone numbers in the clear.

Public/private is probably overkill and unnecessary.  Someone that has access to the web program doing the insertion and retrieval of the phone number will also be able to do retrieval and decoding.

I would instead look at doing something along the lines of symmetric encryption where there is just one key.  The web app uses it to encrypt before putting in the database and decrypt when it is needed for display.  Other apps would also use the same key.

If the key is compromised, you decrypt all the data and re-encrypt it with a new key.

I would strongly encourage you to consider adding additional 'junk' to the data so that it isn't trivially decoded (if you have 10 characters being encoded and it is known that they are all characters that match [2-9][0-9]{9}, the cryptanalysis of the data could be done rather quickly in the event the data is compromised.


问:
Access functions from user control without events?
On some generic functions, it seems that accessing a function on mainform directly from the usercontrol is easier than raising an event. For example: A function on main form that displays one desired usercontrol centered and tweaked.

Making this function static, or access this function by reference from the user control to its parent, rather then raising an event, seems very convenient. Like this:

```<code>usercontrol_A uc_a = new usercontrol_A();
MainForm mainform_functions = (MainForm)Parent;
mainform_functions.DisplayControl(uc_a);
</code>```

Raising an event seems more complex in such cases - I need to declare all new userControl_B's events (which also includes initiating usercontrol_C and displaying it) inside the event that shows (and initiates) userControl_B:

```<code>  userControl_A.ShowUserControl_B+= (s,e) =>
 {
 usercontrol_B uc_b = new usercontrol_B();   DisplayControl(uc_b);
    uc_b.show_uc_c += (s2,e2) => {usercontrol_C uc_c = new usercontrol_C(); DisplayControl(uc_c); }
 }
</code>```

too much clutter here.

That's hard to code and to read later. (In addition, passing parameters to another usercontrol is a nightmare like this - I need to save the parameter artificially on the sender usercontrol class and then cast it back later inside the event)

What is your opinion? Is it a completely "prohibited" to code like this, at least on generic functions like I mentioned? Isn't clearer code that needs some small tweaking for reuse preferable?

答:
This is why creational patterns exist, often times creation of types can be tricky as you have run into.

I think you want an abstract factory here (caveat: not true if user control A/B/C have basically identical attributes, if they're identical you just need a single method that will create a control with the desired configuration which can be treated as control A, B, or C)

```<code>public interface IControlCreator
{
    Control CreateControl();
}

public class ControlFactory<T> where T : IControlCreator, new
{
    GetControl()
    {
        return (new T()).CreateControl();
    }
}

public ControlACreator : IControlCreator
{
    Control CreateControl()
    {
        Control controlA = new Control();
        DisplayControl(controlA);
        controlA.show_uc_b += (s,e) => new ControlFactory<ControlBCreator>().CreateControl();
    }
}

public ControlBCreator : IControlCreator
{
    Control CreateControl()
    {
        Control controlB = new Control();
        DisplayControl(controlB);
        controlB.show_uc_c += (s,e) => new ControlFactory<ControlCCreator>().CreateControl();
    }
}
</code>```

Then anytime you want a control, it will have the appropriate events tied on in by it's Creator class, all you need to call to get one is new ControlFactory<ControlWhateverCreator>().CreateControl();

Please, someone let me know if I got something wrong here; I've actually never written an abstract factory before. It's a lot of overhead so I tend to avoid facotries, but it seems the right approach based on the problem scope the OP detailed.

Body:
This is why creational patterns exist, often times creation of types can be tricky as you have run into.

I think you want an abstract factory here (caveat: not true if user control A/B/C have basically identical attributes, if they're identical you just need a single method that will create a control with the desired configuration which can be treated as control A, B, or C)

public interface IControlCreator
{
    Control CreateControl();
}

public class ControlFactory<T> where T : IControlCreator, new
{
    GetControl()
    {
        return (new T()).CreateControl();
    }
}

public ControlACreator : IControlCreator
{
    Control CreateControl()
    {
        Control controlA = new Control();
        DisplayControl(controlA);
        controlA.show_uc_b += (s,e) => new ControlFactory<ControlBCreator>().CreateControl();
    }
}

public ControlBCreator : IControlCreator
{
    Control CreateControl()
    {
        Control controlB = new Control();
        DisplayControl(controlB);
        controlB.show_uc_c += (s,e) => new ControlFactory<ControlCCreator>().CreateControl();
    }
}

Then anytime you want a control, it will have the appropriate events tied on in by it's Creator class, all you need to call to get one is new ControlFactory<ControlWhateverCreator>().CreateControl();

Please, someone let me know if I got something wrong here; I've actually never written an abstract factory before. It's a lot of overhead so I tend to avoid facotries, but it seems the right approach based on the problem scope the OP detailed.