答: I would say, stop coding, stop testing and take a couple of days or weeks of and try to find a way to enhance and expand your product feature-wise and do it in such a way that it sets it apart from the other product. You may be able to think up some radical changes you hadn't thought of before.</p>

Title: My most cherished dream project seems to resemble a product that already exists. What shall I do?

Body:
I guess this is more of a "comfort seeking" question than legality one.

You see, for the past couple of months I have been brainstorming and developing a product, all by myself. I was planning to release it under some kind of free license. While I know no idea is ever a unique one, I was quite happy to note that the way I had visualized my software, in its form and purpose, was one of its kind, albeit bits and pieces resembling others. That private project was quite cherished one.

Now I find there is a product, at least a decade old, that is so close to mine that mine looks plagiarized. While with the rest of them I had a 8:2 in my favor, feature wise, with this product it seems transposed, including the philosophy. I admit I can vaguely recall hearing the name of it but never thought of reading about it - the name didn't seem to invoke interest etc - until now. I read about it and now I am distraught and agonized.

There is no risk of any legal action as that software is in "free" domain and mine is still a private project, and I don't know if it will be ever make any money from any buyer which will then lead to trouble, but that is not the point of the question.

The point is how to stay focused and enthusiastic as before? I have about a month of work pending, mainly programming and complete testing, and this has completely left me drained. I am in a fetal position. I am telling myself about Newton-Leibniz, Faraday-Henry kind of independent activities with similar to same results but that isn't helping. I don't want this to spill over to my regular life and work life.

I can sense two issues that are pricking me. (1) I wanted praise for my creativity. (2) I was harboring a small desire of a possible chance of making good money by attracting a buyer.

This might be a casual and almost an inconsequential problem for the citizens of the business world, but I am from a different world.

Help.


问:
Should I create interfaces for data transfer objects?
Is it a good idea or a bad idea to create an interface for data transfer objects?  Presuming that the object is usually mutable.

Though my example is in Java, it should be applicable to any other language that has similar concepts.

```<code>interface DataTransferObject  {
    String getName();
    void setName(String name);
}

class RealDataTransferObject  implements DataTransferObject {

    String name;
    String getName() {
        return name;
    }
    void setName(String name) {
        this.name = name;
    }
}
</code>```

Of course, this is a simplified example, in real life there may be more fields.

答:
The general answer is no, because you should never add code without having a specific, concrete reason for it, and there is no general reason for such an interface.

That being said, sometimes there can be a good reason. But in all cases I have seen, these interfaces were partial, covering only one or a few properties shared by multiple classes I wanted to use polymporphically without giving them a common superclass. Typical candidates are an Id property to use in some sort of registry or a Name property to display to the user. But it can be useful in any case where you want some code to handle everything that has an X - just create an XSource interface that contains the getX (and, only if required, the setX) methods.

But a separate interface for every model class, containing all the properties? I can't imagine a good reason to do that. A bad reason would be a badly designed framework that requires it; Entity EJBs did just that, if I remember correctly. Thankfully they were so bad they never gained much traction and are deprecated since EJB 3.0

Sidenote: please avoid using the term "value object" to describe Java beans with only trivial getters and setters - it conflicts with the more common definition of value object as something with no identity that is usually immutable. A better term would be DTO or model class - though in the latter case note that anemic domain models are considered an antipattern.

ContentLicense: CC BY-SA 3.0


问:
What would you think about a new Java persistence tool, that's not really an ORM?

Persistence in Java

Over the past years, I have gathered experience in the field of persistence abstraction in Java, using concepts such as EJB 2.0, Hibernate, JPA and home-grown ones. They seemed to me to have a steep learning curve and lots of complexity. In addition, as a big fan of SQL, I also thought that many abstraction models provide too much abstraction over SQL, creating concepts such as "criteria", "predicates", "restrictions" that are very good concepts, but not SQL.

The general idea of persistence abstraction in Java seems to be based on the Object-relational model, where RDBMS are somehow matched with the OO world. The ORM-debate has always been an emotional one, as there does not seem to exist a single solution that suits everyone - if such a solution can even exist.

jOOQ

My personal preference of how to avoid ORM-related problems is to stick to the relational world. Now the choice of data model paradigm should not be the topic of discussion as it is a personal preference, or a matter of what data model best suits a concrete problem. The discussion I would like to start is around my very own persistence tool called jOOQ. I designed jOOQ to provide most of the advantages modern persistence tools have:

A Domain Specific Language based on SQL

Source code generation mapping the underlying database schema to Java

Support for many RDBMS

