问:
How to structure a modern web application

Background

I recently developed, for two different projects, two web applications.
The two followed quite different approaches. The first one was a classic inventory application (lists of stuff to view, select, edit.. very CRUD) and was developed with Razor and ASP.NET MVC: controller accepting requests, getting a model through a Repository, building different Viewmodels out of it for view and editing, pass the Viewmodel to the view engine and render of the page.

Very direct stuff (you can almost build such an application with wizards only using ASP.NET MVC), with very little Javascript "magic" (only the minimal offered out of the box by the MVC framework, mainly for validation).

The second one was quite different: this application is basically a bunch of screens (views) through which the user can navigate back and forth, which appearance change as users input data in different places - it is basically a hub in which the user views and reviews information linked to his account(s).
I built this second application as a REST service (built with ServiceStack, and therefore following the design patterns it enforces - like Data Transfer Object) and a SPA application implemented using AngularJS. The angular application uses its (excellent) http service to get the JSON objects from the rest service, and then populate its (client side) Viewmodel (the scope). Very neat and clean; it is easy to navigate back and forth the various account information (which is visualized in many different ways: lists, graphs, ...)

It is maybe a little more difficult to code at times (authentication/authorization is a bit more difficult (you have to be careful to mimic control on client and server, for example).

Now, I am starting a third project. It is something in between: it is still a CRUD application, but it needs to be very responsive. For example, in a page, we have a complex information to enter (combo of form and list); in the list the user need to select a item from another list, but if the item is not there we want to open the "edit list items" view, let him/her insert the item, and go back to the original page... all without refresh/pushback/... You got the idea.

The question

Which is the best way to accomplish this, to develop a modern, quick, responsive web application? I have seen too many different approaches:

"control based" (jQuery) approach: build the page using your MVC framework (which will produce html, a table for example), use jQuery to "enrich" the html and make it ajax

"data based" (Angular): build the page as an html page with data bindings, a JS application, and structure the server side as a REST service, that the JS app uses to get/post data

the mix #1: part of the app is built using your MVC framework (which spits out html), part using a data-based framework (like angular). Angular scope/model is initialized using jQuery to extract the initial data out of the html DOM.

the mix #2: part of the app is built using your MVC framework (which spits out html), part using a data-based framework (like angular). In addition to html, the server writes a "script", which is JSON data, and embeds it into the page. Angular then uses it as its model to render the data visualization (client side)

the mix #3: same, but this time no embedded JSON: the server exposes a REST service that is used by Angular to retrieve the data it needs. It is essentially part generated on the server, part on the client through a secon call to get e JSON object

(more...?)

I personally find the mix #1 and #2 ugly, but I am too "new" to modern Javascript development to judge. Are they common? I see for example that one advantage of mix #1 is that you get the initial view immediately, you do not need to wait for JS to render it. And both mix #1 and #2 do only one call to the server.

So, which one is the best practice? Or which one(s) should I really avoid?
I (personally) am more comfortable with a mix of server-side generated pages and client-side JS; making a SPA completely using services was not that easy, more than one time I wished to have something generated using server-side logic, but I may be doing it wrong (that is why I am asking!)

答:
Your Question is going to return some very opinion based answers. So I am trying to answer as neutral as possible regarding which Framework or option to use.

I think every thing you pointed out is fairly modern as are all your listed technologies. jQuery and AngularJs aren't that old I guess.

Also I believe that you have already answered your own question. Let me explain my utterrance in detail :

Out of 3 mentioned practises you don't like 2, so only one mix really remains.

I personally find the mix #1 and #2 ugly

Why not just go with what you are comfortable with for now instead of relying on the opinion of other people. You seem to know what you are doing and have an open mind to new developments in your field so why worry about what other people think for now.
 Your question helped me discover something new. Thx for that. Hope that helped.

Originally a comment was just too long for it to be one.


问:
Encoding a bash script for use in Python
I am writing some code in Python which checks for the validity of a license key after polling a server. If it is valid then the Python program in turn runs some bash scripts.

How to create a combined binary of the python script (to check the license) and the bash script (which performs the task)?

Here are what I think could be the solutions but I am really not sure:

I use the encode function in python and encode the bash script file once and add combine that file and the license_checker.py file into a single binary. When the binary runs, the python code should decode the file into a temp file, run the script and delete the temp file.

Find a mechanism which wraps/embeds the bash code in the python script. I have heard of decorators but I haven't used them and do not know if they would serve the purpose.

答:
I'd use the first option; embed the bash script in a multi-line string in the Python script, then write that out and use the subprocess module to run the script:

```<code>import tempfile
import subprocess

script_one = '''\
echo "Hello world!"
echo "This is a bash script. :-)"
'''

def run_script(script):
    with tempfile.NamedTemporaryFile() as scriptfile:
        scriptfile.write(script)
        scriptfile.flush()
        subprocess.call(['/bin/bash', scriptfile.name])

run_script(script_one)
</code>```

The run_script() function takes a bash script source, writes it to a temporary file, executes it, and automatically cleans up the temporary file when done.

Demo:

```<code>$ python /tmp/scripttest.py
Hello world!
This is a bash script. :-)
</code>```

Python decorators are of no help here; there is no point in looking at those; decorators are simply Python functions that get to wrap other Python functions.

If the script is large, you could try compressing it with zlib, base64 encode it, then embed that into the Python script file; using .decode('base64') and passing the result to the zlib module first gives you a decompressed string again. The ZLIB compression reduces the size but results in binary data, always a little harder to embed without having to deal with proper escaping and line lengths. The Base64 encoding turns the binary data into multi-line ASCII-safe data again, albeit at the price of 25% more bytes:

```<code>>>> import zlib
>>> zlib.compress(script_one).encode('base64')
'eJxLTc7IV1DySM3JyVcozy/KSVFU4koFi4VkZBYrAFGiQlJicYZCcXJRZkGJnoKVrqYSFwDnexDe\n'
>>> print """script_one = '''\\\n{}'''""".format(_)
script_one = '''\
eJxLTc7IV1DySM3JyVcozy/KSVFU4koFi4VkZBYrAFGiQlJicYZCcXJRZkGJnoKVrqYSFwDnexDe
'''
</code>```

Note that for this short script sample, this increased the size, from 54 characters to 77, but for longer scripts you should see a decent size reduction.

Decompression is then as simple as zlib.decompress(script_one.decode('base64'))

ContentLicense: CC BY-SA 3.0

Body:
I'd use the first option; embed the bash script in a multi-line string in the Python script, then write that out and use the subprocess module to run the script:

import tempfile
import subprocess

script_one = '''\
echo "Hello world!"
echo "This is a bash script. :-)"
'''

def run_script(script):
    with tempfile.NamedTemporaryFile() as scriptfile:
        scriptfile.write(script)
        scriptfile.flush()
        subprocess.call(['/bin/bash', scriptfile.name])

run_script(script_one)

The run_script() function takes a bash script source, writes it to a temporary file, executes it, and automatically cleans up the temporary file when done.

Demo:

$ python /tmp/scripttest.py
Hello world!
This is a bash script. :-)

Python decorators are of no help here; there is no point in looking at those; decorators are simply Python functions that get to wrap other Python functions.

If the script is large, you could try compressing it with zlib, base64 encode it, then embed that into the Python script file; using .decode('base64') and passing the result to the zlib module first gives you a decompressed string again. The ZLIB compression reduces the size but results in binary data, always a little harder to embed without having to deal with proper escaping and line lengths. The Base64 encoding turns the binary data into multi-line ASCII-safe data again, albeit at the price of 25% more bytes:

>>> import zlib
>>> zlib.compress(script_one).encode('base64')
'eJxLTc7IV1DySM3JyVcozy/KSVFU4koFi4VkZBYrAFGiQlJicYZCcXJRZkGJnoKVrqYSFwDnexDe\n'
>>> print """script_one = '''\\\n{}'''""".format(_)
script_one = '''\
eJxLTc7IV1DySM3JyVcozy/KSVFU4koFi4VkZBYrAFGiQlJicYZCcXJRZkGJnoKVrqYSFwDnexDe
'''

Note that for this short script sample, this increased the size, from 54 characters to 77, but for longer scripts you should see a decent size reduction.

Decompression is then as simple as zlib.decompress(script_one.decode('base64'))


问:
What is this (anti?)pattern called? (or how to describe it)
The case where a source-level operator actually describes an operation to take place at some future point, thunking the real operator together with its operands.

I don't know if this has any kind of general name, or perhaps it's too low-level a design element to be thought of as a "pattern" at all, but anyway it's an element that is frequently seen in a number of situations:

If I understand correctly (not a frequent C++ user), Boost::Phoenix does this to represent its lambdas and lazy operations, e.g. overloading + to actually capture the arguments along with the real + function for their type

Parser combinators in functional languages (or something like Spirit) look like operators on data, but actually build a parser that runs later

Other EDSLs (in languages with operator overloading) seem to do this a lot, e.g. functional reactive programming libraries tend to invisibly build procedures that will do what the operation looks like it's doing right now

(Again, if I understand correctly) IO in Haskell builds an imperative computation out of pure components that is then "executed" by dark magic hidden in the language runtime, while looking like it's just executing the functions in-place

At a simpler level, Greenspunning an embedded mini-Lisp into a C program could be considered the same thing: S-expressions can be built out of calls to C functions, to be run later (this last one would probably usually be considered the antipattern case), letting you look like you're passing "a lambda" to a C function, when you're really passing interpreter data

