问:
Which k-best shortest-path algorithms should I consider?
I'm solving a graph-search optimization problem. I need to find the k best acyclic shortest-paths through a directed weighted graph.

I know there are a number of exact and approximate k-best algorithms, but most of the recent research seems to be oriented toward very large, very sparsely-connected graphs (e.g. road routing and directions), and my graph is neither.

Distinguishing aspects of my problem:

The graph consists of approximately 160 vertices.

The graph is nearly fully connected (bidirectionally, so ~160^2 ~= 25k edges)

k will be quite small (probably less than 10)

The maximum path length will probably be bounded and very small as well (e.g. 3-5 edges)

I said 'acyclic' above, but just to reiterate - solutions must not include cycles. This isn't an issue for 1-best shortest path, but it becomes a problem for k-best - for example, consider a road routing - the 2nd shortest path from A to B might be the same as the 1-best, with a quick trip around a block somewhere. That's might be mathematically optimal, but not a very useful solution. ;-)

We may need to re-weight edges on-the-fly for each calculation. An edge cost consists of a weighted sum of several factors, and the final requirements (whenever we get them) may allow a user to specify their own prioritization of those weighting factors, altering edge weights. This is a relatively small graph (we should be able to represent it in a few hundred KB), so it's probably reasonable to clone the graph in memory, apply the re-weighting, and then execute the search on the cloned graph. But if there's a more effective method of performing the search while computing weights on-the-fly, I'm interested.

I'm looking at the algorithms described in Santos (K shortest path algorithms), Eppstein 1997 (Finding the k Shortest Paths), and others. Yen's algorithm is of interest, primarily because of the existing Java implementation. I'm not scared to read the research papers, but I thought it was worth throwing out the details of my problem and asking for pointers to save some reading time.

And if you have pointers to Java implementations, even better.

答:
To partially answer my own question:

Since posting this question, I discovered that we need to handle negative edge weights as well as positive (the limitation to acyclic / simple / loopless paths means that the best solution is defined, whereas without that limitation the shortest path through a graph with negative-cost cycles is undefined).

Yen's algorithm, and most of the others I examined, depend on a series of 1-best searches; most use Dijkstra for those intermediate searches. Dijkstra does not support negative edge weights, but we can substitute Bellman-Ford in its place (at least in Yen; presumably in Lawler or Eppstein as well). I've developed a modification of Bellman-Ford with a path-length limitation (in edges) and explicit cycle-checking during search (in place of the standard post-search cycle detection). The computational complexity is worse, but still tractable for my requirements. I'll edit this response and link to a tech report if I get permission to post it.

OwnerDisplayName: AaronD


问:
Should I use TDD and BDD if my project is changing fast?
I have my own little project I am creating using RoR, I plan it to have small-medium load.

With no doubt I started with BDD and TDD (Cucumber and RSpec to be exact, but I am also experienced with TestUnit), I like it but since it's my own project and it's a somewhat startup - I am changing many things in it, many requirements, many ideas how things should work and look. So it becomes too much time-consuming to always code it using BDD and TDD, even if I cover only common cases.

What should I do? Should I sacrifice BDD and TDD for productivity till I get to some point when I have a solid basis and it's time for production, and than I write tests?

Should I write them right now but as minimal as possible? Should I only write RSpec and forget about Cucumber for now? Or maybe just TestUnit to test model for now since it's the most important and everything else can change?

Thanks in advance!

Update:

I know all the pros of TDD and BDD, by no means it makes it easier to scale and bugfix application in future and save time, but maybe it's more reasonable in my situation to wait few weeks till I have at least some skeleton architecture of my app and than once I am sure with it I can cover it with tests to have a solid base? And than continue with TDD and do all the tests with TDD.

答:
There is a difference between prototypes and code written with the goal to be run in production.

Prototypes are done to quickly test a concept. Code quality, security, maintainability don't matter. What matters is to finish the piece of software quickly in order to have the results (i.e. if the ideas behind are viable) as soon as possible.

Production code is expected to be more tested and more reliable, easy to maintain, secure, etc. If you sacrifice code quality, architecture or testing in order to accomplish the task quicker, it will hurt you sooner or later. In essence, not spending one hour testing your code now will cost you (or your colleagues) days later, because of a strange bug you could have caught easily if you were testing your code.

If your intent is to use the code later, write it as it was expected to live forever. Skip testing only if you know, for sure, that the code will be thrown away very soon (soon: in a few weeks).

ContentLicense: CC BY-SA 3.0


问:
Metrics / Methodology for estimating resource utilization for software in planning stage
I'm looking for approaches to estimate the resource utilization of an (web-)application in a JEE environment. The overall target is to get a forecast for hardware/software requirements while the application is still under development or even in planning stage.

Is this task too complex (many different factors) to get a fairly reliable proposition without spending too much time?

答:
It's not a question of too many factors as much as a computability problem. (The proof of this is left to the student)

You'll have to benchmark a prototype of the fundamental operation or 'kernel' of the application of your application.

This is exactly the same thing engineers in other domains do.

If you don't know what the kernel of your application looks like in the planning phase you can't do this. Moreover you can't plan a schedule either, as you don't know how much work it is to complete.

It's one of those things that experience helps with. You might be able to find a local expert to give you an estimate if you can describe the kernel.

If you can't describe it yet you are best to just design for scalability and scale it up or down after you get a prototype working. ( Decide not to decide.)
Sites like highscalability.com document some industry practices for scalability.


答:
It is a trade off, however, in most cases the answer is, yes, you should use TDD (or BDD).

Studies show that TDD may cause a an increase in initial time to develop but reduction in number of defects outweighs this.

Detecting defects later on adds substantially to the cost of development. TDD gives you faster feedback and allows you to identify defects as close to writing the code as possible.

TDD also gives a number of other benefits (when applied correctly).

It encourages more loosely coupled code, as tightly coupled code is harder to test.

It highlights violations of SRP, as extra responsibilities add an extra dimension to the test meaning a combinatorial explosion in number of tests.

It facilitates pair programming, see Ping Pong Programming.

Title: Should I use TDD and BDD if my project is changing fast?

Body:
I have my own little project I am creating using RoR, I plan it to have small-medium load.

With no doubt I started with BDD and TDD (Cucumber and RSpec to be exact, but I am also experienced with TestUnit), I like it but since it's my own project and it's a somewhat startup - I am changing many things in it, many requirements, many ideas how things should work and look. So it becomes too much time-consuming to always code it using BDD and TDD, even if I cover only common cases.

What should I do? Should I sacrifice BDD and TDD for productivity till I get to some point when I have a solid basis and it's time for production, and than I write tests?

Should I write them right now but as minimal as possible? Should I only write RSpec and forget about Cucumber for now? Or maybe just TestUnit to test model for now since it's the most important and everything else can change?

Thanks in advance!

Update:

I know all the pros of TDD and BDD, by no means it makes it easier to scale and bugfix application in future and save time, but maybe it's more reasonable in my situation to wait few weeks till I have at least some skeleton architecture of my app and than once I am sure with it I can cover it with tests to have a solid base? And than continue with TDD and do all the tests with TDD.


问:
Object-Oriented Programming: Why "Oriented"?
I am most of the way through my games programming degree.  This is not a computer science degree, so a lot of the theory is eschewed in favour of practical portfolio building and what I see as JIT learning, which is apparently more important in the games industry.  The first subject was "Introduction to Object-Oriented Programming".

That phrase didn't bother me until I learned about the different programming paradigms (I'm getting this list from https://en.wikipedia.org/wiki/Comparison_of_programming_paradigms):

Imperative

Functional

Procedural

Structured

Event-Driven

Object-Oriented

Declarative

Automata-Based

I get that this is not an exhaustive list, and that not all of these concepts are equal, and most of them aren't even exclusive, but I don't understand why most of them get just one word - imperative; functional; declarative - but when we talk about programming with objects, we have to clarify that we are oriented around those objects.  Can't we just use objects?  Can't we just have objects?  Why must they orient us, as our guiding star?