Adding some features that few modern persistence tools have (correct me if I'm wrong):

Support for complex SQL - unions, nested selects, self-joins, aliasing, case clauses, arithmetic expressions

Support for non-standard SQL - stored procedures, UDT's, ENUMS, native functions, analytic functions

Please consider the documentation page for more details: http://www.jooq.org/learn.php. You will see that a very similar approach is implemented in Linq for C#, although Linq is not exclusively designed for SQL.

The Question

Now, having said that I'm a big fan of SQL, I wonder whether other developers will share my enthusiasm for jOOQ (or Linq). Is this kind of approach to persistence abstraction a viable one? What are the advantages / disadvantages you might see? How could I improve jOOQ, and what's missing in your opinion? Where did I go wrong, conceptually or practically?

Critical but constructive answers appreciated

I understand that the debate is an emotional one. There are many great tools out there that do similar things already. What I am interested in is critical but constructive feedback, based on your own experience or articles you may have read.

答:
One scenario that would make this kind of API well-suited is when you need a database-agnostic SQL builder which most of the ORM doesn't allow you to have. One big situation where I have needed it is in generating Reports. I have needed to build SQL in a object oriented way and going to run this sql on various databases for testing. Hibernate and other ORM are very dependent on configurations, thus limiting my sql construction such that I can't combine table where association doesn't exist in the xmls. Since any association is possible in the Report Module I am developing, I had looked for something different. Then I came across JOOQ. It  just solves my problem. I have just needed a read only access, never encounter painful debugging issues like in hibernate.

I am actually planning to develop a different way of modelling data rather than the common POJO way and use JOOQ as one of the foundation which is a layer to build SQL. So on top of JOOQ, I am planning to create a more flexible way of modelling data/entities by using HashMaps. My design would make it possible to integrate front end and backend design easier in one entry point, though I would use various layers to complete the framework, just like what the above comments have said. JOOQ will really play a very good part like in my own project, it serves as one of the foundations or pillars.

So keep up the good work lukas!


问:
Design pattern for polymorphic behaviour while allowing library separation
Let's say I have a hierarchy of Item classes: Rectangle, Circle, Triangle. I want to be able to draw them, so my first possibility is add a virtual Draw() method to each:

```<code>class Item {
public:
   virtual ~Item();
   virtual void Draw() =0;
};
</code>```

However, I want to split the drawing functionality to a separate Draw library while the Core library contains only the basic representations. There's a couple of possibilities I can think of:

1 - A DrawManager that takes a list of Items and has to use dynamic_cast<> to work out what to do:

```<code>class DrawManager {
  void draw(ItemList& items) {
    FOREACH(Item* item, items) {
       if (dynamic_cast<Rectangle*>(item)) {
          drawRectangle();
       } else if (dynamic_cast<Circle*>(item)) {
          drawCircle();
       } ....
    }
  }
};
</code>```

This isn't ideal as it relies on RTTI and forces one class to be aware of all items in the hierarchy.

2 - The other approach is to defer drawing responsibility to an ItemDrawer hierarchy (RectangleDrawer, etc):

```<code>class Item {
   virtual Drawer* GetDrawer() =0;
}

class Rectangle : public Item {
public:
   virtual Drawer* GetDrawer() {return new RectangleDrawer(this); }
}
</code>```

This achieves the separation of concerns between the base representation of the Items and the code for drawing. The problem though is that the Item classes are dependent on the drawing classes.

How can I separate out this drawing code into a separate library? Is the solution for the Items to return a factory class of some description? However, how can this be defined so that the Core library isn't dependent on the Draw library?

答: The reason why you are having a problem is because objects should not draw themselves. Drawing something correctly depends on a billion pieces of state and a Rectangle is not going to have any of those pieces. You should have a central graphical object which represents the core state like backbuffer/depth buffer/shaders/etc, and then give it a Draw() method.</p>


答:
Creating interface is ok, but NOT the way your example works. You should remove the setter from the interface, and it'll be ok:

```<code>interface ValueObject {
  String getName();
};
</code>```

This allows many different implementations of it, like name can be fetched from database... Setter should be in different interface.

Title: Should I create interfaces for data transfer objects?

Body:
Is it a good idea or a bad idea to create an interface for data transfer objects?  Presuming that the object is usually mutable.

Though my example is in Java, it should be applicable to any other language that has similar concepts.

```<code>interface DataTransferObject  {
    String getName();
    void setName(String name);
}

class RealDataTransferObject  implements DataTransferObject {

    String name;
    String getName() {
        return name;
    }
    void setName(String name) {
        this.name = name;
    }
}
</code>```

Of course, this is a simplified example, in real life there may be more fields.

Body:
Creating interface is ok, but NOT the way your example works. You should remove the setter from the interface, and it'll be ok:

interface ValueObject {
  String getName();
};

This allows many different implementations of it, like name can be fetched from database... Setter should be in different interface.


问:
In MVC, can/should basic data retrieval from the Model be done in the View?
Given the concept of 'skinny controllers, fat models' and the general acceptance that Views can directly call on Models when requiring data for output, should one consider handling the 'get and display' parts of requests within the Views and not the Controller? For example (attempted to keep code fairly generic):

Controller

```<code><?php

class Invoice extends Base_Controller {

    /**
     * Get all the invoices for this month
     */

    public function current_month() {

        // as there's no user input let's keep the controller very skinny,
        // DON'T get data from the Model here, just load the view

        $this->load->view('invoice/current_month');

    }

}
</code>```

View

```<code><?php

// directly retrieve current month invoices here

$invoices = $this->invoice_model->get_current_month();

// get some other display-only data, e.g. a list of users for a separate list somewhere on the page

$users = $this->user_model->get_users();

?>

<h1>This month's invoices</h1>

<ul>
<?php foreach ($invoices as $invoice) { ?>

<li><?php echo $invoice['ref']; ?></li>

<?php } ?>
</ul>
</code>```

To me, this makes at least some sense in the cases where a request is essentially just a View. Why should the Controller have to collect and pass on the data to the View when it can just retrieve it itself? This leaves the Controller open for purely 'Application level' processing (e.g. handling GET/POST requests, managing access rights and permissions etc.) as well as keeping the Models reusable and all the other good stuff.

If this example was extended to allow a user to filter the results, the Controller would just handle the POST from the form and pass the filters to the View, which would then request the data again, this time with the filters.

Is this a valid approach to developing an MVC application? Or am I overlooking an important part of the role a Controller should play?

答:
I found your question very interesting because I ran into the same issue while learning Python recently.

While the answers given make a convincing argument, I thought I would add another opinion I came across in which the View does get the Model's state without going through the Controller.

It is important to note that both the view and the controller depend
  on the model. However, the model depends on neither the view nor the
  controller. This is one the key benefits of the separation. This
  separation allows the model to be built and tested independent of the
  visual presentation. The separation between view and controller is
  secondary in many rich-client applications, and, in fact, many user
  interface frameworks implement the roles as one object. In Web
  applications, on the other hand, the separation between view (the
  browser) and controller (the server-side components handling the HTTP
  request) is very well defined.

Model-View-Controller is a fundamental design pattern for the
  separation of user interface logic from business logic. Unfortunately,
  the popularity of the pattern has resulted in a number of faulty
  descriptions. In particular, the term "controller" has been used to
  mean different things in different contexts. Fortunately, the advent
  of Web applications has helped resolve some of the ambiguity because
  the separation between the view and the controller is so apparent.

In Application Programming in Smalltalk-80: How to use
  Model-View-Controller (MVC) [Burbeck92], Steve Burbeck describes two
  variations of MVC: a passive model and an active model.

The passive model is employed when one controller manipulates the
  model exclusively. The controller modifies the model and then informs
  the view that the model has changed and should be refreshed (see
  Figure 2). The model in this scenario is completely independent of the
  view and the controller, which means that there is no means for the
  model to report changes in its state. The HTTP protocol is an example
  of this. There is no simple way in the browser to get asynchronous
  updates from the server. The browser displays the view and responds to
  user input, but it does not detect changes in the data on the server.
  Only when the user explicitly requests a refresh is the server
  interrogated for changes.

I'm not in a position to say which of the opinions is "right", and to be honest, I am a bit more confused after reading the answers here and the linked article.

Full text of article here.


问:
Should Controller know about View & Model? or vice versa?
I'm conceptually trying to understand if I should be doing this:

```<code>item = Model()
screen = View()
brain = Controller(item, screen)
</code>```

or this..

```<code>brain = Controller()
item = Model(brain)
screen = View(brain)
</code>```

or this..

```<code>class Controller():
    def __init__(self):
        item = Model(self)
        screen = View(self)
</code>```

or something else entirely?

答:
MVC is more like a modularity pattern. Its purpose is that whenever you want to change the user interface layout (view), you don't have to change de application logic (controller) or the internal data processings (model).

In order to acheive this, the pattern is to isolate the implementation logic of each MVC components. Still, it's perfectly normal that there components know each others interfaces.

What I often saw is that the controler create or call model and view (thus it knows their interface) and model or view can notify the controler in return (more like a callback, or observer pattern). The important part is that the controler is not aware of layout structure.


问:
Is it a bad practice to write shell script with many if-else statment and for loops?
I am maintaing several data process shell scripts which are full of if-else statements and for loops . I try to make the scritps tidy and easy to debug.

When I read some suggestions about shell code best practice, it seems that is is not a best practice to have many if-else and for loop statements.

So what should I do, to write a python or c++ script instead of those logical process?

答:
As in any language...

Try never to write the same logic more than once

Maybe a script with many if-then statements can be reduced to a few functions.

Loops (do, for, while, repeat, until), by their nature, are semi-self-contained engines. They're analogous to electric motors in a complex machine. Errors in them are almost universally the cause of all "freeze", "lockup", "100% CPU" and similar catastrophic bugs.

Use sparingly, I would suggest never to have multiple similar loops. "Genericize" the code so the same loop can be put in a function and reused with different variables and conditions. (from one who has taken days to see an 'l' (el) variable that should have been an 'i' (eye))


答:
The 'interface for value object' is what i'm used to call an accessor.

I experienced different policies concerning accessors need. Some people advocate for when as much as possible, some other prohibit then to reduce the quantity of code to write.

Some rationnals for accessors (or direct value usage) are the following:

Accessors allows changing later the way the value is stored

Accessors allows adding access log when you want to debug your software (when adding a log call in a single method, you capture every value change)

Accessors are more in line with object programming, every variable being encapsulated by methods

Accessors reduces code expressivness (more SLOC for the same result)

Accessors takes some CPU

I personally advocate to reduce the number of accessors, and to use them when you expect the setter (setName) to become more than a simple affectation later.


答:
If you should rewrite the scripts in a language like python depends much on

how many scripts with how many lines of code you have

how many new requirements you expect to be added to them in the nearby future (if there are none, why bother?)

how messy they really are

how sure you are that you can implement them really better without introducing new bugs

And before doing any rewrite, even it is a small one like it seems to be in your case, please read this famous article of Joel Spolsky why a rewrite is often a bad choice.

Title: Is it a bad practice to write shell script with many if-else statment and for loops?

Body:
I am maintaing several data process shell scripts which are full of if-else statements and for loops . I try to make the scritps tidy and easy to debug.

When I read some suggestions about shell code best practice, it seems that is is not a best practice to have many if-else and for loop statements.

So what should I do, to write a python or c++ script instead of those logical process?


问:
Do people who get paid to write code but score low on the "programmer competency matrix" have an ethical duty to find a different kind of job?
People advise me to "find a job doing something that you are good at", but the truth is that I don't believe I am good with anything other than just writing code.  I don't think that I can design or structure a program though.

Don't get me wrong, I'm not the kind of programmer who can't write a fizz buzz program; I'm more like the kind of programmer who can't do much besides getting the job done. It's not that I have a "do the bare minimum" attitude; it's that I'm painfully aware of my limitations as a programmer.

For example, implementing a quick sort algorithm is something that I could do only by relying on rote memorization (that is, if I ever find the motivation to spend a good chunk of my day trying to commit the entire algorithm to memory and not just go like "umm, I see, that makes sense, I can see the logic...").

When it comes to structuring and designing an application I feel I'm just as helpless. Since I am unable to see the right answer at the start I just make a judgement call which nine times out of ten I later regret.

I still manage to obtain job promotions and praise from my coworkers, so others don't necessarily share my opinions.  Objectively speaking though, I simply have neither the learning ability nor the sheer brain power to realistically aspire to be anything more than a 'slightly above average' programmer.

I wonder whether I actually have an ethical duty to make room for more talented people and find myself another kind of job, even if I'm fairly confident that I would not find another role I am better qualified for.  My question then is "Do average programmers have a place on a team?"

答:
Reading through your post I kept thinking this person has what it really takes to be a great programmer.

You say you're painfully aware of your limitations.

The more able a person is in its field, the more humble and aware of their own limitations they usually are. Large part of mastering any craft is admitting how little you actually know - and work with that. It will also keep you hungry for improvement and not stagnating. Use it.

You start out wrong and regret it 9 times out of 10.

It's called getting to know the problem space. This is something that takes years and years of mastering (and to be truthful I don't know if you should ever master it - if you make the "right" call from the start - how do you know its the right one?). Getting a good solution in place usually takes a few failed attempts. There lots of current research on how we learn best through fist making mistakes. You just need to do it in a safe and allowing environment. Make sure you're in such an environment and you'll thrive.

You get things done.

This is pure gold, both from team members waiting for what your delivery to and for managers. You're remembering the most important point in any software project - if you don't deliver, no one gets paid.

This might be hard to turn on its head - but all the points you listed I see as signs of having progressed very far already.


问:
What is the advantage of currying?
I just learned about currying, and while I think I understand the concept, I'm not seeing any big advantage in using it.

As a trivial example I use a function that adds two values (written in ML). The version without currying would be

```<code>fun add(x, y) = x + y
</code>```

and would be called as

```<code>add(3, 5)
</code>```

while the curried version is

```<code>fun add x y = x + y
(* short for val add = fn x => fn y=> x + y *)
</code>```

and would be called as

```<code>add 3 5
</code>```

It seems to me to be just syntactic sugar that removes one set of parentheses from defining and calling the function. I've seen currying listed as one of the important features of a functional languages, and I'm a bit underwhelmed by it at the moment. The concept of creating a chain of functions that consume each a single parameter, instead of a function that takes a tuple seems rather complicated to use for a simple change of syntax.

Is the slightly simpler syntax the only motivation for currying, or am I missing some other advantages that are not obvious in my very simple example? Is currying just syntactic sugar?

答: The main motivation (at least initially) for currying was not practical but theoretical. In particular, currying allows you to effectively get multi-argument functions without actually defining semantics for them or defining semantics for products. This leads to a simpler language with as much expressiveness as another, more complicated language, and so is desirable.</p>