It's obviously not an antipattern in all cases, as in some of those it's the only way to use the tool in question (doing it in C might earn one a beating though). I don't think it's "Greenspunning" or "using an EDSL" by itself, as it can be more generic and widely applicable than that. I don't think it's the Interpreter pattern, although I may not have correctly understood that one: the computation is being built directly by executing host language code (so it effectively exists at compile-time, but usually not as a first-class language construct), rather than parsed out of a string or other runtime loaded data.

In all cases, what seems to happen is that an operation looks like it's doing one thing (not necessarily very convincingly, if it's C and you need to write out Add instead of overloading +, but same idea), while actually packaging that action up for later consumption. Something like a "computation builder" pattern? But I haven't found that term in use.

I don't have a practical problem to solve here; it's just bugging me that there seems to be a common design element that I can't put a name to.

(Question originally posted at StackOverflow, moved by hand)

答:
This is called Lazy Evaluation. It is a quite common pattern. In fact, every time you use the && or || operator in a C-like language, the second operand will only be evaluated if it needs to. Likewise, in an if/then/else, only one of the branches is evaluated.

Lazy Evaluation has some interesting properties:

In the absence of side-effects, making something lazy cannot change the result of the program. It can, however, make a non-terminating program terminate. For example, if you have something like:

```<code>False && infiniteLoop
</code>```

Under eager evaluation, this will result in an infinite loop, but under lazy evaluation, this will return False.

IOW: lazy evaluation makes it possible to write programs that cannot be written with eager evaluation. Consider the famous fibonacci sequence example in Haskell:

```<code>fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
</code>```