Looking here (https://en.wikipedia.org/wiki/Object-oriented_programming), nowhere is the use of the term "oriented" addressed as its own term.  Only "object" is explained.

Also, I can see for practical reasons why Event-Driven is used, because Event Programming is already a thing that you do when you're running a conference, and Automata Programming makes it sound like you're setting up a robotic production line, so it helps to have additional clarifying words there.

What makes Object Programming, as a phrase, not enough to describe what we do when we use objects in our programming?

Obviously from my tone I'm not too fond of the word "oriented".  It reminds me of my time as a court reporter, listening to lawyer after lawyer use the phrase "in relation to" as a kind of verbal tick.  It didn't mean anything; it was just a term that they used to fill the air while they tried to think of what to say next.  However, I'm not trying to advocate a change of language, I'm just asking why it is the way it is.  If someone knows why it came to be known that way for purely historical, vestigial reasons, then that's the answer.  It will be ammunition if I ever decide to waste my time advocating for a change of language.

On the other hand, if there is actually a useful reason for why a language or piece of code must point towards objects, to the exclusion of all other directions, as opposed to merely having them in its toolbelt, as tools, I would really be interested to learn about it.  I like learning useful things.

答:
Calling it that helps to explain that objects are a very important part of the paradigm.

Object-Oriented programming has its roots in Simula, which was essentially ALGOL plus some new object-programming features.  And in keeping with that history, even today it's entirely possible in many languages (even the "pure OO languages") to code something that is essentially just a procedural program with some objects in it.  But this is considered bad style by more experienced developers.

Actually doing something "the object-oriented way" is very different from "the procedural way."  The most important concept is the use of inheritance and polymorphism.  When you truly understand and internalize the way classes and virtual methods work, it's an eye-opening experience that changes the way you write code in a lot of cases, a true paradigm shift.  (Assuming, of course, that you started out writing procedural code first.  A lot of students these days go straight to Java or C# as a first language, and IMO they miss out on really understanding the benefits of OO by doing so.)

We call it object-oriented programming because a program written in OO style does not just contain objects; the structure of the whole program is based around them and around the way they work.


答:
but when we talk about programming with objects, we have to clarify that we are oriented around those objects. Can't we just use objects? Can't we just have objects?

Frankly, it's a holdover of history. Functional programming is really function-oriented programming, declarative programming is really declaration-oriented programming... after all don't we just use functions? Can't we just have functions?

"Object oriented" rolls off the tongue better, and is historically ingrained.

The 'orientation' comes because we're not talking about programming but design. Just because we use objects, or use functions, or use events does not mean that our design methodology is done by modelling all three. By specifying the orientation of the design methodology, it helps communicate to programmers how they should interpret and extend that design - how the modelling focus colors the implementation.

Title: Object-Oriented Programming: Why "Oriented"?

Body:
I am most of the way through my games programming degree.  This is not a computer science degree, so a lot of the theory is eschewed in favour of practical portfolio building and what I see as JIT learning, which is apparently more important in the games industry.  The first subject was "Introduction to Object-Oriented Programming".

That phrase didn't bother me until I learned about the different programming paradigms (I'm getting this list from https://en.wikipedia.org/wiki/Comparison_of_programming_paradigms):

Imperative

Functional

Procedural

Structured

Event-Driven

Object-Oriented

Declarative

Automata-Based

I get that this is not an exhaustive list, and that not all of these concepts are equal, and most of them aren't even exclusive, but I don't understand why most of them get just one word - imperative; functional; declarative - but when we talk about programming with objects, we have to clarify that we are oriented around those objects.  Can't we just use objects?  Can't we just have objects?  Why must they orient us, as our guiding star?

Looking here (https://en.wikipedia.org/wiki/Object-oriented_programming), nowhere is the use of the term "oriented" addressed as its own term.  Only "object" is explained.

Also, I can see for practical reasons why Event-Driven is used, because Event Programming is already a thing that you do when you're running a conference, and Automata Programming makes it sound like you're setting up a robotic production line, so it helps to have additional clarifying words there.

What makes Object Programming, as a phrase, not enough to describe what we do when we use objects in our programming?

Obviously from my tone I'm not too fond of the word "oriented".  It reminds me of my time as a court reporter, listening to lawyer after lawyer use the phrase "in relation to" as a kind of verbal tick.  It didn't mean anything; it was just a term that they used to fill the air while they tried to think of what to say next.  However, I'm not trying to advocate a change of language, I'm just asking why it is the way it is.  If someone knows why it came to be known that way for purely historical, vestigial reasons, then that's the answer.  It will be ammunition if I ever decide to waste my time advocating for a change of language.

On the other hand, if there is actually a useful reason for why a language or piece of code must point towards objects, to the exclusion of all other directions, as opposed to merely having them in its toolbelt, as tools, I would really be interested to learn about it.  I like learning useful things.


问:
How to deal with complex codes in (huge) projects
I am preparing a memoir about "Why do (some) IT projects become too complex and how to avoid it ?".

If you have ever encountered projects having complex codes or were hard to maintain, how did you manage to go through it?

If you have to choose between several applications to use in your project, what would be your top priority in their functionality and why?

答:
I don't think you can ever completely avoid complexity over time, but there are ways to mitigate it:

Keep the code as clean as possible at all times, within reason. (In the "how Uncle Bob defines 'clean'" sense.)

Apply code reviews and/or pair programming to lower the odds of one developer over-engineering things needlessly.

Maintain adequate unit tests and integration tests.

Invest in a continuous integration server and build often. Release often too, if possible.

All of this is somewhat dependent on what the project actually entails. Sometimes, for example, it'll be beneficial to accept complexity in exchange for performance. Not all complex code is necessarily a bad thing. In general, though, I think following these guidelines should help.

ContentLicense: CC BY-SA 2.5


问:
How often is Inheritance used?
I admit that I am a junior developer, and so far I've only built simple web applications in ASP.NET MVC. But I've never had to use the inheritance aspect of Object Oriented Programming in my own classes! It is true that in using ASP.NET MVC I inadvertently use inheritance (any controller I create will inherit from the base controller class), but I am referring here to the conscious use of inheritance in my design of a particular web system.

Is it because I am a bad programmer? Or could it be that inheritance only comes into play in certain scenarios? Don't get me wrong, I understand what inheritance is and how to code using inheritance if I had to.

I just can't seem to find a scenario to use it at. Basically, I am wondering how often it is used in OO programming in general.

答:
Knowing when to use inheritance and when to use other features of the language you are working in takes time. There are a many different ways to tackle the same problem and inheritance is only one tool of many at your disposal.

The popularization of object oriented languages might lead one to believe it is the best way to write and reuse code, but even the first paragraph of the Wikipedia article on OOP inheritance stresses that composition is the preferred and more flexible way to reuse code.

So to answer your question, you are not a bad programming for not using it all the time. Like Doc Brown said, it is used far too often as the solution to a problem when composition could be used instead.

Title: How often is Inheritance used?


答:
But I've never had to use the inheritance aspect of Object Oriented Programming !

Oh but you have! If you're using ASP.NET MVC you're deriving your controllers from System.Web.Mvc.Controller. This is what gives your controllers all the power and functionality they have without you having to do any heavy lifting.

I just can't seem to find a scenario to use it at. Basically, I am wondering how often it is used in OO programming in general.

For me, I use inheritance quite often but you need to know when you need to use it. There is little point having a god object that you derive everything from; however if you're implementing business logic you might have a base SectionRule class that you define various rules in.

A real world example could be a driving game. You'd have a base abstract class called Vehicle which couldn't be instantiated on its own because it would be useless but you could define basic behaviour such as IsRunning and CurrentSpeed while providing a Start() method that is abstract meaning you need to implement it. You could derive classes Car, Bike and Truck and each would keep track of whether it is running and the current speed, but you manually implement the Start() method for each object type.

The other thing to bear in mind is that OO is used everywhere within most frameworks (ASP.NET, WinForms, WPF, etc), you may be using it without knowing. Most WinForms components derive from Control.

The biggest advantage of using OO and inheritance is reducing the amount of code you have to write for related objects.

Title: How often is Inheritance used?

Body:
I admit that I am a junior developer, and so far I've only built simple web applications in ASP.NET MVC. But I've never had to use the inheritance aspect of Object Oriented Programming in my own classes! It is true that in using ASP.NET MVC I inadvertently use inheritance (any controller I create will inherit from the base controller class), but I am referring here to the conscious use of inheritance in my design of a particular web system.

Is it because I am a bad programmer? Or could it be that inheritance only comes into play in certain scenarios? Don't get me wrong, I understand what inheritance is and how to code using inheritance if I had to.

I just can't seem to find a scenario to use it at. Basically, I am wondering how often it is used in OO programming in general.


问:
The difference between "concurrent" and "parallel" execution?
What is the difference between the terms concurrent and parallel execution?  I've never quite been able to grasp the distinction.

The tag defines concurrency as a manner of running two processes simultaneously, but I thought parallelism was exactly the same thing, i.e.:  separate threads or processes which can potentially be run on separate processors.

Also, if we consider something like asynchronous I/O, are we dealing with concurrency or parallelism?

答:
Obviously, the terms are used differently in different cultures.

My understanding is the following:

Parallelism is a way to speed up processing. Whether you do matrix multiplication on a single core, on multiple cores or even in the GPU, the outcome is the same (or else your program is broken). It doesn't add new functionality to some program, just speed.

While concurrency is about things you couldn't do sequentially. For example, serving 3 different webpages at the same time to 3 clients, while waiting for the next request. (Though you could simulate this to some degree through interleaving, as it was done in the elder days.)
Note that the behaviour of concurrent programs is nondeterministic. It is for example not clear, which of the 3 clients will be completly served first. You could run quite some tests and get a different result each time regarding the order the request will be finished. The run-time system should guarantee that a) all clients will be served and b) in a reasonable amount of time.

Usually, the work horse of a parallel computation isn't aware of, nor does it care about, parallelism. While concurrent tasks often explicitly employ inter-process or inter-thread communications - such as blocking queues, synchronization and locking mechanisms.


问:
When to separate application concerns
I've worked for a number of companies that have, over time, branched out their core service to provide additional services and/or revenue streams. My question is when is the proper time to separate these concerns into multiple applications, even when they're operating on the same/extensions-of-some data?

For example, say a company has a core business application that resolves around a music index/music discovery. If this company later decided to branch out into offering websites for musicians that utilize their existing index, should this be a separate application that receives its data from the core-business-application via API, or is it reasonable to lump this into a module of the existing application, and use existing business objects?

