问:
Should an event listener be called if attached after the event has already fired?
Should an event listener be called if it is attached after the event has already fired? What if the event will only be fired once?

The first example that comes to mind is the ready event in jQuery. The following snippet, when evaluated after the page has loaded, will still call the callback:

```<code>$(document).ready(function () {
    console.log("Works.");
});
</code>```

The alternative to this behaviour could be a flag that is set when the page is loaded, forcing the consumer of the API to check to see if the event has already happened and act accordingly:

```<code>if (document.readyState == "complete") {
    console.log("Works.");
} else {
    $(document).ready(function () {
        console.log("Works.");
    });
}
</code>```

While the above example is in the context of a web page loading where anything and everything (usually) needs to happen after the page has completely loaded, the same arguments could be made for any single component in an application, which has "singleton" events (load, start, end, etc). An example of a single component could be a map with a load event that fires to specify that the map that has loaded:

```<code>map.on("load", function () {
    console.log("The map has loaded.");
});
</code>```

The above example comes from the ArcGIS API for JavaScript, where that event is fired only once, and if an a consumer "waits" for the map to load after the map is already loaded, the listener will never be called. The desired result requires checking the state of the map before the listener is attached:

```<code>if (map.loaded) {
    console.log("The map has loaded.");
} else {
    map.on("load", function () {
        console.log("The map has loaded.");
    });
}
</code>```

Which behaviour is correct, requiring the consumer to check if an event has already fired or always calling the callback?

答:
In general, no.

Event listeners should not be called if they are attached after the event has already fired. "You snooze, you lose."

There are some important exceptions. $(document).ready() is perhaps the perfect example--a event prior to which the entire evaluation context is not reliably or completely established, and which serves as a "full function processing begins here" marker.

If however you set the rule that an event handler should be fired even if it is installed and/or activated after the event occurs, then you have declared that all events should or must be buffered from the beginning to the end of the program run, for every conceivable event. Else, there might be event handlers established on some event, somewhere down the road, that you don't have sufficient information to know if you should fire when it's established. That means you'd have to instrument every possible event source and infinitely buffer every one of them too. That takes event processing from lazy evaluation (and all of its performance benefits) all the way through eager evaluation and onto whatever is on the far end of the spectrum. Frenetic evaluation based on catastrophized assumptions about what events might need to be handled later?

Events tend to be transient and numerous. Setting rules that require each be buffered, without limitation, on the possibility that they'll eventually be tapped--it's performance suicide. Furthermore, there's no great requirement for doing so, since handlers can generally be established early in program life.

The exceptions to the rule are edge cases--document or subsystem loads, for example, that are essential, unique, major events that are not otherwise captureable or handleable.
This is very close to your "singleton" events. Another group that might need special handling are significant errors, security events, or status changes that have an exceptional need to be flagged even if there are no subscribers to the flag at the moment the event occurred.

One final note: A "ready" event is subtly different from a "load" event. While they're often not clearly distinguished (e.g. HTML's onload and jQuery's $(document).ready() considered logically very similar), and both signaling the availability of a resource or processing environment--but they're not quite the same. Loading (or the finishing of it) is a true event--something signaled from infrastructure to consumer. Readiness, however, is more the rendezvous of the infrastructure's loading the resource/environment and the consumer's getting around to being ready to consume/take advantage of that availability. Readiness comes after the load, and is one of those designated special events/coordination points that must be treated as queueable because you can't capture it any other way. That there are a few very special cases, however, doesn't mean that every event should be fireable a posteriori.


问:
How can I iterate over two loops of mismatched sizes, keeping them in sync?
I have a database table in which each row is one movie (with fields like 'title', 'director' and 'writer'), and a related table where each row is one screenshot from a movie (with the fields 'movie_id' and 'jpeg_data'). Each movie has 2-8 screenshots.

I want to output data in the order

Movie 1

Screenshot 1

Screenshot 2

Movie 2

Screenshot 1

Screenshot 2

Screenshot 3

Screenshot 4

Now the simplest solution I've found is to do (a rough pseudocode):

```<code>for movie in database.select id,title,director from movies
    print movie.title, movie.director
    for screenshots in database.select screenshots where movie_id = id
        print screenshots.screenshot
</code>```

This works -- but it's a nested loop where the inner loop is making a database call. This would make ~2,800 database calls with my current dataset, which seems terribly slow and inefficient.

There must be a better solution, but I can't really think of one. I'd like to select all movies, and select all screenshots, and then find some way of iterating through the two arrays while keeping them in sync with each other, if that's the right word.

What is the correct/optimal thing to do in this case?

答:
After some comments and reading the question again I came to a core realization - you have an XY problem:

and a related table where each row is one screenshot from a movie (with the fields 'movie_id' and 'jpeg_data')

I do see a performance hit, yeah; even with only 12 images on my locally-hosted webpage I'm seeing a 5-second loadtime as it fetches the images.

The web browser is intended to go and fetch all the data as fast as it can. When rendering the page, it would often (not always) prefer to do lots of small fetches of static data (like images) rather than one big fetch.  The one big fetch - it has to wait a bit until it can start rendering.

This is likely the core problem.  Not the iterating over the loops, but rather that you have to iterate over the loop to get the jpeg data.

Don't store the image in the database.  Store the image as a static file that the web server can access as a static file.  Store the file name or path to the file in the database.

Trying to pull large (not consistently sized) binary things out of a database isn't what its designed for or good at - thats what filesystems are good at.

Related:

Should heavy binary files not be stored in database?

Store images in the database, or in files with a database link?

Setting that aside, you've got two result sets.  You can:

Use the database (if it supports it) to store the concatenated information (file name) into one column.

```<code>select M.id, M.moviename, group_concat(S.filename)
from movie M
join screenshots S on (S.movieid = M.id)
group by M.id
</code>```

Just fetch all the data as one joined structure (why get two result sets in the first place?)

```<code>select M.id, M.moviename, S.filename
from movie M
join screenshots S on (S.movieid = M.id)
</code>```

Fetch all the data and put it into a nice structure in your program and iterate over that.

```<code>public class Movie {
    int id;
    String name;
    List<String> files;
}
</code>```

Iterate over the result set and when you get to the next movie, backup.

```<code>for movie in moviesCursor
    print movie.title, movie.director
    for screenshots in screenShotCursor
        if screenshot.movieId != movie.id
            screenShotCursor.previous
            break
        print "<img src=\"screenshots.fileName\">"
</code>```

Some of these may be limited by your choice of language and database.

ContentLicense: CC BY-SA 3.0

Body:
After some comments and reading the question again I came to a core realization - you have an XY problem:

and a related table where each row is one screenshot from a movie (with the fields 'movie_id' and 'jpeg_data')

I do see a performance hit, yeah; even with only 12 images on my locally-hosted webpage I'm seeing a 5-second loadtime as it fetches the images.

The web browser is intended to go and fetch all the data as fast as it can. When rendering the page, it would often (not always) prefer to do lots of small fetches of static data (like images) rather than one big fetch.  The one big fetch - it has to wait a bit until it can start rendering.

This is likely the core problem.  Not the iterating over the loops, but rather that you have to iterate over the loop to get the jpeg data.

Don't store the image in the database.  Store the image as a static file that the web server can access as a static file.  Store the file name or path to the file in the database.

Trying to pull large (not consistently sized) binary things out of a database isn't what its designed for or good at - thats what filesystems are good at.

Related:

Should heavy binary files not be stored in database?

Store images in the database, or in files with a database link?

Setting that aside, you've got two result sets.  You can:

Use the database (if it supports it) to store the concatenated information (file name) into one column.

select M.id, M.moviename, group_concat(S.filename)
from movie M
join screenshots S on (S.movieid = M.id)
group by M.id

Just fetch all the data as one joined structure (why get two result sets in the first place?)

select M.id, M.moviename, S.filename
from movie M
join screenshots S on (S.movieid = M.id)

Fetch all the data and put it into a nice structure in your program and iterate over that.

public class Movie {
    int id;
    String name;
    List<String> files;
}

Iterate over the result set and when you get to the next movie, backup.

for movie in moviesCursor
    print movie.title, movie.director
    for screenshots in screenShotCursor
        if screenshot.movieId != movie.id
            screenShotCursor.previous
            break
        print "<img src=\"screenshots.fileName\">"

Some of these may be limited by your choice of language and database.


问:
What's the rationale behind the ordering of Scala's value/variable declaration when including a type identifier?
I'm trying to wrap my head around Scala, and one thing that keeps throwing me is the ordering of a variable/value declaration when specifying the type.

```<code>val a = 0
</code>```

makes perfect sense. This looks pretty much like any other language.

```<code>val a: Int = 0
</code>```

parses really weird in my head; it just seems nonsensical. Why is the type immediately on the left of the assignment operator? When I cut this in my head, I see "... Int = 0", which obviously doesn't make any sense.

Is there a logical reason behind this that I can refer to? Obviously, as I look at Scala code more, I will adjust to it, but I'm also curious why Martin Odersky would choose to arrange it as such. It can't be just to stand out from other languages, where (as far as I know of), the type identifier, if there is one, precedes the declaration.

答: You're thinking about it the wrong way. The type isn't immediately to the left of the assignment, it's immediately to the right of the declarator. This syntax has the advantage of being unambiguous, whereas for example val a = 0 : Int is ambiguous: does the type specifier refer to the literal, the declaration, or the entire statement? And if the initializer is more complicated than just a literal, it gets really confusing.