[Which is a bad example, BTW, because it doesn't have optimal algorithmic complexity.]

With side-effects however, lazy evaluation may change the order in which side-effects occur, or they won't even occur at all.

For pure and total programs, lazy vs. eager evaluation changes nothing at all, it simply becomes an optimization choice for the compiler. (Total programs always terminate, and the only difference between eager and lazy evaluation is termination, therefore for total programs, there is no difference.)

Body:
This is called Lazy Evaluation. It is a quite common pattern. In fact, every time you use the && or || operator in a C-like language, the second operand will only be evaluated if it needs to. Likewise, in an if/then/else, only one of the branches is evaluated.

Lazy Evaluation has some interesting properties:

In the absence of side-effects, making something lazy cannot change the result of the program. It can, however, make a non-terminating program terminate. For example, if you have something like:

False && infiniteLoop

Under eager evaluation, this will result in an infinite loop, but under lazy evaluation, this will return False.

IOW: lazy evaluation makes it possible to write programs that cannot be written with eager evaluation. Consider the famous fibonacci sequence example in Haskell:

fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

[Which is a bad example, BTW, because it doesn't have optimal algorithmic complexity.]

With side-effects however, lazy evaluation may change the order in which side-effects occur, or they won't even occur at all.

For pure and total programs, lazy vs. eager evaluation changes nothing at all, it simply becomes an optimization choice for the compiler. (Total programs always terminate, and the only difference between eager and lazy evaluation is termination, therefore for total programs, there is no difference.)


问:
How to handle complex views (consisting of several parts) in MVC web application
Lets say I am writing a blog web application using MVC pattern. Typical layout for the main page of the blog application is - some kind of a post index in the main part, and aside there are some addition parts, like timeline, tag navigation panel, subscribing panel, etc. Those controls also appear on a single post view, and may appear on other views I have.

My question is - how should I handle those panels aside in my views and controllers. I see three approaches here:

Create a big viewmodel class that contains all the information
required for rendering the view s (either index or single post).
That case I could make these aside panels a partial views, and
calling them from the view being rendered passing part of that big
viewmodel. The drawback is - I will have the code filling viewmodel
spread amongst various controller method, meaning code is
duplicated. Which is quite bad.

Create another layer of view rendering. Say, the topmost layer of
rendering recives a alreay rendered parts of html, or functions
which when called outputs an html. The layer under this  "combining
partials layer" would give just partial views for each panel I want,
include main content. The drawback here - memory usage. Most modern frameworks renders htmls directly to output stream, but in this approach partial views would be rendered into string objects first - which leads to memory overhead.

Use something like "RenderAction" from asp.net mvc, which calls a
controller method from a view. I think this is a worst solution of 3
given, because it drops an MVC approach.

The question is not tied to any specific framework, I want to understand the general way of doing things like that.

UPDATE

After an answer given, I've found out that post is not clear. So reasonable update here:

Under viewmodel term I understand an object that contains all the data required to render a particular view.

All of three approaches involve building partial views with their own viewmodel. For example (using C# syntax):

```<code>class SinglePostViewModel {
  string Text {get;set;}
  string Title {get;set;}
  string Slug {get;set;}
  DateTime PublishedDate {get;set;}
  ...
}

class TagNavigationPanelViewModel {
  string TagText {get;set;}
  int PostsCount {get;set;}
}

class CalendarNavigationPanelViewModel {
  DateTime YearAndMonth {get;set;}
  int PostsCount {get;set;}
}
</code>```

My question is - how to nicely combine those partial views together.

答:
You may create a single "container" view with all three subviews - SinglePostView, TagNavigationPanelView and CalendarNavigationPanelView. You can also replace the SinglePostView with any other view a page requires. This way you need only replace the "central" (post) view for different pages with another type of view (for example list of posts) and the other views just need to be updated with the corresponding data, not replaced.

Your container view (for example MyView) should hold references to all subviews. It may have different update methods that are used to update different subview. For example - updateCalendar(CalendarNavigationPanelViewModel calendarData) or updatePost(SinglePostViewModel postData). Or even a single update(IViewModel modelData) - then you'll need to check the type of (and cast) the modelData to determine which view to update


问:
Was C designed to facilitate Object-Oriented programming?
I am trying to broaden my understanding of the history and development of object-oriented programming, and I am curious to find out
if C was designed to facilitate Object-Oriented programming? (like C++ and Objective-C definitely are) or if it was, on the contrary, simply just a clever exploitation of the language's constructs.

I cannot seem to find any sources, including K&R, where the original authors comment on this approach.

Recently I have been looking into OOP in ANSI-C, which is described in Object-Oriented Programming With ANSI-C by Axel Schreiner.

For a freely available PDF version visit http://www.cs.rit.edu/~ats/books/ooc.pdf.

A slightly different approach is used in the part of the Linux kernel dealing with file systems, visit http://lwn.net/Articles/444910/ for more info.

The common idea is to put function pointers in a struct along with fields in order to 'emulate' a class' methods and data members.

Chronology

From Wikipedia.org/wiki/Object-oriented_programming#History

Objects as a formal concept in programming were introduced in the 1960s in Simula 67

While Wikipedia.org/wiki/C_programming#K.26R_C states that

In 1978, Brian Kernighan and Dennis Ritchie published the first edition of The C Programming Language.

The chronology seem to suggests that K&R must have been well aware of OOP.

So again:

Was C designed to facilitate Object-Oriented programming?

答:
The idea of "function pointers in a struct along with fields" is a version of "modular programming", which is what came between "structured programming" and "object oriented programming"

C and Pascal were not "modular programming" languages. Pascal went to Modula, Delphi and ADA, which were, amongst other things, modular programming languges, but C never went there. Instead, C eventually jumped directly to the next step, C++, an Object Oriented language.

Many people immediately noticed that C++ was "a better C". There are a couple of reasons for that, but I think it was mostly because of the support for modular programming.

In C, the basic module/object is the File/Compilation Unit. In C++ there is language support for breaking your code up into modules (objects). You might call this OO, but if you aren't using inheritance or polymorphism, your OO is only the encapsulation everyone else had already, and nobody thought that Modula was an Object-Oriented Programming language.

You can of course do modular programming in C and ISO Pascal, but you can do OO and Generic programming in interpreted BASIC. What we mean when we say that C++ is an OO language is that the language does it for you, not that you can do it to the language.

For me, the simple point is that when doing OO in Pascal, I had to write my own vtables. It's the same in C: if you want a virtual method table, you have to maintain it yourself. So was C designed to facilitate OOP?  If it was, where at the vtables?  Cadit quaestio.

BTW, C++ is a Generic programming language as well as Modular and OO. Generic Programming has an even longer pedigree, but...


问:
What are the downfalls of MVC?
I've been using MVC/MV* since I started actually organizing my code years ago. I've been using it so long that I can't even think of any other way to structure my code and every job I've had after being an intern was MVC based.

My question is, what are the downfalls of MVC? In what cases would MVC be a bad choice for a project and what would be the (more) correct choice? When I look up MVC alternatives, nearly every result is just different types of MVC.

To narrow down the scope so this doesn't get closed, let say for web applications. I do work on the backend and front-end for different projects, so I can't say just front-end or backend.

答:
You should always remember - MVC is a UI-related pattern. If you are building a complex application you should take everything, that is not related to UI, out of MVC triplets to any other classes, subsystems or layers.

It was my biggest mistake. I spent a long time understanding that simple rule:

Do not spread a MVC pattern amongst the whole application,

Limit it to UI-related stuff only.

Always check if the code you write is logically in the correct place, meaning it logically fits into it's area of responsibility of the class you place it in. If not - move the code away as soon as you understand it.

All the patterns that you call MVC-alternatives (i.e. Model-View-Presenter,  Model-View-ViewModel) are just a way of implementing the general MVC concept.

Title: What are the downfalls of MVC?


答:
This is a question I thought about once, and since then I've had a chance to work on many, if not all, frameworks and combinations out there. Today, when I think again about how should I plan my next application, I can only think of one thing to keep in mind and that is to "keep the algorithm simple". No matter what you develop, and in whatever you code, you are, most basically, implementing some logic, some algorithm. And in my experience, application will have less bugs if your logic is very simple.

Now, in your context of web applications, understanding the nature of these kind of application, the features what you want to develop and time that you have in hand will help. So for web applications, the nature is that it has to be a client/server application. Most probably, it is storing data on server and being manipulated by a user on the other part of the world. That can be done using any framework on the server. It has to be quick and reliable at the same time. So you should add some javascript and ajax to make the commonly used functions more accessible.
Then comes the question, what features do you need? Is there going to be a lot of user data, like emails/messages/user's list and so on, then you better create a web service that is used by a javascript application (angular?) to provide nice usability. Or is it just going to be a website with company data and a little bit of user data like order history in which case, server should handle most of the logic and javascript should only provide minimal features like animation or ajax or ... (jquery?)

In the end, it's also important to keep in mind how much time you have got to invest in this application. For lesser time, you can use a content management system which will be quick to finish deploy, but for finer control on your application's features you can use a framework which will take longer time to develop and test.

Title: How to structure a modern web application

Body:
Background

I recently developed, for two different projects, two web applications.
The two followed quite different approaches. The first one was a classic inventory application (lists of stuff to view, select, edit.. very CRUD) and was developed with Razor and ASP.NET MVC: controller accepting requests, getting a model through a Repository, building different Viewmodels out of it for view and editing, pass the Viewmodel to the view engine and render of the page.

Very direct stuff (you can almost build such an application with wizards only using ASP.NET MVC), with very little Javascript "magic" (only the minimal offered out of the box by the MVC framework, mainly for validation).

The second one was quite different: this application is basically a bunch of screens (views) through which the user can navigate back and forth, which appearance change as users input data in different places - it is basically a hub in which the user views and reviews information linked to his account(s).
I built this second application as a REST service (built with ServiceStack, and therefore following the design patterns it enforces - like Data Transfer Object) and a SPA application implemented using AngularJS. The angular application uses its (excellent) http service to get the JSON objects from the rest service, and then populate its (client side) Viewmodel (the scope). Very neat and clean; it is easy to navigate back and forth the various account information (which is visualized in many different ways: lists, graphs, ...)

It is maybe a little more difficult to code at times (authentication/authorization is a bit more difficult (you have to be careful to mimic control on client and server, for example).

Now, I am starting a third project. It is something in between: it is still a CRUD application, but it needs to be very responsive. For example, in a page, we have a complex information to enter (combo of form and list); in the list the user need to select a item from another list, but if the item is not there we want to open the "edit list items" view, let him/her insert the item, and go back to the original page... all without refresh/pushback/... You got the idea.

The question

Which is the best way to accomplish this, to develop a modern, quick, responsive web application? I have seen too many different approaches:

"control based" (jQuery) approach: build the page using your MVC framework (which will produce html, a table for example), use jQuery to "enrich" the html and make it ajax

"data based" (Angular): build the page as an html page with data bindings, a JS application, and structure the server side as a REST service, that the JS app uses to get/post data

the mix #1: part of the app is built using your MVC framework (which spits out html), part using a data-based framework (like angular). Angular scope/model is initialized using jQuery to extract the initial data out of the html DOM.

the mix #2: part of the app is built using your MVC framework (which spits out html), part using a data-based framework (like angular). In addition to html, the server writes a "script", which is JSON data, and embeds it into the page. Angular then uses it as its model to render the data visualization (client side)

the mix #3: same, but this time no embedded JSON: the server exposes a REST service that is used by Angular to retrieve the data it needs. It is essentially part generated on the server, part on the client through a secon call to get e JSON object

(more...?)

I personally find the mix #1 and #2 ugly, but I am too "new" to modern Javascript development to judge. Are they common? I see for example that one advantage of mix #1 is that you get the initial view immediately, you do not need to wait for JS to render it. And both mix #1 and #2 do only one call to the server.

So, which one is the best practice? Or which one(s) should I really avoid?
I (personally) am more comfortable with a mix of server-side generated pages and client-side JS; making a SPA completely using services was not that easy, more than one time I wished to have something generated using server-side logic, but I may be doing it wrong (that is why I am asking!)


答:
The mistake a lot of people make with design patterns is seeing it works beautifully in one place and then trying to apply it everywhere.

If you've worked in one place for a while, you can almost date a piece of code by seeing what technologies/design patterns/practices were in vogue at the time e.g. singletons/dependency injection/TDD etc etc.

As for where not to use it. Well, wherever one element of the MVC triplet doesn't apply. Console applications may not implement an interface at all. Utility programs may not have a model. And arguably, if you have neither a model nor a view, you don't require a controller.

The problem is rarely with the concept - more with the implementation. No matter how good the paradigm is, take the time to see if it is a good fit for the problem in hand.

Title: What are the downfalls of MVC?

Body:
I've been using MVC/MV* since I started actually organizing my code years ago. I've been using it so long that I can't even think of any other way to structure my code and every job I've had after being an intern was MVC based.

My question is, what are the downfalls of MVC? In what cases would MVC be a bad choice for a project and what would be the (more) correct choice? When I look up MVC alternatives, nearly every result is just different types of MVC.

To narrow down the scope so this doesn't get closed, let say for web applications. I do work on the backend and front-end for different projects, so I can't say just front-end or backend.


答:
C (and also C++) started out at AT&T. Their 5ESS telephone switch was an early user of C, and it definitely uses C and OOP. The two sides of a call (Originating Party and Terminating Party objects) could exchange messages, and there was a large overlap in the set of messages used. However, it did not use the techniques you describe here. It was all hand-coded.

So, OOP dates back to the early days of C, the two techniques were combined in a single product, and K&R must have known about this. Yet they did not facilitate OOP in C as it was used at the time, in their company.

Body:
I am trying to broaden my understanding of the history and development of object-oriented programming, and I am curious to find out
if C was designed to facilitate Object-Oriented programming? (like C++ and Objective-C definitely are) or if it was, on the contrary, simply just a clever exploitation of the language's constructs.

I cannot seem to find any sources, including K&R, where the original authors comment on this approach.

Recently I have been looking into OOP in ANSI-C, which is described in Object-Oriented Programming With ANSI-C by Axel Schreiner.

For a freely available PDF version visit http://www.cs.rit.edu/~ats/books/ooc.pdf.

A slightly different approach is used in the part of the Linux kernel dealing with file systems, visit http://lwn.net/Articles/444910/ for more info.

The common idea is to put function pointers in a struct along with fields in order to 'emulate' a class' methods and data members.

Chronology

From Wikipedia.org/wiki/Object-oriented_programming#History

Objects as a formal concept in programming were introduced in the 1960s in Simula 67

While Wikipedia.org/wiki/C_programming#K.26R_C states that

In 1978, Brian Kernighan and Dennis Ritchie published the first edition of The C Programming Language.

The chronology seem to suggests that K&R must have been well aware of OOP.

So again:

Was C designed to facilitate Object-Oriented programming?


问:
Is it possible to escape the GPL by deriving the same work from multiple sources?
Suppose you have an arbitrary code base, C, possibly composed of multiple programs, none of which fall under a copyleft license.

Suppose this code, taken together, does the same job as a nice integrated program, A licensed under some copyleft license like the GPL, but that for whatever reason the GPL code is superior (faster, cleaner, less buggy, whatever).

Now suppose that for each feature in C, you find the equivalent feature in A and, through careful step-by-step refactoring, create two chains of patches that converge on a third program, B.

In other words, you can show step by step, via patches, how to derive any of the three programs from any of the others:

```<code>A <--> B <--> C
</code>```

It seems that through this procedure, you have extracted value from A and even created a derived work, but the new work doesn't necessarily resemble A, and there is a clear chain of evidence showing that B was derived from a different code base entirely.

My question is:

Would a "dialectic" implementation like this provide the same legal effect as a traditional "clean room" implementation?

Note: feel free to replace the licenses of A and C with your most and least favorite options, respectively. The question is about the process in general.

答:
Your explanation ends up proving the following:

```<code>A <-----> C
     |
     |
     V
     B
</code>```

That is to say, B is derived from both A and C. Your rights are given in the intersection both both licenses, your obligations by their union.

Body:
Your explanation ends up proving the following:

A <-----> C
     |
     |
     V
     B

That is to say, B is derived from both A and C. Your rights are given in the intersection both both licenses, your obligations by their union.


问:
Source code "prints" at release
Is there a best practice for how to document the source code you're releasing?

Currently, we have a table of the versions of the software, what SVN tag it's labeled as, what SVN rev that tag was created at and the SVN URL.

Then, our CM (Configuration Management) department wants us to include a file listing of all the source files we're including for the .zip that we provide them which is just a zip of the tag we're releasing.

I'm more fishing for ideas to update our print template, hopefully with good arguments to remove the file listing.

答: The part that I add is a hash. That's a much shorter string, and yet it depend on every character in the compiled source.</p>

Title: Source code "prints" at release


问:
Keeping track of projects
In my job I deal with several projects at the same time (and who doesn't?). Sometimes I have to make changes to a project which I dealt with half a year ago or even longer. And it's hard to recollect the details about the project. I usually look for the modification dates of the files, then I start digging into my email to find the relevant conversations. If the project is really small then it's not even in company's VCS. Sometimes it takes much longer to recollect the details of the project than to make the required change. I started using Onenote to keep track of relevant information about projects but I didn't succeed much in this, probably because I don't have a clear picture of how this knowledge base should look like.

It would be nice if I can use some automated tool which can connect relevant emails, source codes, bugs information and feature requests and time periods of different activities related to a particular project. With advanced search capabilities.

How do you keep track of this information?

答:
This isn't going to happen automagically. You've recongnized the problem; now you need to take the steps to find a solution (This question will get closed if you just want a list of possible apps.).

If the project is really small then it's not even in company's VCS.

This is the first problem. No such thing as being too small for source control.

Get away from email. All parties involved won't follow, so you'll need to transfer email from your client to some tracking app, but otherwise, requests, documents, bugs, etc. should be posted in a more central location along with your source code.

Although some apps may fit your needs better than others, it's more important to know the long-term problems you're creating by not being organized. If you think it is possible for such an app to exist, write it and make a lot of money.

Title: Keeping track of projects


答:
MVC, like any paradigm not integral to your development platform, is increased complexity.  It's drawback is that you may wind up seperating classes that should not be separate, and decreasing clarity of how tightly bound they are.  (Or, for trivial projects,even obfuscating your code.)

The alternative for the first problem is to separate out such code into independent sub-projects; the alternative for the second is un-seperated code, either at the class or file model.

Title: What are the downfalls of MVC?


答:
The problem with tools is that you have to keep them up to date somehow. Seems like you are looking for an all-in-one device suitable for every purpose. Perhaps the problem lies in time management or self organisation.

Perhaps this would help: Getting things done

For personal track keeping I use a notepad and a kalender and it works just fine for me and I have quite a few projects running parallel. All ends up being self organising in the end.

Just got to go ahead and take the time to document your progress all the time.

Title: Keeping track of projects

Body:
In my job I deal with several projects at the same time (and who doesn't?). Sometimes I have to make changes to a project which I dealt with half a year ago or even longer. And it's hard to recollect the details about the project. I usually look for the modification dates of the files, then I start digging into my email to find the relevant conversations. If the project is really small then it's not even in company's VCS. Sometimes it takes much longer to recollect the details of the project than to make the required change. I started using Onenote to keep track of relevant information about projects but I didn't succeed much in this, probably because I don't have a clear picture of how this knowledge base should look like.

It would be nice if I can use some automated tool which can connect relevant emails, source codes, bugs information and feature requests and time periods of different activities related to a particular project. With advanced search capabilities.

How do you keep track of this information?


问:
Trying to break elements which are lists in a list?
I am trying to write a program which make the following:

```<code>?- g([2,3, [22,[3],9] ,4,[5],99],X).

X= [2,3,22,[3],9 ,4,5,99]
</code>```

so it searches for lists in the given list and replace it by their elements without brackets [].

so I wrote this program:

The first block just searches for the first element in the list which is list

If there is no such element it returns [there_is_no_list].

```<code>first_list_in_the_list([],[there_is_no_list]):-!.
first_list_in_the_list([H|_],X):-is_list(H),X=H,!.
first_list_in_the_list([_|T],X):-first_list_in_the_list(T,X).
</code>```

The first block works in prolog perfectly.

The second block just search in the list for an element X and then split the  list into a two lists one is the list of all elements before X and the second   is the elements after X.

```<code>splite_when_find_element([H|T],H,[],T):-!.
splite_when_find_element([H|T],X,F,G):-
    splite_when_find_element(T,X,F1,G),append([H],F1,F).
</code>```

it also works fine in Prolog.

and the third block is append, and it joins two list together in a new list.

```<code>append([],L,L).
append([H|T],L,[H|U1]):- append(T,L,U1).
</code>```

and the last part is:

```<code>gg(L,L):-first_list_in_the_list(L,[there_is_no_list]),!.
gg(L,U):-first_list_in_the_list(L,X),
         splite_when_find_element(L,X,F,G),gg(G,R),append(F,X,E),
         append(E,R,U).
</code>```

when I give a query [2,[3],5] I get also [2,[3],5] and I really don't understand why it does this.

答: Your logic is flawed. Your first_list_in_the_list function looks for an empty list or a list with more than one element. The one element list gets ignored.</p>


答:
A lot depends on your definition of "release".

In the military-industrial complex, a release is described by a Version Description Document.  It contains, among other things, a complete list of all files that go into the release, with the exact version number for each file (from whatever CM system), a complete list of all tools needed to recreate the release from the distribution media, and the procedures for (a) recreating the released software using exactly those tools and the distribution media and (b) loading the recreated release onto the hardware.  Ideally, those procedures should be "Heathkit manuals": step-by-step procedures, that have been carefully tested by people who do NOT normally do those things, but I've seen a lot of sloppy work in this department (and at least once been told to sit down and shut up when I pointed out a VDD procedure that was incorrect).

I'm sure I've overlooked something.  Google "Version Description Document" for more information.

Title: Source code "prints" at release

Body:
Is there a best practice for how to document the source code you're releasing?

Currently, we have a table of the versions of the software, what SVN tag it's labeled as, what SVN rev that tag was created at and the SVN URL.

Then, our CM (Configuration Management) department wants us to include a file listing of all the source files we're including for the .zip that we provide them which is just a zip of the tag we're releasing.

I'm more fishing for ideas to update our print template, hopefully with good arguments to remove the file listing.


答:
You should talk about getting a place for small projects in your company's VCS, but at the very least you can put it under local git control.  I've been known to put sample code I'm working on for 5 minutes for a StackExchange question under git source control.  The effort really is negligible.

As far as related documentation, I keep that in a backed up folder with the name of the project on it.  I just throw design documents, emails, datasheets, helper scripts, links to web pages, and notes all in one folder.  If it gets too messy, I make subfolders.

I've tried purpose built organization solutions before, but always come back to folders, because of its simplicity and availability.

Title: Keeping track of projects


问:
When comparing floats, what do you call the threshold of difference?
I'm comparing floats in Java right now and the simplest formula is:

```<code>Math.abs(a - b) < THRESHOLD
</code>```

When naming your variable for the threshold of difference, should you name it delta or epsilon? Specifically, which of the two is the correct term for the smallest value that a floating-point number can represent?

Is the term programming language specific, or is it universal across languages?

答:
I would call it "tolerance".

Maybe that is not the mathematically correct term, but the mere fact that you ask the question implies to me that neither "delta" nor "epsilon" would be a good variable name to use.

In my experience, it is better to use identifier names that makes sense to those who will actually read the code. What good is a perfectly correct name if it means that the reader needs to look it up on Wikipedia to understand what it means?


问:
When making responsive design how many versions of account for?
I am learning how to make responsive layouts for sites and web applications.  It's said we need to use media queries to find out the width(resolution) and then select the layout(wireframe) for that screen.

I would like to know how many layouts(wireframe) should I make for?

Please advice as per your experience.

For example:

960x

480x

800x

答:
You should not focus on how many layouts there should be but try to focus on what your website will look like.

Let's say you build a full-scale site and notice that if you render it under 800px, it isn't user friendly any more. Then you need to create a responsive layout for that size.

Then again, downsizing to maybe about 400px, it starts looking crowded. Build another media query.

As you see, it all comes down to content. Never try to think in the direction of devices. Always content.


问:
Reference Passing Style Anti Pattern
I'm working on a legacy VB.Net code base. There are very few functions that return values, most of the code is in subs/void methods. The general strategy seems to be to pass everything in by reference, mutate it, and then observe the mutated state.

There are some methods that have as many as a dozen parameters that are mutated in this fashion.

I find it very difficult to reason about the code written in this way. It's also rather difficult to write tests to aid in refactoring.

I'd like to know if there's a name for this, mainly in the hopes that I can find better ways of moving the application towards a better structure.

EDIT

I probably should have mentioned that calls tend to be limited to within their own multi-thousand line class files.

Based on the answer below it looks like I need to use extract method to make the methods have meaningful names and to deal with the optional parameters. Once I've done this I can start using extract class to separate out functional unit.

Fun times.

答:
Sounds like Data Envy, where a routine mostly or completely uses a different object.

What you should do is move the routine to the class whose data is being changed.

If you have long routines that take a dozen parameters, you may need to extract the method before moving it.

Title: Reference Passing Style Anti Pattern


问:
Running SQL Server Express on Micro/Extra Small VM
I'm exploring options for running a small cloud Windows Server (either AWS EC2 Micro or Azure Extra Small).

The server won't be hit very hard, but I need to run a simple relational database, which I'm expecting to be moderately sized - probably a few tables with a few hundred thousand records, and running a few thousand queries a day to aggregate the data. I'm most familiar with SQL Server, so I'm looking into using SQL Express. However, the system specs are well below the recommended values for SQL 2012 Express. 2008 is a little better, but still not great.

Anyone have experience (good or bad) with running SQL Server Express on one of these servers? I'll definitely do some testing before making a decision, but with the inconsistency that comes with these shared computing solutions, I can't be confident after just one or two testing sessions, so anecdotal evidence would be great.

If SQL Server doesn't work well, I'll be looking into other solutions - it seems Postgres works well in a wimpy server, or maybe MySQL or one of its forks, or possibly cloud database hosting like Azure SQL Databases.

答:
In my experience, Amazon doesn't seem to expect Micro instances to be used for much of anything other than trying out AWS or hosting an app while still in development. For a database you'll actually be using, you should at least get a Small instance, in my opinion.

That said, if I were you I'd use RDS. It's Amazon's relational database, and it frees you from having to maintain the hardware at all. You just set it up and connect to it like you would any other database. There are several database types, including SQL Server, MySQL, and Oracle. It really will make life easier for you. Amazon has some introductory information about this service that you might find helpful.


答:
I use OneNote to keep track of projects. All of my important emails pertaining to a project go into that project's folder in my OneNote notebook. (Outlook has a simple send to OneNote function for email).

Once I've put the email in OneNote, I delete it from my inbox. It helps me know what email I've dealt with, and what might need further attention. I have less than 30 messages in my inbox at any given time. The rest are either deleted as there's nothing for me to do with them, or put in OneNote as related to something I'm working on.

The great thing about OneNote is that it syncs to the cloud so it's available on all my devices. I haven't used it extensively, but I'd imagine that Evernote would be just as useful following this technique.

Title: Keeping track of projects


问:
ASP.NET tags best practices
I'm working on my first ASP.NET project and I'm torn between using asp tags (<asp:SomeElement) everywhere or use some regular HTML for simple things that need no code behind, like fixed divs, static text, etc.

I think it would be best to use ASP tags only for code behind and other dynamic stuff, whereas static elements can be in vanilla HTML, but that's assuming I won't ever need to turn them into ASP.NET in the future. Is there a best practice/recommended approach for this?

答:
Personally I'd say use HTML controls whenever possible. It makes it much easier to compare your source to the rendered markup, which is nice when you're building CSS and javascript, or when you're troubleshooting rendering issues.

If down the road you need to convert one to a server control, it's really not that bad. In some cases you can just throw a runat="server" on it, and have access to a lot of properties from the code-behind, or you can change the tag as needed (<input> to <asp:TextBox>, etc.) in just a few seconds.

Title: ASP.NET tags best practices


问:
One Scheduler vs. Many Schedulers
I've been using a single scheduler to handle all my scheduled tasks (Quartz.Net).  I'm starting to rethink how this operates because if I need to update 1 task, I have to stop the entire process, release the update, and start it back up.

My Question: Is it better to have many Windows Services running individual tasks (or groups of similar tasks) or 1 Service running all of the tasks (my current set up)?

答:
I've never used Quartz.NET, but I thought it was set up to allow you to modify job configurations simply by editing a config file and/or dropping in a new DLL, and changes would be picked up immediately.

If that's not the case, then something like that seems like a good approach to me. For example, you can have a separate DLL for each job, with a class that implements a common interface. When a job is scheduled to fire, dynamically load the DLL, use reflection to retrieve an instance of the job, and execute it. So if you need to change a job, you'd simply drop a new DLL in, and the next time it picks it up, it will be the new code.

Title: One Scheduler vs. Many Schedulers


答:
Here's my personal list, ordered by width in pixel...

320px (mobile, low cost devices)

480px (small tablet, portrait)

640px (small tablet, landscape, plus iPhone)

768px (iPad - portrait)

1024px (iPad - landscape, old PCs)

1200px (everything over this size is desktop to me)

This worked for me on many websites with no complaint from clients / users. Of course you can adapt one layout to be ok on many different sizes by making it liquid.

Title: When making responsive design how many versions of account for?

Body:
I am learning how to make responsive layouts for sites and web applications.  It's said we need to use media queries to find out the width(resolution) and then select the layout(wireframe) for that screen.

I would like to know how many layouts(wireframe) should I make for?

Please advice as per your experience.

For example:

960x

480x

800x


答:
I use nvALT. I store my notes as text files on a Dropbox account, so I can get at them from any computer or device.

I keep a note for each project with all the pertinent details. I also have an index page which is a list of links to these individual project notes. nvALT supports wiki-style linking between notes. Though nvALT's search engine is good enough that I don't really need it. Still, this lets you build up your own, free-form knowledge base very organically.

Pretty much every bit of I-might-need-this-later type information goes in nvALT now. I have about 300 notes in there now. I couldn't live without it.

Basecamp is a really useful tool for keeping project info in one place. Particularly useful, for your dilema, is you can forward emails into it (and it will automatically store any attachments from them). You can throw files at it, create text documents directly in it, create and assign todo list items, etc. It's pretty great for getting things out of email and into a central location.

Title: Keeping track of projects


问:
GWT vs JSF vs ZK vs Restful+JS
I'm planning to develop a web based ERP, which should be full-ajax and with desktop-like UI. It will be a data-entry & data-report application. For developing it I'm considering all technologies.

GWT: I saw that with GWT Designer you could create cool UIs, but databinding seems to be too complex

JSF: Netbeans no longer supports the visual web editor

ZK: supports databinding in a relatively easy way, and has got an Eclipse-based visual editor

Some people talk about REST + javascript as a winning choice

I'd like to have your opinion about what could be the right choice.

Thank you very much in advance!

答:
I am using ZK for years. It is a great framework if not the best. IMO, it is easy to learn, very productive, and, most important, has a best architecture - it puts MVC, databinding, server+client and server-push together elegantly.

On the other hand, GWT, though pure Java, actually runs at the client. GWT aims for developers that want to have 100% control of the client while don't want to learn JavaScript. Personally I don't like the idea. If I would like to have 100% control, I'll use jQuery.

Forget about JSF, unless your boss forced you. It is over-designed and last generation product.

However, it is worth to consider jQuery and other lightweight JS solution, if your project is migrated from a Website (rather than an enterprise application). If designed well, they allow you to add Ajax features to a Website less painful.

ContentLicense: CC BY-SA 2.5

Title: GWT vs JSF vs ZK vs Restful+JS

OwnerDisplayName: Bill Gloves


答:
My three cents:

If your company policy allows it, you can use bitbucket - which provides private repos for free, along with bug tracker and wiki (with markdown).

use local git repositories (as suggested by Karl Bielefeldt in his answer)

I tend to have plain text file document in projects repository, where I put general notes (for simple projects)

Basically, I think any kind of VCS would help you to solve a lot of troubles.

Title: Keeping track of projects


问:
How to document program flow so the outcome looks professional?
I have designed a simple website on paper. Now I want to produce a professional-looking document for my customer to approve.

How can I do this?

I've tried Visio, but it seems horribly overcomplicated and unsuitable for my purpose.

I could describe what I've written in words in a Word document but that'd be much harder to read and understand.

答:
I use OmniGraffle (http://www.omnigroup.com/products/omnigraffle/). Specifically, I use it for site wireframes, navigation charts, and any sort of thing I want to rough-out for myself and for clients, so I can get some buy-in from them before I'm too far down the development path. It's very nice. </p>

<p>In a pinch, I have used LucidChart (https://www.lucidchart.com/), which is quite good for a web-based, "freemium" app.  </p>

Body:
I use OmniGraffle (http://www.omnigroup.com/products/omnigraffle/). Specifically, I use it for site wireframes, navigation charts, and any sort of thing I want to rough-out for myself and for clients, so I can get some buy-in from them before I'm too far down the development path. It's very nice.

In a pinch, I have used LucidChart (https://www.lucidchart.com/), which is quite good for a web-based, "freemium" app.


答:
Technically responsive design does not depend upon resolution. A good responsive design will flow to fill the available space.

Its said we need to use media queries to find out the width(resolution) and then select the layout(wireframe) for that screen.

No, you should not target a layout to specific media resolutions. You should adjust the cascading flow of the elements as media types change, and adjust your CSS settings according to pixel density.

I would like to know how many layouts(wireframe) should I make for?

You do not design your wireframe to target specific device sizes. You adjust the size of elements in the flow of the document so that everything fits together nicely.

Once you start created fixed layouts for media types you'll run into problems.


答:
The GPL doesn't speak at all about clean rooms or reverse-engineering.

If you study source code from a GPL'd program, and use the knowledge you gain to write your own code yourself, you have not necessarily run afoul of the GPL. An infringement occurs when you use and distribute someone else's code, not when you write your own.

Of course, it must be apparent that it is your code, and not merely a parroting or mechanical transliteration of the original code. IANAL, TANSTAAFL, YMMV.

Title: Is it possible to escape the GPL by deriving the same work from multiple sources?

Body:
Suppose you have an arbitrary code base, C, possibly composed of multiple programs, none of which fall under a copyleft license.

Suppose this code, taken together, does the same job as a nice integrated program, A licensed under some copyleft license like the GPL, but that for whatever reason the GPL code is superior (faster, cleaner, less buggy, whatever).

Now suppose that for each feature in C, you find the equivalent feature in A and, through careful step-by-step refactoring, create two chains of patches that converge on a third program, B.

In other words, you can show step by step, via patches, how to derive any of the three programs from any of the others:

```<code>A <--> B <--> C
</code>```

It seems that through this procedure, you have extracted value from A and even created a derived work, but the new work doesn't necessarily resemble A, and there is a clear chain of evidence showing that B was derived from a different code base entirely.

My question is:

Would a "dialectic" implementation like this provide the same legal effect as a traditional "clean room" implementation?

Note: feel free to replace the licenses of A and C with your most and least favorite options, respectively. The question is about the process in general.


答:
At a previous job, we used Balsamiq. It has a "sketch" look, and fonts that look handwritten, so it's obvious to the client (both consciously and subconsciously) that the prototype is NOT the product. Unlike some other graphics tools, it supports linking and click-through, so your client can "use" your mockup.

Of course, one could also use Delphi, VB6, or Frontpage for quick "clickable" mockups, but the danger there is that the client will not realize (both consciously and subconsciously) that the mockup is just a mockup and not a "prototype" (that could quickly be fleshed out and put in production).

Once upon a time, when dinosaurs roamed the Earth, I once wound up "productizing" an internal test tool that someone in marketing showed to the CEO (because it had some interesting ideas for a future app). The CEO wanted it turned into a product ASAP. Shortly thereafter, we adopted a policy that all prototypes be paper and pencil. If only Balsamiq had been around back then ...

Title: How to document program flow so the outcome looks professional?

Body:
I have designed a simple website on paper. Now I want to produce a professional-looking document for my customer to approve.

How can I do this?

I've tried Visio, but it seems horribly overcomplicated and unsuitable for my purpose.

I could describe what I've written in words in a Word document but that'd be much harder to read and understand.


答:
To directly answer your question, you want to use the term epsilon.  More accurately, it's machine epsilon but common usage drops "machine" and just uses epsilon.

Looking in my local copy of float.h I see:

```<code>#define DBL_EPSILON     2.2204460492503131e-016 /* smallest such that 1.0+DBL_EPSILON != 1.0 */
#define FLT_EPSILON     1.192092896e-07F        /* smallest such that 1.0+FLT_EPSILON != 1.0 */
#define LDBL_EPSILON    DBL_EPSILON             /* smallest such that 1.0+LDBL_EPSILON != 1.0 */
</code>```

And the associated comments makes it clear that epsilon is the term you're referring to.

But we can also rely upon some other, external references to verify that epsilon is the correct term.  See here, here, here, and finally this combination of SO query tags.  I wasn't able to find a direct reference to the IEEE 754 standard to quote.

You didn't ask, but I found this reference that is very relevant to the example you provided to clarify your question.

Have a look at this blog article by Bruce Dawson of Valve on comparing floating point values for some insight as to why you don't want to use the comparison that you suggested.

There's quite a bit of information packed into that article, but this is the most relevant snipppet from there:

If comparing floats for equality is a bad idea then how about checking whether their difference is within some error bounds or epsilon value, like this:

```<code>bool isEqual = fabs(f1 – f2) <= epsilon;
</code>```

With this calculation we can express the concept of two floats being close enough that we want to consider them to be equal. But what value should we use for epsilon?

  Given our experimentation above we might be tempted to use the error in our sum, which was about 1.19e-7f. In fact, there’s even a define in float.h with that exact value, and it’s called FLT_EPSILON.

  Clearly that’s it. The header file gods have spoken and FLT_EPSILON is the one true epsilon!

  Except that that is rubbish. For numbers between 1.0 and 2.0 FLT_EPSILON represents the difference between adjacent floats. For numbers smaller than 1.0 an epsilon of FLT_EPSILON quickly becomes too large, and with small enough numbers FLT_EPSILON may be bigger than the numbers you are comparing!

Dawson goes over quite a few other considerations about the intricacies involved when comparing floats and dealing with very small values like this, so I would encourage your reading the rest of his post.

Title: When comparing floats, what do you call the threshold of difference?

Body:
I'm comparing floats in Java right now and the simplest formula is:

```<code>Math.abs(a - b) < THRESHOLD
</code>```

When naming your variable for the threshold of difference, should you name it delta or epsilon? Specifically, which of the two is the correct term for the smallest value that a floating-point number can represent?

Is the term programming language specific, or is it universal across languages?

Body:
To directly answer your question, you want to use the term epsilon.  More accurately, it's machine epsilon but common usage drops "machine" and just uses epsilon.

Looking in my local copy of float.h I see:

#define DBL_EPSILON     2.2204460492503131e-016 /* smallest such that 1.0+DBL_EPSILON != 1.0 */
#define FLT_EPSILON     1.192092896e-07F        /* smallest such that 1.0+FLT_EPSILON != 1.0 */
#define LDBL_EPSILON    DBL_EPSILON             /* smallest such that 1.0+LDBL_EPSILON != 1.0 */

And the associated comments makes it clear that epsilon is the term you're referring to.

But we can also rely upon some other, external references to verify that epsilon is the correct term.  See here, here, here, and finally this combination of SO query tags.  I wasn't able to find a direct reference to the IEEE 754 standard to quote.

You didn't ask, but I found this reference that is very relevant to the example you provided to clarify your question.

Have a look at this blog article by Bruce Dawson of Valve on comparing floating point values for some insight as to why you don't want to use the comparison that you suggested.

There's quite a bit of information packed into that article, but this is the most relevant snipppet from there:

If comparing floats for equality is a bad idea then how about checking whether their difference is within some error bounds or epsilon value, like this:

bool isEqual = fabs(f1 – f2) <= epsilon;

With this calculation we can express the concept of two floats being close enough that we want to consider them to be equal. But what value should we use for epsilon?

  Given our experimentation above we might be tempted to use the error in our sum, which was about 1.19e-7f. In fact, there’s even a define in float.h with that exact value, and it’s called FLT_EPSILON.

  Clearly that’s it. The header file gods have spoken and FLT_EPSILON is the one true epsilon!

  Except that that is rubbish. For numbers between 1.0 and 2.0 FLT_EPSILON represents the difference between adjacent floats. For numbers smaller than 1.0 an epsilon of FLT_EPSILON quickly becomes too large, and with small enough numbers FLT_EPSILON may be bigger than the numbers you are comparing!

Dawson goes over quite a few other considerations about the intricacies involved when comparing floats and dealing with very small values like this, so I would encourage your reading the rest of his post.


答:
This is an error function; absolute error is usually called ε (epsilon) or Δx for some quantity x:

ε = |expected − actual|

Δx = |x0 − x |

Relative error is sometimes called η (eta):

η = |1 − actual/expected|

For programming purposes, absoluteError and relativeError (or some abbreviations thereof) are more descriptive. If you want to assert that the error is less than a certain value, that value would simply be called a threshold or tolerance.

See:

Absolute Error at Wolfram MathWorld

Approximation Error on Wikipedia


答:
Like Jason Fried suggest in the book "Getting Real", the best thing to do is to go right from paper to HTML/CSS.

Here is a cool article on why you should adopt this practice. Since a lot of tool can generate HTML very quickly and most of designer/programmer will be faster at HTML than any other tool, why play around with gadget and not start creating the real thing right away?

It will take approximately the same amount of time and you will have something done if the project is accepted.


答:
In my opinion there are two types of MVC - pure and impure (for the lack of a better word :)

Pure MVC is what was introduced into small talk:

This was intended for personal computing/desktop applications. As you can see, the model informs the views of any updates/changes made to it. Not so with (impure) MVC.

The other (impure) MVC that's touted for web applications is more of a PAC (Presentation-abstraction-control) pattern instead of the classic MVC above. That's more of code organization and separation of concerns:

Model: Abstraction for stored data

Control: Usually what is known as the business logic layer as well as part of the application responsible for routing the HTTP requests to the corresponding business logic (aka controller)

View: Mostly view templates that format the data from the model and return it to the client. The model NEVER sends updates to the view neither does the view 'subscribe' for updates from a model. It'd be coupling nightmare. Hence it's more like PAC than true MVC.

Now, here's how a web application is usually structured:

Front-end: MVC on client using frameworks as Backbone.js etc., This is the 'true' MVC form in essence.

Back-end: Again, you do have (impure) MVC/PAC for code organization and separation of concerns

Global web app (for the web application as a whole): If you have RESTful backend that returns only JSON data, then your entire backend can be perceived as a model for the front-end client application where the View and Controller reside in essence.

So what are some disadvantages of MVC? Well, the pattern has stood the test of time so there aren't many that matter all that much other than it being a bit 'complicated'. You see, the MVC is a compound pattern - implements strategy/observer pattern and all are well arranged to form a high level pattern.

Should you use it everywhere? Maybe not. Extremely complex web applications maybe split into multiple layers! You may not be able to get away with just View/Business Logic/Data layers. The overarching framework/organization may still be MVC-ish, but only at a macroscopic level.

Here's an example where just MVC by itself maybe a bad choice: Try designing air traffic control system or a loan/mortgage processing application for a large bank - just MVC by itself would be a bad choice. You will inevitably have Event buses/message queues along with a multi-layered architecture with MVC within individual layers and possibly an overarching MVC/PAC design to keep the code base better organized.

Title: What are the downfalls of MVC?


问:
Haskell memory efficiency - which is the better approach?
We are implementing a matrix compression library based on a modified two dimensional grammar syntax. Now we have two approaches for our data types -which one will be better in case of memory usage? (we want to compress something ;)).

The grammars contain NonTerminals with exactly 4 Productions or a Terminal on the righthand side. We will need the names of Productions for equality checks and grammar minimization.

The First:

```<code>-- | Type synonym for non-terminal symbols
type NonTerminal = String

-- | Data type for the right hand side of a production
data RightHandSide = DownStep NonTerminal NonTerminal NonTerminal NonTerminal | Terminal Int

-- | Data type for a set of productions
type ProductionMap = Map NonTerminal RightHandSide

data MatrixGrammar = MatrixGrammar {
    -- the start symbol
    startSymbol :: NonTerminal,
    -- productions
    productions :: ProductionMap
    }
</code>```

Here our RightHandSide data saves only String names to determine the next productions, and what we do not know here is how Haskell saves these strings. For example the [[0, 0], [0, 0]] matrix has 2 productions:

```<code>a = Terminal 0
aString = "A"
b = DownStep aString aString aString aString
bString = "B"
productions = Map.FromList [(aString, a), (bString, b)]
</code>```

So the question here is how often is the String "A" really saved? Once in aString, 4 times in b and once in productions or just once in aString and the others just hold "cheaper" references?

The Second:

```<code>data Production = NonTerminal String Production Production Production Production
                | Terminal String Int

type ProductionMap = Map String Production
</code>```

here the term "Terminal" is a bit misleading because its actually the production that has a terminal as right hand side.
The same Matrix:

```<code>a = Terminal "A" 0
b = NonTerminal "B" a a a a
productions = Map.fromList [("A", a), ("B", b)]
</code>```

and the similar question: how often is the production a saved internally by Haskell? Possibly we will drop the names inside the productions if we don't need them, but we are not sure right now about this.

So lets say we have a grammar with about 1000 productions. Which approach will consume less memory?

Finally a question about integers in Haskell: Currently we are planning on having name as Strings. But we could easily switch to integer names because with 1000 productions we will have names with more then 4 chars (which i assume is 32 bit?). How does Haskell handle this. Is an Int always 32 Bit and Integer allocates memory that it really needs?

I also read through this: Devising test of Haskell's value/reference semantics - but I can't figure out what that exactly means for us - I'm more of a imperative java child then good functional programmer :P

答:
In Haskell, the String type is an alias for [Char], which is a regular Haskell list of Char, not a vector or array. Char is a type that holds a single Unicode character. String literals are, unless you use a language extension, values of String type.

I think you can guess from the above that String is not a very compact or otherwise efficient representation. Common alternative representations for strings include the types supplied by Data.Text and Data.ByteString.

For extra convenience, you can use -XOverloadedStrings so that you can use string literals as representations of an alternative string type, such as provided by Data.ByteString.Char8. That's probably the most space-efficient way to conveniently use strings as identifiers.

As far as Int goes, it's a fixed-width type, but there is no guarantee about how wide it is except that it must be wide enough to hold the values [-2^29 .. 2^29-1]. This suggests it's at least 32 bits, but does not rule out being 64 bits. Data.Int has some more specific types, Int8-Int64, which you can use if you need a specific width.

Edit to add information

I don't believe the semantics of Haskell specify anything about data sharing either way. You shouldn't expect two String literals, or two of any constructed data, to refer to the same 'canonical' object in memory. If you were to bind a constructed value to a new name (with let, a pattern match, etc.) both names would most likely refer to the same data, but whether they do or not is not really visible due to the immutable nature of Haskell data.

For the sake of storage efficiency, you could intern the strings, which essentially stores a canonical representation of each in a lookup table of some sort, typically a hash table. When you intern an object, you get a descriptor for it back, and you can compare those descriptors with others to see if they're the same much more cheaply than you could strings, and they're also often much smaller.

For a library that does interning, you could use https://github.com/ekmett/intern/

As for deciding which integer size to use at run-time, it's fairly easy to write code that depends on Integral or Num type classes instead of concrete numeric types. Type inference will give you the most general types it can automatically. You could then have a few different functions with types explicitly narrowed to specific numeric types that you could choose one of at runtime to do the initial setup, and thereafter all of the other polymorphic functions would work the same on any of them. E.g.:

```<code>polyConstructor :: Integral a => a -> MyType a
int16Constructor :: Int16 -> MyType Int16
int32Constructor :: Int32 -> MyType Int32

int16Constructor = polyConstructor
int32Constructor = polyConstructor
</code>```

Edit: More information about interning

If you only want to intern strings, you could create a new type that wraps a string (preferably a Text or ByteString) and a small integer together.

```<code>data InternedString = { id :: Int32, str :: Text }
instance Eq InternedString where
    {x, _ } == {y, _ }  =  x == y

intern :: MonadIO m => Text -> m InternedString
</code>```

What 'intern' does is look up the string in a weak-reference HashMap where Texts are keys and InternedStrings are values. If a match is found, 'intern' returns the value. If not, it creates a new InternedString value with the original Text and a unique integer id (which is why I included the MonadIO constraint; it could use a State monad or some unsafe operation instead to get the unique id; there are many possibilities) and stores it in the map before returning it.

Now you get a fast compare based on the integer id and only have one copy of each unique string.

Edward Kmett's intern library applies the same principle, more or less, in a much more general way so that whole structured data terms are hashed, stored uniquely, and given a fast comparison operation. It is a bit daunting and not particularly documented, but he might be willing to help if you ask; or you could just try your own string interning implementation first to see if it helps enough.

Body:
In Haskell, the String type is an alias for [Char], which is a regular Haskell list of Char, not a vector or array. Char is a type that holds a single Unicode character. String literals are, unless you use a language extension, values of String type.

I think you can guess from the above that String is not a very compact or otherwise efficient representation. Common alternative representations for strings include the types supplied by Data.Text and Data.ByteString.

For extra convenience, you can use -XOverloadedStrings so that you can use string literals as representations of an alternative string type, such as provided by Data.ByteString.Char8. That's probably the most space-efficient way to conveniently use strings as identifiers.

As far as Int goes, it's a fixed-width type, but there is no guarantee about how wide it is except that it must be wide enough to hold the values [-2^29 .. 2^29-1]. This suggests it's at least 32 bits, but does not rule out being 64 bits. Data.Int has some more specific types, Int8-Int64, which you can use if you need a specific width.

Edit to add information

I don't believe the semantics of Haskell specify anything about data sharing either way. You shouldn't expect two String literals, or two of any constructed data, to refer to the same 'canonical' object in memory. If you were to bind a constructed value to a new name (with let, a pattern match, etc.) both names would most likely refer to the same data, but whether they do or not is not really visible due to the immutable nature of Haskell data.

For the sake of storage efficiency, you could intern the strings, which essentially stores a canonical representation of each in a lookup table of some sort, typically a hash table. When you intern an object, you get a descriptor for it back, and you can compare those descriptors with others to see if they're the same much more cheaply than you could strings, and they're also often much smaller.

For a library that does interning, you could use https://github.com/ekmett/intern/

As for deciding which integer size to use at run-time, it's fairly easy to write code that depends on Integral or Num type classes instead of concrete numeric types. Type inference will give you the most general types it can automatically. You could then have a few different functions with types explicitly narrowed to specific numeric types that you could choose one of at runtime to do the initial setup, and thereafter all of the other polymorphic functions would work the same on any of them. E.g.:

polyConstructor :: Integral a => a -> MyType a
int16Constructor :: Int16 -> MyType Int16
int32Constructor :: Int32 -> MyType Int32

int16Constructor = polyConstructor
int32Constructor = polyConstructor

Edit: More information about interning

If you only want to intern strings, you could create a new type that wraps a string (preferably a Text or ByteString) and a small integer together.

data InternedString = { id :: Int32, str :: Text }
instance Eq InternedString where
    {x, _ } == {y, _ }  =  x == y

intern :: MonadIO m => Text -> m InternedString

What 'intern' does is look up the string in a weak-reference HashMap where Texts are keys and InternedStrings are values. If a match is found, 'intern' returns the value. If not, it creates a new InternedString value with the original Text and a unique integer id (which is why I included the MonadIO constraint; it could use a State monad or some unsafe operation instead to get the unique id; there are many possibilities) and stores it in the map before returning it.

Now you get a fast compare based on the integer id and only have one copy of each unique string.

Edward Kmett's intern library applies the same principle, more or less, in a much more general way so that whole structured data terms are hashed, stored uniquely, and given a fast comparison operation. It is a bit daunting and not particularly documented, but he might be willing to help if you ask; or you could just try your own string interning implementation first to see if it helps enough.


问:
Which component is responsible for updating the database schema?
We have what can be called a distributed application: One full-blown web app and a small REST service. Both must be separately deployable. Both access the same database schema (they actually share only two tables). The common functionality is encapsulated in a common artifact (a JAR file here, since it’s all Java). So far, so good.

However, I’m unsure how to handle schema changes properly. The web app uses Flyway for its schema updates, it works like a charm. But what should be the recommended procedure if one of the shared tables needs an update? Whose responsibility should the upgrade be? (At the moment it is the web app that performs all the upgrades, perhaps that’s good enough, but it worries me.)

I thought of perhaps even changing the architecture to have a separate application or service that has both web app and REST service as a client, but this would only make things difficult, not actually remove the problem.

答:
The way Flyway describes itself, it scans both the existing status of the database schema and all defined "migrations" on the class path of the program it is used in, and then automatically does the right thing. Therefore, the obvious answer is "both". Whoever happens to access the database first will perform the migration, so the other client won't have to.

(Obviously there is a possibility that both clients might access the database in an overlapping way and "steal" each other's upgrades. But this is no different from managing any normal read-write access to a shared resource - if you need transactional semantics, I assume that you already have a way of ensuring it.)


问:
How do I manage the technical debate over WCF vs. Web API?
I'm managing a team of like 15 developers now, and we are stuck at a point on choosing the technology, where the team is broken into two completely opposite teams, debating over usage of WCF vs. Web API.

Team A which supports usage of Web API, brings forward these reasons:

Web API is just the modern way of writing services (Wikipedia)

WCF is an overhead for HTTP. It's a solution for TCP, and Net Pipes, and other protocols

WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

SOAP is not as readable and handy as JSON

SOAP is an overhead for network compared to JSON (transport over HTTP)

No method overloading

Team B which supports the usage of WCF, says:

WCF supports multiple protocols (via configuration)

WCF supports distributed transactions

Many good examples and success stories exist for WCF (while Web API is still young)

Duplex is excellent for two-way communication

This debate is continuing, and I don't know what to do now. Personally, I think that we should use a tool only for its right place of usage. In other words, we'd better use Web API, if we want to expose a service over HTTP, but use WCF when it comes to TCP and Duplex.

By searching the Internet, we can't get to a solid result. Many posts exist for supporting WCF, but on the contrary we also find people complaint about it. I know that the nature of this question might sound arguable, but we need some good hints to decide. We're stuck at a point where choosing a technology by chance might make us regret it later. We want to choose with open eyes.

Our usage would be mostly for web, and we would expose our services over HTTP. In some cases (say 5 to 10 percent) we might need distributed transactions though.

What should I do now? How do I manage this debate in a constructive way?

答:
Why not walk the line with WCF Data Services? nice OData/webapi style queries and usability with the powers of WCF, and the ability to return JSON just fine. Also Wcf isn't that bad if you have a nice automatic wcf hosting code like the following:

https://github.com/ImaginaryDevelopment/MvcOdata

I'd say they aren't far separated at all, except that when we went to use WebApi on the front end and WCF data services on the middle tier, the WebApi threw up on simple things like string contains or string matching odata operators.


问:
How to formalize feature requests
I'm new to developing software and have been handling feature requests for an internal web-app I built.

Sometimes the feature requests are straight-forward and require minimal business logic for me to implement, so I talk to the person for a bit, write their requirements down, and get to work.

However, I'm starting to work on feature X where X has dark-corners of business-logic and special-case scenarios keep on popping-up because I didn't ask the right questions and/or the person I'm speaking with didn't think about mentioning it.

So I'm curious, how do professionals handle this process? Some things that I thought of are:

Require feature requests be written down with the appropriate requirements.

Understand their job well-enough so I can do mine.

An example to illustrate a similar problem is, implementing government regulations in code. I researched the regulations, created a flowchart and went from there. I could have saved a couple days had someone well-versed in said regulations, written the requirements down and handed them to me.

I'm doing the same thing for feature X, except, nothing is written down so I'm unable to deduce their business logic without going through a step-by-step process through their job. Even that fails sometimes, because some special-case wasn't present that day.

Using the above example, is it the responsibility of the developer to research this or something that should be provided?

Any suggestions for making this process go a bit smoother?

答:
It seems the question you're asking is about up-front requirements. Users can provide everything in writing and still not be clear enough for you to write any code. You can require all the contracts you want, but they'll still come back and indicate it's not what they want (Time-cost decisions are another question.).

There are some technical details that you need to do. Going back and forth on clarifying requirements isn't uncommon. In some places, there are business analysts and architects who may do a lot of this, but then the communication still needs to happen. Usually, they're more equiped to understand what you need.

The responsibility is on both parties and there is no perfect spot in the middle of the road where you two will always meet.

Title: How to formalize feature requests


答:
Our team had a similar discussion a couple of months ago. The deciding factor for us came down to how we would create and implement each technology. Since we were already building an MVC application and were using Knockout.js for data binding, we were effectively using MVVM with the controllers just being an API for data.

This allowed us to categorize our use of the technologies with this project as follows:

Web API would be used as our API for knockout and Ajax calls, making them our commands for the MVVM pattern. Our business logic for the web application is wrapped up behind this layer through a number of classes and repositories and factories.

WCF is then used for our data store, exposing data from our database for not only this website, bit also for any other site or service that consumed the exposed data.

While this might not be a popular or hyper technical response, determining what you need first and how or if the technology will help is what helped my team decide which technology to use where.

Title: How do I manage the technical debate over WCF vs. Web API?

Body:
I'm managing a team of like 15 developers now, and we are stuck at a point on choosing the technology, where the team is broken into two completely opposite teams, debating over usage of WCF vs. Web API.

Team A which supports usage of Web API, brings forward these reasons:

Web API is just the modern way of writing services (Wikipedia)

WCF is an overhead for HTTP. It's a solution for TCP, and Net Pipes, and other protocols

WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

SOAP is not as readable and handy as JSON

SOAP is an overhead for network compared to JSON (transport over HTTP)

No method overloading

Team B which supports the usage of WCF, says:

WCF supports multiple protocols (via configuration)

WCF supports distributed transactions

Many good examples and success stories exist for WCF (while Web API is still young)

Duplex is excellent for two-way communication

This debate is continuing, and I don't know what to do now. Personally, I think that we should use a tool only for its right place of usage. In other words, we'd better use Web API, if we want to expose a service over HTTP, but use WCF when it comes to TCP and Duplex.

By searching the Internet, we can't get to a solid result. Many posts exist for supporting WCF, but on the contrary we also find people complaint about it. I know that the nature of this question might sound arguable, but we need some good hints to decide. We're stuck at a point where choosing a technology by chance might make us regret it later. We want to choose with open eyes.

Our usage would be mostly for web, and we would expose our services over HTTP. In some cases (say 5 to 10 percent) we might need distributed transactions though.

What should I do now? How do I manage this debate in a constructive way?


答:
The problem you depict has no general solution. You have internal clients (I guess from your question), which are professionals in their field, but of course not specialists in formalizing requirements.

In short: it's your task as a programmer to understand the domain well enough to build software. Try to build up a glossary of terms/grasp the language your client speak. Do not expect their logic to be perfect.

Also, do not try to make requirements extraction process itself too formal. Iterative development process may help the clients to see missing pieces. Prototypes are also useful. Some clients may be stressed that you do not understand things, which are obvious (to them). Just observing their business process may give you lot of insights.

Read those regulations yourself when possible. Try to find someone, if you don't understand specific moments.

Unless your clients are technically inclined, it's futile to impose formalities (or even your "process") on them. Even worse to speak software-domain language instead of problem-domain language.

However, every situation is unique. The best thing is to gather more experience in the problem domain. Just be open-minded to understand problem-domain to the extent needed to build software. Friendly atmosphere also helps a lot. People may get tired of dull req gathering sessions.

There are some books on the topic. For example, some parts of http://www.amazon.com/Just-Enough-Requirements-Management-Development/dp/0932633641 ("Just Enough Requirements Management: Where Software Development Meets Marketing" by Alan Mark Davis) can help to understand how reqs gathering is done on larger scale. Of course, famous "Code Complete" by Steve McConnell can also give some good insights.

Even if your organization has someone, whose job is writing requirements, it may help to participate in the process to at least give earlier feedback on technical feasibility. If there is no person for that, all that is developer's responsibility.

Title: How to formalize feature requests

Body:
I'm new to developing software and have been handling feature requests for an internal web-app I built.

Sometimes the feature requests are straight-forward and require minimal business logic for me to implement, so I talk to the person for a bit, write their requirements down, and get to work.

However, I'm starting to work on feature X where X has dark-corners of business-logic and special-case scenarios keep on popping-up because I didn't ask the right questions and/or the person I'm speaking with didn't think about mentioning it.

So I'm curious, how do professionals handle this process? Some things that I thought of are:

Require feature requests be written down with the appropriate requirements.

Understand their job well-enough so I can do mine.

An example to illustrate a similar problem is, implementing government regulations in code. I researched the regulations, created a flowchart and went from there. I could have saved a couple days had someone well-versed in said regulations, written the requirements down and handed them to me.

I'm doing the same thing for feature X, except, nothing is written down so I'm unable to deduce their business logic without going through a step-by-step process through their job. Even that fails sometimes, because some special-case wasn't present that day.

Using the above example, is it the responsibility of the developer to research this or something that should be provided?

Any suggestions for making this process go a bit smoother?


问:
I feel lost among the various web technologies and I'm looking for pointers
In the last 3-5 months I was thinking about which web programming language I should use. PHP? Ruby? C#? Python? Perl? And you know what? Every time I keep changing my mind like crazy! I learn some things about each one of them and then move to another.  Now I'm totally lost, totally lost guys. :)

What I want form you is to help me to decide, not to decide for me, and give me some recommendations. It would be more than helpful if you can tell me a short story about yourself, how you got started, where you are now and what web programming technologies you are using.

答:
I got into programming on the DECSystem-10 in Fortran IV and Macro-11 at Worcester Tech in 1974, though I was actually writing programs in BASIC back in 1968 but didn't have access to a computer to run them on. Assembly language was my language of choice on multiple platforms, but I got hooked on Perl4 as a scripting language in the late 80's/early 90's. When Perl5 added classes, I ignored them. I was already using Java by that time too, and Java's classes were much more cleanly implemented, since it had them from the beginning.

I was using PHP primarily for its graphics capabilities in the late 90's, making bandwidth charts of the routers and switches at the Internet company I worked for. It also had SQL integration working well much earlier than other scripting languages. But when I met ESR at a Unix user's group meeting sometime arount 2000, he convinced me to switch to Python. I dropped Perl almost immediately, with gratitude. And over the years, PHP has bitten the dust too, since Python has caught up and exceeded it in both graphics (with PIL) and SQL capability. PHP has become such a bloated accumulation of cruft that I would never consider any code using it to be secure. Same with modern Perl.

I'd therefore recommend C#, Ruby, or Python. Java is still very useful also, especially in the mobile arena. And its similarities to, and compatibility with, Javascript makes it quite easy to learn, since if you're doing web work you need Javascript for the client-side coding.

As for what I'm doing now, it's part web coding (client-server apps using Javascript, Python, and Java), and part bioinformatics (Biopython).


答:
Your webapp directly accesses the DB? That's a bit of an anti-pattern right there and shouldn't be encouraged (for security reasons mainly), so I would try to put the DB with the another app-tier service as much as possible partly to try to encourage splitting DB access from client (or web server) access.

Otherwise, just create a new component that is "the DB" and it handles all schema changes independently of both - then neither is going to mess up the others schema changes, and both will have to get used to using this new project as a dependancy.

Title: Which component is responsible for updating the database schema?

Body:
We have what can be called a distributed application: One full-blown web app and a small REST service. Both must be separately deployable. Both access the same database schema (they actually share only two tables). The common functionality is encapsulated in a common artifact (a JAR file here, since it’s all Java). So far, so good.

However, I’m unsure how to handle schema changes properly. The web app uses Flyway for its schema updates, it works like a charm. But what should be the recommended procedure if one of the shared tables needs an update? Whose responsibility should the upgrade be? (At the moment it is the web app that performs all the upgrades, perhaps that’s good enough, but it worries me.)

I thought of perhaps even changing the architecture to have a separate application or service that has both web app and REST service as a client, but this would only make things difficult, not actually remove the problem.