问:
Where to declare event handlers: Markup or Script?
If the event handler is declared in the markup, it'd be (kind-of) adding presentation logic to HTML.

```<code><button id="btn" onClick="foo()">Click Me!</button>
</code>```

If the event handler is declared in the script, it'd be (kind-of) hard to look at the code and figure out what button does.

```<code>document.getElementById('btn').onclick=foo;
</code>```

Is there any best-practice for this scenario?

The reason for this question is that I was attaching event handlers on page load via the script. However, I ran into a problem where the DOM element may not be present when the page loads (I'm using KnockoutJS's if binding), and the event is not bound to the handler. To attach the handler as and when the if condition is satisfied would complicate the code further. So now I'm thinking of moving my handlers to the click binding. What might be the potential pitfalls and what best-practices should I follow to avoid them?

答:
There's no right or wrong to this, both things are fine. There are a few things to consider which makes one or the other better in one or the other situation.

And actually, there are at least three ways of assigning event handlers:

Using an event handler attribute in HTML, like this:

```<code><button id="buttonSave" onClick="save()">Save</button>
</code>```

Using a script to set the property, like this:

```<code><button id="buttonSave">Save</button>

document.getElementById("buttonSave").onclick = save;
</code>```

Modifying the event handlers using addEventListener()

```<code>document.getElementById("buttonSave").addEventListener("onclick", save);
</code>```

Here's the decision path which I use.

A lot (>~20) of elements share the same handler -> 2. or 3., because doing it in JavaScript will save bytes, and in page loading traffic is slower than JavaScript.

Multiple handlers for a single element needed

Handler needs to be added or removed dynamically -> 3. addEventListener()

Handler doesn't change -> 1. HTML

Single handler sufficient

Handler needs to be added or removed dynamically -> 2. JavaScript

Handler doesn't change -> 1. HTML

The problem which you describe can actually be solved by moving the JavaScript code which installs the handlers into a JavaScript function which itself is installed as onload handler, so the JavaScript would only run when the DOM is ready for it.
There might still be a "race condition" (not in the sense of concurrency but in the sense of sequence) when other JavaScripts run and modify the DOM.
To prevent that, I usually do not install multiple onload handlers, but just a single handler which calls all the functions that need to be executed during onload in the required sequence.

Body:
There's no right or wrong to this, both things are fine. There are a few things to consider which makes one or the other better in one or the other situation.

And actually, there are at least three ways of assigning event handlers:

Using an event handler attribute in HTML, like this:

<button id="buttonSave" onClick="save()">Save</button>

Using a script to set the property, like this:

<button id="buttonSave">Save</button>

document.getElementById("buttonSave").onclick = save;

Modifying the event handlers using addEventListener()

document.getElementById("buttonSave").addEventListener("onclick", save);

Here's the decision path which I use.

A lot (>~20) of elements share the same handler -> 2. or 3., because doing it in JavaScript will save bytes, and in page loading traffic is slower than JavaScript.

Multiple handlers for a single element needed

Handler needs to be added or removed dynamically -> 3. addEventListener()

Handler doesn't change -> 1. HTML

Single handler sufficient

Handler needs to be added or removed dynamically -> 2. JavaScript

Handler doesn't change -> 1. HTML

The problem which you describe can actually be solved by moving the JavaScript code which installs the handlers into a JavaScript function which itself is installed as onload handler, so the JavaScript would only run when the DOM is ready for it.
There might still be a "race condition" (not in the sense of concurrency but in the sense of sequence) when other JavaScripts run and modify the DOM.
To prevent that, I usually do not install multiple onload handlers, but just a single handler which calls all the functions that need to be executed during onload in the required sequence.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
Copy-paste code.

If you don't itch when you are doing that, you are not a real programmer.

ContentLicense: CC BY-SA 2.5

Title: Is anything in programming truly evil?


答:
If the event handler is declared in the script, it'd be (kind-of) hard
  to look at the code and figure out what button does.

You answered your own question.

Registering the handler in the JS code separates the markup from the logic which is always a desirable property.

ContentLicense: CC BY-SA 3.0

Title: Where to declare event handlers: Markup or Script?

Body:
If the event handler is declared in the markup, it'd be (kind-of) adding presentation logic to HTML.

```<code><button id="btn" onClick="foo()">Click Me!</button>
</code>```

If the event handler is declared in the script, it'd be (kind-of) hard to look at the code and figure out what button does.

```<code>document.getElementById('btn').onclick=foo;
</code>```

Is there any best-practice for this scenario?

The reason for this question is that I was attaching event handlers on page load via the script. However, I ran into a problem where the DOM element may not be present when the page loads (I'm using KnockoutJS's if binding), and the event is not bound to the handler. To attach the handler as and when the if condition is satisfied would complicate the code further. So now I'm thinking of moving my handlers to the click binding. What might be the potential pitfalls and what best-practices should I follow to avoid them?


问:
How probability function is computed for the game Battleships?
I'm writing AI for the game and encountered this article that helped me out. I'm not sure how the probability function is computed. Does it rely on some advanced math I'm not understanding or for each move program generates randomly lots of possible set ups and then computes chance by counting times ship is encountered on the given field?</p>

答:
You enumerate every possible legal position that the largest (surviving) ship can be in. Call that N. Then for each cell, you count up how many of those positions include that cell. Call that c. Then your probability is c/N . You can deliberately targeting the largest ship as the probability map is more concentrated for that one, and therefore most likely to give a successful hint, although the authors continue to do the same for other ship sizes.

