问:
Is revision control fundamentally at odds with live coding?
Both live coding, and revision control, are very valuable tools when programming. But they seem to have inherently conflicting characteristics. Is it possible to fully benefit from both at the same time, or are they fundamentally incompatible?

EDIT: To those who don't bother reading the whole length of my question: please at least read the section "Both together?... Existing pseudo-solutions" so that you won't try to sell me on non-solutions that I've already listed.

What I mean by "revision control"

By revision control (a.k.a. version control) I mean mainly (quite obviously in our times) the likes of Git, Mercurial, SVN, CVS, darcs... etc., etc. But I like to think, that this category can be extended somewhat, to include conceptually simpler ideas, like: the now ubiquitous (however volatile) undo/redo; and probably also the notion of primitive "file name versioning" (like in: main.c, main-old1.c, main-old2.c), from which CVS presumably originated.

Anyway, the main premise of revision control is, that a programmer can store multiple versions of a program's source code ("snapshots" from different points in time), and quickly switch between them — "jump backwards and forwards in time". This way, one does never™ lose what he wrote.

What I mean by "live coding"

On the other hand, live coding may sound simpler as a name, but I believe it is a label which covers a much more diverse world of concepts and solutions. Probably the most well-known of them now is the read-eval-print loop, or REPL. It's present as "interactive console" in Python, Ruby, JavaScript, obviously Lisp, to name only a few. But as much as they are useful for "quick testing", in Python and the likes they are merely funny toys, when compared with systems, where REPLs were/are first-class citizens (or even the sole ones), such as IIUC: Smalltalk systems with their "images", to some extent Erlang, some Lisp systems. But then, there are other variations: e.g. Erlang has "hot swapping of modules". Or, there are attempts at editors like Light Table, experimenting with various approaches to instant feedback.

It's a bit harder for me to summarize what live coding is about, but I have to try: it's programming with instant feedback, when changes to a program are executed immediately, while performing the program's main function without serious interruptions; the programming is done in incremental way, often with much experimenting, in tight feedback loop, and in practice usually in volatile memory (RAM).

Both together?... Existing pseudo-solutions

Now, both main ideas described above are very awesome, but I've never seen them successfully combined together. I've encountered several attempts aimed at gaining from both worlds, but they were at best half baked, and often just doubling user's work, instead of reducing it. In no particular order:

Matlab's command log:

each command entered in REPL is auto-saved to a "log"/history window, from which it can be easily recalled and saved into a script file.

live coding: ☺ (REPL)

revision control: ☹ (some help via history, but then laborous manual editing and external VCS tools)

"Experiment in REPL, then copy successful snippets to editor"

live coding: ☺ (REPL)

revision control: ☹☹☹ (no help from computer; "what did I type to do this?"; at best rudimentary history with up/down arrows; generally "Left as an exercise for the reader")

"Compile and run on save"

live coding: ☹☹☹ (slow feedback, whole program is restarted and all state is lost, any inputs leading to particular state must be manually repeated on each restart)

revision control: ☺ (you have the code firmly on disk in some organized files, so you can easily put it in revision control; the current state of files is consistent and contains full and exact code of the program)

Erlang's hot-swapping of modules

also sometimes available (and working) in some RAD IDEs (for Java, C++)

live coding: ☹ (at least don't have to reset whole program and lose whole state; but much slower feedback than in REPL, very much not a tight feedback loop; also, usually supported only for changes not crossing boundaries of some small module; also, often requires the original program to be specially prepared in anticipation for hot-swapping of a particular module)

revision control: ☺ (all the benefits of normal program)

Did you ever see a solution combining advantages of both worlds, i.e. one for which I'd be able to put a smiling face in both categories? Or, do you maybe have some strong arguments why it is logically impossible?

(Also, in comments, I'd happily learn of other compromise solutions. I'd be also happy to learn if there is/was some method of recording history for Smalltalk systems, or at least objects in those systems?)

答:
I've never had any trouble using those two together. I just don't use those two simultaneously.

For example, I use Brackets for developing HTML/CSS templates - it does the same as REPL, but in a browser (page is getting re-rendered when user updates the code). I do it live until I'm done with some particular feature, and then do git add/git commit one or more times to fix the changes, when go back to live coding. When I'm lazy, I can just commit once after I'm done experimenting. I don't rollback my commit history while live coding - that just doesn't make any sense to me.

So, my answer is: don't use a hammer and a saw both at the same time. You can only hurt yourself that way.


问:
Proper Model-View-_____ design
I've been reading up about Model View Controller, Model View Presenter, Model View ViewModel, and so on, and generally, the underlying concept seems pretty simple to understand: keep the pretty visuals and sciencey guts as separate and ignorant of each other as possible. No getting the logic peanut butter in the design chocolate; cool, I like that.

The problem is I'm still a bit fuzzy as to that third part... the not-model-or-view one. Everyone seems to have their own idea of what to call it, what it should do, what's proper, what's just plain wrong... and I'm going nuts trying to figure out when a Presenter becomes a ViewModel and when a View shouldn't be doing that because that's the Presenter's job and--

I'm rambling.

Rather than asking for someone to explain the difference between them--because that's already been done time and time again (I know; I've read more articles than I can count)--I'd be curious to hear the thoughts of a few programmers on the model I've cobbled together myself.

That said, what would you classify this design as, and perhaps more importantly, do you see anything about this that obviously sucks? Sure, I'd love to hear I'm doing good if this truly is solid design, but I'd much rather be given solid advice over praise.

Note: I'll be using "the Bridge" for the mysterious third part of Model-View-? to avoid any subconscious suggestions of what it "should" be.

Model

Is the authority on data.

Receives information about requested changes from the Bridge.

Contains and performs all logic for how data relates to other data.

<s>Informs the Bridge when data changes (for data the Bridge has expressed interest in).</s> Wording edit: Allows outside subscribers (about which it knows nothing) to monitor it's state or calculation results.

Has zero knowledge of the View.

View

Is concerned with providing the user a way to view and manipulate data.

Receives information about data updates from the Bridge.

Contains and performs all logic for how to present data and controls to the user.

Informs the Bridge when the user has performed an action that (possibly) affects the Model.

Informs the Bridge what information it's interested in.

Has zero knowledge of the Model.

Bridge

Is the coordinator and translator between the Model and the View.

Makes any appropriate formatting changes to information being passed between the Model and the View.

Retains information on "who needs to know what".

Has knowledge of both the Model and the View.

Additional Notes

In more complicated programs, it's common for there to be multiple Models. In this situation, the Bridge typically takes on the job of coordinating/translating between the multiple Models, and thus becomes the authority on what protocall/API/design Models should be built to. (e.g. if building a card game program, and you want to build an alternate deck shuffling model, you should use the Bridge for determining what functions are required for properly communication with the Bridge.)

In small simple programs with only one View and Model, it's common for the Bridge to "assume" what functionality is available on either side. However, as programs become more complex, it's recommended that the View(s) and Model(s) report their functionality to the Bridge so that it can avoid inefficiencies and buggy assumptions.

I think that just about covers it. By all means, I welcome any questions you might have about the design I tend to use, and I likewise encourage any suggestions.

And as always, thank you for your time.

答:
While your suggested pattern seems correct on the surface, and will undoubtably work for small instances, as your app becomes more complex, you'll face problems where you're unsure about what updates what, who listens to where, and why am I attempting to control so many Models from within so many Views, all of who need access to eachother, etc.