Title: What is the advantage of currying?


答:
Currying is just syntactic sugar, but you're slightly misunderstanding what the sugar does, I think. Taking your example,

```<code>fun add x y = x + y
</code>```

is actually syntactical sugar for

```<code>fun add x = fn y => x + y
</code>```

That is, (add x) returns a function that takes an argument y, and adds x to y.

```<code>fun addTuple (x, y) = x + y
</code>```

That is a function that takes a tuple and adds its elements. Those two functions are actually quite diffent; they take different arguments.

If you wanted to add 2 to all numbers in a list:

```<code>(* add 2 to all numbers using the uncurried function *)
map (fn x => addTuple (x, 2)) [1,2,3]
(* using the curried function *)
map (add 2) [1,2,3]
</code>```

The result would be [3,4,5].

If you wanted to sum each tuple in a list, on the other hand, the addTuple function fits perfectly.

```<code>(* Sum each tuple using the uncurried function *)
map addTuple [(10,2), (10,3), (10,4)]
(* sum each tuple using curried function *)
map (fn (a,b) => add a b) [(10,2), (10,3), (10,4)]
</code>```

The result would be [12,13,14].

Curried functions are great where partial application is useful - for example map, fold, app, filter. Consider this function, that returns the biggest positive number in the list supplied, or 0 if there are no positive numbers:

```<code>- val highestPositive = foldr Int.max 0;
val highestPositive = fn : int list -> int
</code>```

Title: What is the advantage of currying?

Body:
I just learned about currying, and while I think I understand the concept, I'm not seeing any big advantage in using it.

As a trivial example I use a function that adds two values (written in ML). The version without currying would be

```<code>fun add(x, y) = x + y
</code>```

and would be called as

```<code>add(3, 5)
</code>```

while the curried version is

```<code>fun add x y = x + y
(* short for val add = fn x => fn y=> x + y *)
</code>```

and would be called as

```<code>add 3 5
</code>```

It seems to me to be just syntactic sugar that removes one set of parentheses from defining and calling the function. I've seen currying listed as one of the important features of a functional languages, and I'm a bit underwhelmed by it at the moment. The concept of creating a chain of functions that consume each a single parameter, instead of a function that takes a tuple seems rather complicated to use for a simple change of syntax.

Is the slightly simpler syntax the only motivation for currying, or am I missing some other advantages that are not obvious in my very simple example? Is currying just syntactic sugar?

Body:
Currying is just syntactic sugar, but you're slightly misunderstanding what the sugar does, I think. Taking your example,

fun add x y = x + y

is actually syntactical sugar for

fun add x = fn y => x + y

That is, (add x) returns a function that takes an argument y, and adds x to y.

fun addTuple (x, y) = x + y

That is a function that takes a tuple and adds its elements. Those two functions are actually quite diffent; they take different arguments.

If you wanted to add 2 to all numbers in a list:

(* add 2 to all numbers using the uncurried function *)
map (fn x => addTuple (x, 2)) [1,2,3]
(* using the curried function *)
map (add 2) [1,2,3]

The result would be [3,4,5].

If you wanted to sum each tuple in a list, on the other hand, the addTuple function fits perfectly.

(* Sum each tuple using the uncurried function *)
map addTuple [(10,2), (10,3), (10,4)]
(* sum each tuple using curried function *)
map (fn (a,b) => add a b) [(10,2), (10,3), (10,4)]

The result would be [12,13,14].

Curried functions are great where partial application is useful - for example map, fold, app, filter. Consider this function, that returns the biggest positive number in the list supplied, or 0 if there are no positive numbers:

- val highestPositive = foldr Int.max 0;
val highestPositive = fn : int list -> int


答:
I can really relate to this. I have felt like a mediocre programmer all my life and I have always looked at people who are better than me. And to be honest, a lot of programmers are better than me. But still, like you, I get praise for my work AND like you I make my clients and boss happy AND I even got promoted to senior software engineer so we must be doing SOMETHING right. Even though I am successful at work I still know there are even talented junior programmers who are better at abstracting problems and writing code to deal with those problems in a more elegant and abstract way. It is hugely important that we focus on what we CAN do and praise ourselves for that. And it is much more important to change the way we look at what we have achieved than to try and become a "good" programmer (or architect, or friend, or ice skater, or anything) for the rest of our lives.

There are some things that are just not within our reach. I could dream of being able to set up a hugely complex project with a zillion new technologies and a zillion complex and beautiful programming patterns in a day like my much praised colleague Mark can. But I can't. And I will keep focussing on what I can do and do that to the best of my ability and respect myself for that. And I think you should try to do the same. You could start by telling yourself that being a programmer and getting praised and paid for your work is quite an achievement to start with.

Title: Do people who get paid to write code but score low on the "programmer competency matrix" have an ethical duty to find a different kind of job?

Body:
People advise me to "find a job doing something that you are good at", but the truth is that I don't believe I am good with anything other than just writing code.  I don't think that I can design or structure a program though.

Don't get me wrong, I'm not the kind of programmer who can't write a fizz buzz program; I'm more like the kind of programmer who can't do much besides getting the job done. It's not that I have a "do the bare minimum" attitude; it's that I'm painfully aware of my limitations as a programmer.

For example, implementing a quick sort algorithm is something that I could do only by relying on rote memorization (that is, if I ever find the motivation to spend a good chunk of my day trying to commit the entire algorithm to memory and not just go like "umm, I see, that makes sense, I can see the logic...").

When it comes to structuring and designing an application I feel I'm just as helpless. Since I am unable to see the right answer at the start I just make a judgement call which nine times out of ten I later regret.

I still manage to obtain job promotions and praise from my coworkers, so others don't necessarily share my opinions.  Objectively speaking though, I simply have neither the learning ability nor the sheer brain power to realistically aspire to be anything more than a 'slightly above average' programmer.

I wonder whether I actually have an ethical duty to make room for more talented people and find myself another kind of job, even if I'm fairly confident that I would not find another role I am better qualified for.  My question then is "Do average programmers have a place on a team?"


问:
My most cherished dream project seems to resemble a product that already exists. What shall I do?
I guess this is more of a "comfort seeking" question than legality one.

You see, for the past couple of months I have been brainstorming and developing a product, all by myself. I was planning to release it under some kind of free license. While I know no idea is ever a unique one, I was quite happy to note that the way I had visualized my software, in its form and purpose, was one of its kind, albeit bits and pieces resembling others. That private project was quite cherished one.

Now I find there is a product, at least a decade old, that is so close to mine that mine looks plagiarized. While with the rest of them I had a 8:2 in my favor, feature wise, with this product it seems transposed, including the philosophy. I admit I can vaguely recall hearing the name of it but never thought of reading about it - the name didn't seem to invoke interest etc - until now. I read about it and now I am distraught and agonized.

There is no risk of any legal action as that software is in "free" domain and mine is still a private project, and I don't know if it will be ever make any money from any buyer which will then lead to trouble, but that is not the point of the question.

The point is how to stay focused and enthusiastic as before? I have about a month of work pending, mainly programming and complete testing, and this has completely left me drained. I am in a fetal position. I am telling myself about Newton-Leibniz, Faraday-Henry kind of independent activities with similar to same results but that isn't helping. I don't want this to spill over to my regular life and work life.

I can sense two issues that are pricking me. (1) I wanted praise for my creativity. (2) I was harboring a small desire of a possible chance of making good money by attracting a buyer.

This might be a casual and almost an inconsequential problem for the citizens of the business world, but I am from a different world.

Help.

答:
If you love this thing you've built, there's no reason to stop now.  Nothing has changed.  It was never unique - almost nothing in the software world has been, for many years.

Do you have any idea how many Free/Open Source Software web servers have been written?  With almost no exceptions, they were all written while Apache was the feature-dominant product with the largest install base.  Many of them are well-loved by their users and have enjoyed long lives.  Do their authors care that they are not unique, or that they are matched or over-matched, feature for feature?  Heck no, each of them has a raison d'être that is not "crowd Apache into a tiny, little corner of the market", and they focus on that, not on killing Apache.


答:
For the function

```<code>fun add(x, y) = x + y
</code>```

It is of the form f': 'a * 'b -> 'c

To evaluate one will do

```<code>add(3, 5)
val it = 8 : int
</code>```

For the curried function

```<code>fun add x y = x + y
</code>```

To evaluate one will do

```<code>add 3
val it = fn : int -> int
</code>```

Where it is a partial computation, specifically (3 + y), which then one can complete the computation with

```<code>it 5
val it = 8 : int
</code>```

add in the second case is of the form f: 'a -> 'b -> 'c

What currying is doing here is transforming a function that takes two agreements into one that only takes one returning a result. Partial evaluation

Why would one need this?

Say x on the RHS isn't just a regular int, but instead a complex computation that takes a while to complete, for augments, sake, two seconds.

```<code>x = twoSecondsComputation(z)
</code>```

So the function now looks like

```<code>fun add (z:int) (y:int) : int =
    let
        val x = twoSecondsComputation(z)
    in
        x + y
    end;
</code>```

Of type add : int * int -> int

Now we want to compute this function for a range of numbers, let's map it

```<code>val result1 = map (fn x => add (20, x)) [3, 5, 7];
</code>```

For the above the result of twoSecondsComputation is evaluated every single time. This means it takes 6 seconds for this computation.

Using a combination of staging and currying one can avoid this.

```<code>fun add (z:int) : int -> int =
    let
        val x = twoSecondsComputation(z)
    in
        (fn y => x + y)
    end;
</code>```

Of the curried form add : int -> int -> int

Now one can do,

```<code>val add' = add 20;
val result2 = map add' [3, 5, 7, 11, 13];
</code>```