It seems to me that the ability to lump things into one application shouldn't be reason enough to do so. In Unix, we practice Separation of Concerns, but when it comes to enterprise development, this principal seems to be lost. In the example above, I would feel that these should be separate applications, but in my experience I witness developers lump these together to save time.

答:
I think it boils down to whether or not there is any sense in bundling the functionality as an addon/extension or if it should be standalone on its own right. In your example, it would make more sense to me to expose the relevant data in an SOA manner for the musician websites rather than bolting it onto the core application as there is practically no overlap other than data. Relevant logic would be encapsulated in the services.

Generally I think practicing a separation of concerns is the best bet, modularizing applications and reusing code wherever possible. A prime example of this would be Microsoft Office, which leverages a (fairly) consistent interface provided by various shared libraries, shared spell checkers, VBA, and more whilst implementing their own core logic and interface.

Title: When to separate application concerns


答:
Inheritance is used all the time when writing object-oriented code.  In most OO languages, (with C++ being a prominent exception,) all objects have a single "base object" class that they derive from that provides common functionality, so literally everything that uses an object uses inheritance.

Beyond that obvious point, there are many times when you'll find that you need several different types of object that share a lot of important traits in common.  Inheritance is very useful here.  For example, if you've ever built a GUI in an object-oriented language, you probably used a framework where all of the graphical controls had a common parent class that handled a bunch of functionality that all the controls in the windowing system they run on need to cover.  And if you do any work with parsing or code generation, (which are basically two sides of the same coin) you'll quickly run into other examples where a base class with a bunch of derived classes are useful.

It's true that inheritance is not the only way to make objects work together; you can also use composition, (where one object contains another object of a different type,) which works better in some cases.  Be careful about treating this as a point of dogma, though.  Inheritance is a very useful tool if you know what you're doing.  So is composition, and neither one of them is really a good substitute for the other. The important thing is to know what you're doing, and if you don't, learn and experiment and develop your knowledge and your skills.  (And feel free to ask questions on here or StackOverflow!)

Title: How often is Inheritance used?


答:
The proper time is now, unless you have other requirements to fulfill. The more separated the layers of your application are, the more flexible it will be to adapt to changing requirements. Whether it makes sense to implement a layer as an API or as a service depends on your requirements.

I can not guess as to why more developers do not take the Separation of Concerns principle more seriously. Perhaps they do not see the long benefits out weighing the need to get the job done now.

Title: When to separate application concerns

Body:
I've worked for a number of companies that have, over time, branched out their core service to provide additional services and/or revenue streams. My question is when is the proper time to separate these concerns into multiple applications, even when they're operating on the same/extensions-of-some data?

For example, say a company has a core business application that resolves around a music index/music discovery. If this company later decided to branch out into offering websites for musicians that utilize their existing index, should this be a separate application that receives its data from the core-business-application via API, or is it reasonable to lump this into a module of the existing application, and use existing business objects?

It seems to me that the ability to lump things into one application shouldn't be reason enough to do so. In Unix, we practice Separation of Concerns, but when it comes to enterprise development, this principal seems to be lost. In the example above, I would feel that these should be separate applications, but in my experience I witness developers lump these together to save time.


问:
Can REST API be used as business layer?
I am using PHP Codeigniter MVC design pattern

and I had this project with some sort of specific business processes

In my application I will be dealing with 2 existing REST APIs:

Google

Trello

I came up with idea to create REST API to act as Business Logic Layer (BBL)

that in turns access my models directly to fetch needed data to formulate business rules

and controller with communicate with BLL with REST client,

Is that bad approach for performance ?

Is it better to create 2 layers of Models one as Data Access Layer (DAL) and one as Business Logic Layer (BLL)

答:
The problem I see with your approach is that you are building a REST API for only one consumer, your controllers, and that's overkill. Don't just add a layer just to pass data from one layer to another, there's no point, you'll be creating work for yourself for no additional benefit.

One (quick) way to make your API useful would be if it was the only endpoint your controllers (i.e. your application) ever needs. Consider this:

Suddenly your REST API has a purpose, and that is to provide a unified interface to your various data providers. Your application doesn't need to know about the Google or the Trello API, or any other data provider you might use in the future, it just needs to know about your REST API.

This design, albeit slightly more useful, is still overkill if your application is the only consumer. The whole point of building a REST API is to expose a publicly available interface for your applications to share. And the key here is exposure, your REST API will be available to the world and therefore it must be secure. API authentication and authorization are no simple tasks, if only one application uses your API, why go through all the trouble? Unless of course you want to experiment and learn. If that's the case, by all means go for it.

In any case, performance shouldn't be an issue. You'd be adding an extra layer, so obviously there will be some overhead, but whether that overhead will be significant or not depends entirely on your implementation. If your REST API is the single endpoint, then it will probably be a good idea to also be the one place where caching happens. And not just server side caching, a REST API makes browser caching a bit more easier to exploit, and if you get it right, the overall performance of your application may increase, comparing to a non REST approach.