问:
Return magic value, throw exception or return false on failure?
I sometimes end up having to write a method or property for a class library for which it is not exceptional to have no real answer, but a failure. Something cannot be determined, is not available, not found, not currently possible or there is no more data available.

I think there are three possible solutions for such a relatively non-exceptional situation to indicate failure in C# 4:

return a magic value that has no meaning otherwise (such as null and -1);

throw an exception (e.g. KeyNotFoundException);

return false and provide the actual return value in an out parameter, (such as Dictionary<,>.TryGetValue).

So the questions are: in which non-exceptional situation should I throw an exception? And if I should not throw: when is returning a magic value perferred above implementing a Try* method with an out parameter? (To me the out parameter seems dirty, and it is more work to use it properly.)

I'm looking for factual answers, such as answers involving design guidelines (I don't know any about Try* methods), usability (as I ask this for a class library), consistency with the BCL, and readability.

In the .NET Framework Base Class Library, all three methods are used:

return a magic value that has no meaning otherwise:

Collection<T>.IndexOf returns -1,

StreamReader.Read returns -1,

Math.Sqrt returns NaN,

Hashtable.Item returns null;

throw an exception:

Dictionary<,>.Item throws KeyNotFoundException,

Double.Parse throws FormatException; or

return false and provide the actual return value in an out parameter:

Dictionary<,>.TryGetValue,

Double.TryParse.

Note that as Hashtable was created in the time when there were no generics in C#, it uses object and can therefore return null as a magic value. But with generics, exceptions are used in Dictionary<,>, and initially it didn't have TryGetValue. Apparently insights change.

Obviously, the Item-TryGetValue and Parse-TryParse duality is there for a reason, so I assume that throwing exceptions for non-exceptional failures is in C# 4 not done. However, the Try* methods didn't always exist, even when Dictionary<,>.Item existed.

答:
If you are interested in the "magic value" route, yet another way to solve this is to overload the purpose of the Lazy class.  Although Lazy is intended to defer instantiation, nothing really prevents you from using like a Maybe or an Option.   For instance:</p>

```<code>    public static Lazy<TValue> GetValue<TValue, TKey>(
        this IDictionary<TKey, TValue> dictionary,
        TKey key)
    {
        TValue retVal;
        if (dictionary.TryGetValue(key, out retVal))
        {
            var retValRef = retVal;
            var lazy = new Lazy<TValue>(() => retValRef);
            retVal = lazy.Value;
            return lazy;
        }

        return new Lazy<TValue>(() => default(TValue));
    }
</code>```

OwnerDisplayName: Virtlink

Body:
If you are interested in the "magic value" route, yet another way to solve this is to overload the purpose of the Lazy class.  Although Lazy is intended to defer instantiation, nothing really prevents you from using like a Maybe or an Option.   For instance:

    public static Lazy<TValue> GetValue<TValue, TKey>(
        this IDictionary<TKey, TValue> dictionary,
        TKey key)
    {
        TValue retVal;
        if (dictionary.TryGetValue(key, out retVal))
        {
            var retValRef = retVal;
            var lazy = new Lazy<TValue>(() => retValRef);
            retVal = lazy.Value;
            return lazy;
        }

        return new Lazy<TValue>(() => default(TValue));
    }


问:
How can I tell when a program argument should be a configuration variable?
In simple cases I can see right away which direction to go. If I'm passing  a working directory to my program, and it's the same for the vast majority of the runs, make it a configuration variable.

Conversely if I have to change a configuration for every single run of the program than it should probably be an argument.

What happens if things live in a grey area? What should I pay attention to when deciding one or the other?

NOTE: I'm specifically working on a console program that might be daemonized down the road. I'm interested in this question in general, however.

答:
Nothing precludes command-line arguments from being used when starting a daemon, or configuration files from being used in interactive mode.

The general approach that works well and a lot of programs use is to have a list of prioritized ways to set program options:

Defaults

Global configurations (/etc or HKLM in the registry)

Local configurations (home directory or HKCU in the registry)

Environment variables

Program arguments

Options set while the program is running interactively

The program will start at step 1 and set values in each step, overriding previous values if applicable.

There is no reason this should work differently based on the program running interactively, in the background, at a command prompt, in a GUI, or as a daemon.

This is the way most experienced users and administrators will expect a program to work.


问:
Should a web app for a service access its data via its own API or directly?
I'm building a service that will consist of mobile and desktop apps, which will require me to build my own RESTful web API to easily keep the data for the service in sync.  I am also building a web app in Ruby on Rails.  Initially I plan to host everything on one server due to cost.

I'm curious which is a better design:

Have the Rails app access the database strictly via calls to the API
to allow for the future ability to host them on separate servers.

Host the API and Rails app on the same server always, and have each access the database directly.

I'm currently planning on the API to be private, with the possibility of opening up a small portion of it later.

Disclaimer: This would be my first time building my own API

答:
It is better to go with the first option. Having your 3 clients - mobile, desktop and webapp - use the API in the same way is a better design since all of them use the API in a consistent manner, and any changes in the API will be reflected as-is in all the three clients.

This way it is easier to debug and simpler to extend new features. If your Rails app talks directly to the database you will have to modify the data access code (instead of the ReST client code) in your Rails app every time the API changes and the Rails app might end up modifying the data in a different way than the desktop and mobile app, leading to inconsistencies.

In a nutshell: Keeping consistent access mechanism will ensure better maintainability.


问:
What is the best way to initialize a child's reference to its parent?
I'm developing an object model that has lots of different parent/child classes.  Each child object has a reference to its parent object.  I can think of (and have tried) several ways to initialize the parent reference, but I find significant drawbacks to each approach.  Given the approaches described below which is best ... or what is even better.

I'm not going to make sure the code below compiles so please try to see my intention if the code is not syntactically correct.

Note that some of my child class constructors do take parameters (other than parent) even though I don't always show any.

Caller is responsible for setting parent and adding to the same parent.

```<code>class Child {
  public Child(Parent parent) {Parent=parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  public Child Child {get; set;}
  //children
  private List<Child> _children = new List<Child>();
  public List<Child> Children { get {return _children;} }
}
</code>```

Downside: setting parent is a two-step process for the consumer.

```<code>var child = new Child(parent);
parent.Children.Add(child);
</code>```

Downside: error prone.  Caller can add child to a different parent than was used to initialize the child.

```<code>var child = new Child(parent1);
parent2.Children.Add(child);
</code>```

Parent verifies that caller adds child to parent for which was initialized.

```<code>class Child {
  public Child(Parent parent) {Parent = parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  private Child _child;
  public Child Child {
    get {return _child;}
    set {
      if (value.Parent != this) throw new Exception();
      _child=value;
    }
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public void AddChild(Child child) {
    if (child.Parent != this) throw new Exception();
    _children.Add(child);
  }
}
</code>```

Downside: Caller still has a two-step process for setting parent.

Downside: runtime checking – reduces performance and adds code to every add/setter.

The parent sets the child's parent reference (to itself) when the child is added/assigned to a parent.  Parent setter is internal.

```<code>class Child {
  public Parent Parent {get; internal set;}
}
class Parent {
  // singleton child
  private Child _child;
  public Child Child {
    get {return _child;}
    set {
      value.Parent = this;
      _child = value;
    }
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public void AddChild(Child child) {
    child.Parent = this;
    _children.Add(child);
  }
}
</code>```

Downside: The child is created without a parent reference.  Sometimes initialization/validation requires the parent which means some initialization/validation must be performed in the child’s parent setter.  The code can get complicated.  It would be so much easier to implement the child if it always had its parent reference.

Parent exposes factory add methods so that a child always has a parent reference.  Child ctor is internal.  Parent setter is private.

```<code>class Child {
  internal Child(Parent parent, init-params) {Parent = parent;}
  public Parent Parent {get; private set;}
}
class Parent {
  // singleton child
  public Child Child {get; private set;}
  public void CreateChild(init-params) {
      var child = new Child(this, init-params);
      Child = value;
  }
  //children
  private List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
  public Child AddChild(init-params) {
    var child = new Child(this, init-params);
    _children.Add(child);
    return child;
  }
}
</code>```

Downside: Can’t use initialization syntax such as new Child(){prop = value}.
Instead have to do:

```<code>var c = parent.AddChild();
c.prop = value;
</code>```

Downside: Have to duplicate the parameters of the child constructor in the add-factory methods.

Downside: Can’t use a property setter for a singleton child.  It seems lame that I need a method to set the value but provide read access via a property getter.  It’s lopsided.

Child adds itself to the parent referenced in its constructor.  Child ctor is public.  No public add access from parent.

```<code>//singleton
class Child{
  public Child(ParentWithChild parent) {
    Parent = parent;
    Parent.Child = this;
  }
  public ParentWithChild Parent {get; private set;}
}
class ParentWithChild {
  public Child Child {get; internal set;}
}

//children
class Child {
  public Child(ParentWithChildren parent) {
    Parent = parent;
    Parent._children.Add(this);
  }
  public ParentWithChildren Parent {get; private set;}
}
class ParentWithChildren {
  internal List<Child> _children = new List<Child>();
  public ReadOnlyCollection<Child> Children { get {return _children;} }
}
</code>```

Downside: calling syntax is not great.  Normally one calls an add method on the parent instead of just creating an object like this:

```<code>var parent = new ParentWithChildren();
new Child(parent); //adds child to parent
new Child(parent);
new Child(parent);
</code>```

And sets a property rather than just creating an object like this:

```<code>var parent = new ParentWithChild();
new Child(parent); // sets parent.Child
</code>```

...

I just learned that SE does not allow some subjective questions and clearly this is a subjective question.  But, maybe it is a good subjective question.

答:
I would suggest having "child-factory" objects which are passed to a parent method which creates a child (using the "child factory" object), attaches it, and returns a view.  The child object itself will never be exposed outside the parent.  This approach can work nicely for things like simulations.  In an electronics simulation, one particular "child factory" object might represent the specifications for some kind of transistor; another might represent the specifications for a resistor; a circuit which needs two transistors and four resistors might be created with code like:

```<code>var q2N3904 = new TransistorSpec(TransistorType.NPN, 0.691, 40);
var idealResistor4K7 = new IdealResistorSpec(4700.0);
var idealResistor47K = new IdealResistorSpec(47000.0);

var Q1 = Circuit.AddComponent(q2N3904);
var Q2 = Circuit.AddComponent(q2N3904);
var R1 = Circuit.AddComponent(idealResistor4K7);
var R2 = Circuit.AddComponent(idealResistor4K7);
var R3 = Circuit.AddComponent(idealResistor47K);
var R4 = Circuit.AddComponent(idealResistor47K);
</code>```

Note that the simulator need not retain any reference to the child-creator object, and AddComponent won't return a reference to the object created and held by the simulator, but rather an object that represents a view.  If the AddComponent method is generic, the view object could include component-specific functions but would not expose the members which the parent uses to manage the attachment.

Body:
I would suggest having "child-factory" objects which are passed to a parent method which creates a child (using the "child factory" object), attaches it, and returns a view.  The child object itself will never be exposed outside the parent.  This approach can work nicely for things like simulations.  In an electronics simulation, one particular "child factory" object might represent the specifications for some kind of transistor; another might represent the specifications for a resistor; a circuit which needs two transistors and four resistors might be created with code like:

var q2N3904 = new TransistorSpec(TransistorType.NPN, 0.691, 40);
var idealResistor4K7 = new IdealResistorSpec(4700.0);
var idealResistor47K = new IdealResistorSpec(47000.0);

var Q1 = Circuit.AddComponent(q2N3904);
var Q2 = Circuit.AddComponent(q2N3904);
var R1 = Circuit.AddComponent(idealResistor4K7);
var R2 = Circuit.AddComponent(idealResistor4K7);
var R3 = Circuit.AddComponent(idealResistor47K);
var R4 = Circuit.AddComponent(idealResistor47K);

Note that the simulator need not retain any reference to the child-creator object, and AddComponent won't return a reference to the object created and held by the simulator, but rather an object that represents a view.  If the AddComponent method is generic, the view object could include component-specific functions but would not expose the members which the parent uses to manage the attachment.


问:
Best OOP Practice in C#: Passing the Object as Parameter VS Creating a New Instance of the Object
First of all, I would like to know if passing an object as parameter is much better than creating another object again in a class that will use it again and second what are the pros and cons of each one?

Here's an example:

```<code>public class ClassWithTheObject
{

TheObject obj = new TheObject();

// Somewhere around the code
PassTheObjectHere anotherObj = new PassTheObjectHere(obj);

}
</code>```

Or just go straight declaring the class TheObject inside the PassTheObjectHere class? The case would be that both ClassWithTheObject and PassTheObjectHere classes will use the TheObject class.

Last question, is passing the object too many times causes some bad effects on the program?

Please enlighten me.

答: I think it really depends on the context you are working with. In your example, you are sending the TheObject instance to the PassTheObjectHere constructor, this way of working tells me that, inside your PassTheObjectHere instance, you are working with some previous  initializated data. So if the ClassWithTheObject is going to share the conversational state of the TheObject instance, you are doing right. Thats what i think


答:
stand out from other languages

No. As Jörg already commented, this form is actually used in many languages. It is probably the most common form of variable declaration by number of languages that use it. It was used back then with Pascal and related languages and it is now being used by all the new ones like TypeScript, Go, Rust—and Scala.

type identifier, if there is one, precedes the declaration

The

type identifier [ = value ]

form of declaration in C was in some respects a big mistake. Its serious problem is that it makes the grammar of the language contextual. Type and object identifiers look the same syntactically, but this form of declaration cannot be recognized without knowing that the first identifier identifies a type. So the compiler can't build the syntax tree without referring to the table of already defined types. This causes problems to templates, because the interpretation may depend on the parameter, so the compiler can't know whether it is looking at a type yet.

In C++ this means you have to use typename keyword in the ambiguous cases. Java and C# dodge this by not having typedefs, so you can't have related types, but that seriously limits usefulness of their templates. And it still complicates the compiler anyway.

On the other hand with declarations in the form

keyword identifier [ : type ] [ = value ]

the identifier after : (and some keywords like new) always means type and identifier in any other place never does and the grammar is context-free and everything is much simpler.

It is also more regular when the type is optional. You just omit it. In the C form, you have to replace it with special keyword.

Title: What's the rationale behind the ordering of Scala's value/variable declaration when including a type identifier?

Body:
I'm trying to wrap my head around Scala, and one thing that keeps throwing me is the ordering of a variable/value declaration when specifying the type.

```<code>val a = 0
</code>```

makes perfect sense. This looks pretty much like any other language.

```<code>val a: Int = 0
</code>```

parses really weird in my head; it just seems nonsensical. Why is the type immediately on the left of the assignment operator? When I cut this in my head, I see "... Int = 0", which obviously doesn't make any sense.

Is there a logical reason behind this that I can refer to? Obviously, as I look at Scala code more, I will adjust to it, but I'm also curious why Martin Odersky would choose to arrange it as such. It can't be just to stand out from other languages, where (as far as I know of), the type identifier, if there is one, precedes the declaration.


答:
It's a bit more complicated than that.

Firstly, understand the tradeoffs.  If you are going to pass a copy of the object (essentially "pass by value" semantics) rather than a reference to the original object, you are going to take a performance hit.  Whether that hit is justified or not depends on your software's functional requirements.

Secondly, it might make more sense semantically to write methods that accept the object by reference but return a new object, rather than modifying the passed object in-place or making a copy of it before passing it to the method.

```<code>var modified object = ReturnANewObjectFrom(theOriginalObject);
</code>```

When you create and return new objects in this fashion, you are taking advantage of immutability.  Wherever immutability makes sense, this makes sense to do.  Programs which utilize immutable objects and data structures are easier to reason about, especially when writing concurrent applications (applications that do more than one thing at a time, usually in separate threads or on separate cores).

Title: Best OOP Practice in C#: Passing the Object as Parameter VS Creating a New Instance of the Object

Body:
First of all, I would like to know if passing an object as parameter is much better than creating another object again in a class that will use it again and second what are the pros and cons of each one?

Here's an example:

```<code>public class ClassWithTheObject
{

TheObject obj = new TheObject();

// Somewhere around the code
PassTheObjectHere anotherObj = new PassTheObjectHere(obj);

}
</code>```

Or just go straight declaring the class TheObject inside the PassTheObjectHere class? The case would be that both ClassWithTheObject and PassTheObjectHere classes will use the TheObject class.

Last question, is passing the object too many times causes some bad effects on the program?

Please enlighten me.

Body:
It's a bit more complicated than that.

Firstly, understand the tradeoffs.  If you are going to pass a copy of the object (essentially "pass by value" semantics) rather than a reference to the original object, you are going to take a performance hit.  Whether that hit is justified or not depends on your software's functional requirements.

Secondly, it might make more sense semantically to write methods that accept the object by reference but return a new object, rather than modifying the passed object in-place or making a copy of it before passing it to the method.

var modified object = ReturnANewObjectFrom(theOriginalObject);

When you create and return new objects in this fashion, you are taking advantage of immutability.  Wherever immutability makes sense, this makes sense to do.  Programs which utilize immutable objects and data structures are easier to reason about, especially when writing concurrent applications (applications that do more than one thing at a time, usually in separate threads or on separate cores).


问:
What do you mean by Javascript component development?
I was recently asked by a recruiter if i knew component development with javascript. Since i was hearing this for the first time, i said i had no idea regarding it. I google it and got very few results which did not clear the exact meaning.

So what is component development mean with regard to javascript? Is it a new concept? Is it like creating plugins? Any pointers or examples would be really helpful

答:
The idea behind components is to make reusable pieces of code similar to plugins, like Date Pickers, Sliders and so on. They are similar as functionality, but the difference is that there is a common ground to make the integration easier. Just like jQuery plugin platform, but you don't depend on jQuery. In fact, every component can require different versions of jQuery. Yes, you've guessed it already, jQuery is a component too.

Here is the GitHub page where you can find these components: https://github.com/component
There is also a registry for them for easier retrieval: https://www.npmjs.org/package/component


答:
I would imagine that he was asking whether you're able to separate an application into components. The opposite would be a monolithic JavaScript app—frequent case in JavaScript world (with a small script growing over time).

The answer then could:

Explain the benefits of components (better architecture, ability to reason in terms of interfaces, ability to work on one part without having to deal with others and reduced global scope pollution),

Quote the commonly used JavaScript's module pattern, as well as require.js.

If you're interviewed for a position where you're expected to know node.js as well, you could also mention packages and npm. If not, mention them anyway.

Title: What do you mean by Javascript component development?

Body:
I was recently asked by a recruiter if i knew component development with javascript. Since i was hearing this for the first time, i said i had no idea regarding it. I google it and got very few results which did not clear the exact meaning.