The twoSecondsComputation only needs to be evaluated once. To up the scale, replace two seconds with 15 minutes, or any hour, then have a map against 100 numbers.

Summary: Currying is great when using with other methods for higher level functions as a tool of partial evaluation. Its purpose cannot really be demonstrated by itself.

Title: What is the advantage of currying?

Body:
For the function

fun add(x, y) = x + y

It is of the form f': 'a * 'b -> 'c

To evaluate one will do

add(3, 5)
val it = 8 : int

For the curried function

fun add x y = x + y

To evaluate one will do

add 3
val it = fn : int -> int

Where it is a partial computation, specifically (3 + y), which then one can complete the computation with

it 5
val it = 8 : int

add in the second case is of the form f: 'a -> 'b -> 'c

What currying is doing here is transforming a function that takes two agreements into one that only takes one returning a result. Partial evaluation

Why would one need this?

Say x on the RHS isn't just a regular int, but instead a complex computation that takes a while to complete, for augments, sake, two seconds.

x = twoSecondsComputation(z)

So the function now looks like

fun add (z:int) (y:int) : int =
    let
        val x = twoSecondsComputation(z)
    in
        x + y
    end;

Of type add : int * int -> int

Now we want to compute this function for a range of numbers, let's map it

val result1 = map (fn x => add (20, x)) [3, 5, 7];

For the above the result of twoSecondsComputation is evaluated every single time. This means it takes 6 seconds for this computation.

Using a combination of staging and currying one can avoid this.

fun add (z:int) : int -> int =
    let
        val x = twoSecondsComputation(z)
    in
        (fn y => x + y)
    end;

Of the curried form add : int -> int -> int

Now one can do,

val add' = add 20;
val result2 = map add' [3, 5, 7, 11, 13];

The twoSecondsComputation only needs to be evaluated once. To up the scale, replace two seconds with 15 minutes, or any hour, then have a map against 100 numbers.

Summary: Currying is great when using with other methods for higher level functions as a tool of partial evaluation. Its purpose cannot really be demonstrated by itself.


答: This kind of value object is pretty low level.  I'd suggest pushing it in one of two directions: (1) make the value object immutable, that is, like a real value, or, (2) elevate the mutability to a higher level domain oriented business function, meaning we should expose interfaces in terms of domain relevant units of functionality.


问:
Is the average number of bugs per loc the same for different programming languages?
I have been told that the average number of bugs/defects per line of code is "constant" for different programming languages. 10 KLOC of Ruby would have the same number of bugs as 10 KLOC of c++. The argument is usually used to promote the use of expressive languages (think python/ruby over c++/assembly) since the number of lines to describe the same functionality would be smaller.

Does anybody know where this claim comes from? Does higher-level languages lead to fewer bugs?

答:
I don't find Bugs per LOC to be constant at all for a given language. Bugs per LOC seem like a metric some Managers use to determine the quality of developers when it comes to review time.

Now outside of that, some languages are more prone to errors or defects than others. Usually, but not always this is a lower level language than a higher one. For example coding in C versus C# (or Java.) I say usually because the reality of it and the crux of the answer you are looking for comes down to quality of developer and the coding practices in place. I have seen very good C developers with much higher code quality and lower defect counts than average Java/C# developers. This is one item that separates a senior developer from a junior one. Not how many LOC they write in a given time frame, but quality of the code the write regardless of language, LOC or time frame.

The only thing answer I can give that might relate is that the more LOC there are the more likely-hood of there being a defect and the more defects that exists.


答:
The view should subscribe to changes in the model.  There is latitude in the richness of subscriptions as they may be detailed (show me inventory changes for this particular item) or generic (the model has changed); the view may query the model in response to change notification.  The view presents its desired set of model elements on the screen, updating the screen as when handling change notifications.

The controller should push changes to the model, as a result of user direction (e.g. keyboard in put, mouse & menu commands).

The model maintain the model and a list of subscriptions, and should notify views of applicable changes via their subscriptions.