I recommend extending your ideas using the following pattern (taken from Amy Palamountain's talk Enemy of the State):

Models

Sync state with the data store

Handle validation of new/updated data

Raise events when they change state

Views

Render templates

Handle Model events

Handle DOM events

Mediates the interaction between Model and DOM

Controllers

Manages at most a couple of Models & Views

Keeps track of Views within a container

Modules

The logical grouping of a Controller and its Views & Models

Testable

Small and maintainable (Single Responsibility)

Coordinates (via the Controller) the state and events of the Views & Models it contains

Free to present its own Views

Not free to choose where to present its Views

Layout Manager

Responsible for layout composition

Defines an application shell in the DOM with areas that Modules can present their content

Dispatcher

Listens to Events (via global PubSub stream)

Responsible for loading new Modules based on Events

Hands off loaded Modules to the Layout Manager

Manages entire Module lifetime (creation, clean up, cacheing, etc)

Event examples:

Route changes (including initial load route)

User Interaction

Module event bubbled from a Model event due to server-side state change, etc

Application

Responsible for overall setup, Instantiates things like:

Dispatcher

Router

PubSub stream

Loggers

etc

This kind of pattern allows your application to be composable, unit tested, removes the complexity a Bridge would build up over time, keeps concerns separated nicely, etc.

As Amy points out: Be careful not to build a server on the client. And be careful not to fall into the doctrine of "I am making an MV* framework, therefore I must ___!" Instead, take all these ideas (and the other answers here), and find what works best for your application and team.

I highly recommend watching Amy Palamountain's talk Enemy of the State (from which these ideas came), or at least to look over the slides from the talk.

ContentLicense: CC BY-SA 3.0

Title: Proper Model-View-_____ design


问:
Why is a small fixed vocabulary seen as an advantage to RESTful services?
So, a RESTful service has a fixed set of verbs in its vocabulary. A RESTful web service takes these from the HTTP methods. There are some supposed advantages to defining a fixed vocabulary, but I don't really grasp the point. Maybe someone can explain it.

Why is a fixed vocabulary as outlined by REST better than dynamically defining a vocabulary for each state? For example, object oriented programming is a popular paradigm. RPC is described to define fixed interfaces, but I don't know why people assume that RPC is limited by these contraints. We could dynamically specify the interface just as a RESTful service dynamically describes its content structure.

REST is supposed to be advantageous in that it can grow without extending the vocabulary. RESTful services grow dynamically by adding more resources. What's so wrong about extending a service by dynamically specifying a per-object vocabulary? Why don't we just use the methods that are defined on our objects as the vocabulary and have our services describe to the client what these methods are and whether or not they have side effects?

Essentially I get the feeling that the description of a server side resource structure is equivalent to the definition of a vocabulary, but we are then forced to use the limited vocabulary in which to interact with these resources.

Does a fixed vocabulary really decouple the concerns of the client from the concerns of the server? I surely have to be concerned with some configuration of the server, this is normally resource location in RESTful services. To complain at the use of a dynamic vocabulary seems unfair because we have to dynamically reason how to understand this configuration in some way anyway. A RESTful service describes the transitions you are able to make by identifying object structure through hypermedia.

I just don't understand what makes a fixed vocabulary any better than any self-describing dynamic vocabulary, which could easily work very well in an RPC-like service. Is this just a poor reasoning for the limiting vocabulary of the HTTP protocol?

Reflection

Just to clarify my thoughts a little better than I have done. Suppose you are designing any general purpose API, maybe not even web facing. Would you be happy if someone said you can only use these method names on your objects? REST isn't restricted to HTTP, but consider the situation where every API you write, web facing or otherwise simply consisted of objects containing GET POST PUT and DELETE methods. So that object.foo method you wanted to define isn't possible. You have to define a new object called foo, and call its GET method. That's essentially how REST works, and it makes me a little uncomfortable to think about it. You don't have any better generic understanding of what foo does, you were just forced to create a new object for what is essentially a method on a parent object. Furthermore your API is no less complex, you have just hidden interface complexity by creating more objects. RESTful web services force us to adopt an interface which may or may not be sufficient in the context of the API we are exposing. Perhaps there is a good reason for doing this with web facing APIs, but a good reason to not adopt standard interfaces for every object in every general purpose API. A practical example would be appreciated.

答:
Yes a rest api has a fixed set of verbs, but it doesn't have to be limited to (or include GET, POST, PUT, DELETE). I would look at the GET, POST, PUT, DELETE as a default implementation of REST that works for 80% of all the systems out there.

Other systems that are implementing more than crud operations can (and do) implement their own verbs for their REST API's. Verbs like Publish, Consume, Rate, Comment, Search, Browse can be added and implemented in a REST system. While some might say that a larger vocabulary might make it more complicated, my answer is that it depends. If your target user are tech heads who understand what a POST is then yes it could be more complicated; however, if your API's target users are real people (i.e. people who don't code and don't know what a POST is), then real verbs are much much easier to use. In fact having an appropriate set of verbs for your API helps keep the urls short (which is important if you want to have users type them in a browser. If you use a custom vocabulary, you'd want to make sure that your API and its verbs are well documented. When using a custom REST api, you'd want to ensure that your 'read only actions' as an HTTP GET and 'write actions' with POST.

The teen social network, Piczo.com, (may it rest in peace) featured an extended REST API (including the verbs mentioned above) that was implemented in 7 different languages!


答:
Version control works very well with what you describe as Live coding.  Most coding I have done is more or less what you describe as Live coding, and I would call coding.

The workflow I usually use is:

update (only needed if you are sharing code)

commit any uncommitted changes

code and test (you can use step-wise refinement to add full functionality)

commit changes (try to avoid committing broken code, although committing working but incomplete changes is desirable)

Version control provides a lot of benefits. A few of the key benefits:

You can really delete code when you don't need it now.  (You can retrieve the changes from revision control.)

Git allows you to stash work in progress if you need to deal with a different issue.  Other tools allow you similar but more public functionality.

You can review changes to determine where a bug was introduced.

The risk of experimenting is significantly reduced.  You can always revert back to the code before you started the experiment.

It is easier to maintain production and development versions of code.

For a number of reasons, you need to be able to save the code you are working on.  I have picked up the pieces from people who code and save snippets.  The problem is they kind of work, but you need to re-edit them before you can use them.   If you aren't interested in replicating your results, version control and artifacts you can version control don't matter.   Coding from a recall buffer isn't readily reusable.  Getting the code into a script that can be version controlled is key.

One thing I learned early is that there is little code that can be done as a one-off.  Live coding as you describe it seems like one-off coding.

Title: Is revision control fundamentally at odds with live coding?

Body:
Both live coding, and revision control, are very valuable tools when programming. But they seem to have inherently conflicting characteristics. Is it possible to fully benefit from both at the same time, or are they fundamentally incompatible?

EDIT: To those who don't bother reading the whole length of my question: please at least read the section "Both together?... Existing pseudo-solutions" so that you won't try to sell me on non-solutions that I've already listed.

What I mean by "revision control"

By revision control (a.k.a. version control) I mean mainly (quite obviously in our times) the likes of Git, Mercurial, SVN, CVS, darcs... etc., etc. But I like to think, that this category can be extended somewhat, to include conceptually simpler ideas, like: the now ubiquitous (however volatile) undo/redo; and probably also the notion of primitive "file name versioning" (like in: main.c, main-old1.c, main-old2.c), from which CVS presumably originated.

Anyway, the main premise of revision control is, that a programmer can store multiple versions of a program's source code ("snapshots" from different points in time), and quickly switch between them — "jump backwards and forwards in time". This way, one does never™ lose what he wrote.

What I mean by "live coding"

On the other hand, live coding may sound simpler as a name, but I believe it is a label which covers a much more diverse world of concepts and solutions. Probably the most well-known of them now is the read-eval-print loop, or REPL. It's present as "interactive console" in Python, Ruby, JavaScript, obviously Lisp, to name only a few. But as much as they are useful for "quick testing", in Python and the likes they are merely funny toys, when compared with systems, where REPLs were/are first-class citizens (or even the sole ones), such as IIUC: Smalltalk systems with their "images", to some extent Erlang, some Lisp systems. But then, there are other variations: e.g. Erlang has "hot swapping of modules". Or, there are attempts at editors like Light Table, experimenting with various approaches to instant feedback.

It's a bit harder for me to summarize what live coding is about, but I have to try: it's programming with instant feedback, when changes to a program are executed immediately, while performing the program's main function without serious interruptions; the programming is done in incremental way, often with much experimenting, in tight feedback loop, and in practice usually in volatile memory (RAM).

Both together?... Existing pseudo-solutions

Now, both main ideas described above are very awesome, but I've never seen them successfully combined together. I've encountered several attempts aimed at gaining from both worlds, but they were at best half baked, and often just doubling user's work, instead of reducing it. In no particular order:

Matlab's command log:

each command entered in REPL is auto-saved to a "log"/history window, from which it can be easily recalled and saved into a script file.

live coding: ☺ (REPL)

revision control: ☹ (some help via history, but then laborous manual editing and external VCS tools)

"Experiment in REPL, then copy successful snippets to editor"

live coding: ☺ (REPL)

revision control: ☹☹☹ (no help from computer; "what did I type to do this?"; at best rudimentary history with up/down arrows; generally "Left as an exercise for the reader")

"Compile and run on save"

live coding: ☹☹☹ (slow feedback, whole program is restarted and all state is lost, any inputs leading to particular state must be manually repeated on each restart)

revision control: ☺ (you have the code firmly on disk in some organized files, so you can easily put it in revision control; the current state of files is consistent and contains full and exact code of the program)

Erlang's hot-swapping of modules

also sometimes available (and working) in some RAD IDEs (for Java, C++)

live coding: ☹ (at least don't have to reset whole program and lose whole state; but much slower feedback than in REPL, very much not a tight feedback loop; also, usually supported only for changes not crossing boundaries of some small module; also, often requires the original program to be specially prepared in anticipation for hot-swapping of a particular module)

revision control: ☺ (all the benefits of normal program)

Did you ever see a solution combining advantages of both worlds, i.e. one for which I'd be able to put a smiling face in both categories? Or, do you maybe have some strong arguments why it is logically impossible?

(Also, in comments, I'd happily learn of other compromise solutions. I'd be also happy to learn if there is/was some method of recording history for Smalltalk systems, or at least objects in those systems?)


问:
Why do people disable JavaScript?
I asked a question yesterday Should I Bother to Develop For JavaScript Disabled?. I think the consencus is: Yes, I should develop for JavaScript Disabled. Now I just want to understand why users disable JS. It seems many developers (I guess people who answered the questions are developers) disable JS. Why is that. Why do users disable JS? For security? Speed? or what?</p>

答:
For me it all about security.  I use noscript to allow certain websites to run javascript, while disallowing most.

In the end you really never know where the danger lies (nobel web site infected on techspot.com).  Many zero-day (and other) exploits use javascipt; closing this one avenue of attack feels like a step in the right direction.

ContentLicense: CC BY-SA 2.5

Title: Why do people disable JavaScript?


问:
Is it good practice to rely on headers being included transitively?
I'm cleaning up the includes in a C++ project I'm working on, and I keep wondering whether or not I should explicitly include all headers used directly in a particular file, or whether I should only include the bare minimum.

Here's an example, Entity.hpp:

```<code>#include "RenderObject.hpp"
#include "Texture.hpp"

struct Entity {
    Texture texture;
    RenderObject render();
}
</code>```

(Let's assume that a forward declaration for RenderObject is not an option.)

Now, I know that RenderObject.hpp includes Texture.hpp - I know that because each RenderObject has a Texture member. Still, I explicitly include Texture.hpp in Entity.hpp, because I'm not sure if it's a good idea to rely on it being included in RenderObject.hpp.

So: Is it good practice or not?

答:
You should always include all headers defining any objects used in a .cpp file in that file regardless of what you know about what's in those files.  You should have include guards in all header files to make sure that including headers multiple times does not matter.

The reasons:

This makes it clear to developers who read the source exactly what the source file in question requires.  Here, someone looking at the first few lines in the file can see that you are dealing with Texture objects in this file.

This avoids issues where refactored headers cause compilation issues when they no longer require particular headers themselves.  For instance, suppose you realize that RenderObject.hpp doesn't actually need Texture.hpp itself.

A corollary is that you should never include a header in another header unless it is explicitly needed in that file.


答:
The general rule of thumb is: include what you use. If you use an object directly, then include its header file directly. If you use an object A that uses B but do not use B yourself, only include A.h.

Also while we are on the topic, you should only include other header files in your header file if you actually need it in the header. If you only need it in the .cpp, then only include it there: this is the difference between a public and private dependency, and will prevent users of your class from dragging in headers they don't really need.

Title: Is it good practice to rely on headers being included transitively?

Body:
I'm cleaning up the includes in a C++ project I'm working on, and I keep wondering whether or not I should explicitly include all headers used directly in a particular file, or whether I should only include the bare minimum.

Here's an example, Entity.hpp:

```<code>#include "RenderObject.hpp"
#include "Texture.hpp"

struct Entity {
    Texture texture;
    RenderObject render();
}
</code>```

(Let's assume that a forward declaration for RenderObject is not an option.)

Now, I know that RenderObject.hpp includes Texture.hpp - I know that because each RenderObject has a Texture member. Still, I explicitly include Texture.hpp in Entity.hpp, because I'm not sure if it's a good idea to rely on it being included in RenderObject.hpp.

So: Is it good practice or not?


问:
Store an object's name in the object or externally?
I'm in the process of building an application which needs extensive logging of points in time at which certain events happen. For example when it renders a sequence of different shapes to the screen then we need a logfile with info like 'shape A rendered to surface at time X, shape B rendered to surface at time Y, surface flipped at time C' etc. in response to comments These names (A,B) should be meaningful and will either be user-defined (e.g. 'MyGroupOfRectangles') or automatically generated (like shape type + number, e.g. 'Rectangle1' or for bitmaps/avis/... use the filename). Main reason for this is that most of the time the logfile is going to be interpreted simply by the user reading it and quickly checking out if the sequence is doing what he/she wants to.

In order to make this happen it's clear that at the moment the log function is invoked it needs to know the name of the shape it's going to log about. One could just give any type of object which is going to be logged about a string member. However thinking about that there are some implementation- and design-wise questions which make me doubt that approach. But other approaches in turn have other problems.

The major question being (almost philosophical - I'm probably overthinking this): should an object know it's own name? After all it's merely an implementation detail here, used solely for logging - if I wouldn't want to log Shapes by their name they wouldn't need to be named at all.

So does it make sense to stuff the name in there as well, or would it be a better practice to keep a map somewhere which links object instances to a name? Something like

```<code>Map< Shape, string > shapeNames;

string NameForShape( Shape s )
{
  return shapeNames.Contains( s ) ? shapeNames[ s ] : "<unnamed>";
}
</code>```

This is very much unintrusive but does introduces some other potential problems in keeping the map up to date with existing shapes: should a shape be destructed, it's name also has to be erased from the map.

The other option (or if there are multiple other options, by all means let me know) is to make a Shape returns it's name. Being an interface it could be like this:

```<code>interface Shape
{
  void Render();
  ...
  string Name();
}
</code>```

However this means every implementation has to take care of providing the Name() implementation and they're likely to going to be doing that all in the same way, like

```<code>class Rect : Shape
{
public:
  Rect( string name ) : { this->name = name; }

  string Name() { return name; }

private:
  string name;
}
</code>```

That's quite some boilerplate and DRY is a holy rule so raises more questions: do I get rid of the pure interface and make it abstract instead (not ideal for unit testing)? Or do I add an extra layer with a default Shape implementation like NamedShape which partially implements Shape and just provides Name() (extra inheritance layer is not ideal either)?

答:
Why don't you just use RTTI to get a string representation of the class name directly? Yes, it is implementation defined, so you can't depend on it being some exact thing if you are switching compilers. However if you need human readable logging, this is an excellent solution that doesn't involve adding a line of code outside the Logger class itself.

https://stackoverflow.com/questions/1024648/retrieving-a-c-class-name-programatically


问:
Why is SQL's BETWEEN inclusive rather than half-open?
Semi-open (or Half-Open, Half-Closed, Half-Bounded) intervals ([a,b), where xbelongs to the interval iff a <= x < b) are pretty common on programming, as they have many convenient properties.

Can anyone offer a rationale that explains why SQL's BETWEEN uses a closed interval ([a,b])? This is esp. inconvenient for dates. Why would you have BETWEEN behave like this?

答:
QUESTION: Why is SQL's BETWEEN inclusive?

ANSWER: Because the SQL language designers made a poor design decision, in that they failed to deliver syntax that would allow developers to specify which of the 4 variants of BETWEEN (closed, semi-open-left, semi-open-right, or open) they'd prefer.

RECOMMENDATION: Unless/until the SQL standard is amended, don't use BETWEEN for dates/times.  Instead get into the habit of coding DATE range comparisons as independent conditions on the start and end boundaries of your BETWEEN range.  This is a bit verbose, but will leave you writing conditions that are intuitive (thus less likely to be buggy) and clear to the database optimizers, allowing for optimal execution plans to be determined and indexes to be used.

For example, if your query is accepting an input day specification and should return all records which fell on that date, you'd code as:

WHERE DATE_FIELD >= :dt AND DATE_FIELD < :dt+1

Trying to write the logic using BETWEEN risks performance issues and/or buggy code.  Three common missteps:

1) WHERE DATE_FIELD BETWEEN :dt AND :dt+1

This is almost certainly a bug - user expects to see only records for a particular date, yet one day will wind up with a report containing records from 12:00 a.m. of the next day.

2) WHERE TRUNC(DATE_FIELD) = :dt

Gives right answer, but applying the function to DATE_FIELD will render most indexing / statistics useless (though sometimes DBAs will try to help by adding function-based indexes to the date fields - still burning up man-hours and disk space and adding overhead to IUD operations on the table)

3) WHERE EVENT_DATE BETWEEN :dt AND :dt + 1-1/24/60/60

Tom Kyte, Oracle guru extraordinaire, recommends this less-than-elegant (IMO) solution. Works great until you're spending all day to find that "1-1/24/06/60" in a query that gives incomplete results... or until you accidentally use it on a TIMESTAMP field.  Plus, it's a bit proprietary; compatible with Oracle's DATE data type (which tracks to the second), but needs to be adjusted to the DATE/TIME precision of different database products.

SOLUTION: Petition the ANSI SQL committee to enhance the SQL language specs by modifying the BETWEEN syntax to support specification of alternatives to the CLOSED/INCLUSIVE default.
Something like this would do the trick:

expr1 BETWEEN  expr2 [ INCL[USIVE] | EXCL[USIVE] ] AND expr3 [ INCL[USIVE] | EXCL[USIVE] ]

Consider how easy it becomes to express WHERE DATE_FIELD BETWEEN :dt INCLUSIVE AND :dt+1 EXCLUSIVE (or just WHERE DATE_FIELD BETWEEN :dt AND :dt+1 EXCL)

Maybe ANSI SQL:2015?


问:
What are the skills you look for when hiring a fresher/newbie for developement?
I really want to ask this questions to my fellow developers here in Programmers.SE because i am hiring freshers for my company.. Even though i know some basic questions that can be asked to a fresher during interview and i want to know,

What are the skills you look for when hiring a fresher/newbie for developement?

答:
First and foremost, see if the student has got a desire to learn. According to me puzzles/ English based exams are just pointless. I could probably accept testing a person's English skills, but that should not be based on a "test". It should be based on how they communicate their ideas. Asking them to solve puzzles is just a hogwash.

To see their desire to learn, you could question them in various grounds. Assuming that their resume is true, look for a person who has a good skill set. Interview that student along with 2/3 people who are well-versed in those skill sets (for example C++/ C#/ Java). Normally in India, I have seen students just add C / C++ to their resume irrespective of how confident they are. To test whether they are pretty confident in C/C++, test them in its basics like pointers/related data structures. Probably you could also ask them solve simple problems, or debug a faulty piece of code etc.

Personally, I don't think that the student should be from computer science (neither am I). If they are from CS test them in their basics - like automata, algorithms,discrete structures, computer networks etc. etc. If they are not from CS, you could still test them in data structures, as this course is pretty much common across departments. Even if they are not from CS, based on their resume, you could ask questions related to their area of interest. And, don't just go by their grades. They are not indicators to their programming knowledge.


问:
String splits to create arrays
Creating an array of strings for configuration or verification purposes can get long and ugly in code. For example:

```<code>arrayOfStrings = ['one','two','three','four']
</code>```

Often to reduce the characters and improve readability I will use string operations to contruct these from a raw string:

```<code>arrayOfStrings = 'one two three four'.split(' ')
</code>```

My rationale is that it makes the items easier to read for a person, as they would see the gaps (one two) easier than the string and array delimiters ('one','two').

If its known that the strings will not contain spaces, would this go against good programming practise?

答:
It would be a bad practice, because it introduces a dependency on a subtle assumption that is hard to document and hard to remember accurately: namely, that the values maintained in this place are any strings without spaces in them. This is almost the same as "any strings", and the former definition will inevitably be mistaken for the latter one day.

Configuration values like these will almost certainly have to change as a system develops. Storing them this way will work fine until one day, new data violate the unspoken assumption and introduce a defect. Note that the defect will probably be subtle: values before the string with the space in it will still be processed correctly, and the ones afterwards will appear in slightly the wrong position, only the value itself will be missing and two or more others will take its place.

In a way, subtle preconditions and subtle defects like this are much worse than obvious ones. Glaring errors are noticed quickly and eradicated quickly. A misbehaviour like this is liable to go unnoticed for quite some time and do damage that won't immediately be known, until it can't be easily repaired and the cause can't be easily found because the programmer who constructed the storage method has moved on.

(What, then, should one do to store large numbers of string literals? Unless your language has a quote-less construct like Lisp lists or Perl's qw() operator, you are almost certainly better off holding string values in a properties file or a database than spelling them out in code. There are other reasons why this is a good idea, but avoiding methods that are either hard to read or subtly problematic is reason enough.)

Title: String splits to create arrays


问:
Method ordering
This is the type of question that one would probably get in an exam, but now it happens to be in the real word. :-) I would appreciate some advice regarding the datastructure/algorithm that can be used to solve the following scenario.

A bit of background:

I have a controlling program that reads C# source code from a database, creates C# source files and then compiles the files into a dll. It then uses this dll to run calculations on other data obtained from the database, and writes the results of the calculations back to the database.

Let us call the controlling program, the Engine, and the source files, the Templates. The Engine compiles the Templates into a partial TemplateCalculations class so that each Template corresponds to a method of that class. The Templates contain code that will modify the Elements. The Elements are the objects on which the calculations will be performed.

But now, the actual problem:
Currently, the Engine uses a list in the database to see what the order should be in which the Templates should be executed. The Engine creates a Controller class which manages the calls to the methods in the correct order. The Templates contain many SetValue(elementName, elementValue) and GetValue(elementName) calls. Obviously, it shouldn't try to get the element's value, before it has already set the value.

Unfortunately, this list in the database that contains the template sequence is sometimes messed up by an ignorant person, and then the calculations don't go through correctly.

The SetValue and GetValue calls for a particular element might or might not be in the same Template file (or method of TemplateCalculations once it is compiled).

Assume we have something like the following:

```<code>Template A: Engine.SetValue(“Element2”, Engine.GetValue(“Element1”))
Template B: Engine.SetValue(“Element1”,1)
</code>```

then the present solution would have the list in the database specify that Template B must execute before Template A.

Also, the underlying datastructure for the elements and values during the execution of the calculations is a Dictionary.

I have the source files available in the Engine, as well as the dll that actually does the execution of the calculation. That is, I first start up the Engine, and then the Engine controls the calculations. There can be more than one SetValue for a particular element.

So, the question is, how would the Engine be able to figure out the order of the templates so that the list isn't necessary anymore? That is, how can I determine an order for the template files, so that an element's GetValue is never called before a SetValue for it?

A simpler solution would be to first determine that the order is incorrect, and to pinpoint which element (on which line of code) is causing the trouble. The more advanced solution would be to do away with the list entirely and let the Engine determine the optimal ordering.

I vaguely think that some kind of implementation of a tree might do the trick, but it's very vague. :-)

Let me know if you need more explanation. Any suggestions would be welcome.

答:
If you can have multiple assignments (SetValue calls) to one Element, then it is just impossible to automatically generate the correct order of executing the Templates, for the simple reason that there are multiple possible orders that are equally valid.

Assuming you have

```<code>Template A: Engine.SetValue(“Element2”, Engine.GetValue(“Element1”))
Template B: Engine.SetValue(“Element1”,1)
Template C: Engine.SetValue(“Element1”,2)
</code>```

Without repeating a template, there are 4 equally valid orderings and without knowing the intent of the calculations, it is impossible to tell which one is the correct order. If templates can be invoked repeatedly, the number of possibilities only increases.

If you are given an order o execute the templates in, then it is possible to determine if that order is valid (as in, all Elements were assigned before being used). This is the kind of analysis that compilers do to determine if a variable has been initialized before its first use.

If execution time doesn't really matter (for example, if the calculations are executed automatically at night and you won't see the results until the next morning anyway) and a partial run can't harm anything, the easiest solution is to verify in GetValue that the Element has been entered into the dictionary with a value and to throw an exception that aborts all calculations if it isn't.

If you need to perform the verification up-front, then there are essentially two options:

You parse the source code and you walk the parse tree in the order that the Templates will be executed. For each SetValue call you record which Element is being assigned and for each GetValue call you verify that the referenced Element has been assigned. This can be achieved by simply keeping a lookup table of assigned/existing Elements.

You implement a 'dry-run' mode, in which you run the Templates, but prevent all externally visible changes from being propagated/committed. If all such changes are made through calls to the Engine anyway, this might be the easiest solution.

Title: Method ordering

Body:
If you can have multiple assignments (SetValue calls) to one Element, then it is just impossible to automatically generate the correct order of executing the Templates, for the simple reason that there are multiple possible orders that are equally valid.

Assuming you have

Template A: Engine.SetValue(“Element2”, Engine.GetValue(“Element1”))
Template B: Engine.SetValue(“Element1”,1)
Template C: Engine.SetValue(“Element1”,2)

Without repeating a template, there are 4 equally valid orderings and without knowing the intent of the calculations, it is impossible to tell which one is the correct order. If templates can be invoked repeatedly, the number of possibilities only increases.

If you are given an order o execute the templates in, then it is possible to determine if that order is valid (as in, all Elements were assigned before being used). This is the kind of analysis that compilers do to determine if a variable has been initialized before its first use.

If execution time doesn't really matter (for example, if the calculations are executed automatically at night and you won't see the results until the next morning anyway) and a partial run can't harm anything, the easiest solution is to verify in GetValue that the Element has been entered into the dictionary with a value and to throw an exception that aborts all calculations if it isn't.

If you need to perform the verification up-front, then there are essentially two options:

You parse the source code and you walk the parse tree in the order that the Templates will be executed. For each SetValue call you record which Element is being assigned and for each GetValue call you verify that the referenced Element has been assigned. This can be achieved by simply keeping a lookup table of assigned/existing Elements.

You implement a 'dry-run' mode, in which you run the Templates, but prevent all externally visible changes from being propagated/committed. If all such changes are made through calls to the Engine anyway, this might be the easiest solution.


答:
Opinions differ on this, but I am of the view that every file (whether c/cpp source file, or h/hpp header file) should be able to be compiled or analysed on its own.

As such, all files should #include any and all header files that they need - you should not assume that one header file has already been included previously.

It is a real pain if you need to add a header file and find that it uses an item that is defined elsewhere, without directly including it... so you have to go find (and possibly end up with the wrong one!)

On the other side, it doesn't (as a general rule) matter if you #include a file you don't need...

As a point of personal style, I arrange #include files in alphabetical order, split into system and application - this helps reinforce the "self contained and fully coherent" message.


问:
CSS Preprocessing (SASS or LESS) vs CSS Postprocessing
So I stumbled across some frameworks for doing CSS post processing such as pleeease.io and I was wondering what are some main benefits or use cases for using CSS post processing? I feel you can achieve more or less the same thing with preprocessing mixins/functions. How are they used in conjunction with preprocessing languages like SASS or LESS?</p>

答:
The goals of preprocessing and postprocessing are quite different:

preprocessing focuses on helping programmers write simpler and more maintainable code

postprocessing focuses on improving the runtime efficiency of code

It is true that preprocessors also delve into the realm of efficient code (one common example is minification) and the reason for that is simply because they can. Why force developers use another tool to minify LESS output when a simple pass implemented by the LESS compiler could do that?

Seeing how preprocessors have better access to the intent of the developer, they have a potential to provide better optimizations than postprocessors can. In practice, a specialized tool could yield better results.

There is no reason not to use both a preprocessor and a postprocessor, but the actual usefulness should be determined on a case by case basis (both combination of tools and use cases can influence it). It is entirely possible to obtain the best results by turning off some features of the preprocessor and relying on the postprocessor for them.


答:
I am taking a similar slightly different approach from proposed answers.

In headers, always include just a bare minimum, just what is needed to make the compilation pass. Use forward declaration wherever possible.

In the source files, it is not that important how much you include. My preferences are still to include minimum to make it pass.

For small projects, including headers here and there will not make a difference. But for medium to large projects, it can become a problem. Even if the latest hardware is used to compile, the difference can be noticeable. The reason is that the compiler still has to open the included header and parse it. So, to optimize the build, apply the above technique (include bare minimum, and use forward declare).

Although a bit outdated, Large Scale C++ Software Design (by John Lakos) explains all this in details.


答:
It depends on whether that transitive inclusion is by necessity (e.g. base class) or because of an implementation detail (private member).

To clarify, the transitive inclusion is necessary when removing it can only be done after first changing the interfaces declared in the intermediate header. Since that's already a breaking change, any .cpp file using it has to be checked anyway.

Example: A.h is included by B.h which is used by C.cpp. If B.h used A.h for some implementation detail, then C.cpp shouldn't assume that B.h will continue to do so. But if B.h uses A.h for a base class, then C.cpp may assume that B.h will continue to include the relevant headers for its base classes.

You see here the actual advantage of NOT duplicating header inclusions. Say that the base class used by B.h really didn't belong in A.h and is refactored into B.h itself. B.h is now a standalone header. If C.cpp redundantly included A.h, it now includes an unnecessary header.


答:
I keep wondering whether or not I should explicitly include all headers used directly in a particular file

Yes.

You never know when those other headers might change. It makes all the sense in the world to include, in each translation unit, the headers you know that translation unit needs.

We have header guards to ensure that double-inclusion is not harmful.


问:
Freelance web development vs. design
Do web design freelancers (I'm thinking individuals, not companies) typically do all development and design work themselves? What are the options for those with a strong base in back-end web development but less with web design, color schemes, layouts, graphic design, etc.?

答: As a freelancer myself, this is what I do. I normally talk to the person who is giving me the project and get myself a designer. The designer designs the UI and provides me with all the necessary HTML, CSS etc etc. Using that as the base, I change plain vanilla HTML to server components (ASP.Net) and I start working on the design and then start development. My design methodology is mostly agile, as in freelance projects (depending upon the scale), you normally don't have separation of phases. So agile works well for me. </p>

Title: Freelance web development vs. design


问:
Cloning existing software for commercial purposes - legal implications
I have been asked to clone some existing software for a company. Basically its an old 16 bit DOS console app, which was supplied free of charge in I believe the late 80's. Having replaced the machine that needs to run it with a box running Win7 x64 they can't get it to work. It crashes every couple of minutes under DOSbox.

The company that supplied it appears to no longer exist - if they did the company asking me to do this would almost certainly know about it. Its undetermined whether they have gone entirely or are just trading under a different name. If the latter they seem to have withdrawn from the market related to this product (because again, niche area, we should know about everyone there).

What is the status to this with regards to copyright etc.? The main concern for the company involved is they want an identical interface to what they already have so I would have to clone this entirely. Having no source code / indication of the underlying mechanisms these would be written from scratch.

Is an interface covered by copyright? / Does that still hold 30 years later? What is the assumed license when none at all is provided?

Under UK law would I be under any serious risk were I to take on the project? How would this pan out if I then decided to sell the software on to other companies?

答:
The clean, simple and practical answer is:
Just make it, don't rock the boat and don't draw attention to it. Get some something written down from your superior so you can always have a paper trail to cover your back. The more questions you ask about the legality on open forums the more attention you potentially draw to it and you may cause problems where there were none.

As long as it is only used within your company, the chance of anyone outside finding out that you made a clone is close to 0.

This may not be the most ethical answer but it's practical.


问:
I'm being warned that the Monoid I'm creating is an Orphan Instance. Is there a better way to write this functionality in?
```<code>type PromptSegment = IO (Maybe String)

instance Monoid a => Monoid (IO a) where
  mempty = return mempty
  mappend = liftA2 (<>)
</code>```

This behaves exactly how I want for my purposes.

For example:

```<code>ghci> let a = return $ Just "hello" :: IO Maybe String
ghci> let b = return $ Just " world" :: IO Maybe String
ghci> let c = return $ Nothing :: IO Maybe String
ghci> a `mappend` b `mappend` c
Just "hello world"
</code>```

However, I'm pretty aware that maybe, for a different Monoid a => Monoid (IO a) instance other than a PromptSegment, maybe I wouldn't want mappend to behave the same way??  I feel like there's better way to do this than creating the orphan monoid instance above.

Current API design

```<code>currentDirectory :: PromptSegment
currentDirectory = Just <$> getCurrentDirectory

main :: IO ()
main = buildMainPrompt
         [ bold . fgColor skyBlue <$> currentDirectory
         ,  (fgColor deepSkyBlue3 . underline . bold <$> gitCurrentBranch)
           <> (fgColor defaultDarkGreen . bold <$> gitRepositorySymbol "±")
           <> gitStatusSegment
         ]
         (fgColor red0 . bold <$> makePromptSegment " ➢ ")
         (fgColor slateBlue0 . bold <$> makePromptSegment " λ» ")

gitStatusSegment :: PromptSegment
gitStatusSegment =
  let unstagedSymbol = fgColor gold1 <$> gitUnstagedSymbol "✚"
      stagedSymbol   = fgColor orange <$> gitStagedSymbol "✎"
      pushSymbol     = fgColor red1 . bold <$> gitPushSymbol "↑"
  in prependSpace <$> unstagedSymbol <> stagedSymbol <> pushSymbol
</code>```

This is, of course, a work in progress, but the aim of the program is to create a DSL for defining cli prompt themes (starting with ZSH).This last code sample is mostly to serve the purpose of providing context to the question for why I would want to make IO (Maybe String) a Monoid.  I'm wide open to harsh criticism - especially since this is my first attempt at writing a 'real' program in Haskell.

答:
There is are reasons behind warning again orphan instances. In particular: If we start using orphan instances, modules can become mutually incompatible: What if two modules define two different instances Monoid (IO a)? There is no good way to tell which one should be preferred.

Furthermore using orphan instances often leads to bad program design. If you add an orphan instance to a data type, you're adding some functionality to the data type. And sooner or later you'll also need to modify the functionality, which isn't (by design) possible with Haskell type classes. At this point you either have to refactor your program or start bending the rules add mess up your design. (This is different from the OO world where subclasses are meant to modify some of the functionality of their parents.)

Therefore I'd strongly suggest to create a new data type for your use case. You'll pay a small one-time price for creating aliases for functions you'll use in your project (most likely in a dedicated module), like

```<code>import qualified System.Directory as D
getCurrentDirectory :: MyDSL FilePath
getCurrentDirectory = --  something wraping D.getCurrentDirectory
</code>```

or more generally define instance MonadIO MyDSL and then

```<code>getCurrentDirectory :: MonadIO FilePath
getCurrentDirectory = liftIO D.getCurrentDirectory
</code>```

But then  your implementation will be completely independent and as your project evolves, nothing will limit you to make the internals of MyDSL more complex or add functionality. Moreover, it'll be safe to use as a library in other projects, without the risk of getting conflicting instances.

Such separation is even more important when you're creating a DSL, because in this case you strongly want to separate the language from its internal implementation. Using an existing data type for a DSL is very likely to cause problems, either when implementing it or due to improper usage by its users.

Body:
There is are reasons behind warning again orphan instances. In particular: If we start using orphan instances, modules can become mutually incompatible: What if two modules define two different instances Monoid (IO a)? There is no good way to tell which one should be preferred.

Furthermore using orphan instances often leads to bad program design. If you add an orphan instance to a data type, you're adding some functionality to the data type. And sooner or later you'll also need to modify the functionality, which isn't (by design) possible with Haskell type classes. At this point you either have to refactor your program or start bending the rules add mess up your design. (This is different from the OO world where subclasses are meant to modify some of the functionality of their parents.)

Therefore I'd strongly suggest to create a new data type for your use case. You'll pay a small one-time price for creating aliases for functions you'll use in your project (most likely in a dedicated module), like

import qualified System.Directory as D
getCurrentDirectory :: MyDSL FilePath
getCurrentDirectory = --  something wraping D.getCurrentDirectory

or more generally define instance MonadIO MyDSL and then

getCurrentDirectory :: MonadIO FilePath
getCurrentDirectory = liftIO D.getCurrentDirectory

But then  your implementation will be completely independent and as your project evolves, nothing will limit you to make the internals of MyDSL more complex or add functionality. Moreover, it'll be safe to use as a library in other projects, without the risk of getting conflicting instances.

Such separation is even more important when you're creating a DSL, because in this case you strongly want to separate the language from its internal implementation. Using an existing data type for a DSL is very likely to cause problems, either when implementing it or due to improper usage by its users.


问:
Why don't Python and Ruby make a distinction between declaring and assigning a value to variables?
Two of the most popular dynamically typed scripting languages, Python and Ruby, do not make a distinction in syntax between the declaration of a variable and assignation of a value to it.

That is in both languages, declaring a variable n and assigning a value to it would look like so:

```<code>n = 10
</code>```

And assigning a new value to the variable later on would look just the same.

This creates two major problems:

A typo in a variable's name when changing it's value would create a new variable and cause bugs.

It makes the intentions of the code less clear. Hard to know where a variable is first declared and used, might make the code more confusing.

What I don't understand is why these languages don't have a var keyword to use on declaration, to make a distinction between a declaration and an assignment. This doesn't make the language any less dynamically typed, and I see no drawbacks.

What is the advantage of not having to explicitly define a variable?

答:
It's not that defining a variable is the same as assigning to it -- it's that the variables are not defined at all.  It's called Dynamic Typing.

You can't have a dynamically typed language that lets you define a variable, because that's what dynamic typing is.

The decision to do this completely changes the nature of the parser, and results in a completely different sort of language.  The principal difference to the end-user is usually that, when defining a function, your parameters turn out to be any type at all ("duck typing"), which is both a blessing, in that it makes your code much simpler, and a curse, in that it allows for a multitude of new ways that your code can fail.

I'm no compiler expert but I think it's also true that Dynamic Typing has major implications for the flavour of OOP you get in a language.


答: I'm up front about not doing any design work. I handle only the programming side. However, I keep all HTML seperate from the rest of the code, in easy to identify template files (e.g header.php, footer.php, signup.php, etc), so its very easy for them to get a designer and have him change it without having to deal with much code.

Title: Freelance web development vs. design

Body: Do web design freelancers (I'm thinking individuals, not companies) typically do all development and design work themselves? What are the options for those with a strong base in back-end web development but less with web design, color schemes, layouts, graphic design, etc.?


问:
Is composition and aggregation really a type of association relationship?
From Wikipedia:

There are four different types of association: bi-directional,
  uni-directional, Aggregation (includes Composition aggregation) and
  Reflexive.

From what I know:

Composition relationship is used for objects that have a has-a relationship to each other. E.g. A car has-an engine.

Whereas, aggregation is a weaker form of composition relationship in which the object doesn't take the ownership of another object. E.g. A university department has a teacher.

In association relationship, there's no concept of has a being used and the objects association is completely independent and thus, they don't belong to a certain class. E.g. you drive a car.

What does it mean that composition and aggregation are a type of association relationships? or do they stand on their own?

On some other resources I have read which state that: "Composition is a special form of association" and "Composition is a special case of association" and they are described in independent sections of their own and not in a "sub-section" of association down below it. Therefore, the confusion about how exactly it is type or sub-type of association relationship.

答: Yes they are, composition is usually called a "strong" association, because if you get rid of the main class the other class has no reason for existance. Aggregation is a sort of "light" association, in which the deletion of one of the related classes does not interfere in the existance of the other.</p>


问:
Creating a new type of project file
I'm starting to work on a project where it would be quite useful to have something like a project file that holds all the data being used in a form that can't be opened/modified/used in anything but this application.

Kind of like excel has an xls format or something like that. Right now all I know how to do is creating a data file that can be opened in notepad.

Is there a special word for this?

答:
There are two quite different answers, depending on whether you don't care that other programs will not be able to process the project file, or whether you want to make sure that they can't.

In the first case, this is simply a matter of inventing a new file format. "File format" is the technical term; search for it, and you will get lots of information about how to choose one (binary vs. text-based, upwards compatibility, efficiency etc.).

In the second case you're talking about security from outside influence. That is a much more difficult thing to achieve, and in fact it is virtually impossible if the computer that is supposed to run your application is also supposed to be able to open such a file without user intervention (e.g. typing a password). However you protect your internal data, an attacker can always trace what your program is doing when it reads the project file and copy those actions.

Title: Creating a new type of project file


问:
Is performance the only reason not to use SignalR (websockets) entirely in lieu of a traditional REST API?
I have used SignalR to achieve real-time messaging functionality in several of my projects. It seems to work reliably and is very easy to learn to use.

The temptation, at least for me, is to abandon developing a Web API service and use SignalR for everything.

I feel like this could be achieved by thoughtful design, and if it were, it would mean far less client code would be necessary. More importantly, it would mean that there would be a single interface to services rather than a split interface, and in the worst case, that one could wire this up without thinking about when things get rendered, etc.

So, I would like to know:

Is there any other reason not to use SignalR in lieu of all web services besides performance?

Is SignalR's performance sufficiently concerning that it would not make sense to do so?

It has long been a dream of mine to be able to translate server-side object and service definitions to client-side service access code without something silly like node.js. For instance, if I define an interesting object InterestingObject and a service to CRUD the object InterestingObjectService, I can define a standard URL route to the service - say, "/{serviceName}/{methodName}" - but I still need to write client code to access the service. Since the object is going to be passed from client to server and back, there is no practical reason to have to define the object explicitly in client-side code, nor should there be a need to explicitly define the routes to perform CRUD operations. I feel like there should be a way to standardize all of this so that it is possible to write a client under the assumption that service access works from the client to the server and back as transparently as it would if I were writing a WinForms or Java Applet or Native App or what have you.

If SignalR is good enough to use in lieu of a traditional web  service, it may be a viable way to achieve this. SignalR already includes functionality to make the hub work like service I describe, so I could define a common base (CRUD) service that would offer all of this functionality out-of-the-box with some reflection. Then I could almost take for granted the service access, saving me the annoyance of re-writing code to access something that could be accessed by convention - and more importantly, the time I would have to spend writing code to define how this is updated in the DOM.

After reading my edit I feel like it may be a little nonsensical so please feel free to ask me if you have questions about what I am getting at. Basically, I want the service access to be as transparent as possible.

答:
Just my 2 cents...

I think it's not really about performance or whatsoever. It's about standards. REST is a standard and IMHO has following advantages:

HTTP requests are straightforward to use. Everybody can quickly use a REST API. Heck, you can even open the browser and type an URL to see the data, how more interactive can you be?

(Almost) any programming language can use it. It's kind of a universal interface. Interfacing with SignalR from an exotic language seems less obvious.

It has nice tooling support, like http://petstore.swagger.wordnik.com/

It's a nice "interface" to debug. You can easily monitor incoming and outgoing messages directly in the browser, see the data, etc. With websockets and custom libraries, it's not as obvious, you have to explicitly log everything.


问:
What could be the advantages and disadvantages of decay of Nd arrays to N-level pointers?
I have been thinking of a couple of possible extensions to the C language which I'd like to know the opinion of others about.1 This one is about multi-dimensional arrays.

Imagine the following situation in C:

```<code>void matrix_mul(double **res, double **a, double **b, size_t n, size_t m, size_t r);
</code>```

You cannot pass a double mat[4][4] (for example) to this function. If you define the function as:

```<code>void matrix_mul_N_M_R(double res[N][R], double a[N][M], double b[M][R]);
</code>```

You'd just be wasting a perfectly written fine algorithm on a certain size of matrices.

What came to me (in shower obviously), was decay of multi-dimensional arrays to multi-level pointers. This is an extension to decay of 1d arrays to pointers.

Semantically, this would allow the first type of function to work on any two-dimensional array. Technically, this is how it would be implemented. The following code:

```<code>double a[3][5];
double b[5][4];
double c[3][4];
...
matrix_mul(c, a, b, 3, 5, 4);
</code>```

would be equivalent to:

```<code>double a[3][5];
double b[5][4];
double c[3][4];
...
double **__a_decay = {a[0], a[1], a[2]};               /* generated by compiler */
double **__b_decay = {b[0], b[1], b[2], b[3], b[4]};   /* generated by compiler */
double **__c_decay = {c[0], c[1], c[2]};               /* generated by compiler */
matrix_mul(__c_decay, __a_decay, __b_decay, 3, 5, 4);  /* first three arguments decayed */
</code>```

Is the application for such an extension very limited? Are there pitfalls? Could this possibly lead to insecure code where not using this feature wouldn't? Where else could such a feature come in handy?

1 Note that I'm not going to make another language myself, but would like to be sure of the feature's benefits and pitfalls before trying to suggest them to the C Standard Committee.

答:
How would your proposed extension handle the situation where a multi-dimensional array isn't allocated statically?  Having the extension be limited to cases where the allocation is static would make its behavior inconsistent with other array handling, but if the extension isn't limited to static array allocations then passing a double[5000][5000] to function which is expecting a double** would require the compiler to generate and fully populate a (double*)[5000], even if the function wouldn't use most of (or even any of) its elements each time the function was called.

A more useful extension might be to add types like double[][] and double[][][] as types in the language, and have each such type with N dimensions be stored as a double* along with N-1 values of type type size_t.  It would be necessary to have separate methods for jagged and linear arrays, but it would not be necessary to have different methods for each size of linear array.


问:
Must I provide my project source code if I use a library licensed under Apache 2.0?
I have a private (i.e. no chance of sharing the source) and commercial application, now I would like to use a library which is under the Apache 2.0 license.

I've read the Apache license and FAQ section, but I am not clear about this.

Is it the same as GPL3 which forces the application to provide the source code?

答:
The Apache 2.0 licence is completely unlike GPL.  In particular, it says

You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

So provided you meet the conditions listed (which are generally not onerous), then you do not have to redistribute your source code.


答:
Having an association from object A to object B means that object A knows about the existence of object B and that it can access the (public) interface of object B.

Aggregation and composition can be seen as increasingly stronger forms of "knowing about", because when you "have" a B or even manage that B's lifetime, there is no getting around that you know about that B.

On the other hand, the semantic differences between "knowing about" and "having" are big enough that aggregation and composition really deserve separate treatment in an introductory text.

Title: Is composition and aggregation really a type of association relationship?

Body:
From Wikipedia:

There are four different types of association: bi-directional,
  uni-directional, Aggregation (includes Composition aggregation) and
  Reflexive.

From what I know:

Composition relationship is used for objects that have a has-a relationship to each other. E.g. A car has-an engine.

Whereas, aggregation is a weaker form of composition relationship in which the object doesn't take the ownership of another object. E.g. A university department has a teacher.

In association relationship, there's no concept of has a being used and the objects association is completely independent and thus, they don't belong to a certain class. E.g. you drive a car.

What does it mean that composition and aggregation are a type of association relationships? or do they stand on their own?

On some other resources I have read which state that: "Composition is a special form of association" and "Composition is a special case of association" and they are described in independent sections of their own and not in a "sub-section" of association down below it. Therefore, the confusion about how exactly it is type or sub-type of association relationship.


答:
Those two technologies have a very different purpose.

REST is for ordinary calls to an API, with client being an active actor of the exchange. When the client needs to find GPS coordinates of an address, the client initiates the call to the API and waits until it receives the coordinates, or a error occurs, or a timeout elapses.

Web sockets are for everything which needs to do things the opposite way. For example, when I use an intranet website which shows me in real time the logs and the performance of different servers, the client may be passive and wait until the server sends him a newly published log message or performance metrics.

The difference is clear: in the first case, the client decides when it needs a specific piece of information; in the second case, the client simply waits to be contacted, and may not know when it would be.

In some way, both are interchangeable: you can implement web sockets when you don't need them (i.e. the client will call the server through web sockets instead of making a REST call) and you can use polling or long polling as a substitute to web sockets (given that this was used successfully for years until web sockets became so popular).

But their interchangeability comes at a cost:

When you use polling or long polling instead of web sockets, you're often wasting bandwidth.

When you use web sockets to do what can be done through web api, you keep all the connections from all the active clients opened, which may not be what you really want. For a small website where you expect to have at most 5 clients at the same time, this is not an issue. For a service such as Amazon AWS, this wouldn't be easy to solve technically.

Don't use web sockets when you don't need them. To get GPS coordinates of an address, I gain nothing in opening web sockets connection, making the call, waiting for an answer and closing the connection: REST fulfills my needs for such scenarios.

If you find yourself repeatedly and frequently checking for information through a REST call to a service, this may be a good sign that you should move to web sockets. Similarly, Stack Overflow reduces bandwidth usage by using web sockets, since it helps people to not spend their time pressing F5 on the home page to see if they have new messages.

If you find that you open web sockets connections, use them to make a single call, and then close them, or if your connections remain opened but the server is sending something to the client only on client's request, switch to REST.

Also, web sockets have still a limited support and are not always easy to implement. While SignalR makes it easy to implement, this doesn't mean that you won't have any difficulties to implement it in other languages/contexts/environments. With REST, that's easy: it may be a curl call or a similar feature available in every mainstream language. With web sockets, you can't be sure how long would it take to make a client using [insert the name of a language you don't know yet here].

I've used web sockets in several projects in .NET, Python and node.js.

In .NET, it wasn't too difficult, but still, I've still spent a few days trying to figure out some cryptic problems, such as the connection dropped as soon as it is opened. (This was prior to SignalR; I never tried SignalR). I also used WCF in web sockets mode, which wasn't without issues either (but I believe that WCF always comes with issues).

In node.js, this was doable, but I had to switch twice the libraries until I've found one which works. I believe I've spent at least a week trying to make a web sockets Hello World.

In Python, I tried once, spent two or three days, and abandoned. It never worked.

Compare this to REST: the only problems one can encounter with a new language/framework is to know how to POST files or receive a very large binary response. I remember spending a few hours searching for solutions for some languages. Still, a few hours for a special case is nothing compared to days or weeks for a simple Hello World.

Title: Is performance the only reason not to use SignalR (websockets) entirely in lieu of a traditional REST API?

Body:
I have used SignalR to achieve real-time messaging functionality in several of my projects. It seems to work reliably and is very easy to learn to use.

The temptation, at least for me, is to abandon developing a Web API service and use SignalR for everything.

I feel like this could be achieved by thoughtful design, and if it were, it would mean far less client code would be necessary. More importantly, it would mean that there would be a single interface to services rather than a split interface, and in the worst case, that one could wire this up without thinking about when things get rendered, etc.

So, I would like to know:

Is there any other reason not to use SignalR in lieu of all web services besides performance?

Is SignalR's performance sufficiently concerning that it would not make sense to do so?

It has long been a dream of mine to be able to translate server-side object and service definitions to client-side service access code without something silly like node.js. For instance, if I define an interesting object InterestingObject and a service to CRUD the object InterestingObjectService, I can define a standard URL route to the service - say, "/{serviceName}/{methodName}" - but I still need to write client code to access the service. Since the object is going to be passed from client to server and back, there is no practical reason to have to define the object explicitly in client-side code, nor should there be a need to explicitly define the routes to perform CRUD operations. I feel like there should be a way to standardize all of this so that it is possible to write a client under the assumption that service access works from the client to the server and back as transparently as it would if I were writing a WinForms or Java Applet or Native App or what have you.

If SignalR is good enough to use in lieu of a traditional web  service, it may be a viable way to achieve this. SignalR already includes functionality to make the hub work like service I describe, so I could define a common base (CRUD) service that would offer all of this functionality out-of-the-box with some reflection. Then I could almost take for granted the service access, saving me the annoyance of re-writing code to access something that could be accessed by convention - and more importantly, the time I would have to spend writing code to define how this is updated in the DOM.

After reading my edit I feel like it may be a little nonsensical so please feel free to ask me if you have questions about what I am getting at. Basically, I want the service access to be as transparent as possible.


答:
The Apache 2.0 license is very different from the GPL license, in at least two aspects:

Under the Apache 2.0 license, you are allowed to distribute binaries without providing the source code with it. (Under the GPL, you must always provide the source code)

The GPL license carries over to the entire application. The Apache 2.0 license does not and applies only to those parts that explicitly state they fall under the Apache 2.0 license.

This means that if you use a library with Apache 2.0 license in your project, the permissions/rights/obligations from the Apache 2.0 license do not suddenly carry over to your code.

To distribute a (binary or unmodified) copy of an Apache 2.0 licensed library with your application, you must meet two requirements:

The users of your application must receive a copy of the Apache 2.0 license. To avoid confusion, you should also state which parts of the distribution the license applies to.

The users of your application must receive a copy of the NOTICES file that came with the library, if there is such a file.

Title: Must I provide my project source code if I use a library licensed under Apache 2.0?

Body:
I have a private (i.e. no chance of sharing the source) and commercial application, now I would like to use a library which is under the Apache 2.0 license.

I've read the Apache license and FAQ section, but I am not clear about this.

Is it the same as GPL3 which forces the application to provide the source code?


答:
The difference between postprocessing and preprocessing is non-existent, at least in the case of programming languages. Both describe a transformation from some format A (which is authored by a human) to format B (which is necessary to have, but inconvenient to write):

```<code>“compiler”:   A    -> B

== CSS-related examples ==
less:         LESS -> CSS
sass:         SASS -> CSS
sass:         SCSS -> CSS
autoprefixer: CSS  -> CSS
minifier:     CSS  -> CSS
pleeease:     CSS  -> CSS

== Other examples ==
c preprocessor: C        -> C without macros
gcc:            C        -> machine code
pandoc:         LaTeX    -> HTML
pandoc:         Markdown -> HTML
pandoc:         LaTeX    -> Markdown
</code>```

A few observations on those examples:

The input and output format can be the same. This is the case in code tidiers, minifiers, and other processors that somehow simplify the source. E.g. the C preprocessor expands macros and constants in the source code. This is equivalent to autoprefixer, which expands unprefixed CSS directives into their prefixed variants.

Processors can involve multiple sub-processors that each do some part of the transformation.

pleeease can pipe the code through various processors such as autoprefixer or a minifer.

A C compiler includes a preprocessor stage.

Pandoc has a processor that parses the input (e.g. a Markdown document) into a common data structure, then passes this intermediate representation to another processor that turns it into the target format (e.g. HTML). Pandoc's architecture is fairly pluggable, and allows additional preprocessing stages to be added. For example, this is used to implement bibliography references in Pandoc's Markdown dialect, by expanding the syntax into a more standard Markdown form.

If pleeease calls itself a post-processor rather than a pre-processor, this is done …

to differentiate itself from preprocessors like LESS or SASS. The selling point of LESS and SASS/SCSS is that they extend or replace CSS syntax. Pleeease instead wants to make existing CSS code more portable.

to indicate pleeease is to be used after development. If you use SASS to write your styles, you have to run the compiler before you serve the style sheet to your browser. And after you've written the style, you can run pleeease on the result to make it more palatable to older browsers.

To summarize: There is no technical reason to differentiate between preprocessing and postprocessing in the realm of programming languages. The term “postprocessing” is not widely used in this domain, and one should therefore substitute and prefer “preprocessing”, “compiling”, or “transformation”.

Title: CSS Preprocessing (SASS or LESS) vs CSS Postprocessing

Body: So I stumbled across some frameworks for doing CSS post processing such as pleeease.io and I was wondering what are some main benefits or use cases for using CSS post processing? I feel you can achieve more or less the same thing with preprocessing mixins/functions. How are they used in conjunction with preprocessing languages like SASS or LESS?</p>

Body:
The difference between postprocessing and preprocessing is non-existent, at least in the case of programming languages. Both describe a transformation from some format A (which is authored by a human) to format B (which is necessary to have, but inconvenient to write):

“compiler”:   A    -> B

== CSS-related examples ==
less:         LESS -> CSS
sass:         SASS -> CSS
sass:         SCSS -> CSS
autoprefixer: CSS  -> CSS
minifier:     CSS  -> CSS
pleeease:     CSS  -> CSS

== Other examples ==
c preprocessor: C        -> C without macros
gcc:            C        -> machine code
pandoc:         LaTeX    -> HTML
pandoc:         Markdown -> HTML
pandoc:         LaTeX    -> Markdown

A few observations on those examples:

The input and output format can be the same. This is the case in code tidiers, minifiers, and other processors that somehow simplify the source. E.g. the C preprocessor expands macros and constants in the source code. This is equivalent to autoprefixer, which expands unprefixed CSS directives into their prefixed variants.

Processors can involve multiple sub-processors that each do some part of the transformation.

pleeease can pipe the code through various processors such as autoprefixer or a minifer.

A C compiler includes a preprocessor stage.

Pandoc has a processor that parses the input (e.g. a Markdown document) into a common data structure, then passes this intermediate representation to another processor that turns it into the target format (e.g. HTML). Pandoc's architecture is fairly pluggable, and allows additional preprocessing stages to be added. For example, this is used to implement bibliography references in Pandoc's Markdown dialect, by expanding the syntax into a more standard Markdown form.

If pleeease calls itself a post-processor rather than a pre-processor, this is done …

to differentiate itself from preprocessors like LESS or SASS. The selling point of LESS and SASS/SCSS is that they extend or replace CSS syntax. Pleeease instead wants to make existing CSS code more portable.

to indicate pleeease is to be used after development. If you use SASS to write your styles, you have to run the compiler before you serve the style sheet to your browser. And after you've written the style, you can run pleeease on the result to make it more palatable to older browsers.

To summarize: There is no technical reason to differentiate between preprocessing and postprocessing in the realm of programming languages. The term “postprocessing” is not widely used in this domain, and one should therefore substitute and prefer “preprocessing”, “compiling”, or “transformation”.


问:
Why is Java considered more portable than other languages like C++?
What differs between "writing a specific JRE for each platform" for Java developers and "writing a C++ compiler for each platform" for C++ ones?</p>

答:
One of the reasons Java is considered portable is that it has specific rules for how arithmetic expressions must be valuated and forbids implementations from evaluating them any other way, even when evaluating them in the mandated fashion would require slower code than evaluating them in a more accurate fashion.

For example, given

```<code>long thing1(int x) {
  return (x+1)-1L;
}
double thing2(int x, float y) {
  return x/y;
}
</code>```

The values of thing1(2147483647) and thing2(1123456700,11234567.0f) are required to be -2147483649L and 99.9999923706054688, respectively, even though the arithmetically correct values would be 2147483647L and 100.0, and even though on some platforms code to generate the numerically-incorrect results would be slower than code to generate the correct results (on some 64-bit platforms, forcing the wrapping behavior after (x+1) would require an extra instruction, and on the 8x87 platform, forcing the value of 1123456700 to be rounded to a float would require an extra instruction compared with simply loading it directly to an extended-precision register).

Body:
One of the reasons Java is considered portable is that it has specific rules for how arithmetic expressions must be valuated and forbids implementations from evaluating them any other way, even when evaluating them in the mandated fashion would require slower code than evaluating them in a more accurate fashion.

For example, given

long thing1(int x) {
  return (x+1)-1L;
}
double thing2(int x, float y) {
  return x/y;
}

The values of thing1(2147483647) and thing2(1123456700,11234567.0f) are required to be -2147483649L and 99.9999923706054688, respectively, even though the arithmetically correct values would be 2147483647L and 100.0, and even though on some platforms code to generate the numerically-incorrect results would be slower than code to generate the correct results (on some 64-bit platforms, forcing the wrapping behavior after (x+1) would require an extra instruction, and on the 8x87 platform, forcing the value of 1123456700 to be rounded to a float would require an extra instruction compared with simply loading it directly to an extended-precision register).


问:
Would this be considered a plugin or template type architecture?
I would like to build a system that basically offers the option to make various APIs interchangeable for usage to the end user. For example, the person using the software would have the option of choosing a single existing supported Billing System at any one time. They could for example choose to use WHMCS, Host Bill or Blesta.

The way I picture doing this, I have a base "Billing_System" class that has generic methods that are then inherited and implemented differently depending on the system chosen. For example...

```<code><?

class Billing_System
{
    /* Connect to Billing System API */
    public function connect($hostname, $username, $password)
    {

    }

    /* Fetch list of all due invoices */
    public function get_invoices()
    {

    }

    /* Fetch invoice data by invoice ID */
    public function get_invoice($invoice_id)
    {

    }

    /* Fetch invoices for specific client */
    public function get_client_invoice($client_id)
    {

    }
}

?>
</code>```

Then have WHMCS, HostBill and Blesta classes that extend Billing_System and re-implement these methods as needed for the specific API's being used.

My question would be is this a plugin type system or just architecture? Would it be possible to somehow initialize the Billing System by name making it easier to add additional systems without having to update mass amounts of existing files to add includes/etc?

Example:

```<code>$billing = new Billing_System("WHMCS", "whmcs.mysite.com", "admin", "1234abcd");
</code>```

答:
All I can see above is just an application of the strategy pattern.

How much you have to extend this code to make this a real "plugin architecture" is debatable, but IMHO the central point is to have the deployment of new billing system implementations decoupled from the deployment of the main system. Ideally, you, your team, or a third party can deliver new Billing_System classes without the necessity to deploy a new release of your main system. There should be a fixed, stable, documented plugin API. And ideally it should not even be necessary to restart your server after a new billing system was added (though I think that's not mandatory).


答:
Many people forget or do not take into account the reality of Java when they say that "it's 100% portable" or phrases like that .

Pretty much all the major Corporations / Software house had at least 1 home-made implementation of Java with an associated JRE in the recent past and some still do maintain it, Microsoft, IBM and Apple for example all had their own version of Java reflecting their own ideas and thoughts on where the industry and such language should go .

How is that for "portable" ? A JRE anywhere you turn .

And this is without considering what Sun/Oracle was doing.

An example on why Java code is not really far from C and C++ in terms of portability are the GUIs and the graphical servers, Apple had a non-standard implementation of the GUI framework for its own JRE, as a consequence there were a lot of headaches and double work for anyone who wanted to create/port a GUI using Java for Apple machines and they were basically forced to deal with Quartz ( how is that in terms of "leverage" and high level languages ?).

Sometimes even the most common used words don't really reflect the meaning that people usually give them, to me the term "portability" in the Java world is more like "outlook" in the common sense; in commercial and financial terms there is a better outlook for you if you adopt Java rather than other languages ( at least at the time when Java was born ) because you have a lot of work already done on one side ( you get a JRE on anything that can be considered a "computer" ) and your codebase is likely to be portable as it is, you need less resources to port your program, that's it, whether said resource is money, time or manpower doesn't matter, it's a lower threshold compared to other technologies and that's what Java is for, it is lowering that threshold .

Of course this is true if you accept the premises of Java, which means a virtual machine with garbage collection, which means it consumes more resources if compared to native languages, if you really want to squeeze the maximum out of your CPU or server farm I don't think that you can adopt Java unless you are really low on resources or your company is really small .

I still have to find a single non-trivial Java application that contains only 1 version for each line of code or functionality ( aka without any platform specific stuff ) and it's 100% portable among all the major JREs.

Title: Why is Java considered more portable than other languages like C++?

Body: What differs between "writing a specific JRE for each platform" for Java developers and "writing a C++ compiler for each platform" for C++ ones?</p>


问:
Print Statements Inside Function Or Before Calling It?
I have a script which different people may use. I have print statements so people can follow along what the script is doing, and if it breaks where it went wrong, and if a certain step takes a long time which step it was.

Which way for print statements is better in this case and why?

This:

```<code>def do_something():
    ...

print 'doing something'
do_something()
</code>```

Or this:

```<code>def do_something():
    print 'doing something'
    ...

do_something()
</code>```

I am inclined to think the first is better as it is slightly clearer what is going on when people look at your script; they know there is a print statement before the function is called, and you can add extra detail when sometimes the function name isn't as informative as it could be.

However I see how it could be considered duplication of code. And so the second is better.

But more important than this quite specific question is what general principle would lead you to prefer one over the other?

答:
There is better ways to enable your users to follow the scripts actions. One way is to return an object that describes what steps happend, what the result is and how long the steps took. If it breaks, you should throw an exception which includes additional information.

Another way to do this is using AOP features. These are however not builtin python and you have little IDE support when using reflection/introspection to achieve the desired AOP behaviour. The advantage is, that your logging code and the functional code is seperated and the logging can be enabled and disabled or even extended without having to touch the functional code.

If you want to use neither of these solutions, at least make your users to be able to inject a service that is used for printing, so they can decide what the service should do with your messages. It is really bad if you are using a third-party script and the script just prints to stdout or stderr. You then have to do dirty piping stuff to prevent unwanted output.


答:
Note: don't use print for logging purposes. Using print may work for small applications, but when the application starts increasing, moving to the actual logging would quickly become unavoidable. To avoid future maintenance cost, consider using logging from the beginning. Make sure you use existent predefined logging frameworks and don't reinvent the wheel.

Is the print statement part of the function? In other words, does it make sense to run the function without the print statement?

If the specific statement is inherent to the function, put it inside. If the specific statement is inherent to the context of the caller, put it there.

Example:

```<code>def add_product(product):
    logger.debug("The product %s is about to be added to the database.", product.id)
    ...
</code>```

Here, the logging is inherent to the function: it doesn't matter when and where the function was called, so whenever it is, the log entry should be added.

```<code>def add_product(product):
    ...

logger.debug("Adding the product %s created by the administrator.", product.id)
add_product(self.newProduct)
</code>```

Here, on the other hand, the context is important: the log message indicates why the product is being added to the database—it is added because the administrator just created it. Thus, the message makes no sense within the function.

Title: Print Statements Inside Function Or Before Calling It?

Body:
I have a script which different people may use. I have print statements so people can follow along what the script is doing, and if it breaks where it went wrong, and if a certain step takes a long time which step it was.

Which way for print statements is better in this case and why?

This:

```<code>def do_something():
    ...

print 'doing something'
do_something()
</code>```

Or this:

```<code>def do_something():
    print 'doing something'
    ...

do_something()
</code>```

I am inclined to think the first is better as it is slightly clearer what is going on when people look at your script; they know there is a print statement before the function is called, and you can add extra detail when sometimes the function name isn't as informative as it could be.

However I see how it could be considered duplication of code. And so the second is better.

But more important than this quite specific question is what general principle would lead you to prefer one over the other?

Body:
Note: don't use print for logging purposes. Using print may work for small applications, but when the application starts increasing, moving to the actual logging would quickly become unavoidable. To avoid future maintenance cost, consider using logging from the beginning. Make sure you use existent predefined logging frameworks and don't reinvent the wheel.

Is the print statement part of the function? In other words, does it make sense to run the function without the print statement?

If the specific statement is inherent to the function, put it inside. If the specific statement is inherent to the context of the caller, put it there.

Example:

def add_product(product):
    logger.debug("The product %s is about to be added to the database.", product.id)
    ...

Here, the logging is inherent to the function: it doesn't matter when and where the function was called, so whenever it is, the log entry should be added.

def add_product(product):
    ...

logger.debug("Adding the product %s created by the administrator.", product.id)
add_product(self.newProduct)

Here, on the other hand, the context is important: the log message indicates why the product is being added to the database—it is added because the administrator just created it. Thus, the message makes no sense within the function.