tl;dr: Don't build stuff that don't have an actual purpose (unless you're learning).

Title: Can REST API be used as business layer?


问:
Do frameworks put too much abstraction?
I've been programming for a little under a year and have some experience writing systems applications, web apps, and scripts for businesses/organizations. However, one thing I've never really done is working with a framework like Django, Rails or Zend.

Looking over the Django framework, I'm a little frustrated with how much is abstracted away in frameworks. I understand the core goals of DRY and minimal code, but some of this over-reliance on different modules and heavy abstraction of core functions feels like it:

Makes programs get dated really fast because of the ever-changing nature of modules/frameworks,

Makes code hard to understand because of the plethora of frameworks and modules available and all of their idiosyncrasies,

Makes code less logical unless you've read all of the documentation; i.e., I can read through some list comprehensions and conditional logic and figure out what a program is doing, but when you see functions that require passing in arbitrary strings and dictionaries, things get a little hard to understand unless you're already a guru in a given module; and:

Makes it difficult and tedious to switch between frameworks. Switching between languages is already a challenge, but it's manageable if you have a strong enough understanding of their core functionality/philosophy. Switching between frameworks seems to be more a matter of rote memorization, which in some ways seems to encourage the very inefficiency these frameworks were designed to eliminate.

Do we really need to put like 50 layers of abstraction on top of something as simple as a MySQL query? Why not use something like PHP's PDO interface, where prepared statements/input testing is handled but the universally understandable SQL query is still a part of the function?

Are those abstractions really useful? Isn't feature bloat making them useless, making applications more difficult compared to similar applications written without using a framework?

答:
It seems to me that you misunderstand abstractions and code reuse.

The whole software development industry is built on abstractions. Just because not using them, i.e. avoiding using frameworks, libraries and in general code which is not written in-house, would increase the cost you need to produce a piece of software by hundred, thousand, probably even more.

Like you don't create a jumbo jet from scratch, without using any engineering knowledge developed for years when building other aircraft, you don't write business software from scratch.

You do get that by using PHP or Ruby in the first place, you already have a huge amount of abstractions, are you? The most obvious ones:

The operating system, the programming language and the compiler provide a huge abstraction over Assembler and hardware,

The web server provides an abstraction of sockets, failover, HTTP protocol, etc.,

SQL provides an abstraction over how data is stored on a permanent storage support and kept in memory for faster access, ensures ACID, mirroring, etc.

You may always try to create a web app without using neither an operating system, nor a web server, a database or a high level programming language. You'll quickly find that you spent years reinventing the wheel, i.e. recreating your programming language, your web server and your database, given that their quality would be far from the quality of products we actually use.

Frameworks are not different from that. You can do what they do. Just that you will waste your time redoing the same functionality, with the difference that those frameworks will do it better and very often their code will be tested and documented better than yours.

Take the example of a cart for an e-commerce website. You may invent your own and spend a few weeks developing it, or you may take the one which was developed for years by a bunch of people inside a framework. Theirs is expected to be tested, not counting the fact that during a few years, those developers discovered and patched a bunch of bugs you won't imagine when developing your own cart.

You may reply that theirs is more complicated because it has more user cases. For example theirs should deal with rebates, while you don't have rebates on your website and don't need this feature in the cart. Well, you're not forced to use this feature, and it's not like it will penalize the performance of your web app.

You may have a very basic scenario when it's really easier to develop your own cart instead of using the existent one. In the same way, if the only thing your app needs is to store a list of numbers, nothing more, you don't need a database: a simple text fill would be enough. In those cases, don't over-engineer your app: simple scenarios require simple solutions.

Another factor is the readability of your code. Imagine you've created an e-commerce website. Later, you left the project, and another developer should maintain it.

If you had used a cart provided by a framework, your colleague would be relieved: he have to maintain a small piece of code which relies on a reliable, heavily documented framework. Even better: this developer may have been used to work with this framework and is familiar to it. If not, he can ask questions on Stack Overflow: for sure, somebody have already used the framework.

If you had your own cart, then your colleague would have to maintain some custom code, maybe not even documented, without being able to obtain help anywhere.

By using a framework, you rely on a code which is:

Written by experienced developers,

Often pair-reviewed,

Unit-tested,

Extensively documented,

Used for years by thousands of developers,

Often supported, so you can report a bug and see it actually fixed,

Known by many developers who know the possible caveats and issues and can help on sites like Stack Overflow.

Available for you right now, for free.

Title: Do frameworks put too much abstraction?


问:
Does anybody ever uses the OpenId url Log in?
As programmers I think we are the most inclined to use new technologies and things that are not so mainstream.

I absolutely love OpenId's ability to log in with credentials you already have, but I always use a provider that I already use and that is the fastest to log in, like google. God knows I'd never used it if i had to type in the whole "https://www.google.com/accounts/o8/id" I like to click on the google button and then just say yes (the first time, then its just clicking the button).

Does any of you ever uses the Generic "Enter your own provider" OpenId?

Do you think its worth to even offer it to more casual end users?

答:
I'd say the benefits outweigh the disadvantages. If you didn't provide that feature, you'd have to include more presets to make sure everyone was covered, and (as Mr. C said) some people use their own sites to redirect to their OpenId. Forcing some users to create a new OpenId just to use your site would probably turn most of them away.

If you're worried about it confusing new users, you could always hide it under an advanced option.


答:
Document, Document, Document!

I work with some pretty complex MVC code, and am only now actually understanding how it works, as opposed to accepting it on faith. Whenever I make a change that I have a hard time figuring out, I put a comment in the code at that section to help clarify what is happening. It might not have helped me since it wasn't there, but it'll help the next person around. I also like to ask other programmers around me to look at my changes to see if they are clear.

My company has an internal wiki that we use for documenting a lot of the meta tasks we do, like virtual server problems, common queries, etc. Whenever I come across something I've not done before but will have to do often, I check to see if there's a wiki on it. If there isn't I'll make one. More people have gotten involved in it as well recently, so I hope it will grow faster. I think it really helps communication of the more mundane tasks we have.

Title: How to deal with complex codes in (huge) projects

Body:
I am preparing a memoir about "Why do (some) IT projects become too complex and how to avoid it ?".

If you have ever encountered projects having complex codes or were hard to maintain, how did you manage to go through it?

If you have to choose between several applications to use in your project, what would be your top priority in their functionality and why?


问:
Singleton: Is Singleton an Anti-Pattern
Was reading an interesting blog post on Singleton design pattern which is so widely used.
If it's stupid or as in some quora posts, its an anti-pattern why is it so widely used even in frameworks.

For e.g., Spring framework (java) makes all the classes available through dependency injection as Singleton classes and adding prototype is optional.

答:
Not at all. In my opinion, if used sparingly, it's actually one of the most useful patterns you'll find. It's an easy way to solve otherwise extremely difficult problems. Sure, every criticism is true, but to be honest, I'm willing to deal with a little bit of a bad pattern in an otherwise well designed application / framework that follows the other, better patterns.

The best example of an effective singleton, in my opinion, is a LogManager—something you typically use throughout your application, but you want to have it defined, configured, and managed in only one place. In most other cases where I started out using a singleton, I eventually ended up refactoring the code into something else. But I still keep the singleton pattern in my back pocket for those rare cases where it does more good than harm.

I've never used Spring, and barely used Java, so feel free to take this answer with a grain of salt.

Title: Singleton: Is Singleton an Anti-Pattern


答:
Based on your drawing, it seems like there should be a model called by your controller that deals with talking to Google, getting the results back, formatting it for your app, and then that is sent to controller ready to go. In other words all the google specific details would be in that model. same for trello. that way if you need to add more apis to consume, you have kept everything nice and separate.

this is a small detail - but remember in your overall app design - you have to account for possible delays in sending / getting the information from the api server to your server. in other words make sure your app doesnt completely hang up if the trello server is slow or down.

Apis have to be concerned with security but they don't necessarily have to be 'public'. many apis are business to business with nothing public.

i've read most of this book - its short, still early release, and not enough examples - but its very current, its all php, and the author is actively creating and teaching about apis.
http://shop.oreilly.com/product/0636920028291.do

the author has php rest api related posts on her blog.
http://www.lornajane.net/blog

and be sure and read the comments for the api posts! seriously it will give you very valuable perspective.

Suggest that you google "hypermedia" and api. you might not want to use it, but it will show you some other techniques for api creation.

I've just joined programmers - i would upvote this question if i could! most businesses will not be able to create entirely new applications for consuming  or publishing apis. so coming up with best practices for integrating apis into existing mvc frameworks -- this is really important.

Title: Can REST API be used as business layer?

Body:
I am using PHP Codeigniter MVC design pattern

and I had this project with some sort of specific business processes

In my application I will be dealing with 2 existing REST APIs:

Google

Trello

I came up with idea to create REST API to act as Business Logic Layer (BBL)

that in turns access my models directly to fetch needed data to formulate business rules

and controller with communicate with BLL with REST client,

Is that bad approach for performance ?

Is it better to create 2 layers of Models one as Data Access Layer (DAL) and one as Business Logic Layer (BLL)


答:
Frameworks usually result in more productivity (perhaps after a slight learning curve), but there is often a trade-off involved. In some cases, for example, you gain programmer productivity at the cost of decreased performance.

Consider Object-Relational Mappers (ORMs). They are great in that they take care of a lot of the tedious mapping code for you. They may even create your objects for you. However, in abstracting away the SQL, it's much harder to reason about performance and optimize your bottlenecks.

If you are building an application that won't have a lot of data or complex queries, performance may not be an issue for you. Indeed, programmer time is the bottleneck for a lot of projects, and frameworks, libraries, and high-level languages help to alleviate that.

Title: Do frameworks put too much abstraction?

Body:
I've been programming for a little under a year and have some experience writing systems applications, web apps, and scripts for businesses/organizations. However, one thing I've never really done is working with a framework like Django, Rails or Zend.

Looking over the Django framework, I'm a little frustrated with how much is abstracted away in frameworks. I understand the core goals of DRY and minimal code, but some of this over-reliance on different modules and heavy abstraction of core functions feels like it:

Makes programs get dated really fast because of the ever-changing nature of modules/frameworks,

Makes code hard to understand because of the plethora of frameworks and modules available and all of their idiosyncrasies,

Makes code less logical unless you've read all of the documentation; i.e., I can read through some list comprehensions and conditional logic and figure out what a program is doing, but when you see functions that require passing in arbitrary strings and dictionaries, things get a little hard to understand unless you're already a guru in a given module; and:

Makes it difficult and tedious to switch between frameworks. Switching between languages is already a challenge, but it's manageable if you have a strong enough understanding of their core functionality/philosophy. Switching between frameworks seems to be more a matter of rote memorization, which in some ways seems to encourage the very inefficiency these frameworks were designed to eliminate.

Do we really need to put like 50 layers of abstraction on top of something as simple as a MySQL query? Why not use something like PHP's PDO interface, where prepared statements/input testing is handled but the universally understandable SQL query is still a part of the function?

Are those abstractions really useful? Isn't feature bloat making them useless, making applications more difficult compared to similar applications written without using a framework?


问:
Would it be possible to publish my code on an official site with a third-party library?
I'm building a rather large and extensive wrapper in Delphi for an email system called Mandrill. There are wrappers for this API in many other languages, but not for Delphi. So, I'm hoping to produce the first full wrapper. The problem is, I'm utilizing a third-party JSON parser called superobject. I'm afraid that if I complete this wrapper, I won't be able to provide my code for Mandrill to share, because of this third-party library.

If I do complete this wrapper, is there any chance that Mandrill will be able to legally publish it on their site, based on the fact that I'm using superobject? Or would I need to parse my own JSON to be applicable?

PS - I mean this question in a general concept, not necessarily for my precise scenario, but in general, if I use a third-party library, can I legally post it with my code on another third-party's site?

答:
I'm assuming that the superobject that you're using is this one. It is distributed using the Mozilla Public License, which permits you to use this library for free even in commercial projects.

If you make a modification to the superobject library, you must distribute that modification.


答:
Hmmm  One aspect of LedgerSMB that we worked on a lot was our approach to framework.  There are two fundamental problems that come with this sort of abstraction though.  These are:

Dependency explosion, and

Wrong abstraction

The first is actually better than the alternative which is re-inventing the wheel.  The second is a bit of a hard one to label because it can come from a poorly defined problem case or, more often, from people using something outside its intended use.

Let's look at ORMs for example.  I avoid using ORMs because it is very often the case that the db ends up designed to the object model of the application because at best they are leaky abstraction layers.  This isn't necessarily the case.  I have met developers who manage to preserve good DB design and good app while using ORMs but they resort to a lot of things the orm hype says shouldn't be required, like encapsulating the relational API of the db behind updateable views.

A major problem of course is that the more highly automated the code, particularly when it is also opaque, the harder it is to see what is going wrong.  This is a point about ORMs that @jhewlett makes above (see https://softwareengineering.stackexchange.com/a/190807/63722).

A good parallel might be advanced avionics as a framework for piloting an aircraft.  These have been highly engineered for reliability and are a factor in the increase in flight safety.  However, as many articles in the IEEE Spectrum point out this comes at a cost of recoverability from errors outside the bounds of what is considered acceptable from an automation perspective.  The same goes for debugging.  It's one thing to debug SQL code in your program.  It's a very different thing to debug a part of your program that writes SQL code for your program to use.

We wrote the LedgerSMB framework from scratch because at the time we started, there were no really good frameworks that did what we wanted.  It's actually one thing I am pretty happy with, and according to a newer developer on the project, it makes customization of the application quite straight forward.  (We actually keep the SQL code generation to a minimum and instead focus on hand-written user defined functions, meaning the sql-writing portions are very thin glue).  Yes it provides a lot of abstraction in some places, more than some programmers are comfortable with (in particular "map object properties to arguments in that stored procedure" gets us pushback from time to time).  We try, however, to keep everything simple and consistent so that it is straight forward to determine what went wrong.  This works pretty well.

In the end "too much" is a bit subjective, but on an objective level it also depends on what you are doing.  If you are doing exactly what the framework was designed to do, a well-designed framework will provide a perfect amount of abstraction.  If you are doing something which is a bit less of a fit, the abstraction will become both too much and too leaky.

Title: Do frameworks put too much abstraction?


问:
Streamlining ASP.Net MVC deployment?
I own a VPS with Windows Server 2012 on it. I can install whatever I want on it.

In the past when deploying an ASP.Net MVC project, I would right click the project in the solution and Publish it.

I would then copy over the files to the IIS folder and that would be a deployment for me. But this is no longer something I want to do. There has to be an easier way right?

How can I streamline the deployment process? I'm 100% in the dark on this subject with .NET.

Can I set something up on my server so I can Web Deploy to my VPS? Or is there a better alternative?

Thank you!

答:
There's a lot of different options, here's a few I've worked with:

Octopus - packages up your site as a NuGet package (depending on what you have included in compilation in your cs/vbproj files) and delivers it on command to any number of servers that have the Octopus "Tentacle" service installed. I've used it for a few pet projects and it's been great, but may be overkill for what you're doing. Works really well in combination with a build server (in my case, TeamCity).

VCS Deployment - what we've been doing at the company I work for has been a combination of uploading binaries and using our Git repository to deploy non-compiled files to the application. Seems to be working well for us so far. If you really wanted to make it a one-step process (and your compiled files are relatively small), you could include binaries in the repo and just deploy entirely this way. (Don't recommend that, but, well, you could.) It's not one click (unlike Octopus) and you can run into issues with DLL Hell if you don't remember to deploy your resources properly, but you generally ensure at least your static content is always in line with your repository.

Web Deploy - admittedly, I haven't done much with it, so I can't really offer too much of a recommendation. I've heard success stories, and I've also heard war stories with its use. YMMV on this one.

FTP - just FTP the whole dang thing up to your VPS every build. Only appropriate for small projects, but hey, sometimes it's the appropriate tool. Why use a sledgehammer to crush an aluminium can when you can just step on it? (Besides the obvious entertainment factor.)

.NET deployment is definitely getting better, but still has a long way to go. Good luck!

Title: Streamlining ASP.Net MVC deployment?


答:
Frameworks can be tricky indeed. Problems can easily arise when a framework is too "opinionated", i.e. when it really prefers one particular style of application and all parts are geared towards supporting this particular style.

For instance, if the framework completely abstracts the authentication process of a user by allowing you to just add one component, add a login template somewhere and voila, you get user authentication for free. This saved you a lot of repetitive work in worrying about cookies, session storage, password hashing and whatnot.

The problems begin when you realize that the default behavior of the framework's authentication code is not what you need. Maybe it's not following the latest best security practices. Maybe you need a custom hook in the process to trigger some action, but the framework doesn't offer one. Maybe you need to change the details of the cookie that is being set, but the framework offers no way to customize this.

The abstraction afforded by the framework allowed you to add an important feature to your site within minutes instead of days initially, but in the end you may have to fight against the framework to make it do what you need it to do, or you'll have to reinvent the functionality from scratch again anyway to suit your needs.

This is not to say framework abstractions are bad, mind you. It is to say that this is always a possibility you need to keep in mind. Some frameworks are explicitly geared towards this, they offer a way to get something up very quickly as a prototype or even production framework for a very specific, limited type of app. Other frameworks are more like loose collections of components which you can use, but which still allow you a lot of flexibility to change it around later.

When using an abstraction, you should always understand at least roughly what it's abstracting away. If you don't understand cookies and authentication systems, starting from an abstraction is not a good idea. If you do understand what you're trying to do and just need code which already does it instead of having to tediously write your own, abstractions are a great time saver. Poorly written abstractions can get you into trouble later though, so it's a double edged sword.

You should also distinguish between technical abstractions and "business rule" abstractions. Programming in a higher level language is an abstraction you probably don't want to miss (Python, PHP, C# vs. C vs. Assembler; Less vs. CSS), while "business rule abstractions" can be difficult if they don't meet your needs exactly (one-click authentication vs. hand-coding cookies).

That's because technical abstractions rarely "leak", i.e. you will hardly have to debug machine code when writing applications in Python. Business rule abstractions work on the same technical level though and are just "code bundles" really. You probably will need to debug the cookie that is set or the password hash that is created at some point, which means you'll be diving through lots of 3rd party code.

Title: Do frameworks put too much abstraction?


答:
You've already recognized that you frequently use inheritance.  What you're really asking is why you never seem to need to create your own new base class.

The reason is that base classes tend to be created most often in frameworks, libraries, and in the early stages of a project when the architecture is just being defined.  These sorts of tasks tend to be given to more senior programmers, but even they might not create many new base classes in their code in a framework-heavy job like web development.

And no, it does not mean you are a bad programmer.  Quite the opposite, in fact.  A lot of new programmers have a hard time distinguishing the proper situation to use inheritance, and have a tendency to overuse it, creating tightly coupled code.

If you're wondering if you're accidentally missing out on opportunities to use inheritance properly, the trick is to look at the calling code for a lot of if or switch statements that do different things depending on the type of a variable.  For example:

```<code>if (user.isAdmin())
    drawAdminForm();
else if (user.isEditor())
    drawEditorForm();
else
    drawUnprivilegedForm();
</code>```

Just keep an eye out for code like that, and you'll do just fine.

Title: How often is Inheritance used?

Body:
You've already recognized that you frequently use inheritance.  What you're really asking is why you never seem to need to create your own new base class.

The reason is that base classes tend to be created most often in frameworks, libraries, and in the early stages of a project when the architecture is just being defined.  These sorts of tasks tend to be given to more senior programmers, but even they might not create many new base classes in their code in a framework-heavy job like web development.

And no, it does not mean you are a bad programmer.  Quite the opposite, in fact.  A lot of new programmers have a hard time distinguishing the proper situation to use inheritance, and have a tendency to overuse it, creating tightly coupled code.

If you're wondering if you're accidentally missing out on opportunities to use inheritance properly, the trick is to look at the calling code for a lot of if or switch statements that do different things depending on the type of a variable.  For example:

if (user.isAdmin())
    drawAdminForm();
else if (user.isEditor())
    drawEditorForm();
else
    drawUnprivilegedForm();

Just keep an eye out for code like that, and you'll do just fine.


问:
How do I perform some actions in my Java program whenever a particular network interface comes up?
I wanted to perform some actions in my Java program whenever a particular interface comes up (network interface ppp0 e.g.). However I figured out it was way too clumsy to keep polling the interface to verify its status.

After finding out if-up.local file in Linux, now I can run a bash script whenever the interface comes up. Works fine, however considering my running Java program, how can I make this script interact with my Java code?

I am considering the following options:

Write a listening socket and from this script send message to this Java socket.

Invoke a C program, and through JNI run my java code.

I am looking for intuitive and less resource intensive approach.

答:
Probably the simplest way is your first option. Just open a TCP socket and make a request to it from the if-up.local script you found. Using wget/curl for example.

A more complex alternative is to somehow use a netlink socket from java. I think that NETLINK_ROUTE will give you updates on interface creation events, see the first example in that link.

For this second option, either write some JNI or try to find a java library for using unix sockets. In a quick search I've found this one, although I've never used it, so I don't know if it would work for your needs.

A third idea, similar to the first one, instead of a socket, use a FIFO pipe (mkfifo command), you could read it from java as a regular file, and write to it from the bash script with simply a *echo > fifo_file*.

OwnerDisplayName: Space Rocker

OwnerDisplayName: gargc


问:
Approach to submitting forms from a multi-platform native/hybrid app with unstable internet connection
Sorry for the long question, but I want to be sure to define my problem clearly.

For my thesis (in aerospace engineering, so not much programming experience) I want to develop a (prototype) mobile application which will facilitate the reporting of safety related events in African aviation. Although the content of my thesis focuses on the more technical and sociological aspects of safety (management) I decided to include some practical design for demonstrative purposes.

Considering the criteria I will present below, my first guess is to develop a mobile app using PhoneGap or something similar. But life can't be that simple, so I'll need more than just this single framework. My question to you is, what a convenient and effective approach would be to satisfy the following description?

Quite simply this is what I envision (in layman's terms):

A user (pilot, ground crew, etc.) experiences or notices a safety related event

The user fills out a form (Air Safety Report) about the event on his/her phone

Additional information (pictures/videos) are attached

Once a stable internet connection comes available (we're in Africa) the report/form is submitted to a server.

Important considerations here are:

The limited availability of internet -> I need a native/self-contained solution/app so the reporter does not have wait with reporting, and which stores data and submits once possible.

I don't want - nor should - exclude potential users (for multiple reasons) -> The app should be available on as many platforms as possible (especially BlackBerry and Symbian are still very popular in Africa!).

I am doing this as a form of development aid and want it to be cheaply available -> open source preferably.

Altogether, the following criteria can be defined: It should

be open-source

support multiple-platforms

allow file attachments (pictures mainly)

be self contained/native

support/allow web services

provide geolocation and date/time support (automate report whereabouts)

allow camera use for direct attachment (optional, but preferable)

identify an internet connection and submit the data once possible

store data until submission

Besides PhoneGap (which doesn't support image library browsing? -> apparently is possible, see supporting documentation), I have considered the following frameworks:

Mobl (not tested for all major platforms, no date/time support?)

QuickConnect (does not support BlackBerry and Symbian)

Rhodes (meets my requirements as for as I can see)

Appspresso (doesn't support BB and Symbian, no date picker)

I've read the following thread on stackoverflow:

https://stackoverflow.com/questions/9058341/how-can-i-send-the-form-data-from-a-native-jquery-mobile-app-to-a-remote-server

https://stackoverflow.com/questions/6690571/phonegap-choose-image-from-gallery

答:
I think the closest you'll get to a "convenient and effective approach" that works on as many platforms as possible will be a pure web app. HTML5 allows web-based apps to run even without a connection and store data offline. It looks like these features are supported on Blackberry and Symbian.

That said, your focus on BB and Symbian makes the problem much more difficult that it would be otherwise. Compared to iOS and Android, the number of developers working on those platforms is quite small. Sticking to a pure HTML5 approach could help here by minimizing the amount of platform-specific knowledge you'll need, but I think it's still going to be a difficult path. Instead of looking at what's popular right now, think about what the mobile market will look like between the time the app becomes available (say, 6 months or more from now) and over whatever period of time you plan to support the app (several years, at least). Also, consider your target demographic -- for example, it may be that pilots are more likely to carry an Android or iOS device, especially considering that there are a number of existing aviation-related apps available for those platforms.

OwnerDisplayName: Arnold de Jager


问:
OOP - Separate Manager class
I have started using OOP in PHP recently. For every model, I create two classes. One class for read operations and another Manager class for all the create / update / delete operations. For example,

```<code><?php
// This is a sample class, just to convey the idea
class Image {
    public static function loadById() {}
    public static function loadByName() {}
    public static function search() {}

    public function __construct () {}
    public function __get () {}
    public function getData() {}
    public function getRating() {}
    public function getSimilar() {}
    public function getRelatedNews() {}
}

class ImageManager extends Image {
    public function __construct() {}
    public function __set() {}
    public function remove() {}
    public function update() {}
    public function save() {}
    private function updateSomethingElse() {}
}
?>
</code>```

The reason I separated this into two classes was that I thought it was a bit more secure, since it did not expose the C/U/D methods to a normal user. Also, I thought this might be faster / memory efficient since I am loading only the smaller class for 95% of the requests. But now I think these reasons are too insignificant for maintaining two files.

Is this a bad practice? Normally, the Manager classes are loaded only during admin operations. User actions rarely update the database (except maybe during a rating operation, or a cron job for updating view count). Should I combine both the classes into the Image class?

答:
This looks a bit like a DCI architecture. So similar structuring is used by some people . It has some advantages related to security and having to "maintain" more files is often enough the better thing compared to a single file with lots of functions. I split them sometimes just for that reason.

Though I wouldn't expect much for speed or memory. Your framework or whatever you use should cache your project in memory anyway and loading a single image is most likely using more memory and taking more time than those few bytes.

OwnerDisplayName: Joyce Babu

Title: OOP - Separate Manager class


问:
How to motivate co-workers to write unit-tests?
We're working on a large product which has been in production for about 5 years. The codebase is.. erm.. working. Not really well but it is working. New features are thrown into production and tested with a small QA. Bugs are fixed, etc. But no one, except me, is writing unit-tests. No one uses the power of "tracking" down bugs by writing unit tests to ensure this special bug (test case) would never, ever occur again.

I've talked to management. I've talked to developers. I've talked to everyone in the whole company. Everybody says: "Yep, we must write more unit-tests!" That was about a year ago. Since then I have forced introduction of pre-commit code review (Gerrit) and continuous integration (Jenkins).

I held some meetings about unit-tests and I also showed the benefits of writing unit-tests. But no one seems to be interested.

Q1: How do I motivate my fellow co-workers to write unit-tests?

Q2: How do I stay motivated to follow my personal code quality standards? (Sometimes it' s really frustrating!)

PS:
Some frustrating facts (reached in 1 year):

Total unit-tests: 1693

Total "example unit-tests": around 50

Done by me: 1521

Edit: Am I expecting too much? Its my first working place and I'm trying to do my best.

Edit 2: Based upon all answers I've made a small checklist for myself. I've talked to two developer in private and we had a good and honest talk.

One of them told me, like Telastyn said, that he is really uncomfortable with unit-tests. He said that he would like to be "more professional" but he needs a kickstart.   He also said that our unit-test meeting with all developers (around 9-11) was good, but it was too crowdy. Meh. Some critics for me, but I'll learn from that. (see answers below concering tdd kata meetings!)

The other one said that he is not interested in writing unit-tests. He thinks that his work is good enough for his salary. He don't want to put more effort in. I was quite speechless. Typical 9-5 "worker".

Next week I'm going to talk to the other developers.

Thanks for your great answers (so far!) and your support. I really appreciate it! I'ved learned a lot, thank you very much!

答:
I've used a few techniques:

a) set up an automated build. When someone breaks something that you tested, show them how the test detected it and how bad the bug would have been.

b) Do complex projects with tests (you drive). This will show how few bugs exist in that project. I had one complex server interaction project that started working flawlessly. It never failed QA and all integration tests went 100% smoothly. That system became known as highly stable and overall management was happy with it. What you do in these situations is present how unit testing enabled that.

c) Pull in one person at a time. The one who listens to you. Take on bugs and show how tests expose deep and difficult problems. This helps. It's never an easy thing. But once you get a fan, he will only help. It's a domino effect.


答:
My two cents. It is a good idea to separate "executors" from "targets of executions" in general. This is the main idea of the MVC paradigm, and perfectly summarized by the Single responsibility principle in object oriented programming (for the other "laws" see here).

In your case though, you are not really doing that. Your ImageManager doesn't really have the only responsibility of C/U/D your Image(s). It also gets the rating, gets the similar (images saved somewhere?) and (I believe) stores the image data. That is because it inherits Image (I think I've just heard something :D).

What I would do, which is more verbose but much more modular, flexible and SOLID, would be to store all my data in an ImageStorage class and then have many *Managers which accept an ImageStorage (or array of them) as input and perform their operations on it (them).

However, your first thought is correct (imho), not bad pratice at all. You should expand this idea and start writing OO code this way.

Title: OOP - Separate Manager class

Body:
I have started using OOP in PHP recently. For every model, I create two classes. One class for read operations and another Manager class for all the create / update / delete operations. For example,

```<code><?php
// This is a sample class, just to convey the idea
class Image {
    public static function loadById() {}
    public static function loadByName() {}
    public static function search() {}

    public function __construct () {}
    public function __get () {}
    public function getData() {}
    public function getRating() {}
    public function getSimilar() {}
    public function getRelatedNews() {}
}

class ImageManager extends Image {
    public function __construct() {}
    public function __set() {}
    public function remove() {}
    public function update() {}
    public function save() {}
    private function updateSomethingElse() {}
}
?>
</code>```

The reason I separated this into two classes was that I thought it was a bit more secure, since it did not expose the C/U/D methods to a normal user. Also, I thought this might be faster / memory efficient since I am loading only the smaller class for 95% of the requests. But now I think these reasons are too insignificant for maintaining two files.

Is this a bad practice? Normally, the Manager classes are loaded only during admin operations. User actions rarely update the database (except maybe during a rating operation, or a cron job for updating view count). Should I combine both the classes into the Image class?


问:
What functionality does WebStorm contain which RubyMine does not?
I am looking at buying Rubymine as I am doing a small amount of ruby, but a large amount of html5/javascript.

I was going to get Webstorm as I do have a lot of pure html5/js based frameworks/apps that I am working on, however I then read that WebStorm/PhpStorm/Rubymine etc are all based on their IDEA framework, and made out like each framework contained the functionality of WebStorm anyway, other than a few features which were not there out of the box but could be added through plugins.

The main features that interest me about WebStorm are:

JS Unit testing from IDE

JS Lint/Hint coverage within UI

DOM/JS Refactoring/Intellisense

Coffeescript support

SVN/Git integration

FTP and remote sync (although not as important as the rest)

So given the above, would Rubymine provide the above functionality too? as I would rather have 1 IDE which I can do both in, than having 2 IDEs which have a lot of overlapping functionality.

Is there any specific functionality which is ONLY within Webstorm but not in any of the other IDEs?

答:
They aren't in sync, and it's very disappointing.

I read something like this saying 'RubyMine' has everything as Webstorm, so I buy it.  Then Webstorm comes out with 6.0 with many new features not in Rubymine.

Then the only answer you get when you ask is 'some' will be made as plugins.

Very vague - no dates, no list of what plugin's, etc... is a confusing guessing game.

So far very disjointed - and no official announcements or details.


问:
Better OOP in Javascript - multiple methods or methods with options?
Let's say I have an object like this:

```<code>function Foo() {
  this.parser = new DataParser();
};
</code>```

Within Foo I have a method that does something like this:

```<code>Foo.prototype.getResponse = function(message, callback) {
  var payload = {data: message, type: 'normal'};
  var response = this.parser.parse(payload, function(data){
    callback(data);
  });
}
</code>```

Now, let's say that somewhere else I need to call foo.getResponse(). Most of the time I want it to run just like this, but on occasion I need the format of the payload to be slightly different - let's say I need to specify a different type.

Would it be better to make a different method for this slightly different kind of request, like so...

```<code>Foo.prototype.getSimilarResponse = function(message, callback) {
  var payload = {data: message, type: 'other'};
  var response = this.parser.parse(payload, function(data){
    callback(data);
  });
}
</code>```

... or to take an option on getReponse, like so...

```<code>Foo.prototype.getSimilarResponse = function(message, type, callback) {
  var payload = {data: message, type: type};
  var response = this.parser.parse(payload, function(data){
    callback(data);
  });
}
</code>```

... or to do something else entirely?

Using a type option in the example above is a lot more DRY, but I don't like the way it requires the caller to know about payload type, which is really the concern of Foo and doesn't need to be exposed anywhere else.

How would you recommend approaching a situation like the above?

答:
I would recommend to pass the type argument 'optionally' so you'd get a function like:

```<code>Foo.prototype.getSimilarResponse = function(message, type, callback) {
  if (typeof(type) === 'function') {
    callback = type;
    type = 'normal';
  }

  var payload = {data: message, type: type};
  var response = this.parser.parse(payload, function(data){
    callback(data);
  });
}
</code>```

That way, your code is DRY and you don't have to worry about the type if you don't want/need to.

Body:
I would recommend to pass the type argument 'optionally' so you'd get a function like:

Foo.prototype.getSimilarResponse = function(message, type, callback) {
  if (typeof(type) === 'function') {
    callback = type;
    type = 'normal';
  }

  var payload = {data: message, type: type};
  var response = this.parser.parse(payload, function(data){
    callback(data);
  });
}

That way, your code is DRY and you don't have to worry about the type if you don't want/need to.


问:
Is using `continue`, `break` in non-`switch` loops and `?:` bad practice?
Back in college I've been told that using break; and continue; outside switch statements (e.g. to escape for or while loops) is wrong, bad practice and bad habits at the same time because it only means that you cannot write loops properly. Is it really?

A friend of mine also told me that using conditional ?: is bad practice too, however I've started using this more often because it allows me to write stuff in less than 70 lines of code while without it i'd end up with something like 200 lines of code. It comes in very useful in almost every project I work on and I use it quite often. Should I stop?

答:
On break and continue

I don't think there's anything fundamentally wrong with a break or continue. I think the motivation to avoid them is really has to do more with readability than anything else. Consider the following loops (not strictly c/c++ code):

```<code>// loop 1
for(int i = 0; i < a.length; i++)
{
    if (!found(a[i]))
        continue;

    result = a[i];
    break;
}

// loop 2
for(int i = 0; i < a.length; i++)
{
    if (found(a[i]))
    {
        result = a[i];
        break;
    }
}

// loop 3
{
    bool resultFound = false;
    for(int i = 0; !resultFound && i < a.length; i++)
    {
        if (found(a[i]))
        {
            result = a[i];
            resultFound = true;
        }
    }
}
</code>```

All three of these loops run essentially the same code, but are written in slightly different ways. The real question is which one most effective conveys the author's intent?

loop 1 - very bad. The logic here seems to be inverted, and the continue is pretty much gratuitous. If translated to English this would read something like:

Loop through the list while the item is not found, but if it is set the result then stop.

loop 2 - good. This is how such loops are generally written. If translated to English this would read something like:

Loop through the list and if the item is found, set the result then stop.

loop 3 - slightly bad. The break / continue logic is found in the condition of the for
loop, which is not as common. It means if someone reading your code wants to know what
will happen next, they have to go back to the top of the loop. A break (as in loop 2)
specifies that logic in exactly one place. If translated to English this would read something like:

Loop through the list while the item is not found and if an item is found, set the result.

On the ?: operator

Again, there's nothing fundamentally wrong with it. It's really a matter of personal style and readability.

```<code>// Good uses of conditional operator
string result = (someBool) ? "YES" : "NO";
string oddness = (someInt % 2 == 0) ? "even" : "odd";

// Bad use of conditional operator
int result = ConditionA() ? (ConditionB() ? 0 : 1) : (ConditionC() ? 2 : 3);
</code>```

Again the programmers intent is pretty clear in the first two examples, but is much more obscured in the last.

Body:
On break and continue

I don't think there's anything fundamentally wrong with a break or continue. I think the motivation to avoid them is really has to do more with readability than anything else. Consider the following loops (not strictly c/c++ code):

// loop 1
for(int i = 0; i < a.length; i++)
{
    if (!found(a[i]))
        continue;

    result = a[i];
    break;
}

// loop 2
for(int i = 0; i < a.length; i++)
{
    if (found(a[i]))
    {
        result = a[i];
        break;
    }
}

// loop 3
{
    bool resultFound = false;
    for(int i = 0; !resultFound && i < a.length; i++)
    {
        if (found(a[i]))
        {
            result = a[i];
            resultFound = true;
        }
    }
}

All three of these loops run essentially the same code, but are written in slightly different ways. The real question is which one most effective conveys the author's intent?

loop 1 - very bad. The logic here seems to be inverted, and the continue is pretty much gratuitous. If translated to English this would read something like:

Loop through the list while the item is not found, but if it is set the result then stop.

loop 2 - good. This is how such loops are generally written. If translated to English this would read something like:

Loop through the list and if the item is found, set the result then stop.

loop 3 - slightly bad. The break / continue logic is found in the condition of the for
loop, which is not as common. It means if someone reading your code wants to know what
will happen next, they have to go back to the top of the loop. A break (as in loop 2)
specifies that logic in exactly one place. If translated to English this would read something like:

Loop through the list while the item is not found and if an item is found, set the result.

On the ?: operator

Again, there's nothing fundamentally wrong with it. It's really a matter of personal style and readability.

// Good uses of conditional operator
string result = (someBool) ? "YES" : "NO";
string oddness = (someInt % 2 == 0) ? "even" : "odd";

// Bad use of conditional operator
int result = ConditionA() ? (ConditionB() ? 0 : 1) : (ConditionC() ? 2 : 3);

Again the programmers intent is pretty clear in the first two examples, but is much more obscured in the last.


答:
break and continue are perfectly fine, there are many programs that will be hard to express without them. The only time using them become a problem is if you want to formally prove correctness. In most real life code, correctness are ensured using unit test, not formal proof. Nevertheless, if a loop can be just as easily expressed without break and continue, don't use them unnecessarily.

Using ?: is actually a good practice. Good practice for ?: though, is that all expressions (i.e. conditional part, true part, and false part) should have no side effect except for their return value. If the expression contains side effect, you might want to use conventional if-block statement instead. This is a case of command-query separation, command that have side effect should use if-block while queries that are side-effect-free should use :?, this is a guideline though, not a hard and fast rule, sometimes complicated queries might be better expressed using if-block.

Title: Is using `continue`, `break` in non-`switch` loops and `?:` bad practice?

Body:
Back in college I've been told that using break; and continue; outside switch statements (e.g. to escape for or while loops) is wrong, bad practice and bad habits at the same time because it only means that you cannot write loops properly. Is it really?

A friend of mine also told me that using conditional ?: is bad practice too, however I've started using this more often because it allows me to write stuff in less than 70 lines of code while without it i'd end up with something like 200 lines of code. It comes in very useful in almost every project I work on and I use it quite often. Should I stop?


答:
It is just a tool of programmers. No tool is bad or good by itself, it is on the user how efficiently he/she can use that tool and what he can produce with that.

It becomes necessary when you want to write optimized codes and when there is no sense to keep going further into the loops

Very common example to use break statement is into the Bubble sort algorithm. When make a check that if no swap is done into the loop stop further looping as the array is already sorted out.

Same time it is bad when it is used badly into nested loops and you embed into too much nested loops that you forgot the flow and highly chances are that you can get logical errors into your code.

? :  ---is a way to write code. Just a short hand, also is a tool and depends where you use it. Can reduce lines of code on some places and on the same time can reduce the code readability.


答:
If you want to set this up as a community open source project, and you just need to start with a prototype, I'd actually argue it doesn't matter to much to start with.

Eg. If you have an Android app and a published good API and server platform, when the project starts to take off you'll probably find someone to do an iPhone app, either natively or in a cross platform framework.

Also, you could start by looking at http://www.ushahidi.com or http://www.fixmystreet.com and see if those open source platforms could be a base for you to build on. They both have many open source client apps you could use.

Title: Approach to submitting forms from a multi-platform native/hybrid app with unstable internet connection

Body:
Sorry for the long question, but I want to be sure to define my problem clearly.

For my thesis (in aerospace engineering, so not much programming experience) I want to develop a (prototype) mobile application which will facilitate the reporting of safety related events in African aviation. Although the content of my thesis focuses on the more technical and sociological aspects of safety (management) I decided to include some practical design for demonstrative purposes.

Considering the criteria I will present below, my first guess is to develop a mobile app using PhoneGap or something similar. But life can't be that simple, so I'll need more than just this single framework. My question to you is, what a convenient and effective approach would be to satisfy the following description?

Quite simply this is what I envision (in layman's terms):

A user (pilot, ground crew, etc.) experiences or notices a safety related event

The user fills out a form (Air Safety Report) about the event on his/her phone

Additional information (pictures/videos) are attached

Once a stable internet connection comes available (we're in Africa) the report/form is submitted to a server.

Important considerations here are:

The limited availability of internet -> I need a native/self-contained solution/app so the reporter does not have wait with reporting, and which stores data and submits once possible.

I don't want - nor should - exclude potential users (for multiple reasons) -> The app should be available on as many platforms as possible (especially BlackBerry and Symbian are still very popular in Africa!).

I am doing this as a form of development aid and want it to be cheaply available -> open source preferably.

Altogether, the following criteria can be defined: It should

be open-source

support multiple-platforms

allow file attachments (pictures mainly)

be self contained/native

support/allow web services

provide geolocation and date/time support (automate report whereabouts)

allow camera use for direct attachment (optional, but preferable)

identify an internet connection and submit the data once possible

store data until submission

Besides PhoneGap (which doesn't support image library browsing? -> apparently is possible, see supporting documentation), I have considered the following frameworks:

Mobl (not tested for all major platforms, no date/time support?)

QuickConnect (does not support BlackBerry and Symbian)

Rhodes (meets my requirements as for as I can see)

Appspresso (doesn't support BB and Symbian, no date picker)

I've read the following thread on stackoverflow:

https://stackoverflow.com/questions/9058341/how-can-i-send-the-form-data-from-a-native-jquery-mobile-app-to-a-remote-server

https://stackoverflow.com/questions/6690571/phonegap-choose-image-from-gallery


问:
In an interview, is it better to code a brute-force solution to a tough question, or to spend the interview examining the question carefully?
Sometimes interview questions are hard, whether the interviewer intends them to be, or not.  It can come down to a choice of whether to use the limited interview time to code up an ugly, inefficient, brute-force solution, or spend the time understanding every aspect of the problem with the interviewer.

For example, Problem 91 at Project Euler can be solved by a not-so difficult brute-force solution of calculating every possible triangle, writing an isRightTriangle() test, and popping all triangles that pass the test into a set.  But the two pair of X/Y coordinates make that an O(x^4) solution with a high constant value.  A friend and I just came up with a solution that is much more elegant and efficient, but the two of us spent 3 hours on it and drew dozens of diagrams, tested multiple formulae, examined multiple approaches, etc.

Not every interview question is fair.  Also what's easy for one person may be hard for another.  If someone struggles with a question, would you be more impressed by a brute force ugly solution that works?  Or excellent problem comprehension and in-roads toward an elegant solution, but no coded solution?  Is there a rule like after 20 minutes you should just start coding no matter what?

答: In that case inroads towards an elegant solution is better than a worse but complete solution. Both cases are good though. Its absolutely fine to have written down pusdocode demonstrating you understand the problem and how you intend to solve it even if you didn't have any time to actually code the program. </p>


答:
I'd want both, but they may display a "code that just works" in one solution and then possibly discuss potential solutions for improvement in that one or another problem.

If you ask someone to write code and they just want to talk about possible solutions with zero code, that would be a concern.

Like you said, someone may struggle with the particular problem for whatever reason, but you have to learn how they go about solving them. They could get lucky and have already heard about a solution to a similar problem. It happens.

Watch someone go about writing enough code and discussing it and you can figure-out if they're right for the job.

Title: In an interview, is it better to code a brute-force solution to a tough question, or to spend the interview examining the question carefully?

Body:
Sometimes interview questions are hard, whether the interviewer intends them to be, or not.  It can come down to a choice of whether to use the limited interview time to code up an ugly, inefficient, brute-force solution, or spend the time understanding every aspect of the problem with the interviewer.

For example, Problem 91 at Project Euler can be solved by a not-so difficult brute-force solution of calculating every possible triangle, writing an isRightTriangle() test, and popping all triangles that pass the test into a set.  But the two pair of X/Y coordinates make that an O(x^4) solution with a high constant value.  A friend and I just came up with a solution that is much more elegant and efficient, but the two of us spent 3 hours on it and drew dozens of diagrams, tested multiple formulae, examined multiple approaches, etc.

Not every interview question is fair.  Also what's easy for one person may be hard for another.  If someone struggles with a question, would you be more impressed by a brute force ugly solution that works?  Or excellent problem comprehension and in-roads toward an elegant solution, but no coded solution?  Is there a rule like after 20 minutes you should just start coding no matter what?


答:
Interviewers will ask you to improve your solution anyway.

And the "brute force solution first" approach has one indisputable advantage: if you don't manage to find an ideal solution, you still have something completed to show them.


答:
break and continue are invaluable, they often make the code shorter and better readable.

Well, except when they don't. If you find yourself using them too often or multiple times in one block, it may be that you really want the loop body to be a function (i.e. "method" in the OO terminology). It's sometimes better to have a function with early returns than a block with multiple breaks and continues.

Regarding ?:, this is actually the functional cousin of the if statement. Functional programming is hip, so yes, use it. But remember, that functional code should be free of side effects, like others here said.


问:
Jumping around to work on different features when you get stuck, is it a source of project failures?
On personal projects (or work), if one gets stuck on a problem, or waiting to figure out a solution to the problem, if you jump to another section of your code, don't you think it will be a good reason your application will be buggy or worse yet never get completed?

Assuming you are not using git and code each feature to a specific branch, things can get out of hand since you have 3 different features you are working on, and you have unresolved issues in each.

So when you get done to work, you get stressed out because you have these hanging issues and half-baked code lingering about.

What's the best way to avoid this problem? (if you have it)

I'm guessing using something like git and creating a branch per feature is the safest way to avoid this bad habit.

Any other suggestions?

答:
While getting away from a problem may help you solve it, keep in mind that there is a cost to switching contexts. You should try to do so only when you are truly stuck or a mission-critical task comes up (e.g. a customer is down).

If you are constantly switching back and forth between tasks, you may end up with several half-finished features and lots of wasted time. This is why practices like kan-ban encourage you to set a work in progress limit. This way you can focus on completing, at most, only a few tasks at a time, thus increasing throughput.


答:
As a hiring manager, if I'm asking you to solve a problem with code right there in front of me, I'm not doing it so much to see the code itself (although it's important) but rather to ascertain the how and why you did what you did.  One of those things that you might do is not code, and instead interrogate me as to the aspects of the problem itself, to better solve it. That's meaningful to me, and usually more meaningful than the solution laid out there in code.  However, that is not how everyone does it, nor is what everyone wants to see (and in fact, I rarely do ask people to code in an interview setting but I do put problems on the table and we talk through them and sometimes pseudocode emerges, which is just as good for me).

You're right that not every interview question is fair, and what is easy for someone is difficult for another, in that setting and with those constraints, and that is why those interviews who understand that are typically not looking for the code solution (although, again, that does play an important role) but rather the solution process.

"Is there a rule like after 20 minutes you should just start coding no matter what?" I'd answer this by saying that within a very short time of thinking about the problem, you should at least be doing something -- asking more questions, sketching out a framework for a solution, or saying you just can't do it/don't know where to start.

If I put a hard problem in front of you and the solution you provided -- given constraints of time and what have you -- was brute force and ugly, I would then ask you a series of questions as to why that was the case, and what would change it to something more elegant: more information? more time? a different environment? Being self-aware and in touch with the why of what you've done, and what you've not done, and being able to rationally explain it, is a big gold star in my book, but those are the sorts of developers I look for.  So, "excellent problem comprehension and in-roads toward an elegant solution" would work for me, too, but not everyone.


答:
First of all, a question that takes two experienced developers three hours to elegantly optimize is a poor choice for an interview question.  If you ask it, you shouldn't expect perfect answers.

On the other hand, sometimes you learn the most about someone when you make them hit their limits.  That's why a lot of college courses ramp up the difficulty then grade on the curve.  If everyone scores 100% on each exam, you're leaving a lot of potential learning out.

My ideal candidate would probably do the complexity calculation first, say "Oh, that's only 6 million iterations, which won't take very long," then quickly write the brute force solution.  Then they would discuss approaches they could take to optimize it, without necessarily implementing them unless the interviewer asked them to.

Partly, this is because a lot of the project euler type problems that come up in the real world are one-shot problems that you need to solve once then forget about it.  I want to know that someone I hire will be able to recognize a brute force algorithm that takes 2 minutes to write and 10 minutes to run is more efficient than an algorithm that takes 3 hours to write and 10 seconds to run, if you only need to run it that one time.


答:
As a manager, If I ask you to code as a test, I am most interested in:

Whether you can write code

Your coding style

The algorithm you selected

Does the attempt indicate that you understood the problem

If I'm really hot about a specific technology, did you demonstrate that you more or less know it.

The first item may seem crazy, but you would be surprised...

Coding style -- by that I don't just mean where you put your braces, but things like:

Did you choose composition or inheritance to solve that problem?  Why?

For that value, why did you choose to use an enum vs. a string vs. an int (or whatever permutation applies)

Did you use properties, fields or get/set methods for that value?  Why?

How did you handle state in your classes?

Do you understand how inheritance, interfaces, and lambdas work?

Do you understand the parameter conventions of the language (what is by ref vs by value?)

Do you know how to write unit tests?

Here's what I really don't care about:

That it compiles (assuming that I just gave you notepad and no compiler)

That you knew by memory the order of those 2 parameters in that one function

That you can recite a SQL Server or Oracle connection string by heart

That you can code perfectly while I am standing over your shoulder watching every mistake.

In all honesty, I was never much of a fan of coding tests -- except as a tool to analyze style.