So what is component development mean with regard to javascript? Is it a new concept? Is it like creating plugins? Any pointers or examples would be really helpful


问:
Design Pattern Question
I'm relatively new to the world of OOP, and having read through some design patterns, I'm struggling with that 'aha' moment.

I have the following objects
Event (Single event, with start time and end time, and it's availability)
EventCollection (Contains multiple instances of the Event, either cloned and set, or instantiated with 'new', and a date attribute)
Booking (With a collection of EventCollections)

This in turn, gives the ability to pick multiple event 'slots' per day.

The object, EventCollection will either contain static pre-computed time 'slots', for 'picking', or a set of Events for which have been booked.

Now my first stab at this, at least up to the point of EventCollection has been along these lines

```<code>class Event {
    protected startTime
    protected endTime
    protected status //available, booked, unavailable

    public function __construct(startTime, endTime, status = 'available')
    {
        this->startTime = startTime
        this->endTime = endTime
        this->status = status
    }

    public function changeStatus(status)
    {
        this->status = status
    }

    public function getStatus()
    {
        return this->status
    }
}

class EventCollection {
    protected date
    protected events

    public function __construct(date)
    {
        this->date = date
    }

    public function buildAvailableEvents()
    {
        // Loop through construction of events calculated by pre defined offsets
        this->events[] = new Event(startTime, endTime, 'available')
    }

    public function populateFromDb(SomeInterface db)
    {
        // Loop through construction of events determined by the interface of a database source
        this->events[] = new Event(startTime, endTime, status)
    }

    public function getAvailableEvents()
    {
        return this->getEvents('available')
    }

    public function getBookedEvents()
    {
        return this->getEvents('booked')
    }

    public function getUnavailableEvents()
    {
        return this->getEvents('unavailable')
    }

    protected function getBlocks(status)
    {
        selectedEvents = []
        foreach (this->events as event) {
            if(event->getStatus() == status)
            {
                selectedEvents[] = event
            }
        }

        return selectedEvents
    }
}

class Booking {
    protected name
    protected email
    protected moreCustomerDetails

    protected EventCollection

    public function __construct(name, email ...)
    {
        this->name = name
        this->email = email
    }

    public function addEventCollection(EventCollection eventCollection)
    {
        this->eventCollection[] = eventCollection
    }
}

//Client
booking = new Booking('me', 'me@myself.irene')
eventCollection = new EventCollection()->buildAvailableEvents()
booking->addEventCollection(eventCollection)
</code>```

Is this conforming to any pattern? I feel I'm missing something due to the fact I'm just using objects as simplified holders of arrays of objects. Can this be refactored into any such patterns to reduce class bulk? I do see some duplication of code, but have simply refactored that within the same class.

I have tried to separate into single responsibilities.

Can anyone suggest any improvements? This isn't operational code, I've just semi-stubbed it up.

答:
Design patterns are "best practice" solutions for challenges that occur frequently when designing software. The benefit of design patterns lies in

If you find that your problem (nearly) fits a design pattern, you have a short name to call your problem by, which eases communication with others

The solutions presented in design patterns are generally well researched and the advantages, disadvantages, challenges in implementation and when not to use it are usually well documented.

On the other hand, design patterns do not and will never cover all aspects of a design. They are usually focused more on design challenges that have non-trivial solutions or trade-offs.

A composition of (collections of) classes as you show in your example is not described in any design pattern I know of. This is not bad and is most likely because it is not considered a big enough design challenge to justify the effort it takes to write a design pattern about.

Title: Design Pattern Question


答:
Your question shows some misconceptions, I guess: if the alternative to

passing an object as parameter

is to create a new instance directly in the constructor PassTheObjectHere, then you are obviously not using any values/state of the previously created obj within PassTheObjectHere. If that is the case, it is pretty useless to pass obj as a parameter to PassTheObjectHere. In fact, in such a case I would typically check if TheObject has any member variables, which might make it a candidate for a static class (but don't get me wrong, I am not telling the usage of a static class would improve the design here in any way).

On the other hand, if the constructor of PassTheObjectHere needs the values / state of the previously created obj to work properly, it would be plain wrong to have a constructor like this.

```<code> PassTheObjectHere()
 {
      var obj = new TheObject();

      // ... do something which expects having obj
      // ... some values provided by the caller
 }
</code>```

(I hope this is obvious).

can passing the object too many times cause some bad effects on the program?

This is not a question of "too many times". One can pass objects around 1000 times correctly, which is fine, and one time wrong, which is bad. For example, if one passes obj to the constructor, and the constructor changes the state of obj in a way the caller does not expect (called a "side effect")

```<code>  PassTheObjectHere(TheObject obj)
  {
       // ... use methods/properties/values of obj
       // ... for this constructor

       // and finally
       obj.MakeValuesInvalid();
  }
</code>```

and the caller does something like

```<code>public class ClassWithTheObject
{

   TheObject obj = new TheObject();
   obj.Initialize()
   PassTheObjectHere anotherObj = new PassTheObjectHere(obj);
   obj.MethodWhichExpectsObjToBeValid();
}
</code>```

then the program now has a bug.

Fortunately, one can use one of the following alternatives to protect oneself from that:

Avoid the side effect by not changing "obj" within the constructor

If one needs to change "obj", they can make a copy beforehand within the constructor.

Avoid adding methods to TheObject which allow the change of internal state of obj (which is called "immutability")

Number 3 leads to the same code as 1, but with additional protection against introducing unintentional side effects at a later point in time, when PassTheObjectHere might be changed.

Body:
Your question shows some misconceptions, I guess: if the alternative to

passing an object as parameter

is to create a new instance directly in the constructor PassTheObjectHere, then you are obviously not using any values/state of the previously created obj within PassTheObjectHere. If that is the case, it is pretty useless to pass obj as a parameter to PassTheObjectHere. In fact, in such a case I would typically check if TheObject has any member variables, which might make it a candidate for a static class (but don't get me wrong, I am not telling the usage of a static class would improve the design here in any way).

On the other hand, if the constructor of PassTheObjectHere needs the values / state of the previously created obj to work properly, it would be plain wrong to have a constructor like this.

 PassTheObjectHere()
 {
      var obj = new TheObject();

      // ... do something which expects having obj
      // ... some values provided by the caller
 }

(I hope this is obvious).

can passing the object too many times cause some bad effects on the program?

This is not a question of "too many times". One can pass objects around 1000 times correctly, which is fine, and one time wrong, which is bad. For example, if one passes obj to the constructor, and the constructor changes the state of obj in a way the caller does not expect (called a "side effect")

  PassTheObjectHere(TheObject obj)
  {
       // ... use methods/properties/values of obj
       // ... for this constructor

       // and finally
       obj.MakeValuesInvalid();
  }

and the caller does something like

public class ClassWithTheObject
{

   TheObject obj = new TheObject();
   obj.Initialize()
   PassTheObjectHere anotherObj = new PassTheObjectHere(obj);
   obj.MethodWhichExpectsObjToBeValid();
}

then the program now has a bug.

Fortunately, one can use one of the following alternatives to protect oneself from that:

Avoid the side effect by not changing "obj" within the constructor

If one needs to change "obj", they can make a copy beforehand within the constructor.

Avoid adding methods to TheObject which allow the change of internal state of obj (which is called "immutability")

Number 3 leads to the same code as 1, but with additional protection against introducing unintentional side effects at a later point in time, when PassTheObjectHere might be changed.

ContentLicense: CC BY-SA 4.0


问:
Finding same numbers in a matrix
I have a question here and I am trying to find a solution of it. But I want to see some other opinions as well.

The problem is the following:

There is a matrix NxN which holds integer numbers. You should count all the different numbers in the matrix with the following conditions:

If two-or-more same numbers are adjacent (left, right, above, below) each of other it counts as one.

Example of the matrix:

```<code>1 2 3 4

1 1 2 4

5 6 2 2
</code>```

So for the above example there are: 7 different numbers because at the position of matrix : [1,1][2,1][2,2] there are 1s which has the condition of the problem true therefore these 3 numbers counts as one, at position [1,4][2,4] there are 4s so counts as one as well, and finally at positions [2,3],[3,3] and [3,4] there are 3s so count as one number.

My thought is to set the duplicate numbers to negative and then count only the positives, but I am not sure if that will work for all cases including and the corner cases.

My Code:

```<code>public class matrix
{
   public static void main(String[] args)
   {
      int[][] arr =
      {
          {1, 2, 3, 4},
          {1, 1, 2, 4},
          {5, 6, 2, 2},
      };

      for(int row = 0; row < arr.length; ++row)
      {
         for(int col = 0; col < arr[row].length; ++col)
         {
            //top
            if(row!=0)
            {
               if((arr[row][col] == arr[row-1][col]) || (Math.abs(arr[row][col]) == arr[row-1][col]) || (arr[row][col] == Math.abs(arr[row-1][col])))
               {
                  arr[row-1][col] = -arr[row-1][col];
               }
            }

            //botom
            if(row!=arr.length-1)
            {
               if(arr[row][col] == arr[row+1][col] || Math.abs(arr[row][col]) == arr[row+1][col] || arr[row][col] == Math.abs(arr[row+1][col]))
               {
                  arr[row+1][col] = -arr[row+1][col];
               }
            }

            //left
            if(col!=0)
            {
               if(arr[row][col] == arr[row][col-1] || Math.abs(arr[row][col]) == arr[row][col-1] || arr[row][col] == Math.abs(arr[row][col-1]))
               {
                  arr[row][col-1] = -arr[row][col-1];
               }
            }

            //right
            if(col!=arr[0].length-1)
            {
               if(arr[row][col] == arr[row][col+1] || Math.abs(arr[row][col]) == arr[row][col+1] || arr[row][col] == Math.abs(arr[row][col+1]))
               {
                  arr[row][col+1] = -arr[row][col+1];
               }
            }
         }
      }

      for(int row = 0; row < arr.length; ++row)
      {
         for(int col = 0; col < arr[row].length; ++col)
         {
            System.out.print(arr[row][col] + " ");
         }

         System.out.println();
      }
   }
}
</code>```

Expected Outcome:

```<code> 1  2  3  4

-1 -1  2 -4

 5  6 -2 -2
</code>```

Code Outcome:

```<code> 1  2  3 -4

 1 -1 -2 -4

 5  6  2 -2
</code>```

答:
My thought is to set the duplicate numbers to negative and then count only the positives

It sounds like you're using negatives as an "isDuplicate" flag. This is a great example of the difference between competitive programming and professional programming.

In a competitive environment, you're trying to optimize the time it takes to write the program. Declaring more variables (e.g. declaring an explicit "isDuplicate" data-structure) would require t.y.p.in.g. m.o.r.e. c.o.d.e. w.h.i.c.h. t.a.k.e.s. m.o.r.e. t.i.m.e. You don't have to declare anything new to use negatives, so you don't have to type as much, so it feels like that might be a productive approach.

In a professional environment, I would never consider using negatives this way. Use negatives if you actually want to perform arithmetic on negatives. There are several reasons:

Negatives have peculiar properties -- e.g. "1 + -1 == 0" and "-1 * -1 == +1"; these properties are nonsensical for the isDuplicate flag.

Most other developers (who review/update your code) wouldn't readily intuit the idea that "negative" means "isDuplicate" (unless, by some miracle, they were also competitive coders working from the same narrow problem-definition in the same narrow time-frame).

Requirements change. Today, "isDuplicate" is important information. Tomorrow, "isPrime" might be important information. Next week, we might decide to drop the "isDuplicate" information. The only way to keep these things straight is to give them very clear names.

As it happens, your bug does in fact relate to one of those peculiar properties of negative numbers. (I'll bite my tongue on the specific problems because, as the commenters noted, it's good for you to work through it.)

Title: Finding same numbers in a matrix


问:
Securing sensitive data from developers
I have an enterprise application running that uses both MySQL and MongoDB datastores. My development team all have SSH access to the machine in order to perform application releases, maintenance, etc.

I recently raised a risk in the business when users started storing highly sensitive data on the application that the developers have indirect access to this data which caused a bit of a storm, so I have now been mandated with securing the data so that it is not accessible.

To me this does not seem possible because if the application has access to the database then a developer with access to the machine and application source will always be able to access the data.

答:
You are right. If an application is capable of accessing content stored on corporate machines without the user passing extra information every time, then the programmers, maintainers, sysadmins etc. of the service provider can access that content. This is fundamentally unavoidable, and a major source of insecurity (Edward Snowden was a sysadmin, and had special privileges above "Top Secret" because there simply isn't a way of not granting them.)

The only way of avoiding this is to require the user to provide information that never makes it to the corporate machines. This is tedious and error-prone, since no one can possibly remember enough information to form a secure access barrier, and therefore people will immediately begin to store their credentials electronically in some place, which will then become the new attack target (and probably a weaker target than the one you are maintaining). But if you want to truthfully assert "Our employees are not physically capable of accessing our users' content", it's the only way.

(Note also that such a business model seems to be becoming politically untenable. Businesses have been forced out of operation by security services for trying to do exactly this. I understand that giving privacy guarantees has business value, but it can't possibly have more business value than the fundamental goal of staying in business.)

Title: Securing sensitive data from developers


问:
Changing method signature while keeping backwards compatibility
I've inherited an API to maintain.

Users can pass a callback function to the class which gets called on some event. The callback function is currently passed in a single argument.

I need to change the expected signature of the callback function to accept additional arguments.

This would be fine if everyones' callback function took in *args and **kwargs, but unfortunately they don't and it's too much work to get everyone to change them.

What is the cleanest way for me to make the change in the API while keeping the callback backwards compatible?

I have this as a shoe-in but it's not very future proof, nor is it very elegant:

```<code>...
if self._callback.func_code.co_argcount > 1:
    self._callback( data, additional_arg )
else:
    self._callback( data )
...
</code>```

答:
In Python, it's "Easier to ask for forgiveness than permission" - it is common "Pythonic" practice to use exceptions and error handling, rather than e.g. if checking up-front ("Look before you leap") to handle potential problems. The documentation provides a few examples that demonstrate where the latter can really cause problems - if the situation changes between the look and the leap, you have serious trouble!

On that basis, and given that a function will raise a TypeError if provided with the wrong number of arguments, you could use:

```<code>try:
    # Have a go with the new interface
    self._callback(data, additional_arg)
except TypeError:
    # Fall back to the old one
    self._callback(data)
</code>```

You could use a decorator function to wrap any callback:

```<code>def api_compatible(func):
    @functools.wraps(func)
    def wrapper(data, *args, **kwargs):
        try:
            return func(data, *args, **kwargs)
        except TypeError:
            return func(data)
    return wrapper
</code>```

Now it becomes:

```<code>self._callback = api_compatible(callback)
...
self._callback(data, additional_arg)
</code>```

Body:
In Python, it's "Easier to ask for forgiveness than permission" - it is common "Pythonic" practice to use exceptions and error handling, rather than e.g. if checking up-front ("Look before you leap") to handle potential problems. The documentation provides a few examples that demonstrate where the latter can really cause problems - if the situation changes between the look and the leap, you have serious trouble!

On that basis, and given that a function will raise a TypeError if provided with the wrong number of arguments, you could use:

try:
    # Have a go with the new interface
    self._callback(data, additional_arg)
except TypeError:
    # Fall back to the old one
    self._callback(data)

You could use a decorator function to wrap any callback:

def api_compatible(func):
    @functools.wraps(func)
    def wrapper(data, *args, **kwargs):
        try:
            return func(data, *args, **kwargs)
        except TypeError:
            return func(data)
    return wrapper

Now it becomes:

self._callback = api_compatible(callback)
...
self._callback(data, additional_arg)


问:
When is inlining worth it?
Modern compilers often inline functions when they decide it is worth it.

But here comes my question: how does one define if it is optimal to inline function at given time, or more important how to decide that it should be avoided?

答:
It is also likely to help when arguments are constants, as you can often eliminate whole code paths. Simple example:

```<code>function foo(b:Bool) {
  if (b) {
    lots;
    of;
    code;
  }
  else {
    and;
    even;
    more;
    code;
  }
}
</code>```

If b is a constant, that helps. Equally small int arguments that are loop bounds may allow for loop unrolling in the inlined body, and what not.

Furthermore, inlined functions make escape analysis easier, which can then again help you to avoid allocation.

The reduction of invocation cost is usually insignificant. The actual advantage that comes from function inlining are the subsequent optimization opportunities that may arise when you get rid of the indirection and can combine the information of the call site and the callee.

If any significant performance can be achieved by saving invocation cost, it is most likely achieved for JITs when they are able to inline virtual methods, because it gets rid of all the indirection involved with the vtable lookup. While you will need to cache more code, you don't need to load the vtable.

Title: When is inlining worth it?

Body:
It is also likely to help when arguments are constants, as you can often eliminate whole code paths. Simple example:

function foo(b:Bool) {
  if (b) {
    lots;
    of;
    code;
  }
  else {
    and;
    even;
    more;
    code;
  }
}

If b is a constant, that helps. Equally small int arguments that are loop bounds may allow for loop unrolling in the inlined body, and what not.

Furthermore, inlined functions make escape analysis easier, which can then again help you to avoid allocation.

The reduction of invocation cost is usually insignificant. The actual advantage that comes from function inlining are the subsequent optimization opportunities that may arise when you get rid of the indirection and can combine the information of the call site and the callee.

If any significant performance can be achieved by saving invocation cost, it is most likely achieved for JITs when they are able to inline virtual methods, because it gets rid of all the indirection involved with the vtable lookup. While you will need to cache more code, you don't need to load the vtable.


答:
You're quite right; some developers will always need access to the Live data, if only to diagnose production problems.  The best you can do is to limit the potential damage by reducing the number of people involved.

```<code>With great power comes great ... opportunity to really, *really* foul things up.
</code>```

Many developers won't want that responsibility and others, just won't be "ready" to hold it, and so shouldn't have.

Question: Why is your Development team performing Live releases?

I would suggest you need a Release Management "team" (even it that's just a subset of your team, plus Business representation to make any on-the-day "decisions", like "Go/No-Go")?  This would remove much of the "need" for developers to touch anything Live.

Do you have any sort of non-disclosure/ confidentiality agreement between developers and company?  It's heavy-handed, but it might have some merit.

Title: Securing sensitive data from developers

Body:
I have an enterprise application running that uses both MySQL and MongoDB datastores. My development team all have SSH access to the machine in order to perform application releases, maintenance, etc.

I recently raised a risk in the business when users started storing highly sensitive data on the application that the developers have indirect access to this data which caused a bit of a storm, so I have now been mandated with securing the data so that it is not accessible.

To me this does not seem possible because if the application has access to the database then a developer with access to the machine and application source will always be able to access the data.

Body:
You're quite right; some developers will always need access to the Live data, if only to diagnose production problems.  The best you can do is to limit the potential damage by reducing the number of people involved.

With great power comes great ... opportunity to really, *really* foul things up.

Many developers won't want that responsibility and others, just won't be "ready" to hold it, and so shouldn't have.

Question: Why is your Development team performing Live releases?

I would suggest you need a Release Management "team" (even it that's just a subset of your team, plus Business representation to make any on-the-day "decisions", like "Go/No-Go")?  This would remove much of the "need" for developers to touch anything Live.

Do you have any sort of non-disclosure/ confidentiality agreement between developers and company?  It's heavy-handed, but it might have some merit.


答:
The problem is your developers having access to the systems. If they need production data for debugging then give them a database dump where all that sensitive information is removed. Then the developers can work with that dump.

Deploying a new version should not involve any developer - that a pure admin task, or even better - a fully automated task. Also be aware of releasing and deploying being two very different tasks. If your process isn't aware of that then change it accordingly.

Title: Securing sensitive data from developers


答:
Security is not a magic wand you can wave at the end of a project, it needs to be considered and built in from day 1.  It is not a bolt-on, it is the consistent application of a range of solutions applied iteratively and reviewed regularly as part of a whole system, which is only as strong as the weakest link.

As it stands you have flagged a security concern which is a good first step.  Now as a minimum you have to define:-

What data you are trying to protect?

Who are you trying to protect that data from?

Who actually needs access to what (and when)?

What is the legal/financial/business impact of that data being compromised?

What is the legal/financial/business need for a person/group having access to the data?

What budget is the business willing to assign to a "get secure, stay secure" strategy when it was not a business requirement previously?

What access does the system need to the data?

What does this process and systems this application rely on?

What is done to secure those environments?

Who is going to be responsible for implementing it and reviewing the whole process?

Until you know all those in detail you really don't have anything to work with.  That information will define what mitigations to those threats you can (and cannot) apply and why.

It may be that the best thing to do is recognise that you don't have the necessary experience and that it would be best to bring in someone new with that experience.  I quite often hear the response that there's no budget - if it is considered genuinely important then the budget will be found.

Title: Securing sensitive data from developers


答:
Set up two deployments of the application which also use separated database deployments. One is the production deployment and one is the test deployment.

The test deployment should only have test data. This can either be fantasy data which got created for that purpose or a copy of the production data which was anonymized to prevent the developers from finding out the real people and entities behind the data.

Title: Securing sensitive data from developers


问:
Why doesn't Android use shared libraries?
In Android if you use a library in your app (such as the Support Library) the code for the library is duplicated on the device for each app that uses it.

Why can't android use the linux "shared library" concept, so each app wouldn't have to duplicate the library's code?

答:
Android does have a facility for sharing libraries, but it is a little cumbersome to use so seems to be rarely used in practice. Applications that use Google Play Services, for instance, use this model.

The support library, however, specifically does not use this facility because it is expected that applications may be closely tied to a specific version of it, and the shared library system only allows a single version to be installed at a time.


答:
This is largely due to the security model. On Android, each application runs in its own silo. This is completely different to a desktop OS, where all applications have full access to all the user's data.

If we have two applications, A and B, that both use a shared library. If they used the same copy, then potentially application A could break into application B's silo - which is not desired.

As paulkayuk comments, this is also to avoid DLL Hell - problems caused by applications expecting different versions of a shared library. These days storage is cheap - even on mobile - so avoiding DLL Hell is more important than saving a bit of storage space.

Title: Why doesn't Android use shared libraries?

Body:
In Android if you use a library in your app (such as the Support Library) the code for the library is duplicated on the device for each app that uses it.

Why can't android use the linux "shared library" concept, so each app wouldn't have to duplicate the library's code?


问:
Specific empty children classes
Is having empty children classes, just to specify, a bad practice?

Lets suppose I've a generic Product class. There are electrical, electronic and mechanical products. I need to represent all them and must be able to differ each one in some operations.
I've two options:

add a member named "type" in Product class to specify whether it's a electrical, electronic or mechanical product.

create children classes of Product, one for each kind of product: ElectricalProduct, ElectronicProduct and MechanicalProduct. As these classes don't differ from each other in methods or members - already defined in parent class - they would be all empty.

I consider second option a better approach, but is it the right way? I've never seen such thing on any application or library.

What do you thing? Any suggestion?

Edit:

Here is an example of doing it using second option: https://gist.github.com/tsouzar/c2ffebbcdad30920bf06

I can't see a better way of doing it, but I don't know if it is a good practice to have that empty classes.

答:
Now that you've explained more fully, it seems that there really is no subclass-specific logic.  In that case, inheritance is not the right choice.  If there really are only minor ways in which other parts of the code treat products, putting code into product classes would be wrong - a violation of separation of concerns which would encumber the product classes with knowledge of other parts of your system.  The sorting example makes that clear. Products should not know how they are sorted or stored or presented; if the code which sorts or presents objects is changed, the product class should not need to be rewritten.

I apologise for doubting you on that.  We see so many people here presenting questions which are based on poor OO knowledge and I assumed this was the case when I should have asked for more info first.

In fact...

The method overloading choice, as shown in your example code, is actually going against principles like the separation of concerns and DRY.  What is the common thing about the  add_product method?  It adds a product to the appropriate collection.  But in the example code, that single, fundamentally identical task is duplicated in three different places.  This is really scarcely different to a chain of if..then..else logic.

The logic is duplicated and any changes to the common behaviour will have to be duplicated in each place.  Mistakes are likely and will go undetected.

The product-adding code should not need to know what types of products are available.  All it needs to know is that there are a variety of products, each of which should be added to an appropriate collection.  Making it aware means you have to change this section of the code every time you add a new product.

A better way to do this, if you really do need a separate collection for each type of product, would be to have a map of product collections.  The key would be the product type.  Then you could have one single product_add method, which consults that map and adds the product to the right place.  Even if you discovered that there is some need for different product subclasses, this method doesn't need to know.  The object class itself could be the key to the map, for example.

Since more than one method is likely to want to update or read from those collections, it is probably better to have a Products object which stores the objects.  Whether it contains a map of N different collections or one collection which it knows how to filter/search by type is an implementation detail which need not concern other parts of your code.

In Summary

Since there really seems to be no product-specific code, extra empty classes are not only useless, they complicated your code and make it more fragile.  A 'type' member is better.

Most of your code doesn't even need to know that there is such a member.

In each domain (the clearly separate sections of your application), identify those few bits which genuinely need to differentiate between product types.

Isolate them in special helper classes or functions which will return the appropriate product (or do the appropriate thing which matches the type)

Maps are very useful (they can contain not only collections but other helper objects/functions to hand back to some other code to do the appropriate thing with this object) but should be hidden from anything but the privileged code which really needs to be product-type aware.

If you do that, not only will your code be cleaner and more elegant (free from ugly if..then..else chains, for one thing), if you ever do find a real need for product subclasses, almost none of your existing code will have to change.  And even they need only change their internal implementation, because their code will still be no concern of the product class or any of its subclasses.

There is still plenty of fun to be had with adding new classes in the respective domains to encapsulate any "I know what kind of products there are".  One challenge is differentiating between the bits of those code which are domain specific (e.g. sorting in a collection which is only relevant in one domain) from those which are actually general.  The list of all valid product types, for example, should be an enum which can be fetched by any product-aware domain-specific code.  Any map should use that enum as the type for its key.  Any function which takes a product "type" as a parameter should take a parameter only of that enum type and so on. Now, where in your code are you going to define that enum?

Title: Specific empty children classes


问:
How to test when arranging the data is too cumbersome?
I am writing a parser and as a part of that, I have an Expander class that "expands" single complex statement into multiple simple statements. For example, it would expand this:

x = 2 + 3 * a
```
<p>into:</p>
<pre class="lang-cs prettyprint-override"><code>tmp1 = 3 * a
x = 2 + tmp1
</code>```

Now I'm thinking about how to test this class, specifically how to Arrange the tests. I could manually create the input syntax tree:

var input = new AssignStatement(
    new Variable("x"),
    new BinaryExpression(
        new Constant(2),
        BinaryOperator.Plus,
        new BinaryExpression(new Constant(3), BinaryOperator.Multiply, new Variable("a"))));
```
<p>Or I could write it as a string and parse it:</p>
<pre class="lang-cs prettyprint-override"><code>var input = new Parser().ParseStatement("x = 2 + 3 * a");
</code>```

The second option is much simpler, shorter and readable. But it also introduces a dependency on Parser, which means that a bug in Parser could fail this test. So, the test would stop being a unit test of Expander, and I guess technically becomes an integration test of Parser and Expander.

My question is: is it okay to rely mostly (or completely) on this kind of integration test to test this Expander class?

答:
You're going to find yourself writing a lot more tests, of much more complicated, interesting, and useful behavior, if you can do so simply. So the option that involves

var input = new Parser().ParseStatement("x = 2 + 3 * a");
```

<p>is quite valid. It does depend on another component. But <em>everything</em> depends on <em>dozens</em> of other components. If you mock something to within an inch of its life, you're probably depending on a lot of mocking features and test fixtures.</p>

<p>Developers sometimes over-focus on the purity of their unit tests, or developing unit tests and unit tests <em>only</em>, without any module, integration, stress or other kinds of tests. All those forms are valid and useful, and they're all the proper responsibility of developers--not just Q/A or operations personnel further down the pipeline.</p>

<p>One approach I've used is to start with these higher level runs, then use the data produced from them to construct the long-form, lowest-common-denominator expression of the test. E.g. when you dump the data structure from the <code>input</code> produced above, then you can easily construct the:</p>

<pre class="lang-cs prettyprint-override"><code>var input = new AssignStatement(
    new Variable("x"),
    new BinaryExpression(
        new Constant(2),
        BinaryOperator.Plus,
        new BinaryExpression(new Constant(3), BinaryOperator.Multiply, new Variable("a"))));
</code>```

kind of test that tests at the very lowest level. That way you get a nice mix: A handful of the very most basic, primitive tests (pure unit tests), but have not spent a week writing tests at that primitive level. That gives you the time resource needed to write many more, slightly less atomic tests using the Parser as a helper. End result: More tests, more coverage, more corner and other interesting cases, better code and higher quality assurance.

Body:
You're going to find yourself writing a lot more tests, of much more complicated, interesting, and useful behavior, if you can do so simply. So the option that involves

var input = new Parser().ParseStatement("x = 2 + 3 * a");

is quite valid. It does depend on another component. But everything depends on dozens of other components. If you mock something to within an inch of its life, you're probably depending on a lot of mocking features and test fixtures.

Developers sometimes over-focus on the purity of their unit tests, or developing unit tests and unit tests only, without any module, integration, stress or other kinds of tests. All those forms are valid and useful, and they're all the proper responsibility of developers--not just Q/A or operations personnel further down the pipeline.

One approach I've used is to start with these higher level runs, then use the data produced from them to construct the long-form, lowest-common-denominator expression of the test. E.g. when you dump the data structure from the input produced above, then you can easily construct the:

var input = new AssignStatement(
    new Variable("x"),
    new BinaryExpression(
        new Constant(2),
        BinaryOperator.Plus,
        new BinaryExpression(new Constant(3), BinaryOperator.Multiply, new Variable("a"))));

kind of test that tests at the very lowest level. That way you get a nice mix: A handful of the very most basic, primitive tests (pure unit tests), but have not spent a week writing tests at that primitive level. That gives you the time resource needed to write many more, slightly less atomic tests using the Parser as a helper. End result: More tests, more coverage, more corner and other interesting cases, better code and higher quality assurance.


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

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

Do they really violate the three-tier separation ?

答:
Atwood's advice from 2004 rings true still today, only we now have the benefit of ORM as well.

http://blog.codinghorror.com/who-needs-stored-procedures-anyways/

Stored Procedures should be considered database assembly language: for
  use in only the most performance critical situations. There are plenty
  of ways to design a solid, high performing data access layer without
  resorting to Stored Procedures; you'll realize a lot of benefits if
  you stick with parameterized SQL and a single coherent development
  environment.


问:
Why do UTC Dates have different days of the week for some months?
I've been using the Javascript Date API for a calendar application, and I noticed that for every month between 3 and 9 (April and November) the methods Date.getDay() and Date.getUTCDay() return different results.

For each of these months, Date.getUTCDay() will consistently return the same as Date.getDay() - 1.

I eventually noticed this only happened when I built the dates with the default constructor. Once I tried using the Date.UTC() method to build the dates, everything went as expected.

Which is to say:

Date date = null;
for (var month = 0; month < 12; month++) {
  date = new Date(2014, month, 1);
  if (date.getUTCDay() !== date.getDay()) {
    console.log(month);
  }
}
```

<p>Will output: 3, 4, 5, 6, 7, 8 and 9.</p>

<pre class="lang-js prettyprint-override"><code>Date date = null;
for (var month = 0; month < 12; month++) {
  date = new Date(Date.UTC(2014, month, 1));
  if (date.getUTCDay() !== date.getDay()) {
    console.log(month);
  }
}
</code>```

Will not output anything.

I'm assuming it has something to do with DST, but I'd still like to have some deeper understading on what is happening and why.

Aside: I'm also assuming this is not something specifically related to Javascript, which is why I tagged the question with language-agnostic. Feel free to re-tag as appropriate.

Edit: Completely forgot to update the title after writing the question. I apologize.

答: You're constructing dates based on midnight local time.  During daylight savings time, which UTC does not follow, midnight local time is the same as 11 p.m. the day before UTC time, if your local time zone is set to London\Western Europe time.</p>


答:
Unit tests allow you to pin point specific items that break and where in the code they broke.  So they're good for very fine grained testing.  Good unit tests will help decrease debugging time.

However, from my experience unit tests are rarely good enough to actually verify correct operation.  So integration tests are also helpful to verify a chain or sequence of operations.  Integration tests get you part of the way through functional testing.  As you pointed out though, because of the complexity of integration tests, it is harder to find the specific spot in the code where the test breaks.  It also has somewhat more brittleness in that failures anywhere in the chain will cause the test to fail.  You will still have that chain in the production code however, so testing the actual chain is still helpful.

Ideally you'd have both, but at any rate, generally having an automated test is better than having no test.

Title: How to test when arranging the data is too cumbersome?

Body:
I am writing a parser and as a part of that, I have an Expander class that "expands" single complex statement into multiple simple statements. For example, it would expand this:

x = 2 + 3 * a
```
<p>into:</p>
<pre class="lang-cs prettyprint-override"><code>tmp1 = 3 * a
x = 2 + tmp1
</code>```

Now I'm thinking about how to test this class, specifically how to Arrange the tests. I could manually create the input syntax tree:

var input = new AssignStatement(
    new Variable("x"),
    new BinaryExpression(
        new Constant(2),
        BinaryOperator.Plus,
        new BinaryExpression(new Constant(3), BinaryOperator.Multiply, new Variable("a"))));
```
<p>Or I could write it as a string and parse it:</p>
<pre class="lang-cs prettyprint-override"><code>var input = new Parser().ParseStatement("x = 2 + 3 * a");
</code>```

The second option is much simpler, shorter and readable. But it also introduces a dependency on Parser, which means that a bug in Parser could fail this test. So, the test would stop being a unit test of Expander, and I guess technically becomes an integration test of Parser and Expander.

My question is: is it okay to rely mostly (or completely) on this kind of integration test to test this Expander class?


答:
Of course it is OK!

You always need functional/integration test that exercise the complete code path. And complete code path in this case means including evaluation of the generated code. That is you test that parsing x = 2 + 3 * a produces code that if run with a = 5 will set x to 17 and if run with a = -2 will set x to -4.

Below this, you should do unit tests for smaller bits as long as it actually helps debug the code. The finer grained tests you'll have, the higher probability that any change to the code will need to change the test too, because the internal interface changes. Such test have little long-term value and add maintenance work. So there is a point of diminishing returns and you should stop before it.


问:
Why aren't there cherry-pick requests?
One disadvantage to pull requests (aka merge requests) is lots and lots of merge commits.

It's not the worst thing, but it does clutter the commit logs, and make for lots of unnecessary non-sequential history.

```<code>A - C - E - G
   /   /   /
  B   D   F
</code>```

What I think would be better is to cherry-pick the commits.

```<code>A - B' - D' - F'
</code>```

Of course I can do that myself, but one of the advantages in a pull request system like Github, Bitbucket, Stash, or Gerrit is the ability to do this through the interface, immediately following a review of the changes. And doing that manually wouldn't show the pull request as accepted in the UI.

Why don't pull request tools offer "cherry-pick requests"?

I understand the advantages of merges and non-sequential history in the general case. (Otherwise, I'd be using SVN.) I am specifically taking about one or two commit changes from transient branches. (Many tools even help you delete the branch right after merging.) A one-commit change is probably the most common case for pull requests.

答:
The thing about pull requests is that it makes known that there are changes that someone wants to bring into the project.

If the owner/maintainer wants to cherry pick parts of the pull request, they can do that from that pull request.

And just because there is a pull request does not mean that the maintainer is not allowed, or incapable, of doing a rebase.

So this is indicative of a style that may be wanted in the history.

You can always display the history without the merge history, or even the other way around.

git log --merges

git log --no-merges

So it boils down to, I think:

The project owner wanting to enforce, or not, a certain style of history

The fact that you can get either set of information easily from Git itself, regardless.

You also mention that "A one-commit change is probably the most common case for pull requests" but I am not sure about that.

For one, the number of commits may be unknown due to the developers habits of doing micro-commits and then rebasing them.  Also, it is common for me to see project owners asking for those commits to be squashed in the CONTRIBUTING.txt file, or other communication.

Edit: Of course, I can't answer the question of why doesn't X, Y and Z companies do something.  Not sure anyone can, except for those entities.

Title: Why aren't there cherry-pick requests?


问:
GPL license for software and online service comparison
I have two questions that are linked :

1) Can someone sell a fork of an open-source software under GPL without distributing the source?
Example: Can I modify a little bit GIMP, repackage it under another name, and sell it as a commercial product without giving source code (like Adobe Photoshop) ?

Is this explicitely forbidden by GPL license?
(But then, if the source is not published, how could someone prove it reuses a part of GIMP's code?)

2) Same question for online websites.

Example: Let's assume SVG Edit is on GPL License (it's not but I haven't found a better example for my question). Can I reuse its code, fork the project, and do a commercial website "online SVG Editor" without sharing the code?

Note: These are just examples in order to understand how licenses work; of course I do want to do what is mentioned here.

答:
The GPL requires all derivative works to be licensed under the GPL as well. If you fork a GPLed software and distribute your fork, then you are required to offer your software under the GPL. This implies that you have to make the source code available.

From the GPL v3:

5. Conveying Modified Source Versions.

You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:

a) The work must carry prominent notices stating that you modified it, and giving a relevant date.

b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.

c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. […] This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.

[…]

6. Conveying Non-Source Forms.

You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:

[…]

You can choose to violate the license, and distribute binaries of your fork without also distributing the source. In the best case, no one finds out because no one is interested in your software since a better open source alternative exists. But then someone does look at your software – and finds it's incredibly similar to GIMP. Not just like GIMP is similar to Photoshop, but similar down to the way the menu is structured, or what special effects are available. This person writes a curious email to the GIMP team. Which in turn finds that this is in fact a GIMP fork (e.g. by looking at the disassembled binary or by looking at included assets such as textures) and that you are not distributing the software under the GPL.

What are the consequences?

If you violate the license of a GPL-licensed software, you loose the rights to use and distribute that software:

You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).

You are performing a copyright violation. GIMP representatives can shut down any attempt of yours to distribute your illegal software, e.g. by using the U.S.' DMCA mechanism. For example, you might have created a website to advertise and distribute your software. Using the DMCA, your hosting provider could be forced to suspend your website. If you don't stop there and are intent on repeatedly infringing the copyright in question, the issue could be escalated to a lawsuit (but no one would be interested in that).

There'll be a couple of angry blog posts. Not that problematic in itself, except that anyone searching online for your software will only find posts like “PiratedDraw is a cheap GIMP rip-off” instead of your software.

That's far too much stress to go through. Don't be dumb and read the licenses of software you use, even more so of software you want to distribute. In the absence of a license, you are not given any rights to distribute the software – by default, all rights are reserved.


问:
Building a calculator using MVC
I've been programming in Java for about 6 months, and I thought a good and challenging test of my skills would be to build a GUI calculator. I have very recently heard about this MVC idea, and I thought (perhaps foolishly) that it would be a good fit for this pet project. But I'm running into trouble during the design, and I'm not sure how to proceed.

So I have a Model, View, and Controller class. The Model is responsible for all the actual calculation; the View draws the calculator and the display; and the Controller:

passes button clicks to View

gets the display value from Model and passes it to View

Ah, but the buttons! I want to have a Button interface, where a Button instance has:

(unique) ID number;

Name;

function.

Then I would have my Controller build up a collection of Buttons, and [not sure how to do this] let both the View and Model use those buttons: View for drawing, Model for calculating.  Thus I have the revised list for Controller:

pass clicks to View

return Button ID to Model

get display value from Model and pass it to View

But the more I work on this, the more I can't figure out how this would all come together. So I have several related questions:

Should View really be responsible for sorting out which Button a click corresponds to? Should that be done in Controller?

Should I have more than one type of Button? Is it necessary to distinguish between numbers, operators, equals, etc.? Which of the three MVC classes needs to know the difference?

Is MVC even the right way to go here? Is there a more fundamental, accepted way of building an OOP calculator?

If MVC is indeed appropriate, what am I doing wrong? I think adding in the Buttons has really thrown me off.

答:
The big problem is deciding what is a Model in your application. Usually MVC is used for data presentation/manipulation, and you don't really have any data.

You could - for fun (education) - create for example a MathOperationModel that would be exchanged between Server and Client. Implementing typical CRUD (Create Read Update Delete) actions for it etc.

The calculator 'gui' would be probably a View of MathOperationModel, and all button - pushing would be GUI-side. Then after filling calculator fields (operand a, operand b, operator) the model would be submitted to the Controller and saved, or just calculated (either by Controller or some external class) and user could be redirected to a simple View for either double result or something that encapsulates it :) Or maybe the Model would keep the history and you would redirect him back to the View, just with the operands/operation fields cleared and a a list displaying history.

Long story short: you might do better if you think of an application that has to do with more data-oriented scenario (standard school students database or employees on a payroll or even an address book). Is not really a requirement, but it fits it well...

Title: Building a calculator using MVC


答:
1) Can someone sell a fork of an open-source software under GPL
  without distributing the source? Example: Can I modify a little bit
  GIMP, repackage it under another name, and sell it as a commercial
  product without giving source code (like Adobe Photoshop) ?

Holy cow NO! That's exactly the sort of behavior that the FSF made the GPL to fight against. This is blatantly obvious, but it sets up the rest of the questions, which have some details we can help you with.

Is this explicitely forbidden by GPL license? (But then, if the source
  is not published, how could someone proove it reuses a part of GIMP's
  code?)

Yes. The owners of the GPL'd code would sue you, and prove it in court in front of a judge and jury. The evidence they would show would include similarities between the programs' outward appearance, file structure, code-size, performance, any other characteristics I'm missing, documentation, as well as your personal background of asking if this was illegal on stack overflow.

2) Same question for online websites.

Depends how you make it online. You can, apparently, modify GPL'd code and let others interact with it online... as long as you don't distribute the software. This operates under the idea that you can take GPL'd code and do whatever you want to it as long as you don't hand it out to anyone else. Some codeshops have their own proprietary code adjustments to the gcc and never release those publicly or privately, but the employees can still use it in-house. (and every update they must recompile with their own code update).

Presumably, you could sell access to that service... but that kind of makes me uncomfortable. And the owners of the GPL'd code might throw some legal action your way if they feel you're violating their license. They may or may not be right. Remember, anyone can sue anyone for anything at any time.

Title: GPL license for software and online service comparison

Body:
I have two questions that are linked :

1) Can someone sell a fork of an open-source software under GPL without distributing the source?
Example: Can I modify a little bit GIMP, repackage it under another name, and sell it as a commercial product without giving source code (like Adobe Photoshop) ?

Is this explicitely forbidden by GPL license?
(But then, if the source is not published, how could someone prove it reuses a part of GIMP's code?)

2) Same question for online websites.

Example: Let's assume SVG Edit is on GPL License (it's not but I haven't found a better example for my question). Can I reuse its code, fork the project, and do a commercial website "online SVG Editor" without sharing the code?

Note: These are just examples in order to understand how licenses work; of course I do want to do what is mentioned here.


问:
Is "White-Board-Coding" inappropriate during interviews?
This is a somewhat subjective quesiton but I'd love to hear feedback/opinions from either interviewers/interviewees on the topic.

We split our technical interview into 4 parts. Write Code, Read & Analyse Code, Design Session & Code on the white board.

For the last part what we ask interviewees to do is write a small code snippet (4-5 lines) on the whiteboard and explain as they go through it. Let me be clear the purpose is not to catch people out. We're not looking for perfect syntax. Hell it can even be pseudo-code. but the point is to give them a very simple problem and see if their brain can communicate the solution to us. By simple problems I mean "Reverse a string", "FizzBuzz" etc...

Note that we always ask for an explicit language first. We're a .NET C# house. we've only said "pseudo-code" where someone has been blanking/really struggling with the code.

My question is "Is it inappropriate / unreasonable to expect a programmer to write a code snippet on a whiteboard during an interview ?"

答:
I think it's not a reasonable thing. We try to find candidates, which are good at the task we want them to do. Writing code on a whiteboard is not one of them and I don't think it's a valid filter to find good candidates.

Good code doesn't get written, it gets rewritten. A whiteboard is pretty much immutable, as it's hard to change once you wrote it. It should be as easy as possible to change your mind as soon as you understand the problem better.

Being in an interview is a stressful situation as it is, there is no need to put additional pressure on the candidate. Many computer people don't have a good handwriting. Modern IDEs provide lots of tools that you're used to. And being able to google something the minute you need it is also part of the working style of most programmers. Why take all these things away and create an artificial environment, that they'll never have to work in if you make them an offer?

We're also very interested in the ability to write good tests, maybe even do TDD. This is not possible to see during whiteboard coding.

Most of the clues that you could get out of a whiteboard coding session you also could get out of a pairing session - And I believe, pairing is a much better tool to get a feeling, how a candidate solves a problem and how he works. He can bring his/her own computer and work in an environment he's/she's comfortable with. And it's much easier to apply to the task you want them to do once they join. We for example have a large legacy code base, so we ask them to refactor some extracted code for the real project. And we actually pair as much as possible in our daily work, so it's well fitting.

While a whiteboard session probably helps to filter out bad candidates, it probably also filters out many good programmers.


问:
Are compilers used outside of development?
As far as my understanding goes, compilers are meant for developers compiling their code into executable (machine-code) files. Compilers don't extend to a client's machine or end-user system.

Instead, developers just use the compiler to convert their code into machine code, which is then transported to the other machines for use as applications.

Do compilers have a function outside of this process? If so, when are they used?

答:
Some programs are meta-programs: while running, they might generate some other program (or some source code) and compile it then run it somehow. Read also about multi-stage programming.

So to use these kind of programs, a compiler would be needed, even if the user does not know how to program himself (because the computer would generate some code which needs to be compiled).

For an example, see MELT (which generates C++ code to extend GCC) or J.Pitrat's CAIA artificial intelligence system (which generate C code -notably its own code- to solve combinatorial problems).

Also, some languages and some implementations nearly require a compiler to be present everywhere (in every program coded in that language & implementation). First, several web browsers contain a Javascript JIT engine (like V8). Also, most Common Lisp implementations -e.g. SBCL- contain a compiler (even useful to running applications, which might generate and evaluate expressions). Read also about homoiconic languages and Qine programs.


问:
Would you use C, today, for a software project?
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.

答: Yes. I spent most of my career programming C++, but now I write most of my code in Ruby and if I need performance or access to low level stuff I write a C extension. It's the future Man!</p>

ContentLicense: CC BY-SA 2.5