There also needs to be a mechanism to create new views and controllers (since in MVC you should be able to have two or more views of the same model (they could be the same view(point) or different view(point)s).  Logically, we can consider that the controller needs to perform or have access to a view & controller (pair) factory, which can be part of the controller or another component.

Title: Should Controller know about View & Model? or vice versa?

Body:
I'm conceptually trying to understand if I should be doing this:

```<code>item = Model()
screen = View()
brain = Controller(item, screen)
</code>```

or this..

```<code>brain = Controller()
item = Model(brain)
screen = View(brain)
</code>```

or this..

```<code>class Controller():
    def __init__(self):
        item = Model(self)
        screen = View(self)
</code>```

or something else entirely?


答:
The claim is - at best - naive.

SLOC isn't exactly a reliable metric for anything useful, except perhaps comparing the size of two or more projects. Furthermore there are two distinct types of SLOC, physical LOC and logical LOC, and those might differ significantly. Consider this example, from Wikipedia:

```<code>for (i = 0; i < 100; i += 1) printf("hello");
</code>```

Here we have one physical LOC, but two logical ones (for and printf statements). But we could of course write the example as:

```<code>for (i = 0; i < 100; i += 1)
  printf("hello");
</code>```

Which would give us two physical and two logical LOCs. I think it's clear that any "bug per loc" measurement that would depend on physical LOCs would be tainted by programming style, thus our measurement would be largely useless.

If, on the other hand, we went with logical LOCs then our measurement would heavily depend on the language's syntactic idiosyncrasies. Although the resulting metric might be a bit useful when comparing projects written in the same language, it would be fairly useless for projects written in different languages.

One possible source for the claim is Les Hatton's Software failures-follies and fallacies:

We can conclude that programming language choice is at best weakly related to reliability.

Later on, the paper mentions similar defect densities for C and C++:

In a recent study comparing two similar systems of similar size, (around 50,000 lines each), one in C and one in object-designed C++, the resulting defect densities were shown to be around the same at 2.4 and 2.9 per 1000 lines respectively.

This, however, doesn't mean that "bug per LOC" is constant across programming languages, or that it would be significant if it was.

Title: Is the average number of bugs per loc the same for different programming languages?

Body:
I have been told that the average number of bugs/defects per line of code is "constant" for different programming languages. 10 KLOC of Ruby would have the same number of bugs as 10 KLOC of c++. The argument is usually used to promote the use of expressive languages (think python/ruby over c++/assembly) since the number of lines to describe the same functionality would be smaller.

Does anybody know where this claim comes from? Does higher-level languages lead to fewer bugs?

Body:
The claim is - at best - naive.

SLOC isn't exactly a reliable metric for anything useful, except perhaps comparing the size of two or more projects. Furthermore there are two distinct types of SLOC, physical LOC and logical LOC, and those might differ significantly. Consider this example, from Wikipedia:

for (i = 0; i < 100; i += 1) printf("hello");

Here we have one physical LOC, but two logical ones (for and printf statements). But we could of course write the example as:

for (i = 0; i < 100; i += 1)
  printf("hello");

Which would give us two physical and two logical LOCs. I think it's clear that any "bug per loc" measurement that would depend on physical LOCs would be tainted by programming style, thus our measurement would be largely useless.

If, on the other hand, we went with logical LOCs then our measurement would heavily depend on the language's syntactic idiosyncrasies. Although the resulting metric might be a bit useful when comparing projects written in the same language, it would be fairly useless for projects written in different languages.

One possible source for the claim is Les Hatton's Software failures-follies and fallacies:

We can conclude that programming language choice is at best weakly related to reliability.

Later on, the paper mentions similar defect densities for C and C++:

In a recent study comparing two similar systems of similar size, (around 50,000 lines each), one in C and one in object-designed C++, the resulting defect densities were shown to be around the same at 2.4 and 2.9 per 1000 lines respectively.

This, however, doesn't mean that "bug per LOC" is constant across programming languages, or that it would be significant if it was.

ContentLicense: CC BY-SA 4.0


问:
Micro vs Monolithic Server architecture
We are currently working on our new product/project, it is a client-server application directed towards certain specific industrial/service enterprises. We are building a server (C Language and Linux Only) running a custom protocol on top of TCP with a Java front-end. We are about 20% into the coding work and are faced with a situation having to choose between Micro or Monolithic Kernel Architecture.

I am aware that Micro vs. Monolithic is usually in relation to kernel architecture, but we are specifically talking about servers.

Why a custom server and not something existing?

Our UI needs are significant and very dynamic, thus Web/Web-browser based solutions were not appropriate.

The statistical processing is significant at the client end and therefore, again, browsers were of little help. (Of course, we could do the processing at the server end and pass on the processed data to the client but that would imply lot of load on the server and wastage of client resources).

Moreover, with atleast three technologies (JS/HTML/CSS) to manage even a single event makes the whole experience like sweeping the house in the midst of a desert storm - you sweep it n-times, the dust accumulates n+1 times.

What about Micro and Monolithic Server? What are you talking?

Consider the following (hypothetical) client request:

```<code>request-id: 123
request-service: HistoricDataSets
request-message: Fetch all records upto the year 2010
</code>```

On receving such request, a server, typically, does (we are ignoring concurrency techniques like thread and forks for simplicity):

Parse the request string

Identify the action (Fetch HistoricDataSets LIMIT  Year (2010) in our case)

Interact with the persistance layer (Oracle, lets say, in our example) and fetch the data.

Format the data as per the protocol. Ex:

response-id: 123

success: true

response-text: DataSets

Respond to the client with the thus formatted data.

This is what we are calling a Monolithic Server (akin to a monolithic kernel where all OS workings are done in the kernel space).

Consider the same request again, on receipt, this time the server (we have assumed only shared memory as IPC, again for simplicity):

Puts the request into the shared memory for the Parser process

The Parser parses the string, identifies the task and directs the Executioner process to execute the tasks.

The Executioner then passes the data to Fomatter process which, after formatting the data into a protocol string, returns to the server.

The server dispatches it to the client (response).

Of course, instead of Parser, Executioner and Formatter it could have been a single but separate process.  This is what we are calling a Micro Server (akin to a micro kernel doing barely minimum that is required). The server effectively is only listening and responding whereas all steps are taken care of by different process(es).

Which one to pick? We are confused! While monolithic servers are tried and tested (most HTTP-Web Servers?) and easier to program and can handle concurrency quite well. Micro servers, prima facie, seem swift and in line with UNIX principle of one program to do one task, but are also complicated to develop, esp. keeping concurrency in mind.

Question(s)

- What are (possibly could be) the pros and cons of each approach?

- When to use which? (It could also be interpreted as a general question: When to use IPC?)

- If Micro kernel is chosen, then what functions need to be a part of core-server and what not?

Similar/Related questions

Dangers of huge monolithic application

External Vs Embedded browser (Tangential)

Advice for converting Monolithic app into multithreaded (Tangential)

Some information that may be helpful:

Our prospective customers can be divided into two categories:

Large: About 1,700 - 2,000 requests per minute

Small: About 650 - 700 requests per minute

Data volume per request cycle (request and the subsequent response) can be assumed to be normally distributed with mean ~ 1.20 MB and worse case about 250-300 MB.

The product concept is relatively new but has the capability of impacting the core operations, therefore we expect the customer budgets to be flexible only post a certain lag (9-12 months) post deployment, this limits the amount of hardware the client will be willing to commit esp. the small ones.

Each customer will have his own client-server stack. The server will be running on the customer's hardware managed by the customer's team, while clients will be deployed on the machines of the functional employees

Remote updates for both client and server application is a must

Real time PUSH services by the server may be 'highly' desired if the product clicks!

答:
Monolithic kernel is much older than Microkernel. It’s used in Unix .
while
Idea of microkernel appeared at the end of the 1980's.

the example of os having the Monolithic kernels are UNIX , LINUX
while
the os having Microkernel are QNX , L4 , HURD , initially Mach (not mac os x) later it will              converted into hybrid kernel , even MINIX is not pure kernel because device driver are compiled as part of the kernel .

Monolithic kernel are faster than microkernel .
while
The first microkernel  Mach is 50% slower than Monolithic kernel while later version like L4 only 2% or 4% slower than the Monolithic kernel .

Monolithic kernel generally are bulky .
while
Pure monolithic kernel has to be small in size even fit in s into processor first level cache (first generation microkernel).

in the Monolithic kernel device driver reside in the kernel space .
while
In the Microkernel device driver reside in the user space.

since the device driver reside in the kernel space it make monolithic kernel less secure than microkernel . (Failure in the driver may lead to crash)
while
Microkernels are more secure than the monolithic kernel hence used in some military devices.

Monolithic kernels use signals and sockets to ensure IPC
while
microkernel approach uses message queues . 1 gen of microkernel poorly implemented IPC so were slow on context switches.

adding new feature to a monolithic system means recompiling the whole kernel
while
You can add new feature or patches without recompiling.

Title: Micro vs Monolithic Server architecture


问:
MVC Pattern - How to get errors from the model to the controller?
Say I have a typical MVC setup. The controller passes on some input to the model, and asks it to do something with it. But the validation of the data fails, or there is some other problem. What's the best way of getting these errors passed back to the controller, which will then pass them to the view to be displayed to the user?

At the moment, I just have an errors array in my model. When any errors occur, I simply add the error messages to this array, and return false to the controller, so it knows that errors occurred. And in the controller, I do this:

```<code>boolean result = model.process( input );

if (! result)
{
   view.displayErrors( model.getErrors() );
   return;
}
else
   view.displaySuccess();
</code>```

Is there a better way of handling this?

答:
So what you're suggesting / currently doing is one method, and it's certainly a valid way of gathering additional information about error messages.

It's a reasonably lightweight approach - the caller gets a success | failure message and then it's up to the caller to dig deeper for additional information if it so cares.  The downside is what you alluded to with the comments - what if there are multiple issues within the validation?

It wouldn't be too hard to extend this approach so that the caller loops over a GetErrorDetails() call until that method returns an indicator of "no more errors."

Another potential issue with this approach is the implicit assumption that the caller is in the best position to deal with whatever the error messages may be.  Since you're using MVC, the controller isn't always the best layer to fix that problem.  The validation errors need to be pushed back to the View so the user can correct the issue.  I'm not focusing on this aspect since there are some valid counter-arguments to indicate that the Controller could / should indicate the error.  That discussion is not the point of your question.

Altertnative 1

As an alternative, consider making a full blown object to return errors with.  Instead of the boolean that you're currently returning, you'll return that error object instead.

Obviously, the error object will need to have a value to indicate success | failure | partial-success | whatever.  The benefit is that you can now add a collection of errors within the error object itself.

Here's some pseudo-code to give you an idea of what I'm suggesting.

```
ErrorParent()
{
  bool success;
  List errorMsgs;
}

ErrorMessages()
{
  string message;
  int  severity;
  List callstack;
}
```

The caller has to work a little harder to determine success, but it's an equally simple ErrorParent.success check as opposed to a success check.  Yes, yes, I know the troubles of typing out a few more characters...

If the caller cares about the errors, then it can iterate over the ErrorParent.errorMsgs collection and see what all went wrong.  If the caller doesn't care about the errors then it can pass the error object off to an error handler and let the handler do all the hard work.

Alternative 2

Instead of returning a bool for success / error, you could return a numeric value.  The numeric value would indicate the number of failed validations.  The Controller could pass that numeric error return to the "best" error handler for that situation, and then the error handler would loop over the GetErrorDetails() method.

Body:
So what you're suggesting / currently doing is one method, and it's certainly a valid way of gathering additional information about error messages.

It's a reasonably lightweight approach - the caller gets a success | failure message and then it's up to the caller to dig deeper for additional information if it so cares.  The downside is what you alluded to with the comments - what if there are multiple issues within the validation?

It wouldn't be too hard to extend this approach so that the caller loops over a GetErrorDetails() call until that method returns an indicator of "no more errors."

Another potential issue with this approach is the implicit assumption that the caller is in the best position to deal with whatever the error messages may be.  Since you're using MVC, the controller isn't always the best layer to fix that problem.  The validation errors need to be pushed back to the View so the user can correct the issue.  I'm not focusing on this aspect since there are some valid counter-arguments to indicate that the Controller could / should indicate the error.  That discussion is not the point of your question.

Altertnative 1

As an alternative, consider making a full blown object to return errors with.  Instead of the boolean that you're currently returning, you'll return that error object instead.

Obviously, the error object will need to have a value to indicate success | failure | partial-success | whatever.  The benefit is that you can now add a collection of errors within the error object itself.

Here's some pseudo-code to give you an idea of what I'm suggesting.

ErrorParent()
{
  bool success;
  List errorMsgs;
}

ErrorMessages()
{
  string message;
  int  severity;
  List callstack;
}

The caller has to work a little harder to determine success, but it's an equally simple ErrorParent.success check as opposed to a success check.  Yes, yes, I know the troubles of typing out a few more characters...

If the caller cares about the errors, then it can iterate over the ErrorParent.errorMsgs collection and see what all went wrong.  If the caller doesn't care about the errors then it can pass the error object off to an error handler and let the handler do all the hard work.

Alternative 2

Instead of returning a bool for success / error, you could return a numeric value.  The numeric value would indicate the number of failed validations.  The Controller could pass that numeric error return to the "best" error handler for that situation, and then the error handler would loop over the GetErrorDetails() method.


问:
Software Requirement Specification documentation by professionals
I just wanted to know what is the significance of SRS(Software Requirement Specification) in programming? and what are the techniques used in preparation of an SRS .. also who writes the SRS.. is it the programmers?</p>

答:
For some organizations, the SRS is a very important document.  Other organizations don't bother.  So the significance of the document will depend upon the organization and their development process.

Larger, "less agile" organizations tend to rely upon them more but I don't intend to start a flame war over their usage versus various development methodologies.  Both waterfall and unified process approaches have a place for the SRS document.

The SRS can be very helpful in making sure that the business clients are clearly expressing their requirements of the application to the architects and developers.  It can also be useful in identifying conflicting requirements and providing the basis to resolve those conflicts.  The sooner conflicts are caught and resolved then the less likely that expensive design and coding changes will be required.

Generally, representatives from the business, business analysts, architects, and lead programmers will contribute to the SRS at various stages.  Any particular instantiation will depend upon that organization and that project.  Ultimately, there needs to be at least two people involved - one to express what is required and one to capture those requirements in a way that will have meaning to developers.

Techniques used to prepare an SRS is a huge subject, and there are a number of resources available to describe the process.  Consider looking at the Software Engineering Book of Knowledge as a starter course on SRS development.

Normally, I would provide a link to the SWEBOK but it's under review for the next release and IEEE has been moving the hosting URL around.  At the moment, it's easier to just google for it.


答:
Interfaces define a contract between the classes implementing the interfaces and their clients. They are used as an abstraction mechanism so that clients can manipulate "stuff having a given behaviour".

So the general answer to the question "should I create and use this interface?" is: Yes, if you can associate a (a single one) concept being semantically relevant for your clients.

For instance, Comparable is a good interface, because it explains that things can be compared thanks to one of their methods, and as a client I'm interested in dealing with comparable objects (e.g. for sorting them). A contrario, CoolStuff is not a good interface if you admit the cool objects don't have a specific behaviour (in fact, you can imagine a software in which dealing with cool objects makes sense, because they have a common behaviour such as a beCool method).

In your particular case, I believe your interface is useless. Who will use it, how and when? You cannot create an interface for each of the mutable values. So ask yourself what is the relevant and interesting property behind your methods.

If what you want is dealing with objects having all their mutable values accessible through a couple of methods, have a look at the notion of Java bean and the way you can force your classes to adopt their conventions.


答:
Bugs Per Line Of Code

Bugs / LOC is only relative to an individual. For businesses that implement bug tracking tools that link with their source code repository. It's possible for a manager to organize issues by developer, sorted by past issues and code changes.

Bugs Are Relative To Your Job

A senior software developer, who is highly experienced, highly skilled, very smart and able to take on independent jobs is far more likely to have way more bugs logged in a tracking system, then a junior developer with little experience.

How is that possible?

Senior developers are often engaged in higher risk development tasks. Refactoring of code and building new systems as an example. Junior developers are often assigned to fix known issues that aren't worth the time of a senior developer.

Therefore, by task assignment a junior isn't introducing bugs but fixing them, and a senior developer is allowed the risk of introducing them, because the benefit of what they are trying to archive is more important then the minor issues that are raised completing those tasks.

Language Syntax Is Important

The argument that a language introduces less bugs, because it can achieve more in fewer lines of code is a complete myth. Highly structured languages like C++/C#/Java force the developer to clearly express in writing what the desired instruction should be, where as languages like Python/PHP are very unstructured. Those languages allow for written expressions that not only will confuse a developer, but also the language parser.

The Compiler Reduces Bugs

How many bugs in Python/PHP have made it out into production servers, because there was no compiler to warn the developer that something was incorrect. When you measure bugs per LOC is that before or after a compiler has processed the source code?

Update 2019:

Compilers make no difference on the nature or number of bugs. Bugs are purely relative to the person who wrote the source code, and bugs themselves can be very subjective in nature.


问:
Is it possible to use GNU GPL for application that has no source?
I mean, it is possible to create application without source code - for example using HEX editor or some debugger that can assembly instructions (actually every decent debugger can).

Creating programs this way is of course hard, but possible for small applications.

I even can imagine cases, where it is the only possible way - for example, on some very old hardware where you simply does not have any development tools.

For another example - read the article
"Programming in extreme conditions", published in Assembly programming journal, issue 9

So, what if the author of such application wants to distribute it under GNU GPL?

答:
The GPL requires a distributor to make the preferred form for editing of the program available. This usually means the source code, and it has to be machine-readable (no print-outs or narrations in haiku form).  If you were on a platform where byte-patching executables is the only way of creating them, then that would have to count as the "preferred" form, but I can't think of a system where this would be the case.

It's arguable what it would mean for someone to create a program in a needlessly cumbersome way (e.g. writing hexadecimal machine language out of sheer bloody-mindedness, or to impress the community, etc.) and then put it under the GPL. Your preference may not be the same as my preference, and might be legally untenable to require someone to provide something that doesn't actually exist. The correct people to ask about this are the Free Software Foundation, and ultimately the courts.


答: I believe that this is not possible. It violates freedoms two and four of free software. Access to source code is a precondition for distributing software under the GPL, and in this case what you define as source code (HEX) is not human-readable. I think that the lowest level of code that can be distributed with the GPL is assembly language of a specific architecture. Public domain or another license might be more suitable for the case that you describe.</p>

Title: Is it possible to use GNU GPL for application that has no source?

Body:
I mean, it is possible to create application without source code - for example using HEX editor or some debugger that can assembly instructions (actually every decent debugger can).

Creating programs this way is of course hard, but possible for small applications.

I even can imagine cases, where it is the only possible way - for example, on some very old hardware where you simply does not have any development tools.

For another example - read the article
"Programming in extreme conditions", published in Assembly programming journal, issue 9

So, what if the author of such application wants to distribute it under GNU GPL?


答:
As Michael said, don't add an interface unless you have a specific need for it.

Testing is an example of a good reason. Though I prefer to use real collaborators if they are just "value objects" as you call them, for true unit test isolation you may need to create a fake object for testing, in which case an interface is quite helpful.


答:
Contrary to intuition, the number of errors per 1000 lines of does seem to be relatively constant, reguardless of the specific language involved. Steve McConnell, author of Code Complete and Software Estimation: Demystifying the Black Art goes over this area in some detail.

I don't have my copies readily to hand - they're sitting on my bookshelf at work - but a quick Google found a relevant quote:

Industry Average: "about 15 - 50 errors per 1000 lines of delivered
  code."

  (Steve) further says this is usually representative of code that has some
  level of structured programming behind it, but probably includes a mix of
  coding techniques.

Quoted from Code Complete, found here: http://mayerdan.com/ruby/2012/11/11/bugs-per-line-of-code-ratio/

If memory serves correctly, Steve goes into a thorough discussion of this, showing that the figures are constant across languages (C, C++, Java, Assembly and so on) and despite difficulties (such as defining what "line of code" means).

Most importantly he has lots of citations for his sources - he's not offering unsubstantiated opinions, but has the references to back them up.

It seems to boil down to this: The average number of defects per kloc seems to be more a property of the fact that developers are fallible humans than of the peculiar advantages or disadvantages of a particular language or platform.

(Aside: If you don't already have Code Complete, go buy yourself a copy and read it thoroughly - it's well worth the investment. )

Update: There's another factor at play with some of the answers here - large scale statistics are useful for making general predictions but not specific ones. Consider, population mortality tables can predict about how many people will be killed in traffic accidents this year but can't tell you which people will die. Similarly, industry statistics that show a relatively constant number of defects per kloc can't be used to predict how well - or how poorly - a particular developer will perform or what will happen on a given project.


问:
Should extension scripts be run in a sandbox?
In particular, this is about game extensions written in lua (luajit-2.0). I was contemplating whether I should restrict what these scripts can do, and arrived at the conclusion that I probably shouldn't:

It's hard to get right. Sounds silly, but chances are my sandbox is gonna end up leaky anyways.

The only benefit I could think of would be giving users some sense of security when running third party scripts.

The disadvantages would be that it's just incredibly annoying for extension writers. That is, for now, myself (game content will be mostly scripted).

The reason I'm asking this now before I actually have anything presentable is that adding a sandbox early on is easy, but would impose said annoying restrictions on myself too. However if I first go on with it and then later decide I do need a sandbox after all, I'm gonna run into problems (I'd either have to rewrite the scripts that are already there, or introduce some form of trust management system which seems to be more trouble than it's worth).

答:
It's hard to get right

It is actually not very hard to create a basic sandbox with whitelist of functions and then add custom implementations of potentially unsafe functions. This SO question seems like a good starting point.

but chances are my sandbox is gonna end up leaky anyways

I think it would be enough to start to provide some basic security: restricting access to files outside some special directories. There is no such thing as 100% secure applications anyway. Think of what can happen if someone will write some malicious extention: users will probably blame you as a developer. If you plan to give someone a chance to write extention, you will eventually need some security. If it's only you - it is OK as it is.

The only benefit I could think of would be giving users some sense of security when running third party scripts.

This is exactly the reason why you should do sandboxing and it is not a valid argument against sandboxing.

The disadvantages would be that it's just incredibly annoying for extension writers

I have some experience in game scripting and I don't find it annoying to work in a sandboxed environment by itself. What annoys me is lack of functionality which is game-related, like specific APIs of in-game objects or poor implementations of such.

It may help if you look into LOVE engine as a good example (if you haven't already), especially tutorial on filesytem API.


问:
Should methods always return from one place?

Possible Duplicate:

  Where did the notion of “one return only” come from?

I got into a little argument with a coworker about whether a method should be written like this:

```<code>public Thing getThing(int key){
    if(!things.containsKey(key))
        return null;

    return things.get(key);
}
</code>```

or this:

```<code>public Thing getThing(int key){
    Thing t = null;

    if(things.containsKey(key))
        t = things.get(key);

    return t;
}
</code>```

I personally think the first way is cleaner and easier to read. However, I was taught in school that you should always return from one place. Since no one has ever been able to give me a good reason to prefer one over the other (baring stylistic concerns), I usually go with whatever makes the code easier to read.

Are there any good reasons to prefer one way over the other, or does it vary by situation?

答:
Should methods always return from one place? NO.

Should I never use goto? NO.

Should I never inherit form non polymorhic types? NO.

There are lot of questions like these, that lies like sediments in the history of the computer languages, creating sort of sectarian cultures (not to call them even Religions) where everything must be Pure, Intact, Elegant, Virginal, ...

Luckily the most of "humans" (in "humanist" sense) don't follow this rules, otherwise humanity had already been extinguished for the practical impossibility for people to meet themselves.
(out of metaphor: program must also work, not just be elegant!)

All of these rules comes from philosophies of the languages with all the good intention to keep things in order, but that may fail dramatically when such order becomes a mania.

I personally avoid to trust teachers or mentors that create their leadership abusing of little words like "always", "never": whatever great their experience can be, they cannot have the knowledge of the everything and every-time.

Avoiding spurious retunrs can be a good thing, but doing it introducing 4 variables and 5 level of if-nesting is bad more than a multiple return.

Goto randomly up and down jumping arbitrarily into code structures is bad, but introducing a network of fake variable states to avoid goto-s to describe a state machine is even worse (since it makes you anymore able to identify the states, that can easily defined as jump labels)

There was a time (try search a listing of a BASIC program of the '80s) where variables didn't have a scope, where labels where just numbers, where if could only do a goto. Jumping in the middle of the loop skipping index initialization, or modify a loop index from within a called subroutine, or jumping in the middle of a function from the outside was the major source of mistakes impossible to be found, inside code written for the machines, and not for the maintainers.

But today variables have scope, goto-s have scope, function call have scope. All of those "tool" have very well defined influence limits. The problem is not avoid this or that tool, but use the right one, in the proper place within its proper limitations. Language features exist for a reason! Don't drop them just for purity: drop them when they don't help you.

When coding something, also thing to the possible variants: What should I modify if my spec. change this or that way? What (between this or that) will be the most probable "next requirement" from my users/clients/bosses ?

Once you did a reasonable prediction, code in a way what you will expect to furthermore change, can be easily found, and can be easily changed without too much "things at contour" to look around an change as well.  5 levels of if, to avoid four returns is in the most of the case not the way to go, since it risk to make all text to be modified if another escape condition is required to be introduced.


答:
FWIW, in my experience

There are two kinds of bugs: a) where the program does not meet expectations, and b) where the program cannot meet any reasonable expectations, because it crashes/hangs/won't compile.

Regardless of language, bugs of type (b) are caused by redundancy in data/class structure, where changing something in one part of the data structure puts the structure in an inconsistent/broken state until one or more corresponding changes are made in other parts. Contributing to this is redundancy of source code, where an edit to one line of code makes the code incorrect until one or more changes are made in other parts. These two types of redundancy are closely related, of course, and since programmers are not super-persons they get distracted, forget things, and make mistakes, thereby putting in bugs.

These things (again, in my experience) are not really a function of the language, but of the skill/maturity of the programmer. Programs that are much less bug-prone also tend to be much smaller, in terms of LOC, for a given set of functionality.

I've seen systems where some people write programs, while others write directories, and the former tend to "just work" compared to the latter.


答:
I'm not a lawyer or anything, but I would think this should be possible. As Kilian said, you must distribute the "preferred form for editing". I think in this case though it would go a step further than just distributing the byte codes. I'd think that any thing that helped you to understand or create the source would also go under. Of course, your hex editor wouldn't be included. However, if you used drawn-out diagrams with flowcharts or some such to figure out the byte code that needed to be edited, those would probably also need to be included. And, if you wrote a program which generated the byte code, that would also have to be include.

After all, if you think about it, source code itself is a program which is just processed by a very complicated "CPU" called a compiler to get an expected output. Either way, at this point GPL becomes pretty pointless if you don't have anything written to help understand the byte codes you write


问:
Rigorous Definition of Syntactic Sugar?
It seems like in language holy wars, people constantly denigrate any feature they don't find particularly useful as being "just syntactic sugar".  The line between "real features" and "syntactic sugar" tends to get blurred in these debates.  What do you believe is a reasonable and unambiguous definition of syntactic sugar that avoids it being defined as any feature the speaker/writer doesn't find useful?</p>

答:
I'm not sure about within the fields of the computer sciences, but with the field of logic there are the concepts of conservativeness and eliminability of definitions [1] seem to be in the same vein.

Applying the Curry-Howard correspondence, one might be able to come up with a parallel concept regarding “syntactic sugar”.

ContentLicense: CC BY-SA 2.5

Title: Rigorous Definition of Syntactic Sugar?


答:
Another thing I haven't seen mentioned yet is that currying allows (limited) abstraction over arity.

Consider these functions that are part of Haskell's library

```<code>(.) :: (b -> c) -> (a -> b) -> a -> c
either :: (a -> c) -> (b -> c) -> Either a b -> c
flip :: (a -> b -> c) -> b -> a -> c
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
</code>```

In each case the type variable c can be a function type so that these functions work on some prefix of their argument's parameter list. Without currying, you'd either need a special language feature to abstract over function arity or have many different versions of these functions specialized for different arities.

Title: What is the advantage of currying?

Body:
Another thing I haven't seen mentioned yet is that currying allows (limited) abstraction over arity.

Consider these functions that are part of Haskell's library

(.) :: (b -> c) -> (a -> b) -> a -> c
either :: (a -> c) -> (b -> c) -> Either a b -> c
flip :: (a -> b -> c) -> b -> a -> c
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c

In each case the type variable c can be a function type so that these functions work on some prefix of their argument's parameter list. Without currying, you'd either need a special language feature to abstract over function arity or have many different versions of these functions specialized for different arities.


问:
Programming with ADD/ADHD
I have diagnosed ADD.  Mild but enough to affect my work:

Easily distracted

Can't concentrate on one project at a time

Addicted to the web

Procrastination

etc.

What strategies do you use to compensate?

One clarification

I have real  ADD.  I was diagnosed with it when I was a child and have wrestled with it all my life.  I am not talking about artificial ADD, which is induced by media overload.

Update

I just read this description ADD/ADHD.  It's a great description, especially for us programming ADDers:

I am like a toolbox,

  with all the tools I will ever need

  lain gently and neatly in the box,

  ready for me to use them.

  The toolbox is translucent

  so I can see them there.

  The key to the toolbox is locked inside of it.

答: I have ADD, I am a programmer, and I use timeboxing as my main time management technique and it works well for me.   I also wrote a windows app that automatically conversts todo lists into a timeboxed list with an alarm and progress bars.  Here's a link: http://ericjorgensen.com/TimeBoxer.html </p>

OwnerDisplayName: lamcro

Title: Programming with ADD/ADHD


问:
Need some advice and feedback on my code's design
I am looking for feedback on the design of my program.

I have a shell script call function.sh that defines a lot of helper functions. My intent is to use those bash functions defined in functions.sh in a C program. I am doing this so that I don't have to rewrite the bash functionality (in functions.sh) again in C. I want to use one common library for functions I need (which is functions.sh).

Here is my C code and functions.sh

C code:

```<code>#include <stdlib.h>
#include <sys/wait.h>
#include <stdio.h>

void shellCall(char * command)
{
    int status, commandexitcode=0;
    if(command == NULL)
    {
        printf("NULL command string sent\n");
        exit(1);
    }

    status = system(command);

    if(status == -1)
    {
        printf("Error during call, value %d\n", status);
        exit(1);
    }

    if (WIFEXITED(status))
    {
        commandexitcode =  WEXITSTATUS(status);
        if (commandexitcode != 0)
        {
            printf("non zero exit code: %d\n", commandexitcode);
            exit(1);
        }
    }

    else
       if (WIFSIGNALED(status))
    ...
}

int main(int argc,char **argv)
{
    char  command[100]; //command
    int i = 0;

    for (i = 1 ; i <= 10 ; i++)
    {
        sprintf( command, "source $PWD/functions.sh ; i=%d ; myfunc %d", i,i );
        shellCall(command);
    }
}
</code>```

functions.sh:

```<code>#!/bin/sh
# functions.sh

myfunc()
{
    echo "I received $1"
}
</code>```

Please note that I have only shown a very simple example of the way I am using functions in functions.sh. In reality functions.sh has many functions, some of which implement decent logic.

My Questions - I need feedback on the following aspects.

Is it a bad programming practice ( something that will make experienced and senior developers mad when they see this) to use system() calls to call functions in functions.sh as I have done?

If it is a bad practice, what  are the reasons (technical and other) for which it is considered a bad programming practice?

What changes should I make to my C code so that experienced and senior developers will find it acceptable?

答:
I am writing a C program because bash shell does not allow dynamic
  memory allocation and I need that for my logic ( although I have not
  shown that above).

At a high level, this appears to be a conglomeration of a C and shell scripts where one is controlling the other - the exact nature of where the logic exists isn't well defined in the example.

The one classic example of such a design is a shell script (with the application logic in it) which is invoking a number of compiled C programs that do what the shell script cannot.  To an extent this is 99% of all shell scripts - invoke something, pipe it to grep, pipe it to cut, set a variable from that, invoke something based on that variable, pipe that output to awk and sed, etc...

Such a design is quite reasonable and common and nothing for one to be extremely offended about.

Another approach is where the application is a single complied program that is doing whatever it is doing (listening for network connections, chugging away at calculation intensive bits, formatting xml and tossing it on a message queue, displaying a gui, etc...).  Sometimes this application finds itself in need of interacting with the underlying system - for example, in attempting to put a message on a queue it may have found that that demon has died and needs to restart it - set a bunch of environment variables, sudo /etc/init.d/amqd start.  While it is possible for this compiled program to instead fork a copy of itself that then modifies its environment and does system calls, that can be expensive for the compiled application and is likely prone to more bugs than something that is easier to understand and maintain.  It is perfectly for this model too and while some people may grumble about multiple parts of the application, it isn't a serious offense.

Let us look at the quote again and put this into context of the code sample in the question.

I am writing a C program because bash shell does not allow dynamic
  memory allocation and I need that for my logic ( although I have not
  shown that above).

It appears that the application as a whole has its logic split between the functions in functions.sh and the compiled C code.  There is a state machine (of sorts) that exists in the combination of the two pieces.  The application logic doesn't appear to exist solely in one part or the other.  The compiled program invokes a shell script with a function that then runs and its output is used to determine which shell to run next.  The compiled program exists as a dynamic data store for the shell programs.

This is poor design.

Changes in one affect changes in the other.  There is no single point of responsibility for the logic.  Maintaining two sets of languages with interdependence between the two can be challenging to keep in working order, test, and deploy.

I am a fan of the camel.  This will color my suggestion.

Any shell script longer than 10 lines should be rewritten in perl.

The original justification for the split design was that bash didn't have acceptable performance with dynamic arrays memory.  Ok, so don't use bash.  However, it appears there is some desire to interact with the system at a higher level than C provides.  Ok, so don't use C.  Use perl (or python, or if you must, ruby).

These languages excel doing the complex processing that shell scripts alone have difficulty doing without having to go to a C program.  In many cases, one can do everything that is traditionally done in shell (cut, grep, awk, sed, tr, open file, write to file, etc... ) without having to fork another process.  Furthermore, having a single application that contains all of the logic within itself is a superior design than trying to split it between two dissimilar ones.

Yes, it does mean rewriting functions.sh in perl (though at the moment, the entirety of the provided code is the builtin print).  It also means that after this is done, you will have a library of calls in a nice, self contained module.


答:
The Model and View are independent of each other.

Don't think of the Controller as the brains of the MVC structure. Think of it as the dispatcher which handles the requests from the browser, and dispatches them to the Model. It then takes the data from the Model and packages it in a template friendly way, and then sends it to a View.

The Model is the brains in the MVC structure, and this is where you should put your business rules. Business rules are common across multiple controllers. So a document controller, and a reports controller may both use a User model to see who has access to those things. You wouldn't want to repeat those rules in both controllers.

The View should use a HTML template to present the data in a non-datasource specific way. It should not be tightly bound to the schema of your database. To show the title of a document you would have the view output the contents of a template variable called document_title, and only the Controller knows how that variable was set, and only the Model knows why that document has that title.


问:
Are chained methods that require only one parameter per method equivalent to currying?
I've been toying around with Ruby lately and I found myself wondering if in pure object oriented languages (and even those that are not pure) making methods that take only one parameter and then get chained together is equivalent to currying in languages with a functional style? If not, why not? I'd appreciate a detailed, even rigorous answer on the subject.</p>

答:
Method chaining in object oriented languages is a little different from currying.  By definition, the result of currying is a more restricted form of the original function.  By convention, the result of method chaining is a modified form of the original (usually non-function) object.  Method chaining can be used with unrelated methods on the same class, whereas currying involves returning a function where one or more parameters of the original function are fixed (predetermined).

In Java, method chaining is like:

```<code>String myString = new StringBuilder("Hi ").append(firstName)
                                          .append(" ")
                                          .append(lastName)
                                          .append("!")
                                          .toString();
</code>```

So, each of those .append() method calls returns a pointer to the anonymous StringBuilder object.  This object is complete after each .append(), and it is not a function.

By contrast, in Scala, partial application or currying is like:

```<code>def simple(x:Int, y:Int, z:Int) = x * (y + z)
val simpler = simple(2, _:Int, _:Int)
simpler(3, 4) => 14
</code>```

(Sample taken from Daniel Yankowsky's blog)

simpler() in this example is a wrapper-function for simple().  simpler() is still a function that takes more parameters before it can evaluate to anything but a more limited version of itself.

EDIT: Reading this a day later, I think "wrapper-function" is the key.  Currying or partial application might best be simulated in Java with wrapper methods.

```<code>public interface Simpler {
    public int apply(int y, int z);
}

public class Simple {
    public int apply(int x, int y, int z) { return x * (y + z); }

    public Simpler partiallyApply(final int x) {
        final simple = this;
        return new Simpler() {
            @Override
            public int apply(int y, int z) {
                // x is the final int parameter to partiallyApply()
                simple.apply(x, y, z);
            }
        }
    }
}
</code>```

:END-EDIT

Method chaining can be similar to partial application or currying, but it can only be equivalent with methods that return other methods (look up Functors), and then the methods need to be set up with return types that meaningfully model currying or partial application.

Method chaining is more often used to implement something like lazy evaluation, as is done with the "Builder" design pattern and the new Collections Library interfaces in Java 8.

I hope that helps.

Body:
Method chaining in object oriented languages is a little different from currying.  By definition, the result of currying is a more restricted form of the original function.  By convention, the result of method chaining is a modified form of the original (usually non-function) object.  Method chaining can be used with unrelated methods on the same class, whereas currying involves returning a function where one or more parameters of the original function are fixed (predetermined).

In Java, method chaining is like:

String myString = new StringBuilder("Hi ").append(firstName)
                                          .append(" ")
                                          .append(lastName)
                                          .append("!")
                                          .toString();

So, each of those .append() method calls returns a pointer to the anonymous StringBuilder object.  This object is complete after each .append(), and it is not a function.

By contrast, in Scala, partial application or currying is like:

def simple(x:Int, y:Int, z:Int) = x * (y + z)
val simpler = simple(2, _:Int, _:Int)
simpler(3, 4) => 14

(Sample taken from Daniel Yankowsky's blog)

simpler() in this example is a wrapper-function for simple().  simpler() is still a function that takes more parameters before it can evaluate to anything but a more limited version of itself.

EDIT: Reading this a day later, I think "wrapper-function" is the key.  Currying or partial application might best be simulated in Java with wrapper methods.

public interface Simpler {
    public int apply(int y, int z);
}

public class Simple {
    public int apply(int x, int y, int z) { return x * (y + z); }

    public Simpler partiallyApply(final int x) {
        final simple = this;
        return new Simpler() {
            @Override
            public int apply(int y, int z) {
                // x is the final int parameter to partiallyApply()
                simple.apply(x, y, z);
            }
        }
    }
}

:END-EDIT

Method chaining can be similar to partial application or currying, but it can only be equivalent with methods that return other methods (look up Functors), and then the methods need to be set up with return types that meaningfully model currying or partial application.

Method chaining is more often used to implement something like lazy evaluation, as is done with the "Builder" design pattern and the new Collections Library interfaces in Java 8.

I hope that helps.


问:
What's a good way to explain the need for pointing to a pointer?
Understanding what a pointer (an address) is, is fairly easy and an eleven-year old can understand it. But how do we express why we have a need for a pointer to a pointer? what is a very pedagogical example? Does it extend to pointing to a pointer to a pointer (and/or onward)?

Example problem

T[][] does not decay to a T**

Example problem 2

```<code>brainfuck command   C equivalent
(Program Start) char array[30000];
                char *ptr=array;
>   ++ptr;
<   --ptr;
+   ++*ptr;
-   --*ptr;
.   putchar(*ptr);
,   *ptr=getchar();
[   while (*ptr) {
]   }
</code>```

答:
Sometimes called a Handle, Windows and the Mac OS use this structure
  to allow memory compaction on the heap. The program manages the
  pointer p, while the operating system manages the pointer *p. Because
  the OS manages *p, the block pointed to by p (*p) can be moved, and
  *p can be changed to reflect the move without affecting the program using p. Pointers to pointers are also frequently used in C to handle
  pointer parameters in functions.

http://computer.howstuffworks.com/c32.htm


答:
If you have a pointer, and you want to call a function that modifies the pointer, you need to tell that function where the pointer is stored. In order to tell the function where it is stored, you need to get the address of the pointer, which is a pointer to a pointer

```<code>int foo(const char **error_message)
{
    if (!bar())
    {
        // The type of error_message is const char ** (the parameter)
        // The type of *error_message is const char * (the caller's msg)
        // The type of **error_message is const char ('N' from "No error")

        // Note here, I have a * before error_message, it changes the callers msg
        // *error_message is the caller's msg variable
        // reading or writing *error_message will read/write msg
        // before this line executes, msg points to the first character of "No error"
        // after this line, msg points first character of "bar failed"
        *error_message = "bar failed";
        return -2;
    }

    return 0;
}

int main()
{
    // make a variable 'msg' and point it to the first character of "No error"
    const char *msg = "No error";

    // Get the address of 'msg' and pass it to foo.
    // '&msg' is a pointer to 'msg' (which happens to be a pointer).
    int status = foo(&msg);

    // foo could have modified msg, since it knew the address of msg
    if (status < 0 && msg != 0)
       printf("%s\n", msg);
}
</code>```

In my example, the caller needs to pass a pointer to msg (a pointer to a pointer) so foo can set it to point to the error message.

The idea is the same as any use of a pointer. If you want a piece of code to be able to read or write at arbitrary addresses, you pass a pointer. A pointer to a pointer, simply points to a pointer.

Title: What's a good way to explain the need for pointing to a pointer?

Body:
Understanding what a pointer (an address) is, is fairly easy and an eleven-year old can understand it. But how do we express why we have a need for a pointer to a pointer? what is a very pedagogical example? Does it extend to pointing to a pointer to a pointer (and/or onward)?

Example problem

T[][] does not decay to a T**

Example problem 2

```<code>brainfuck command   C equivalent
(Program Start) char array[30000];
                char *ptr=array;
>   ++ptr;
<   --ptr;
+   ++*ptr;
-   --*ptr;
.   putchar(*ptr);
,   *ptr=getchar();
[   while (*ptr) {
]   }
</code>```

Body:
If you have a pointer, and you want to call a function that modifies the pointer, you need to tell that function where the pointer is stored. In order to tell the function where it is stored, you need to get the address of the pointer, which is a pointer to a pointer

int foo(const char **error_message)
{
    if (!bar())
    {
        // The type of error_message is const char ** (the parameter)
        // The type of *error_message is const char * (the caller's msg)
        // The type of **error_message is const char ('N' from "No error")

        // Note here, I have a * before error_message, it changes the callers msg
        // *error_message is the caller's msg variable
        // reading or writing *error_message will read/write msg
        // before this line executes, msg points to the first character of "No error"
        // after this line, msg points first character of "bar failed"
        *error_message = "bar failed";
        return -2;
    }

    return 0;
}

int main()
{
    // make a variable 'msg' and point it to the first character of "No error"
    const char *msg = "No error";

    // Get the address of 'msg' and pass it to foo.
    // '&msg' is a pointer to 'msg' (which happens to be a pointer).
    int status = foo(&msg);

    // foo could have modified msg, since it knew the address of msg
    if (status < 0 && msg != 0)
       printf("%s\n", msg);
}

In my example, the caller needs to pass a pointer to msg (a pointer to a pointer) so foo can set it to point to the error message.

The idea is the same as any use of a pointer. If you want a piece of code to be able to read or write at arbitrary addresses, you pass a pointer. A pointer to a pointer, simply points to a pointer.