Whether this is a good measure is debatable - it assumes all remaining positions are equally likely, which in turn assumes your opponent scatters his ships at random. I suspect humans will tend to follow patterns they believe makes life difficult for the opponent, eg. not having touching ships (so that hitting one won't lead you into hitting another while in TARGET mode).


问:
Hamming Distance using a dictionary
First time poster. I'm currently programming a hamming distance program using a dictionary.

So if we start with the word "cat" and we want to transform it into "dog", the sequence is cat-->cot-->dot-->dog, and "full" to "tree" is full-->fuel-->feel-->teel-->tyee-->tree. All intermediates must exist in a dictionary.  I've implemented that part and it works quite well. My question is about the fringe cases. Some words have no transformations, such as dragon and cosmo. But that's fine, I implemented a quick check.

The real problem is there are lots of paths in which transformations are impossible and I can't seem to find a way to check whether they are impossible. For example, heist to flame is heist-->feist-->feast-->feaseX --> flame. Getting to the end point is impossible and an infinite loop occurs.

My possible options are that after around 20 transformations, I stop the calculation and throw an error, which is fine. Or, there might be way to detect a dead path before the program is ran, this is the best option, I'm not optimistic this is possible.

答:
You can solve this with a standard breadth-first search, with the addition of also storing the path taken to a node whenever you enqueue it in the to search queue.  BFS algorithms avoid loops by keeping a visited or discovered set.  Because they use a queue instead of a stack, they are not normally implemented using recursion, unless the implementation uses immutable data structures.

If you reach a point in the algorithm where you have nothing remaining in the to search queue, you know there is no possible path.  Note at this point, the visited set contains all the nodes reachable from the given starting point.  You can take advantage of that to precalculate and store all the sets of connected words, by just skipping the part where you check if you reached the goal word.  However, it's simpler and may often work out faster to just run the BFS.

Title: Hamming Distance using a dictionary


问:
How to avoid loop in a dept-search in a graph?
I must implement , in Lisp , a depth-search algorithm in an implict graph (namely a graph where I have the starting node, the goal node, and the successor function ,f, that give a node create his successors). There is a depth limit d. The algorithm must return a path (obviously cannot be minimal).

My problem is how manage the loop .

My first question is: If I use this following stupid method work it?

I have 2 list. The first is a LIFO ((I call it list1) when I insert in the head the succesor nodes. Evry time I expand the node in the head.

In the second list (I call it list2) I keep a list where put all nodes already met and every time that I expand a node I check if successor nodes obtained are in the list above (list2). For the nodes that  are in it (in list2) I don't insert in list1.

This method sucks because in the worst case i must keep in list2 all nodes of the graph and I must search at every expansion if some successor nodes are in the list2. (for example, this method certainly works with breadth-first search)
But at least it works? Or I would risk to cut relevant paths ?

Second question is:
How can I implement it efficiently (pseudocode, or simply idea)?

Thanks in advance

答:
Use recursion:</p>

```<code>;; you might want to implement sets using hash tables
(defun make-set (&rest elements)
  elements)
(defun set-empty-p (s)
  (null s))
(defun set-union (s1 s2)
  (union s1 s2))
(defun depth-search (start end next max-depth
                     &key (seen (make-set start))
                       (depth 0) (path (list start)))
  ;; untested!
  (when (eq start end)
    (return path))
  (when (= depth max-depth)
    (return t))                 ; no path
  (let ((candidates (set-difference (funcall next start) seen)))
    (loop for candidate in candidates
      for path = (depth-search candidate end next max-depth
                               :seen (set-union seen (make-set candidate))
                               :depth (1+ depth) :path (cons candidate path))
      do (when (listp path) (return path))
      finally (return t))))
</code>```

Body:
Use recursion:

;; you might want to implement sets using hash tables
(defun make-set (&rest elements)
  elements)
(defun set-empty-p (s)
  (null s))
(defun set-union (s1 s2)
  (union s1 s2))
(defun depth-search (start end next max-depth
                     &key (seen (make-set start))
                       (depth 0) (path (list start)))
  ;; untested!
  (when (eq start end)
    (return path))
  (when (= depth max-depth)
    (return t))                 ; no path
  (let ((candidates (set-difference (funcall next start) seen)))
    (loop for candidate in candidates
      for path = (depth-search candidate end next max-depth
                               :seen (set-union seen (make-set candidate))
                               :depth (1+ depth) :path (cons candidate path))
      do (when (listp path) (return path))
      finally (return t))))


问:
Do objects in OOP have to represent an entity?
Does an object have to represent an entity?

By an entity I mean something like a Product, Motor, a ParkingLot etc, a physical, or even a clear-cut non-physical conceptual object -- something that is well defined, with some core data clearly belonging to the object, and some functions/methods that clearly operate on the core data.

For example, I can have an object of a Demon, an entity in itself, an imaginary one perhaps and not physical but an entity nevertheless

Can an object be just a collection of methods, a common set of procedures that tie in with a common goal?

Example:  can a class be called MotorOperations or MotorActions, where there is no entity, but methods inside the class do things like

getMotorDataFromHTMLForm()

getMotorManufacturers()

selectMotorFromUserRequirements($requirements)

canMotorCanHandleOperatingConditions($conditions)

computePowerConsumptionForMotor($id)

A class is typically defined as data central to the object + operations on data.  So for a Motor there may be some motor variables relating to motor specifications, and there can be operations that combine those data to produce something.

In my case it is more like I have a class with operations on data + data that is passed through the class, there is no data centric to "Motor Operations", other than temporary pass-through-the-class data.

Question

Can classes represent entity-less objects?
If not, why they are bad/incomplete/non-OOP-centric?  Are there ways they need to be changed/improved conceptually to be in line with OOP?

答:
Taking the given examples:

```<code>getMotorDataFromHTMLForm()
selectMotorFromUserRequirements($requirements)
</code>```

These look like "factory" methods, that would return a Motor object. The second implies that either you're creating a new object to meet requirements, or you have a database or in-memory collection of motors that you're examining. In which case it should be a method on that. Or it could be a method on the requirements object.

```<code>getMotorManufacturers()
</code>```

From where are you getting them? That's what this should be a method of.

```<code>canMotorCanHandleOperatingConditions($conditions)
computePowerConsumptionForMotor($id)
</code>```

These look like they should be methods on Motor.

Body:
Taking the given examples:

getMotorDataFromHTMLForm()
selectMotorFromUserRequirements($requirements)

These look like "factory" methods, that would return a Motor object. The second implies that either you're creating a new object to meet requirements, or you have a database or in-memory collection of motors that you're examining. In which case it should be a method on that. Or it could be a method on the requirements object.

getMotorManufacturers()

From where are you getting them? That's what this should be a method of.

canMotorCanHandleOperatingConditions($conditions)
computePowerConsumptionForMotor($id)

These look like they should be methods on Motor.


问:
Nested POJOs, exposing collections, detecting changes
I have a couple plain object classes to represent data read from a file. They look something like this:

```<code>public class Command {
    private String name;
    private List<Message> messages;
}
public class Message {
    private Type type;
    private Map<String, Object> params;
}
</code>```

with getters and setters for the variables. However, I wasn't sure how to expose the messages list or the params map. At first I wanted to have a getter that just returns the list or map, to avoid having to write a bunch of add/remove/iterate methods for each list or map. The collection objects have these methods and many more, so it seemed most convenient to just return those objects. However, I also the objects to know when data is changed, so that a view can be updated accordingly, or to keep track of if a particular file has been modified and needs to be saved. This means I would have to implement delegates for add/remove/iterate/keyset/entrySet/etc for those fields, but would add a lot of extra methods and make the code much less convenient. What is the best practice here, when dealing with plain objects that can have lists, maps, sets, etc in them, while also being able to know when data is changed?

I also had a related question regarding whether a child object should have a reference to the object that created it. I was thinking about this because in the event that a Message object is modified, how does its parent Command object know about that change? Should the Message class have events that Command subscribes to with listeners, or should the Message object have a reference to the Command object it is contained in, and call a method/set a field in that Command object when data is modified? What is the best practice here, or should I completely change how file data is being stored as objects?

答:
It is good practice not to expose contained collections directly to clients. There is a list of "standard" methods that you typically provide on the containing class to manage the relationship (get all, add, remove, etc.).

In theory, it's advised that you don't ever return the actual collection to the client, rather an immutable copy of it containing the same objects. This way the client can't modify the collection directly, but has to go through your delegate methods.

Bi-directional relationships are not a problem, but slightly more tricky; use them where needed, but avoid the additional complexity if you don't. You have to make sure that the bi-directionality is maintained correctly in the model, and not rely on client code to do it. The complexity will depend on which mutations are possible after construction, but generally:

If you add a Message to a Command, that Command must always be the one set on the Message (and vice versa)

If you remove a Message from a Command, the Command reference of the Message must be set to null (and vice versa)


问:
What is the actual value of a consistent code style
I am part of a consultant team implementing a new solution for a customer. I am
responsible for the majority of code reviews on the client-side codebase (React and javascript).

I have noticed that some team members use unique coding patterns to a point that I could pick a file at random at tell who was the author from the style alone.

Example 1 (one-off inline functions)

```<code>React.createClass({
  render: function () {
    var someFunc = function () {
      ...
      return someValue;
    };
    return <div>{someFunc()}</div>
  }
});
</code>```

The author argues that by assigning a meaningful name to someFunc the code will be easier to read. I believe that by inlining the function and adding a comment instead the same effect could be achieved.

Example 2 (unbound functions)

```<code>function renderSomePart(props, state) {
    return (
      <div>
        <p>{props.myProp}</p>
        <p>{state.myState}</p>
      </div>
    );
}

React.createClass({
  render: function () {
    return <div>{renderSomePart(this.props, this.state)}</div>;
  }
});
</code>```

This is how we usually do it (avoids having to pass state and props):

```<code>React.createClass({
  renderSomePart: function () {
    return (
      <div>
        <p>{this.props.myProp}</p>
        <p>{this.state.myState}</p>
      </div>
    );
  },
  render: function () {
    return <div>{this.renderSomePart()}</div>;
  }
});
</code>```

While these coding patterns are technically correct they are not consistent with the rest of the codebase nor with the style and patterns that Facebook (the author of React) hints at in tutorials and examples.

We need to keep a fast pace in order to deliver on time and I don't want to burden the team unnecessarily. At the same time we need to be on a reasonable quality level.

I am trying to imagine myself as the customers' maintenance developer faced with inconsistencies like these (every component might require you to understand another way of doing the same thing).

Question:

What is the value as perceived by the customer and its maintenance developers of a consistent code base vs. allowing inconsistencies like these to remain and potentially spread?

答:
The topvoted answers here repeat the easily agreeable theoretical best practices detailing how we would all like our codebases to be. But real code somehow never looks like that. If you try to make that perfect codebase, you will almost inevitably fail. That is not to say that we shouldn't try to do better, but there has to be a limit for how far from the realistically achievable we set our goals.

Too much focus on minor stuff has the risk of losing focus on more important issues, like how to solve the job in the overall most efficient manner.

I wouldn't refer to you first example as style, style is the choices where there in no clear right or wrong, in this case the extra function is code bloat with no upside. It is only 2 extra lines, still easy to read, and easy to fix, so this example itself is no big issue.

The much bigger issue is the convoluted code bloat. Wrapper functions, class hierarchies, and all sorts of other constructs, where the surrounding code is complex enough that it isn't obvious that they serve no real purpose. If there is obvious bloat in the code, there is probably a lot more non-obvious bloat. It is a lot harder to do something about, and harder to spot, but also a far bigger issue.

About customers

Customers tend to focus on getting a working product that solve their needs. Even if you have one of the few customers that do worry about code quality, it is going to be a secondary priority, and their idea of code quality might not be perfectly consistent with yours. The customer company may have its own programmers, but it is still management that will decide whether or not you did a good job, and management most likely doesn't even know what code quality means.


问:
Strategy for fixing signed/unsigned warnings
I'm working on obtaining a clean compile with -Wsign-conversion for existing library code. The library is 25 years old or so. Eventually, this higher bar will be a security gate, and all check-ins will need to meet it or be rejected.

The existing library code does a fair amount of the following (a gross simplification that captures the essence):

class SHA1 : <inherited interfaces (contracts) and classes (behaviors)>
{
    ...
    enum {DIGEST_SIZE = 20U};
    unsigned int MaxDigestSize() { return DIGEST_SIZE; }
    ...
    int m_digestSize;
}
```

<p>Then, the library does things like (the interaction is more complex, but this captures the essence):</p>

<pre class="lang-none prettyprint-override"><code>if(m_digestSize == -1)
    m_digestSize = MaxDiegstSize();
</code>```

External callers may use it like:

```<code>SHA1 sha;
...

// Calculate truncated digest
sha.Final(buffer, 8 /*signed or unsigned*/);
// Calculate using full digest
sha.Final(buffer, -1 /*signed*/);
// Calculate using full digest
sha.Final(buffer, sha.MaxDigestSize() /*unsigned*/);
</code>```

The reason -1 is popular is because the following "just works" (notice the switch from SHA-1 to SHA-512):

```<code>SHA512 sha;

// Calculate using full digest
sha.Final(buffer, -1 /*signed*/);
</code>```

For the library, we want to convert to unsigned types to squash the warning. Then, setup an enum {DEFAULT_DIGEST_VALUE=...}; to handle the case of "default digest" that was compatible with the existing "-1 pattern". Finally, remove the compares to -1 and use a compare with DEFAULT_DIGEST_VALUE.

But enum {DEFAULT_DIGEST_VALUE=std::numeric_limits<unsigned int>::max()}; turned out to be a dead end due to limitations in numeric_limits.

Someone suggested to use UINT_MAX, but I'm not sure if I should use it (OS X lacks <cstdint>, so it introduces a C header dependency). Other potential candidates are __INT_MAX__ * 2U + 1 (from <limits> on OS X), and ~(0) (popular in lots of library code, but maybe not correct). In fact, I'm not sure this is the proper path in general.

What is the proper or best way to:

switch to unsigned for consistency and eventual security gate

handle the "-1 pattern" for existing, non-library callers

provide a portable, C++ solution

address potential issues with bit patterns

My apologies for asking a simple question. I am a security architect by trade. I need the help of the software architects because I don't have the software engineering experience.

From the comments, here's some more information regarding constraints:

Existing Code - The library already exists, and its called Crypto++. It was authored in the 1990s, and it enjoys continued development. It is cross platform, and runs on the BSDs, Linux, OS X, Solaris, Windows. The solution needs to support older standards like C++98 and C++03. We can drop support for C++98 if the community agrees.

ABI Changes - we can change the API if the community agrees. I'm fairly certain that will happen when we make the policy change of a "clean compile as a security gate." We don't need to have 100% compatibility, but we do need to handle an existing code base of users using -1 in the field. We can even give users warning to modify their code with the preprocessor macro CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY. But in the end, things have to "just work" for them.

答:
This is really more a case of the design of an API being more idiomatic C (and not even good idiomatic C at that) rather than idiomatic C++.

If your callers are explicitly plugging in -1 or the result of MaxDigestSize(), it means they know ahead of time that they're using that default value.  It also means they can leverage the C++ concept of a default value for an argument:

```<code>class SHA {
public:
  static const size_t MAX_DIGEST_SIZE = 20;
   ...
  Final(Buffer buffer, size_t digest_size = MAX_DIGEST_SIZE);
};
</code>```

Callers wanting the largest digest invoke Final(buffer) and those wanting shorter ones invoke Final(buffer, digest_size).  The important thing here is that this keeps all understanding of the default behavior inside the class and eliminates magic numbers and the signed escape hatch being used to support them.

You will, of course, have to go through all invocations of Final() and change the ones using -1 or MaxDigestSize() to drop their second arguments, but this is a good thing because it gets the problem children out of the code base.  It's tedious, but it's worth doing.

If you're constrained by not being able to remove these things from the existing code, you will not be able to switch to unsigned values and expect warning-free compilation.  The best way to proceed in this case would be to have Final() validate its input and throw an exception if it's out of the expected bounds.  (The code should be doing this anyway for safety.)

Body:
This is really more a case of the design of an API being more idiomatic C (and not even good idiomatic C at that) rather than idiomatic C++.

If your callers are explicitly plugging in -1 or the result of MaxDigestSize(), it means they know ahead of time that they're using that default value.  It also means they can leverage the C++ concept of a default value for an argument:

class SHA {
public:
  static const size_t MAX_DIGEST_SIZE = 20;
   ...
  Final(Buffer buffer, size_t digest_size = MAX_DIGEST_SIZE);
};

Callers wanting the largest digest invoke Final(buffer) and those wanting shorter ones invoke Final(buffer, digest_size).  The important thing here is that this keeps all understanding of the default behavior inside the class and eliminates magic numbers and the signed escape hatch being used to support them.

You will, of course, have to go through all invocations of Final() and change the ones using -1 or MaxDigestSize() to drop their second arguments, but this is a good thing because it gets the problem children out of the code base.  It's tedious, but it's worth doing.

If you're constrained by not being able to remove these things from the existing code, you will not be able to switch to unsigned values and expect warning-free compilation.  The best way to proceed in this case would be to have Final() validate its input and throw an exception if it's out of the expected bounds.  (The code should be doing this anyway for safety.)


问:
Best practices for scope of returned data per stored procedure
I have the following situation:

table1
------------
ID  Name    Param1  Param2  Param3  RegistrationID
1   Test    Value1  Value2  Value3  101

table2
------------
RegistrationID  LangID  Value
101             EN  English-Value
101             DE  German-Value
101             IT  Italian-Value
```

<p>I am interested in what are good programming conventions. For example</p>

<ol>
<li><p>Return two stored procedures </p>

```select id, name, param1, param2, param3, registrationID from table1 where id = @ID

select registrationID, langid, value from table2 where registrationid = @RegistrationID
```

<p>If necessary on a different layer merge these data into a single class.</p></li>
<li><p>Have one stored procedure that will return everything</p>

```select id, name, param1, param2, param3, registrationID, langid, value from table1
inner join tabl2 on table.registrationid = table1.registrationid
where id = @ID
```

And create a class from returned data.

The approaches are different, because solution 1 will have to access DB twice but it is easier to reuse stored procedures since they do not join objects (tables).
In solution 2 only one trip to DB is needed, but stored procedure gets messy and returns both foreign key and all its values.

I know there is no one answer for all, but what is a good practice? I lean towards solution 1, but I am slightly concerned regarding DB round trips.

答:
If you data requirement is the joined data (solution 2) then tailor your stored procedure for that data.  Overly reusing a bunch of stored procedures that are select * from table is best case... cumbersome and worst case... high performance impact (think, pulling back more data than you need over the wire).

Let the relational database management system do what it does best, and go with the stored procedure that gives you back the data you need, and only the data you need.


问:
Agile requirements gathering in embedded project
I am working on a project where we develop an embedded application for a Linux-based device handling data from different sensors and visualizing them to the end user. We try to use Scrum process but came across different difficulties related to our and management team perception of Requirements Engineering.

Basically Scrum recommends User Stories maintained in a Backlog prioritized by the Product Owner. Scrum assumes that there is no "requirements freeze" or single document describing the project at the start.
User stories can be added "on demand" when stake holders thinks they are necessary to have a "releasable" software version.

On the other hand embedded system due to tight coupling with hardware need upfront specification of different system features, e.g.

HW / SW interfaces (e.g. shared memory between main CPU and FPGA)

Data formats, what and how will be stored with what frequency

hard real time requirements, how fast must the system react on certain events

interaction with other disciplines, eg. HW, optics, mechanics

What are the best practices to handle requirements engineering in embedded systems in a lightweight (Agile) way (in contrary to e.g. automotive processes) ?

答:
Scrum is not concerned with requirements freezing or not. Scrum works equally well if you start with 100 stories in your backlog that never change, or 5 stories with more being added/changed all the time. Scrum is supposed to be an iterative process and it requires a totally different mindset than more traditional waterfall models.

Technically with Scrum you could have several sprints where all the user stories are gather requirements for foo, gather requirements for bar, etc. I really recommend not doing this though, because it will waste a ton of effort trying to gather every requirement when you know the least about what you are building.

What I do recommend is working to prioritize all the high level features that you know you need, and then start with the highest priority and gather requirements only for that single feature and then begin implementing them, and only move to the next feature when you believe you have completed the current feature. The reason this is a superior approach is because at the worst case, its the same as the other approach, but in most cases it will save effort overall. If any assumptions/early requirements you made about the highest priority feature change during development using this method there is no chain reaction of other requirements affected because you haven't created them yet, instead when you get to related features you have many things you know because parts of the system already exist.


问:
Why does SOP permit cross-origin form submissions?
Same Origin Policy does not prevent origin foo.bar from creating a form with action attribute set to another origin baz.duh and even allows to programmatically submit this form without the user knowing through untrusted events originating via JavaScript just by loading the page. To solve this issue, programmers are forced to use CSRF tokens.

If AJAX requests originating from XMLHttpRequest and canvas objects are subject to Same Origin Policy and not allowed to access the response, why aren't form submissions/XHR requests simply disallowed? What is the reasoning behind this allowance?

I know endpoints accepting the GET request method can be exploited by images as well, but this question is about POST and similar method forms only. Wouldn't the need of CSRF tokens vanish if SOP didn't permit cross-origin form submission? What purpose does cross-origin form submission serve?

答:
The Same Origin Policy protects the client. CSRF tokens protect the server.

SOP prevents malicious site A from accessing cookie credentials held by the client for site B which would otherwise be submitted along with the cross-origin request. See How do web servers enforce the same-origin policy? (short answer: they don't)

The link in the other answer states:

While prevention of cross-origin writes would mitigate entire classes of web security vulnerabilities (CSRF, XSS, etc), the web is a far richer platform because some forms of Cross-Origin Writes are permitted in most cases.

In particular, things like OpenID and quite a lot of credit card processing systems make use of the ability to pass state from one domain's system to another. So banning all cross-origin HTTP would be seriously limiting. Therefore an alternative mechanism is needed. CSRF tokens prove that whatever's sending the HTTP request (remember, not necessarily a browser at all!) got the authorization token from a web page that the server previously emitted.

ContentLicense: CC BY-SA 4.0


问:
How much information can a user reasonably process from a UI?
As an example, say there's an interface that contains a table/grid of information that is periodically updated.  The table is meant to represent an event that has happened, perhaps the date and time of a stock price change.

The actual frequency of these events could be dozens of events per second.  This is obviously too much information for a user to process/understand, so I'm trying to find out how much information a user COULD process in a given amount of time so that we can throttle the data and come up with an alternate display.

I know some studies have been done on this, but I can't seem to find an authoritative source.

答:
This depends on a lot of factors:

Is the table as a whole updating (eg, every row changes), or is it just one row at a time?

If it's a row at a time, is it an arbitrary row that a user has to jump their eyes to, or is it always a new row at the top? The former would require more spacing between updates than the latter.

How much data is on each row?

Is most of it unimportant, and only the outliers are important to the user (in which case they're probably skimming the data, so you can put it out a lot faster)?  Or does all the data need to be read and mentally processed.

My (admittedly minimal- a couple college classes worth) experience with calculating user experience metrics (like data processed per second) has lead me to believe that the field is pretty immature, and that you're better off doing empirical measurement.  If you really want to try to optimize a specific UI, nothing beats usability testing.


答: Depending on your scenario, you either would expose your collection as a ReadOnlyCollection (or the like, depending on your programming language), or you would use an ObservableCollection (that has events for add, remove, etc), which will allow you to react to changes. Consider if the latter is really necessary though. In most scenarios you would go the first route. If a downstream developer is allowed to make changes to the collections you manage, then make this an explicit API.

Title: Nested POJOs, exposing collections, detecting changes

Body:
I have a couple plain object classes to represent data read from a file. They look something like this:

```<code>public class Command {
    private String name;
    private List<Message> messages;
}
public class Message {
    private Type type;
    private Map<String, Object> params;
}
</code>```

with getters and setters for the variables. However, I wasn't sure how to expose the messages list or the params map. At first I wanted to have a getter that just returns the list or map, to avoid having to write a bunch of add/remove/iterate methods for each list or map. The collection objects have these methods and many more, so it seemed most convenient to just return those objects. However, I also the objects to know when data is changed, so that a view can be updated accordingly, or to keep track of if a particular file has been modified and needs to be saved. This means I would have to implement delegates for add/remove/iterate/keyset/entrySet/etc for those fields, but would add a lot of extra methods and make the code much less convenient. What is the best practice here, when dealing with plain objects that can have lists, maps, sets, etc in them, while also being able to know when data is changed?

I also had a related question regarding whether a child object should have a reference to the object that created it. I was thinking about this because in the event that a Message object is modified, how does its parent Command object know about that change? Should the Message class have events that Command subscribes to with listeners, or should the Message object have a reference to the Command object it is contained in, and call a method/set a field in that Command object when data is modified? What is the best practice here, or should I completely change how file data is being stored as objects?


答:
I'm gonna turn this around and say that while there's no absolute evil, there are tools and constructs which make it more plausible for our feeble humans with such a limited skull size to make mistakes than others.

So I'd say you could talk about the evilness of a construct based on how likely people are to make mistakes with it. Sure you can cut bread with a knife or with a chainsaw with blades as grip, but one is more likely to cause damage than the other, even though you may be able to pull it off with enough care.

Title: Is anything in programming truly evil?

Body:
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...


问:
Is REST only limited to optimistic concurrency control?

Context

Due to the statelessness of the REST architectural style involving that each requests stands completely alone, leading server to never store any informations about client.

Thus, pessimistic concurrency control are not suitable because it would requires that server store which client gets the lock on a resource.
Optimistic concurrency control are then used, with the help of Etag header. (btw, as I asked there https://stackoverflow.com/questions/30080634/concurrency-in-a-rest-api)

Problem

The main problem with an optimistic concurrency control mechanism is that you allow all the time, all clients, to perform any operations.

And i would like to avoid that without breaking the statelessness principle of REST. I mean that all clients cannot perform any operation at any time.

Question

In my mind, it would possible with a semi-optimistic concurrency control mechanism, like that:

Clients can request a token

Only one token can be generated and has a limited period of validity

To perform operations on resources (such as POST or PUT), client must give this token as part of the body (or header?) of the request. Client that don't have the token cannot do these operations.

It is very similar to optimistic concurrency control, except that only one client can do some operations (the one that got the token)... at the opposite of "all clients can do all operations".

Does this mechanism is compatible with a REST architectural style ? Does it break any of its constraint ?
I was thinking to ask on SO, but this seems more an high-level question, related to software design.

答:
You should never ( as in never ever EVER) lock any resource while waiting for a user interaction.

At some point some of your users will take off for a long weekend leaving some vital records locked.

Ah but you won't let that happen because you have some clever time out/deadlock resolution scheme; then at some point this will go horribly wrong and a user who got a nice "your widget has been ordered" message will be screaming at the help desk demanding to know why his widget was not delivered.

Most people can deal with "sorry another user has just ordered this part" message.


问:
What's the etiquette of contributing to OSS that doesn't have a Contributing page
I'm thinking about contributing to a small R package on github that has only 1 contributor. What's the standard etiquette when there's not Contributing.md page on small projects like this?

Should I email him about whether my feature is wanted? Or just clone and then issue a pull request?

答:
Since your issue is a missing contribution statement, and it's on Github which supports issue tracking, you could open an issue to politely ask for support. Something like:</p>

```<code>Issue title: Contribution guidelines

Issue description: I was looking for ways to contribute to your project,
but I cannot find any guidelines on how to do so. If you're accepting
contributions on this repo, please consider adding contribution
guidelines to the repo at the standard location (CONTRIBUTING.md).
</code>```

Body:
Since your issue is a missing contribution statement, and it's on Github which supports issue tracking, you could open an issue to politely ask for support. Something like:

Issue title: Contribution guidelines

Issue description: I was looking for ways to contribute to your project,
but I cannot find any guidelines on how to do so. If you're accepting
contributions on this repo, please consider adding contribution
guidelines to the repo at the standard location (CONTRIBUTING.md).


问:
How to provide a good User Experience with a slower app
I am working on an embedded application that has a web server as a GUI. The webserver supports what you would expect, and I am using javascript to request data from the application and supply it to the user.

The user can interact with the hardware by changing physical relays on it. This is all displayed and controlled from a central GUI. The GUI updates every 5 seconds using AJAX.

The issue is that turning on and off these relays can be nearly instant or take up to 4 seconds (really depends how busy the system is). I therefore cannot simply send a "turn this relay off" command and expect that the next update will contain the correct information (it may not be off yet in the real world). To remedy this, when I send a command, I stop my update interval, visually turn the relay off, and wait a max of 4 seconds. There is still an issue, however, that if the user triggered this command while the GUI was updating, the control may come back on immediately, pause for 4 seconds, then update properly.

This is resulting in a really bad UX. At this point the only thing I can think of is having that portion of the GUI lock itself (with some kind of loading... message). Is that my best approach here?

答:
The basic approach would be to allow your local changes to override the received updates for a time, perhaps with some visual indication that your changes are pending.  Something like this:</p>

```<code>if (locally commanded state != updated state and time since command < 10 seconds)
   show locally commanded state with pending indication
else
   show updated state
</code>```

Body:
The basic approach would be to allow your local changes to override the received updates for a time, perhaps with some visual indication that your changes are pending.  Something like this:

if (locally commanded state != updated state and time since command < 10 seconds)
   show locally commanded state with pending indication
else
   show updated state


问:
Obstacle bypass in 2d environment
For this 2d grid (black square are not penetrable, white square are):

I want to find path who permit to move an object to a start point (x:18, y:18) to a end point (x:1, y:1), square by square. Imagine this object is an ant or a robot, so:

It can only know the direction of its objective, distance from its objective and if around (1 square distance) square are penetrable or not.
Object can keep memory of its path, if it is bypassing because previously blocked, etc ...

At (x:18, y:18), ant know X direction is (x:-1, y:-1) vector, distance from X is 18 square, vector (x:-1, y:-1) is penetrable).

At (x:17, y:17), ant know X direction is (x:-1, y:-1) vector, distance from X is 17 square, vector (x:-1, y:-1) is penetrable).

...

At (x:11, y:11), ant know X direction is (x:-1, y:-1) vector, distance from X is 11 square, vector (x:-1, y:-1) is not penetrable).

?

But it can't know other things. So we can't use here an A* algorithm or Dijkstra's algorithm. Imagine object is a robot in your house. It can test every position like Dijkstra's algorithm but it will take two week to bypass a chair.

Which algorithm can be used to find path from S to X without "walking" on a black square, according to "ant"/"robot" limitations ?

I write some, but with some problems like difficulty to follow "wall" and

go round in circles ...

UPDATE: After Karl Bielefeldt response, i write alogithm available here and procuding: EDIT: I finally not use A* inspiration, but "follow wall inspiration"

You are free to fork and suggest enhancement !

答:
It looks like you are looking for an A* or Dijkstra algorithm.

Depending on the language you are working with, there is likely already libraries built that you can use for these.
Here is a some Pseudocode for A* algorithm and an example for Dijkstra's algorithm

EDIT: Although Dijkstra would technically work, it wouldn't nearly as efficient as it should be.

Title: Obstacle bypass in 2d environment


问:
Functional Languages that compile to Android's Dalvik VM?
I have a software problem that fits the functional approach to programming, but the target market will be on the Android OS.  I ask because there are functional languages that compile to Java's VM, but Dalvik bytecode != Java bytecode.

Alternatively, do you know if the dx utility can intelligently convert the .class files generated from functional languages like Scala?

Edit:
In order to add a bit more helpfulness to the community, and also to help me choose better, can I refine the question a bit?

Have you used any alternate languages with Dalvik?  Which ones?

What are some "gotchas" (problems) that I might run into?

Is performance acceptable?  By that, I mean the application still feels responsive to the user.

I've never done mobile phone development, but I grew up on constrained devices and I'm under no illusion that there is a cost to using non-standard languages with the platform.  I just need to know if the cost is such that I should shoe-horn my approach into default language (i.e. apply functional principles in the OOP language).

答:
There has been a lot of movement on Clojure on Android (https://github.com/clojure-android/neko)Neko.

There are performance issues related to the Dalvik VM and the Clojure Compiler; these issues are slowly being resolved.

A presentation about the current (July 2015) status:
https://www.youtube.com/watch?v=mVXTcAEKgF8&index=9&list=PLZdCLR02grLoBx0Y5ZrpdmLxc160PIwzQ


答:
Does an object have to represent an entity?

Question: Which entity does a Logger represent?

Not metaphorically - literally.

When explaining OOP to students it is helpful to explain objects with analogies to the physical world.

Alan Kay - one of the fathers of OOP  - wrote the following:

[...]

The original conception of it had the following parts.

I thought of objects being like biological cells and/or individual
  computers on a network, only able to communicate with messages

I wanted to get rid of data.

[...]

OOP to me means only messaging, local retention and protection and

hiding of state-process, and extreme late-binding of all things.

almost unbelievable HW architecture. I realized that the

cell/whole-computer metaphor would get rid of data

source

From this, objects are best understood as

autarkic objects encapsulating / hiding data

communicating with other objects via messages

Can classes represent entity-less objects?

Definitely: Think of Math

Regarding your example:

Example: can a class be called MotorOperations or MotorActions, where there is no entity, but methods inside the class do things like

getMotorDataFromHTMLForm()

getMotorManufacturers()

selectMotorFromUserRequirements($requirements)

canMotorCanHandleOperatingConditions($conditions)

computePowerConsumptionForMotor($id)

To decide, where to put these methods, you have to take a look at responsibilities: who is respnsible for what.

getMotorDataFromHTMLForm()

The context of such a method would be constructing a motor-object.
It is not the responsibility of the motor to create itself from Data retrieved via a form. There are at least two objects involved; one is the motor and the other is the creator of the motor.

getMotorManufacturers()

The typical context in which one would write such a method is a service.

selectMotorFromUserRequirements($requirements)

This would also be used in a service-context

canMotorCanHandleOperatingConditions($conditions)

This is a question to a motor-object

computePowerConsumptionForMotor($id)

This too is a question best asked a motor itself.

tl;dr

The metaphor of objects as physically objects is more irritating than helpful.

Title: Do objects in OOP have to represent an entity?

Body:
Does an object have to represent an entity?

By an entity I mean something like a Product, Motor, a ParkingLot etc, a physical, or even a clear-cut non-physical conceptual object -- something that is well defined, with some core data clearly belonging to the object, and some functions/methods that clearly operate on the core data.

For example, I can have an object of a Demon, an entity in itself, an imaginary one perhaps and not physical but an entity nevertheless

Can an object be just a collection of methods, a common set of procedures that tie in with a common goal?

Example:  can a class be called MotorOperations or MotorActions, where there is no entity, but methods inside the class do things like

getMotorDataFromHTMLForm()

getMotorManufacturers()

selectMotorFromUserRequirements($requirements)

canMotorCanHandleOperatingConditions($conditions)

computePowerConsumptionForMotor($id)

A class is typically defined as data central to the object + operations on data.  So for a Motor there may be some motor variables relating to motor specifications, and there can be operations that combine those data to produce something.

In my case it is more like I have a class with operations on data + data that is passed through the class, there is no data centric to "Motor Operations", other than temporary pass-through-the-class data.

Question

Can classes represent entity-less objects?
If not, why they are bad/incomplete/non-OOP-centric?  Are there ways they need to be changed/improved conceptually to be in line with OOP?


问:
Is it a good practice to write distinct queries in a single stored procedure based on input parameters
I am going through the stored procedures written throughout our project and see that multiple distinct queries are written inside a single stored procedure and are called by passing different values to input parameter.

Will this not be a performance issue? If multiple clients are calling the same stored procedure by passing different values to the input parameter then the stored procedure execution plan will have to be recompiled each time it is called and degrade the performance?

The only reason I can comprehend is to save from writing new service methods to call different stored procedures and reuse existing service methods by just passing different parameters.

Does anyone see any other advantage of writing the stored procedure this way?

What could be the other disadvantages of writing it this way besides performance?

答:
Yes, I have seen significant performance problems result from this sort of pattern. If you have branches in your sproc that result in making significantly different queries, under certain circumstances this can cause huge performance problems.

SQL server will build an execution plan for a sproc when it needs to based on the values of the parameters passed into that sproc at the time when it is called. Then that execution plan will be cached and reused in subsequent calls. Depending on how the sproc is written and which branch will be executed with those parameters, it is possible for the execution plan that gets cached to be one that performs very poorly when the sproc is called with different parameters.

The worst cases I have seen of this have been when there is a bit parameter that is tested in an if statement to return different results - for example returning one record vs. returning a page of records.

This problem can behave very intermittently - if a particular branch of the sproc generates an execution plan that works well enough for the other branches then you won't notice a problem. That is, until the execution plan is rebuilt using another branch.

Performance problems with this are known and well documented. There are various workarounds, like using OPTIMIZE FOR UNKNOWN and OPTIMIZE RECOMPILE but a better option IMHO is to write sprocs to avoid these issues by limiting sprocs to perform specific tasks and avoiding branching clauses.


答:
If you are allowed to remember past data, A* is indeed your best bet.  I used it on Google's Ant AI challenge, which only has a small radius of view.

The main difference with a limited field of view is you do a lot more walking around just to explore, but that's unavoidable.  A* will give you a pretty good list of where to explore, without having to visit the entire map.

For fun, I coded a solution for your example.  The following is the output:

```<code>(18,18)
(17,17)
(16,16)
(15,15)
(14,14)
(13,13)
(12,12)
(11,11)
(11,10)
(10,11)
(9,12)
(8,13)
(8,14)
(8,13)
(9,12)
(10,11)
(11,10)
(12,9)
(13,9)
(13,10)
(13,11)
(14,12)
(15,11)
(15,10)
(15,9)
(15,8)
(14,7)
(13,6)
(12,5)
(11,4)
(10,3)
(9,2)
(8,1)
(7,0)
(6,1)
(5,1)
(4,1)
(3,1)
(2,1)
(1,1)

real    0m0.404s
user    0m0.727s
sys     0m0.040s
</code>```

It's even more efficient than I anticipated.  Only 40 moves, when the ideal with an omnipotent view of the map would be 25.  You can see it follows your arrows at first, explores along the wall to the Northwest a little, then turns around and follows the wall until it escapes the indentation, after which it's almost a straight shot.  It could maybe be improved even further by tweaking the weights on unseen cells to be proportional to distance from your current position.

Title: Obstacle bypass in 2d environment

Body:
For this 2d grid (black square are not penetrable, white square are):

I want to find path who permit to move an object to a start point (x:18, y:18) to a end point (x:1, y:1), square by square. Imagine this object is an ant or a robot, so:

It can only know the direction of its objective, distance from its objective and if around (1 square distance) square are penetrable or not.
Object can keep memory of its path, if it is bypassing because previously blocked, etc ...

At (x:18, y:18), ant know X direction is (x:-1, y:-1) vector, distance from X is 18 square, vector (x:-1, y:-1) is penetrable).

At (x:17, y:17), ant know X direction is (x:-1, y:-1) vector, distance from X is 17 square, vector (x:-1, y:-1) is penetrable).

...

At (x:11, y:11), ant know X direction is (x:-1, y:-1) vector, distance from X is 11 square, vector (x:-1, y:-1) is not penetrable).

?

But it can't know other things. So we can't use here an A* algorithm or Dijkstra's algorithm. Imagine object is a robot in your house. It can test every position like Dijkstra's algorithm but it will take two week to bypass a chair.

Which algorithm can be used to find path from S to X without "walking" on a black square, according to "ant"/"robot" limitations ?

I write some, but with some problems like difficulty to follow "wall" and

go round in circles ...

UPDATE: After Karl Bielefeldt response, i write alogithm available here and procuding: EDIT: I finally not use A* inspiration, but "follow wall inspiration"

You are free to fork and suggest enhancement !

Body:
If you are allowed to remember past data, A* is indeed your best bet.  I used it on Google's Ant AI challenge, which only has a small radius of view.

The main difference with a limited field of view is you do a lot more walking around just to explore, but that's unavoidable.  A* will give you a pretty good list of where to explore, without having to visit the entire map.

For fun, I coded a solution for your example.  The following is the output:

(18,18)
(17,17)
(16,16)
(15,15)
(14,14)
(13,13)
(12,12)
(11,11)
(11,10)
(10,11)
(9,12)
(8,13)
(8,14)
(8,13)
(9,12)
(10,11)
(11,10)
(12,9)
(13,9)
(13,10)
(13,11)
(14,12)
(15,11)
(15,10)
(15,9)
(15,8)
(14,7)
(13,6)
(12,5)
(11,4)
(10,3)
(9,2)
(8,1)
(7,0)
(6,1)
(5,1)
(4,1)
(3,1)
(2,1)
(1,1)

real    0m0.404s
user    0m0.727s
sys     0m0.040s

It's even more efficient than I anticipated.  Only 40 moves, when the ideal with an omnipotent view of the map would be 25.  You can see it follows your arrows at first, explores along the wall to the Northwest a little, then turns around and follows the wall until it escapes the indentation, after which it's almost a straight shot.  It could maybe be improved even further by tweaking the weights on unseen cells to be proportional to distance from your current position.


答:
I don't have personal direct experience in embedded systems - but I do understand waterfall and agile and the differences between the two, as I am sure you do too. I have also discussed this issue - of applying Agile in industries such as embedded software development, semiconductor design/ development, etc. with friends who work in those industries - so hopefully, I have some understanding of the issues you are facing..

The fundamental objective of Agile is to ensure that what you ultimately deliver to your customer/ business user is timely, works as per requirements and most importantly, is done in a manner that allows you to handles changes to requirements effectively along the way. These were the biggest challenges of waterfall projects - and in spite of careful planning and large up-front efforts to define the perfect requirements - caused delivery of software that did not meet business requirements.

Given what you have said about the need for upfront requirements and design due to hardware dependencies, etc. I'd say that to become (more) agile, you can try break up your overall product scope into the most 'feasible' (self-contained) modules (or themes, epics or MVPs, whatever you choose to call them) and define all the requirements/ user stories up-front for each such module, including hardware dependencies, et al.

Depending on the size of the modules, you can then still build each module in multiple sprints, taking either the highest priority users stories first - or taking them in the order of 'functional dependencies' between user stories. This way, you ensure that at the end of each sprint, you are delivering working features onto a staging server/ device that allows you to demo it to your product owner/ business users/ customers - collect feedback, especially any changes to requirements - or new requirements - and incorporate them into future sprints/ modules.

So, instead of looking at this as an "agile requirements gathering" issue, perhaps you just need to focus on overall "agile product development" that helps your team(s) delivery early, deliver often and ultimately deliver right?

Just my 2 cents. Hope it helps.

Title: Agile requirements gathering in embedded project

Body:
I am working on a project where we develop an embedded application for a Linux-based device handling data from different sensors and visualizing them to the end user. We try to use Scrum process but came across different difficulties related to our and management team perception of Requirements Engineering.

Basically Scrum recommends User Stories maintained in a Backlog prioritized by the Product Owner. Scrum assumes that there is no "requirements freeze" or single document describing the project at the start.
User stories can be added "on demand" when stake holders thinks they are necessary to have a "releasable" software version.

On the other hand embedded system due to tight coupling with hardware need upfront specification of different system features, e.g.

HW / SW interfaces (e.g. shared memory between main CPU and FPGA)

Data formats, what and how will be stored with what frequency

hard real time requirements, how fast must the system react on certain events

interaction with other disciplines, eg. HW, optics, mechanics

What are the best practices to handle requirements engineering in embedded systems in a lightweight (Agile) way (in contrary to e.g. automotive processes) ?


答: It's very much about the legibility of the diffs.  If code style thrashes around, the diffs hide changes with no semantic meaning to the program, and can make merges hard or impossible.</p>

Title: What is the actual value of a consistent code style

Body:
I am part of a consultant team implementing a new solution for a customer. I am
responsible for the majority of code reviews on the client-side codebase (React and javascript).

I have noticed that some team members use unique coding patterns to a point that I could pick a file at random at tell who was the author from the style alone.

Example 1 (one-off inline functions)

```<code>React.createClass({
  render: function () {
    var someFunc = function () {
      ...
      return someValue;
    };
    return <div>{someFunc()}</div>
  }
});
</code>```

The author argues that by assigning a meaningful name to someFunc the code will be easier to read. I believe that by inlining the function and adding a comment instead the same effect could be achieved.

Example 2 (unbound functions)

```<code>function renderSomePart(props, state) {
    return (
      <div>
        <p>{props.myProp}</p>
        <p>{state.myState}</p>
      </div>
    );
}

React.createClass({
  render: function () {
    return <div>{renderSomePart(this.props, this.state)}</div>;
  }
});
</code>```

This is how we usually do it (avoids having to pass state and props):

```<code>React.createClass({
  renderSomePart: function () {
    return (
      <div>
        <p>{this.props.myProp}</p>
        <p>{this.state.myState}</p>
      </div>
    );
  },
  render: function () {
    return <div>{this.renderSomePart()}</div>;
  }
});
</code>```

While these coding patterns are technically correct they are not consistent with the rest of the codebase nor with the style and patterns that Facebook (the author of React) hints at in tutorials and examples.

We need to keep a fast pace in order to deliver on time and I don't want to burden the team unnecessarily. At the same time we need to be on a reasonable quality level.

I am trying to imagine myself as the customers' maintenance developer faced with inconsistencies like these (every component might require you to understand another way of doing the same thing).

Question:

What is the value as perceived by the customer and its maintenance developers of a consistent code base vs. allowing inconsistencies like these to remain and potentially spread?


问:
iOS bluetooth development: mimicking the SPP profile
I need to interface a custom device with bluetooth 2.1 (it has the RN-42 chip), with an iPhone and iPad. The device uses the Bluetooth SPP profile. From my research it appears that iOS supports Bluetooth Low Energy and accessories through the MFi ("Made for iPod") program.

The device I have is BT2.1, so doesn't have BLE. The MFi program requires hardware modification, which isn't an option. Is there other ways of interfacing the device, ideally not jailbraking them?

I've also found this list of supported profiles in iOS. Can one of these profiles be used to "wrap" the SPP profile? Or somehow circumvent it?

答: You might be able to interface it by using an intermediate device (Arduino+shields?) that supports both BLE and classic Bluetooth SPP to relay data.</p>


问:
Scraping data from website and passing into Office - a lot of restrictions
Recently, I was asked to help with some side optimization project at our company, I've made some good research. I'm still not 100% sure if this is most efficient way to do this.

Problem:

Scraping for over a dozen different information from a internal system ( website ) and passing them into Microsoft Office document template.

Restrictions:

Website is working only in IE 9

System does not have any API / web services

This will be used at more than 100 different workstations

On workstations, there is only IE 9, no FF or Chrome allowed

Getting acceptance for installation any software except default Windows tools on workstations is almost impossible

We have made a small working proof of concept for this. It is using Visual Basic + javascript combo. Short description: Visual Basic opens instance of IE, then using javascript we are able to log into system, go to tabs that we need and find proper information, then we are able to push this data into the Office template.

It is working, but I'm not really sure that this approach is the best one.

We have tried some different solutions, nodejs server, Selenium, some other web scrapers, but they all seem to have some limitations.

答:
Uncle Bob once said: "We don't ship shit...".

Working with legacy tools(IE 9) and scraping website you are:

Spending significant amount of time on unscalable, potentially unreliable technology.

Introducing very custom component understanding which would require future developers a lot of time understand and potentially will cost you a lot more in  along run.

Run into risk of upgrading Windows on those machines and being unable to use IE9 any further, which requires application update, etc...

What I would do if I was in this situation:

Option 1: API and Node.js based client.
This one is simple and probably most smart cost and future wise. I would try to convince the managing party that we need additional software installed on the machines. I understand it's their policy not to, but they have to understand that they are the ones requesting extra functionality, so they got to make a choice there.

Update the system with API capabilities - potentially you might need them somewhere else in the future. What if your company introduces mobile-tablet based terminals, there is no IE9 anymore there, so API is a good idea long term.

Option 2: Node.js based scraper without API.
Again, requires installation of additional piece on the Windows machines, can't get around that and business has to understand that. Using Node.js you can use a number of modules that simulate DOM and you can navigate in it just like you would in the browser, except with no UI. It will probably take you longer than API and probably will cost more, so this option is viable if you don't own the scrapee :)

Options 3: Proceed with your approach, but I personally wouldn't. You are hired as a professional developer, and part of being a professional is letting business know that sometimes it's too wrong to proceed :)


答:
Does the software team has any influence on the hardware specs? Or is it purely the other way around (hardware team dictates low-level software interface)?

In the latter case, a HAL (hardware abstraction layer) person must sit with hardware team to write the low-level software interface; GUI team can work at their own pace, possibly using Scrum or any other Agile methodology.

If the hardware and software co-evolves, it is going to be a rapid prototyping project. The focus is on maximizing learning rates (will-works and won't-works), keeping cost under control (spending it wisely, knowing it very well that prototyping means a lot of throwaway work and is going to be expedited, making it much more costly than typical projects).

There are many Q&A on rapid prototyping, on this site and elsewhere.

If it is rapid prototyping, it is probably not going to be scrum. It might still be Agile in spirit but it might be different from any of the mainstream Agile frameworks - because mainstream Agile frameworks mostly cater to purely-software, market-driven development.

You certainly have to "Responding to change over following a plan"; it's being forced onto you because hardware and software co-evolve projects are full of "won't-works".

Scrum has the so-called "spikes", but if a project is full of spikes, you typically don't call it scrum. Instead of fixed time-box sprints, you will have milestones, where each milestone has some deliverables, and the milestone ends only if these items  are delivered or otherwise having some of the items amicably cancelled by the stakeholders.

Scrum management software might still work, stand-up meetings will always work, etc.


问:
Does knowing Latin or other logical languages contribute to being a better programmer?
I'm currently studying Latin at school, and what I've learned is that it's a very logical language. I feel this has contributed to my programming ability, as it makes it my code easier to understand.

Is there any relation between knowledge of a very logical language such as Latin and the comprehension of code?

答: Perhaps the most important language skills that you need for programming are the ability to be precise and the ability to express what you mean in the language that you are using.  (Not a direct answer, but maybe relevant.)</p>


问:
What is a transaction?
When reading Spring tutorials I'm quite often coming across the @Transactional annotation.

When I google it, I get documentation that says things like:

Comprehensive transaction support is among the most compelling reasons to use the Spring Framework. The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:

or:

A transaction manager is the part of an application that is responsible for coordinating transactions across one or more resources. In the Spring framework, the transaction manager is effectively the root of the transaction system. Hence, if you want to enable transactions on a component in Spring, you typically create a transaction manager bean and pass it to the component.

I have no idea what they're referring to here.

Can someone explain?

答:
A transaction is a set of actions related to each other in some way. Transaction is deemed complete when all actions have executed successfully.

One of main advantages of a transaction is ability to roll it back.

In development we have Command Pattern - commands are also transactions that can be executed, rolled back and queued.

Title: What is a transaction?


问:
What is a good Design Pattern for a bundle of methods that comprises an algorithm?
This is a Design question relating to finding out a good OO design pattern or design structure or class combination that can house an algorithm that processes user selection to produce product recommendations.

Scenario

User specifies Motor and Product requirements and hits Submit.  Algorithm processes input, loads various motors and products, selects relevant motors and products as per specifications.  It then combines them, computes various parameters of the combos, and also notes any discrepancies.  Then, it provides an output in a form of valid product-motor combinations with computed specs, and also any discrepancies noted as warnings.

Question

Can I have an object called Algorithm, that is essentially a bundle of methods that loads Products, Motors, combines them, does computations on them, sets up various flags, etc?  Or is there a better design?

Current Design

My current design came from procedural background and used to be just a series of functions, now housed in a couple of classes.  Simplified algorithm is something like this (where Algorithm is a bundle of methods related to driving the algorithm, and BundleOfComputationalMethods that focuses on computational needs):

class Algorithm
{
    public $bundle;

    function __construct()
    {
        $this->bundle = new BundleOfComputationalMethods();
    }

    function getRequestDataFromPOST()
    {
        $this->bundle->options = $_POST;
    }

    function loadMotors(){}

    function loadProducts(){}

    function combineProductsAndMotors()
    {
        $this->getRequestDataFromPOST();

        $this->loadMotors();
        $this->loadProducts();

        for ($k = 1; $k <= $this->bundle->spec->max; $k++)
        {
            $this->bundle->computeRotationalSpeed();
            $this->bundle->checkIfSpeedWithinLimits();
            if ($this->bundle->speedIsOkay)
            {
                //bundle contains a "selection" to be presented back to the user
                //(Motor, Product, computed specifications, pricing, any warnings/errors)
                $result .= json_encode($this->bundle);
            }
        }

        return $result;
    }
}
```

答:
I would improve on OOP part a bit.

Provide better naming:

You can to change Algorithm to something more specific like RelatedProductsService. Then, expose a method: getrelatedProducts($options)

Separate Your responsibilities:

You also want to avoid just passing POST along the class into it's children. That is a code smell and creates unnecessary dependencies. Have your caller of RelatedProductsService extract the post data into some structure and only what's needed and pass it inside as $options.

I would also move the functionality to load and combine engines, JSON encoding out as well into it's own classes. You have too many things crammed into one class :)

Good Read: Single Responsibility Principal


答:
In its broadest sense, a "transaction" is a group of actions that should be performed as if they were a single "bulk" action. The term is most often used in the context of databases, but it can be applied to many kinds of programs (particularly ones that implement a command pattern). When we're talking about databases, and often even if we aren't, we want transactions to have the so-called ACID properties:

Atomicity - The transaction is a single, unbreakable unit. It cannot be partially applied, or partially undone. It is either completely done, or not done at all.

Consistency - The application/database/whatever must be in a valid state both before and after the transaction. If attempting to execute a transaction results in an invalid state, then we must "rollback" to the last valid state.

Isolation - Every transaction is separate from every other transaction. No two transactions can ever "interleave". They are always executed one at a time (or in a way that is indistinguishable from "one at a time").

Durability - Once the transaction has been executed, it stays executed forever. This one is mostly relevant for databases, where it means the change in data has actually been committed to disk, so that the new data cannot be lost even if the machine suddenly reboots.

Not all kinds of transactions need to have all four properties, but usually when the word "transaction" is used in a programming context, that implies a system that enforces at least some if not all of them. I believe Spring is referring to database transactions and does claim to enforce all of these properties.

Title: What is a transaction?

Body:
When reading Spring tutorials I'm quite often coming across the @Transactional annotation.

When I google it, I get documentation that says things like:

Comprehensive transaction support is among the most compelling reasons to use the Spring Framework. The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:

or:

A transaction manager is the part of an application that is responsible for coordinating transactions across one or more resources. In the Spring framework, the transaction manager is effectively the root of the transaction system. Hence, if you want to enable transactions on a component in Spring, you typically create a transaction manager bean and pass it to the component.

I have no idea what they're referring to here.

Can someone explain?


问:
Agile development where customer collaboration is difficult
The agile manifesto states

Customer collaboration over contract negotiation

My question is how do you make this work effectively when there is distance between the developers and the users?

I currently work in a "waterfall" team maintaining a large enterprise system. The customer is in a different country but we do have people travelling out most weeks. Once onsite though it's rare you get to speak to end users as it's a large corporation with several layers of "the business" in the way. So the distance is not just geograhpical and it won't be the same people going out every week.

I know agile could help us to give a quicker turnaround but I'm trying to picture how we can replace these unwieldy documents today with short user stories that get fleshed out via customer collaborations. We do collaborate when writing specifications but meetings have to be organised usually with lots of people brought in which doesn't sound very agile.

I'm also not sure where the product owner would fit in. This is a large system and the customer has different contacts for each part of the system. The development is all one big team though and each release it will be different parts of teh system that get worked on.

I have worked in a scrum team at a different company but I'm not sure it was very agile. There the BA's wrote a spec for each story and then the developer would code from the spec. This approach seems to lack collaboration and is document heavy. It did at least break things down into smaller chunks which were more manageable (no bad thing) but it doesn't seem to meet the benchmarks set out in the agile manifesto.

答:
While significant supporting motivation and explanation was provided, the core question seems to be:

...how do you make this work effectively when there is distance
  between the developers and the users?

To me, this challenge is not unique to Scrum. Effective collaboration between geographically dispersed individuals is a common challenge. While the impact of this challenge may be greater on scrum, where collaboration is king, the potential solutions are still similar. They include:

physical travel (as you mentioned)

telephone conversations and conference calls (which I assume you might also do, but didn't mention)

simple video conferences

more sophisticated online collaboration environments, shared white-boards, etc.

Taking advantage of some of the above common solutions would probably be beneficial, regardless of the degree to which you have adopted Agile practices.


问:
What is the actual value of a consistent code style
I am part of a consultant team implementing a new solution for a customer. I am
responsible for the majority of code reviews on the client-side codebase (React and javascript).

I have noticed that some team members use unique coding patterns to a point that I could pick a file at random at tell who was the author from the style alone.

Example 1 (one-off inline functions)

```<code>React.createClass({
  render: function () {
    var someFunc = function () {
      ...
      return someValue;
    };
    return <div>{someFunc()}</div>
  }
});
</code>```

The author argues that by assigning a meaningful name to someFunc the code will be easier to read. I believe that by inlining the function and adding a comment instead the same effect could be achieved.

Example 2 (unbound functions)

```<code>function renderSomePart(props, state) {
    return (
      <div>
        <p>{props.myProp}</p>
        <p>{state.myState}</p>
      </div>
    );
}

React.createClass({
  render: function () {
    return <div>{renderSomePart(this.props, this.state)}</div>;
  }
});
</code>```

This is how we usually do it (avoids having to pass state and props):

```<code>React.createClass({
  renderSomePart: function () {
    return (
      <div>
        <p>{this.props.myProp}</p>
        <p>{this.state.myState}</p>
      </div>
    );
  },
  render: function () {
    return <div>{this.renderSomePart()}</div>;
  }
});
</code>```

While these coding patterns are technically correct they are not consistent with the rest of the codebase nor with the style and patterns that Facebook (the author of React) hints at in tutorials and examples.

We need to keep a fast pace in order to deliver on time and I don't want to burden the team unnecessarily. At the same time we need to be on a reasonable quality level.

I am trying to imagine myself as the customers' maintenance developer faced with inconsistencies like these (every component might require you to understand another way of doing the same thing).

Question:

What is the value as perceived by the customer and its maintenance developers of a consistent code base vs. allowing inconsistencies like these to remain and potentially spread?

答:
I have had good luck treating code styles just like I treat writing styles in natural English.  There's a huge range of styles from conversational English, which mimics the way we speak in every day conversation, to formal English, which is often heavy and stilted by always very precise in its meaning.

Consider what you would like the final product to look like in that sense.  Some situations are very supportive of using whatever structure is best at the time.  Others require a uniform cadence and structure.  This is especially true if your product is best though of as though it was written in formal English.  Colloquialisms may help in that case, but they tear at the overarching feel of the product.

In general, the more consistent your coding standard is, the less effort a developer must take to call their attention to something interesting.  If you support great diversity in coding standards, developers must be louder when announcing that they are doing something that is unusual or unique.  This attempt to express what a developer considers to be important can often overshadow the dynamic range of the code itself.  When this happens, it is easy to have bugs slip through because its simply too hard to see them.

On the flip side of that argument, the looser your coding standards are, the more freedom developers have to adapt their syntax to the problem.  In ironic contrast with the pro-coding standards argument, too much standardization can lead to stilted code structure, which can also make it easy to have bugs slip through.

What you are looking for is your own team's happy medium.


答:
While the question, as posed, has broad scope, the core issues seem to be:

...Scrum assumes that there is no 'requirements freeze'...

...embedded system due to tight coupling with hardware need upfront specification...

Scrum aims to produce high quality increments of a deliverable solution. It does not aim to minimise re-work or minimize time to production of a final product, for example. You need to consider if this priority is appropriate to your environment.


答:
Can I have an object called Algorithm, that is essentially a bundle of methods that loads Products, Motors, combines them, does computations on them, sets up various flags, etc? Or is there a better design?

The Strategy Software Design Pattern seems to match the description of your post:

https://en.wikipedia.org/wiki/Strategy_pattern

This Pattern allows a method or group of methods to be treated as an "object", as you require.

Don't coerce yourself into using "Software Design Patterns" because are are a trend, use them because, may help you solve a problem.

Title: What is a good Design Pattern for a bundle of methods that comprises an algorithm?

Body:
This is a Design question relating to finding out a good OO design pattern or design structure or class combination that can house an algorithm that processes user selection to produce product recommendations.

Scenario

User specifies Motor and Product requirements and hits Submit.  Algorithm processes input, loads various motors and products, selects relevant motors and products as per specifications.  It then combines them, computes various parameters of the combos, and also notes any discrepancies.  Then, it provides an output in a form of valid product-motor combinations with computed specs, and also any discrepancies noted as warnings.

Question

Can I have an object called Algorithm, that is essentially a bundle of methods that loads Products, Motors, combines them, does computations on them, sets up various flags, etc?  Or is there a better design?

Current Design

My current design came from procedural background and used to be just a series of functions, now housed in a couple of classes.  Simplified algorithm is something like this (where Algorithm is a bundle of methods related to driving the algorithm, and BundleOfComputationalMethods that focuses on computational needs):

class Algorithm
{
    public $bundle;

    function __construct()
    {
        $this->bundle = new BundleOfComputationalMethods();
    }

    function getRequestDataFromPOST()
    {
        $this->bundle->options = $_POST;
    }

    function loadMotors(){}

    function loadProducts(){}

    function combineProductsAndMotors()
    {
        $this->getRequestDataFromPOST();

        $this->loadMotors();
        $this->loadProducts();

        for ($k = 1; $k <= $this->bundle->spec->max; $k++)
        {
            $this->bundle->computeRotationalSpeed();
            $this->bundle->checkIfSpeedWithinLimits();
            if ($this->bundle->speedIsOkay)
            {
                //bundle contains a "selection" to be presented back to the user
                //(Motor, Product, computed specifications, pricing, any warnings/errors)
                $result .= json_encode($this->bundle);
            }
        }

        return $result;
    }
}
```


问:
What design patterns could be used here?
I'm trying to come up with a nice design (preferably pythonic) for the following use case.

Say there's three services - A, B, C in multiple locations L1, L2, L3, etc. Each service provides different values, e.g. A returns a1, B returns b1, C returns c1.

The task is to periodically run a function that fetches these parameters from all the available locations, does some math (say, sum up) on the values of corresponding services and writes the calculated values back to the services in each location. I.e.

```<code>for l in locations:
    as.append(getAfrom(l).get_a())
    bs.append(getBfrom(l).get_b())
    cs.append(getCfrom(l).get_c())

new_a = calculate(as)
new_b = calculate(bs)
new_c = calculate(cs)

for l in locations:
    getAfrom(l).write(new_a)
    getBfrom(l).write(new_b)
    getCfrom(l).write(new_c)
</code>```

The above code does this in a very straightforward way (that's probably not that bad), but it fails to scale if the number of services or parameters grows.

What design patterns would make this solution more flexible, extensible (more params, more services)?

答:
You probably want to use something like the visitor pattern, or the strategy pattern.

something like (assuming a few refactors):

```<code>services = [a,b,c] # add more as needed

accum_strat = lambda l,s: s.Find_Service(l).GetVal()
accum_list = [[] for x in range(len(services))]

for l in locations:
    for srv, lst in zip(services, accum_list):
        lst.append(accum_strat(l, srv)

calcd = [calculate(lst) for lst in accum_list]
write_strat = lambda l,s,v: s.Find_Service(l).write(v)

for l in locations:
    for s,v in zip(services, calcd):
        write_strat(l,s,v)
</code>```

you could even refactor further:

```<code>def visit_locations(func, args):
    for l in locations:
        for a in args:
            func(l,*a)

services = [a,b,c] # add more as needed

accum_strat = lambda l,s: s.Find_Service(l).GetVal()
accum_list = [[] for x in range(len(services))]
write_strat = lambda l,s,v: s.Find_Service(l).write(v)

visit_locations(lambda l,s,t: t.append(accum_strat(l,s)), zip(services, accum_list))

calcd = [calculate(lst) for lst in accum_list]

visit_locations(write_strat, zip(services, calcd))
</code>```

Adding a new service, one only needs to extend the service list. A new operation adds another visit_locations call, or whatever intermediate needs to be computed.

this could be abstracted further:

```<code>...
operations = [lamdba : visit_locations(...),
              lamdba : calcd=...,
              ...
             ]

for op in operations:
    op()
</code>```

Depending on the actual requirements of your system this could be a step too far, or just what is needed for your system. One could do something equivalent but with classes; this exercise will be left to the reader.

N.b. I have conflated the visitor and strategy patterns, IIRC the difference between them is mainly how they are used.

Body:
You probably want to use something like the visitor pattern, or the strategy pattern.

something like (assuming a few refactors):

services = [a,b,c] # add more as needed

accum_strat = lambda l,s: s.Find_Service(l).GetVal()
accum_list = [[] for x in range(len(services))]

for l in locations:
    for srv, lst in zip(services, accum_list):
        lst.append(accum_strat(l, srv)

calcd = [calculate(lst) for lst in accum_list]
write_strat = lambda l,s,v: s.Find_Service(l).write(v)

for l in locations:
    for s,v in zip(services, calcd):
        write_strat(l,s,v)

you could even refactor further:

def visit_locations(func, args):
    for l in locations:
        for a in args:
            func(l,*a)

services = [a,b,c] # add more as needed

accum_strat = lambda l,s: s.Find_Service(l).GetVal()
accum_list = [[] for x in range(len(services))]
write_strat = lambda l,s,v: s.Find_Service(l).write(v)

visit_locations(lambda l,s,t: t.append(accum_strat(l,s)), zip(services, accum_list))

calcd = [calculate(lst) for lst in accum_list]

visit_locations(write_strat, zip(services, calcd))

Adding a new service, one only needs to extend the service list. A new operation adds another visit_locations call, or whatever intermediate needs to be computed.

this could be abstracted further:

...
operations = [lamdba : visit_locations(...),
              lamdba : calcd=...,
              ...
             ]

for op in operations:
    op()

Depending on the actual requirements of your system this could be a step too far, or just what is needed for your system. One could do something equivalent but with classes; this exercise will be left to the reader.

N.b. I have conflated the visitor and strategy patterns, IIRC the difference between them is mainly how they are used.


问:
Would Rebol (or Red) benefit from Lisp-style Macros?
As a 'seasoned' Rebol developer with some knowledge of the world outside, I'd be curious as to the utility/pitfalls of implementing Lisp-style macros in Rebol (and/or Red).

My understanding (always happy to revise) is that Lisp is able to preprocess code prior to evaluation/compilation, modifying that code according to the rules of the applicable macros. This can allow for more complex/expressive statements than otherwise, with efficiencies as those statements are expanded only once as a body of code is loaded. The macro rules themselves are relatively straightforward as the homoiconicity of Lisp allows the code to be manipulated by the same terms one would modify data.

As Rebol is also a homoiconic language, it stands that it too could accommodate macros between loading and evaluation with similarly expressive transformation grammar (though I'd posit that Rebol's more freeform evaluation model—statements not generally bound by parentheses—makes it harder to identify the portions of code to be transformed).

My own inclination is that in the main, macros aren't really necessary in Rebol—you can already create complex code structures that are fairly efficient, and where more efficiency is desired, Rebol has the capabilities to accommodate without significant loss of expressivity. On the other had, 'fairly' and 'no significant loss' could be considered weasel words and macros do offer an efficiency/expressivity bump, but at what implementation cost?

Also, as in Rebol you can load code prior to evaluation, it would be possible to implement a mechanism for load-expand-evaluate at the user-level permitting third-party macro implementations.

This post is partly a response to this question and everything (pretty much) I know about macros comes from this exchange.

Update

Entering the World of Macros

Red introduced a rudimentary macro system in version 0.6.2. I have used them effectively to create cross-compatible scripts that target both the Ren-C branch of Rebol 3 and Red.

答:
This is the first time I hear about Rebol, but from a quick look at the Wikipedia page it seems to me that Rebol dialects are just like Lisp macros: they both receive ordinary code of the language that has passed lexical and syntactic(but not semantic!) processing, and process it with their own semantical rules.

So, Rebol will not benefit from Lisp macros, because it already has that feature under a different name, and having two core-language features that do exactly the same thing is bad - especially for languages that rely on Homoiconicity, where uniform simplicity in the syntax is the key to their magic.

Update

The asker explainer in the comments that macros have the advantage that they are expanded once, before the code execution, and injected into the code.

This, IMO, will make things worse, because it would mess up the order of parsing!

For example, let's say we have the Rebol command foo x bar y, where foo is a dialect and bar is a macro. What should the interpreter do? Depends on foo's arit:

If foo accepts a single argument, that means we have two commands: foo x and bar y. So bar y needs to be expanded.

If foo accepts three arguments, that means that we have one command, and bar is the second argument of foo. This means bar shouldn't be expanded, and instead passed to foo as-is.

The rules are clear - for a human, and probably for static compilers as well. But Rebol is dynamic and interpreted, so foo is only evaluated when it needs to be executed - but bar should be expanded before that happens! So now the interpreted needs to evaluate the dialects before it expands the macros, so it can expand the macros before it evaluated the dialect, and round and round the interpreted goes trying to resolve the circle...

Lisp doesn't have this problem, because:

It's easy to know where a function/macro begins, because you need to put them in parenthesis. You can't have foo x bar y - you need to either have (foo x bar y) or (foo x) (bar y) or even (foo x (bar y)), so it's easy for the interpreter to know what you are trying to do.

Lisp doesn't have dialects - only functions and macros. And since functions don't control the evaluation of their arguments - macros always evaluate themselves. If Rebol didn't have dialects, and foo was a function, foo x bar y would require the interpreter to first evaluate x, bar and y, and since bar is a macro it would have expanded regardless of foo's arity, because foo has no control whatsoever on the evaluation of it's arguments.


答:
As an owner of an open source project, I love hearing from potential contributors. Since you're interested in contributing, I'm guessing you also have some issue with the current software, either a bug you'd like to fix or a feature you'd like to add. Open an issue and then in a comment on the issue, express interest and willingness to do the work. If the owner is still interested in the project, I'm sure you'll get a positive response.

However, if the owner isn't interested (you get no response), check the license and see if you're allowed to modify the source and distribute derivative works. You can always fork the project and implement it anyway, for yourself and the community.

Title: What's the etiquette of contributing to OSS that doesn't have a Contributing page

Body:
I'm thinking about contributing to a small R package on github that has only 1 contributor. What's the standard etiquette when there's not Contributing.md page on small projects like this?

Should I email him about whether my feature is wanted? Or just clone and then issue a pull request?