问:
Classic ASP to Java UI Conversion
My question is based on a business model of a financial services organization that currently is supporting applications that are a hybrid mix of Classic ASP and Java, with some JSP’s already in some of the applications.

Specifically, in our large application, all of the FE starts with ASP and then uses a crude request based token that is used by other code to determine which JSP to call.  In the other application, which is a suite of four linked applications, the main application and one other use all ASP in the front end and java code for the BE.  The two others that are linked to it use JSPs and java code exclusively.

Due to excessive maintenance costs of using this hybrid system and concerns for using obsolete technology, management has bought into modernizing our applications to all Java and removing all ASPs on these applications.  I'm on a panel group that would have to propose which Java UI to use as each UI technology has its own set of strengths and weaknesses.

Making the assumption that the following item makes up our basic use case: modernizing our current classic ASP UI to a Java standard, which incorporates the following goals:

In general, a system that is more amenable to change.

That would be flexible for future growth based on technology changes in the market.

Not tied to a niche market or something experimental or unstable or cutting edge.

More modularized code that would allow the UI to be converted to another technology, if the business need arises.  This would coincide with the code structure and not just the technology, but I felt it was worth mentioning.

Better performance.

Stable and scalable.

More secure than classic ASP.

Better ROI on development time.  It's been hard finding people with Classic ASP that also know Java well.  Also, this would also have to incorporate the learning curve for new developers as I've heard JSF has a steep one.

Now, to the point, with the number of java UI frameworks that I’m aware of: JSP, JSF, JavaFx, Tapestry, Vaadin, GWT, Velocity, Freemarker, and Thymeleaf, based on actual experience from other developers that have actually had to do this type of conversion what have you used to do this?

Do you have any lessons learned that would coincide with this use case and business model?  I don't want opinions, but answers from real life experiences.

Currently, we are being asked to limit ourselves to just JSP or JSF, but I'm not so sure those should be the only alternatives.  Currently, the talk is to move everything to one or the other as another team is going down the JSF route.  We are wanting to adopt a standard for everyone however.  So overall, we have some infrastructure for JSF, but it's heavily favored for JSP at this time.

答:
If you've already used JSP in part of your application, don't rewrite it into a different framework. Chances are, the team you're working with already has some knowledge of JSP, and you'll be able to build on the existing core of pages that utilize it, limiting the amount of work to be done and the subsequent number of bugs needing squashed.

Remember your Joel on Software: never rewrite from scratch.

Title: Classic ASP to Java UI Conversion


问:
What is the best way to create REST API error response model and error codes system?
My REST implementation will return errors in JSON with next structure:

```<code>{
 "http_response":400,
 "dev_message":"There is a problem",
 "message_for_user":"Bad request",
 "some_internal_error_code":12345
}
</code>```

I suggest to create special response model, where I can pass needed values for properties(dev_message, message_for_user, some_internal_error_code), and return them. In code it would be similar to this:

```<code>$responseModel = new MyResponseModel(400,"Something is bad", etc...);
</code>```

How this model should look like? Should I implement methods e.g. successResponse() where I'll pass only text information, and code will be default 200 there? I'm stuck with this.
And this is first part of my question: do I need to implement this model, is this good practise? Because for now, I'm just returning arrays directly from code.

The second part is about error code system. Error codes will be described in documentation. But the problem I'm encountering is in code.
What is the best way to manage error codes? Should I write them inside model? Or it would be better to create separate service for handling this?

UPDATE 1

I've implemented model class for response. It is similar Greg's answer, the same logic, but additionaly I have hardcoded written errors in model  and here it is how it looks like:

```<code>    class ErrorResponse
    {
     const SOME_ENTITY_NOT_FOUND = 100;
     protected $errorMessages = [100 => ["error_message" => "That entity doesn't exist!"]];

     ...some code...
    }
</code>```

Why I did this? And what for?

It's looks cool in  code:
return new ErrorResponse(ErrorResponse::SOME_ENTITY_NOT_FOUND );

Easy to change error message. All messages are in one place instead of controller/service/etc or whatever you'll placed it.

If you have any suggestions to improve this, please, comment.

答:
In this situation, I always think of the interface first, then write PHP code to support it.

It's a REST API, so meaningful HTTP status codes are a must.

You want consistent, flexible data structures being sent to and from the client.

Let's think of all the things that could go wrong and their HTTP status codes:

The server throws an error (500)

Authentication failure (401)

The resource requested was not found (404)

The data you are modifying has been changed since you loaded it (409)

Validation errors when saving data (422)

The client has exceeded their request rate (429)

Unsupported file type (415)

Note, there are others which you can research later.

For most of the failure conditions, there is only one error message to be returned. The 422 Unprocessable Entity response, which I've used for "validation errors" could return more than one error --- One or more errors per form field.

We need a flexible data structure for error responses.

Take as an example, the 500 Internal Server Error:

```<code>HTTP/1.1 500 Internal Server Error
Content-Type: text/json
Date: Fri, 16 Jan 2015 17:44:25 GMT
... other headers omitted ...

{
    "errors": {
        "general": [
            "Something went catastrophically wrong on the server! BWOOP! BWOOP! BWOOP!"
        ]
    }
}
</code>```

Contrast that with simple validation errors when trying to POST something to the server:

```<code>HTTP/1.1 422 Unprocessable Entity
Content-Type: text/json
Date: Fri, 16 Jan 2015 17:44:25 GMT
... other headers omitted ...

{
    "errors": {
        "first_name": [
            "is required"
        ],
        "telephone": [
            "should not exceed 12 characters",
            "is not in the correct format"
        ]
    }
}
</code>```

They key here is the content type being text/json. This tells client applications that they can decode the response body with a JSON decoder. If, say, an internal server error isn't caught and your generic "Something went wrong" web page gets delivered instead, the content type should be text/html; charset=utf-8 so client applications won't attempt to decode the response body as JSON.

This looks all find and dandy, until you need to support JSONP responses. You must return a 200 OK response, even for failures. In this case you'll have to detect that the client is requesting a JSONP response (usually by detecting a URL request parameter called callback) and change up the data structure a bit:

(GET /posts/123?callback=displayBlogPost)

```<code>HTTP/1.1 200 OK
Content-Type: text/javascript
Date: Fri, 16 Jan 2015 17:44:25 GMT
... other headers omitted ...

displayBlogPost({
    "status": 500,
    "data": {
        "errors": {
            "general": [
                "Something went catastrophically wrong on the server! BWOOP! BWOOP! BWOOP!"
            ]
        }
    }
});
</code>```

Then the response handler on the client (in a web browser) should have a global JavaScript function called displayBlogPost which accepts a single argument. This function would have to determine if the response was successful:

```<code>function displayBlogPost(response) {
    if (response.status == 500) {
        alert(response.data.errors.general[0]);
    }
}
</code>```

So we've taken care of the client. Now, let's take care of the server.

```<code><?php

class ResponseError
{
    const STATUS_INTERNAL_SERVER_ERROR = 500;
    const STATUS_UNPROCESSABLE_ENTITY = 422;

    private $status;
    private $messages;

    public function ResponseError($status, $message = null)
    {
        $this->status = $status;

        if (isset($message)) {
            $this->messages = array(
                'general' => array($message)
            );
        } else {
            $this->messages = array();
        }
    }

    public function addMessage($key, $message)
    {
        if (!isset($message)) {
            $message = $key;
            $key = 'general';
        }

        if (!isset($this->messages[$key])) {
            $this->messages[$key] = array();
        }

        $this->messages[$key][] = $message;
    }

    public function getMessages()
    {
        return $this->messages;
    }

    public function getStatus()
    {
        return $this->status;
    }
}
</code>```

And to use this in the case of a server error:

```<code>try {
    // some code that throws an exception
}
catch (Exception $ex) {
    return new ResponseError(ResponseError::STATUS_INTERNAL_SERVER_ERROR, $ex->message);
}
</code>```

Or when validating user input:

```<code>// Validate some input from the user, and it is invalid:

$response = new ResponseError(ResponseError::STATUS_UNPROCESSABLE_ENTITY);
$response->addMessage('first_name', 'is required');
$response->addMessage('telephone', 'should not exceed 12 characters');
$response->addMessage('telephone', 'is not in the correct format');

return $response;
</code>```

After that, you just need something that takes the returned response object and converts it into JSON and sends the response on its merry way.

ContentLicense: CC BY-SA 3.0

Body:
In this situation, I always think of the interface first, then write PHP code to support it.

It's a REST API, so meaningful HTTP status codes are a must.

You want consistent, flexible data structures being sent to and from the client.

Let's think of all the things that could go wrong and their HTTP status codes:

The server throws an error (500)

Authentication failure (401)

The resource requested was not found (404)

The data you are modifying has been changed since you loaded it (409)

Validation errors when saving data (422)

The client has exceeded their request rate (429)

Unsupported file type (415)

Note, there are others which you can research later.

For most of the failure conditions, there is only one error message to be returned. The 422 Unprocessable Entity response, which I've used for "validation errors" could return more than one error --- One or more errors per form field.

We need a flexible data structure for error responses.

Take as an example, the 500 Internal Server Error:

HTTP/1.1 500 Internal Server Error
Content-Type: text/json
Date: Fri, 16 Jan 2015 17:44:25 GMT
... other headers omitted ...

{
    "errors": {
        "general": [
            "Something went catastrophically wrong on the server! BWOOP! BWOOP! BWOOP!"
        ]
    }
}

Contrast that with simple validation errors when trying to POST something to the server:

HTTP/1.1 422 Unprocessable Entity
Content-Type: text/json
Date: Fri, 16 Jan 2015 17:44:25 GMT
... other headers omitted ...

{
    "errors": {
        "first_name": [
            "is required"
        ],
        "telephone": [
            "should not exceed 12 characters",
            "is not in the correct format"
        ]
    }
}

They key here is the content type being text/json. This tells client applications that they can decode the response body with a JSON decoder. If, say, an internal server error isn't caught and your generic "Something went wrong" web page gets delivered instead, the content type should be text/html; charset=utf-8 so client applications won't attempt to decode the response body as JSON.

This looks all find and dandy, until you need to support JSONP responses. You must return a 200 OK response, even for failures. In this case you'll have to detect that the client is requesting a JSONP response (usually by detecting a URL request parameter called callback) and change up the data structure a bit:

(GET /posts/123?callback=displayBlogPost)

<script type="text/javascript" src="/posts/123?callback=displayBlogPost"></script>

HTTP/1.1 200 OK
Content-Type: text/javascript
Date: Fri, 16 Jan 2015 17:44:25 GMT
... other headers omitted ...

displayBlogPost({
    "status": 500,
    "data": {
        "errors": {
            "general": [
                "Something went catastrophically wrong on the server! BWOOP! BWOOP! BWOOP!"
            ]
        }
    }
});

Then the response handler on the client (in a web browser) should have a global JavaScript function called displayBlogPost which accepts a single argument. This function would have to determine if the response was successful:

function displayBlogPost(response) {
    if (response.status == 500) {
        alert(response.data.errors.general[0]);
    }
}

So we've taken care of the client. Now, let's take care of the server.

<?php

class ResponseError
{
    const STATUS_INTERNAL_SERVER_ERROR = 500;
    const STATUS_UNPROCESSABLE_ENTITY = 422;

    private $status;
    private $messages;

    public function ResponseError($status, $message = null)
    {
        $this->status = $status;

        if (isset($message)) {
            $this->messages = array(
                'general' => array($message)
            );
        } else {
            $this->messages = array();
        }
    }

    public function addMessage($key, $message)
    {
        if (!isset($message)) {
            $message = $key;
            $key = 'general';
        }

        if (!isset($this->messages[$key])) {
            $this->messages[$key] = array();
        }

        $this->messages[$key][] = $message;
    }

    public function getMessages()
    {
        return $this->messages;
    }

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

And to use this in the case of a server error:

try {
    // some code that throws an exception
}
catch (Exception $ex) {
    return new ResponseError(ResponseError::STATUS_INTERNAL_SERVER_ERROR, $ex->message);
}

Or when validating user input:

// Validate some input from the user, and it is invalid:

$response = new ResponseError(ResponseError::STATUS_UNPROCESSABLE_ENTITY);
$response->addMessage('first_name', 'is required');
$response->addMessage('telephone', 'should not exceed 12 characters');
$response->addMessage('telephone', 'is not in the correct format');

return $response;

After that, you just need something that takes the returned response object and converts it into JSON and sends the response on its merry way.


问:
Method for determining if a line segment is an external edge of a Delauney triangulation?
I've created a Delauney triangulation of a set of points. Now I want to iterate over the triangulation and remove any line segments/edges on the exterior for which the following are true:

The outside edge is the hypotenuse of the triangle

Call the hypotenuse the "base" and determine the "height" of the triangle. Then if base/height > x (where x is some criteria value, say 4), delete that edge/triangle (depending on data structure/object definitions).

In essence I'm trying to remove edges from the triangulation to create a more characteristic shape by deleting edges that are long, skinny, and on the outside of the triangulation. I might add in a check later for size of the triangle relative to the average of the rest, too.

My question is: is there an easy way to check if a given edge is on the exterior of the triangulation?

I figured I could build in to the triangulation process itself a design that will make every line segment its own object, then have each line segment "know" its neighboring polygons, and if it has an empty neighbor slot then it is external. This seemed inefficient, though, and the code I currently have just spits out a bunch of triangle objects with its vertices's indexes stored. Calculating the line segments shouldn't be too bad, but then I only want to do the deletion process on external edges as opposed to all of them.

Not sure if this question belonged in math or programming, apologies if it should not be in here or if I provided too little/too much information.

I'm working in Python, but my concern here is about theoretical approach/algorithm as opposed to code so I don't feel it necessary to include code.

EDIT to note: I'll want to iterate over the exterior multiple times in the event that after deleting one exterior triangle the first round through it reveals a new exterior that fits the deletion parameters. Therefore I'd like to avoid completely recalculating the exterior edges each time -- thus the question about a quick-and-easy, if it exists.

答:
A triangulation of your point set gives you for each point a list of "adjacent" points, the neighbours to which a point is connected.

Once you have calculated the triangulation, you can determine the outer edges by applying an algorithm similar to the classic gift-wrapping algorithm for convex hulls. You start with, for example, the "rightmost" point (which is part of the convex hull and so at the outer edge). Then step from point to point using only outer edges of the triangulation. The only difference to the "convex hull" algorithm is, when having points p_(n-1) and p_(n), you choose p_(n+1) as the point among all adjacent points minimizing the angle between p_(n)->p_(n-1) and p_(n) ->p_(n+1).

Hope this helps.


问:
Purpose of authentication on API's?
After asking this question I found that I have a different question. What's the purpose of authenticating an API anyway?

Take Twitter for instance. If you want to use this link to load some user's posts:

```<code>https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={username}
</code>```

Then you have to authenticate.

HOWEVER, why would you when you can just make an HTTP request to:

```<code>https://twitter.com/i/profiles/show/{username}/timeline
</code>```

Which does the same exact thing, except requires no authentication?

So why would I need authentication? Also, I don't see how authentication can ever make the use of an API exclusive to a particular app/etc.; can't you always make the same HTTP requests from another app? The referrer can be spoofed as well, so I really don't understand.

答:
Authentication on APIs allows the server to verify that the client making the request has the authorization (i.e. privileges) to take whatever action the request encapsulates.

Sticking to your Twitter example, direct messages are private to a user, so in order to allow access to them, Twitter must verify that the client has valid credentials for that user account.

Title: Purpose of authentication on API's?


答:
It's fortunate you can start with a list of triangle objects, because that makes it easy:

flatMap the list of triangles into a list of edges.

Your outer edges appear only once in the list.

You can see how this works by looking at a picture.  Each inner edge is shared by exactly two triangles.  Each outer edge belongs to exactly one triangle.

When you remove an edge, the other two edges in that triangle always become outer edges, if they weren't already.  Just add them to the set of outer edges before you remove the triangle from its list.  This can be sped up by keeping a map from edges back to triangles.

Title: Method for determining if a line segment is an external edge of a Delauney triangulation?

Body:
I've created a Delauney triangulation of a set of points. Now I want to iterate over the triangulation and remove any line segments/edges on the exterior for which the following are true:

The outside edge is the hypotenuse of the triangle

Call the hypotenuse the "base" and determine the "height" of the triangle. Then if base/height > x (where x is some criteria value, say 4), delete that edge/triangle (depending on data structure/object definitions).

In essence I'm trying to remove edges from the triangulation to create a more characteristic shape by deleting edges that are long, skinny, and on the outside of the triangulation. I might add in a check later for size of the triangle relative to the average of the rest, too.

My question is: is there an easy way to check if a given edge is on the exterior of the triangulation?

I figured I could build in to the triangulation process itself a design that will make every line segment its own object, then have each line segment "know" its neighboring polygons, and if it has an empty neighbor slot then it is external. This seemed inefficient, though, and the code I currently have just spits out a bunch of triangle objects with its vertices's indexes stored. Calculating the line segments shouldn't be too bad, but then I only want to do the deletion process on external edges as opposed to all of them.

Not sure if this question belonged in math or programming, apologies if it should not be in here or if I provided too little/too much information.

I'm working in Python, but my concern here is about theoretical approach/algorithm as opposed to code so I don't feel it necessary to include code.

EDIT to note: I'll want to iterate over the exterior multiple times in the event that after deleting one exterior triangle the first round through it reveals a new exterior that fits the deletion parameters. Therefore I'd like to avoid completely recalculating the exterior edges each time -- thus the question about a quick-and-easy, if it exists.


问:
Implementing a NoSQL and RDBMS compatible DAO
What would be the correct way to design a DAO which implementation is first going to be targeting a MS SQL database with a STAR model, but yet, business requirements specify the application must be flexible enough that it would be able to be migrated to a NoSQL database in the future if required. Which type of NoSQL, no idea...

My confusion is that i cannot seem to figure out how could I build independent DAOs for the STAR Dimensions and Facts tables which could then be swapped for a completely different model that might not even be table oriented (riak/mongo/whatever).

Therefore,

Should I create DAOs which rather than abstracting the table, it abstracts the CRUD operations - for example create IDaoInsert which can then be implemented as SQLInsertDaoImpl and MongoInsertDaoImpl, each with a completely different model logic etc.

or

Should I just create the typical DAO design whose interface would be something like IDaoCustomerDimension, and the implementation SqlDaoCustomerDimesionImpl and MongoDaoCustomerDimentionImpl respectively?

Hibernate/Etc are out of the scope of this question for the time being.

答:
Your architecture should look something like this:

```<code>Data source <--> Data source driver <--> CRUD interface <--> Application
</code>```

You'll need one data source driver implementation for each type of data source.  The CRUD interface will be the same regardless of data source.

Note that you can have more than just CRUD methods.  You might want to return collections, for example.  Just make sure that whatever you do on the Data Source side is translatable to your API on the CRUD side for all possible data sources.

OwnerDisplayName: Carlos

Body:
Your architecture should look something like this:

Data source <--> Data source driver <--> CRUD interface <--> Application

You'll need one data source driver implementation for each type of data source.  The CRUD interface will be the same regardless of data source.

Note that you can have more than just CRUD methods.  You might want to return collections, for example.  Just make sure that whatever you do on the Data Source side is translatable to your API on the CRUD side for all possible data sources.


问:
Is there any material difference between queries joined by WHERE clauses, and queries using an actual JOIN?
In Learn SQL the Hard Way (exercise six), the author presents the following query:

```<code>SELECT pet.id, pet.name, pet.age, pet.dead
    FROM pet, person_pet, person
    WHERE
    pet.id = person_pet.pet_id AND
    person_pet.person_id = person.id AND
    person.first_name = "Zed";
</code>```

and then goes on to say that:

There are actually other ways to get these kinds of queries to work called "joins". I'm avoiding those concepts for now because they are insanely confusing. Just stick to this way of joining tables for now and ignore people who try to tell [you] that this is somehow slower or "low class".

Is that true? Why or why not?

答:
No, it's not true at all.  The author is setting up his readers for confusion, and encouraging cargo-cult programming that avoids a very powerful structural difference between the standard syntax and this older variant he prefers.  Specifically, a cluttered WHERE clause makes it harder to figure out what makes his query special.

His example leads a reader to generate a mental map of its meaning that has an awful lot of clutter.

```<code>SELECT pet.id, pet.name, pet.age, pet.dead
    FROM pet, person_pet, person
    WHERE
    pet.id = person_pet.pet_id AND
    person_pet.person_id = person.id AND
    person.first_name = "Zed";
</code>```

Roughly, the above is:

Get the pet's ID, NAME, AGE, and DEAD for all pets, person_pet, and persons where the pet ID happens to match a person_pet's pet_id, and the person_id of that record happens to match the person_id of a person whose FIRST_NAME is "Zed"

With a mental map like that, the reader (who is writing the SQL by hand for some reason) may very easily make a mistake, possibly by omitting one or more tables.  And a reader of code written in such a way will have to work harder, to figure out exactly what the SQL-author is trying to do.  ("Harder" is on the level of reading SQL with or without syntax-highlighting, but it's still a greater than zero difference.)

There's a reason why JOIN's are common, and it's the old classic "seperation of concerns" canard.  Specifically, for a SQL query there's good reason to seperate how data is structured vs how data is filtered.

If the query is written cleaner, such as

```<code>SELECT pet.id, pet.name, pet.age
FROM pet
  JOIN person_pet ON pet.id = person_pet.pet_id
  JOIN person ON person.id = person_pet.person_id
WHERE
  person.first_name = "Zed";
</code>```

Then the reader has a clearer distinction between the components of what's being asked for.  The distinctive filter of this query is separated from how its components relate to each other, and the necessary components of each relation are directly next to where they are required.

Of course, any modern database system shouldn't see a meaningful difference between the two styles.  But if database performance was the only consideration, the SQL query wouldn't have white space or capitalization, either.

Body:
No, it's not true at all.  The author is setting up his readers for confusion, and encouraging cargo-cult programming that avoids a very powerful structural difference between the standard syntax and this older variant he prefers.  Specifically, a cluttered WHERE clause makes it harder to figure out what makes his query special.

His example leads a reader to generate a mental map of its meaning that has an awful lot of clutter.

SELECT pet.id, pet.name, pet.age, pet.dead
    FROM pet, person_pet, person
    WHERE
    pet.id = person_pet.pet_id AND
    person_pet.person_id = person.id AND
    person.first_name = "Zed";

Roughly, the above is:

Get the pet's ID, NAME, AGE, and DEAD for all pets, person_pet, and persons where the pet ID happens to match a person_pet's pet_id, and the person_id of that record happens to match the person_id of a person whose FIRST_NAME is "Zed"

With a mental map like that, the reader (who is writing the SQL by hand for some reason) may very easily make a mistake, possibly by omitting one or more tables.  And a reader of code written in such a way will have to work harder, to figure out exactly what the SQL-author is trying to do.  ("Harder" is on the level of reading SQL with or without syntax-highlighting, but it's still a greater than zero difference.)

There's a reason why JOIN's are common, and it's the old classic "seperation of concerns" canard.  Specifically, for a SQL query there's good reason to seperate how data is structured vs how data is filtered.

If the query is written cleaner, such as

SELECT pet.id, pet.name, pet.age
FROM pet
  JOIN person_pet ON pet.id = person_pet.pet_id
  JOIN person ON person.id = person_pet.person_id
WHERE
  person.first_name = "Zed";

Then the reader has a clearer distinction between the components of what's being asked for.  The distinctive filter of this query is separated from how its components relate to each other, and the necessary components of each relation are directly next to where they are required.

Of course, any modern database system shouldn't see a meaningful difference between the two styles.  But if database performance was the only consideration, the SQL query wouldn't have white space or capitalization, either.


问:
Printing to out vs Logging, given the nature of this app?
I'm writing a command line application in Java. That app will scan a list of remote resources, do several attempts to access those resources, report failed attempts, and if succesfully accesed, perform some maintenance or diagnosis action and report the outcomes of that action.

As you can imagine, there's a lot of error handling and error reporting. But reporting the errors is a feature. Let me explain: a report with the errors encountered when attempting to access to the remote resource is something the user expects from the app, since those failures are useful for the diagnosis. Such access failures are expected in many cases and the causes should be reported.

As you can see, there's a blurry line between what's an error and what's the expected output of the app, which as every app will have its own errors also.

I'm using the Java Logging API and I'm designing my classes in a way as to be able to add different loggers and swap loggers and/or handlers (to screen, to file, to database, etc), as well as different list of resources to scan (and different types of those resources).

The problem is that I'm tempted to call logger.log() everywhere I was previosly using System.put.println();

Right now I'm now in a position where there's a blury line between what should be printed with System.out.println() and what should be send to the Logger instance.

I believe I'm having a conceptual confusion.

So the questions are, given the fact that errors reporting is a part of the core functionality of the app and that, as any app, it has to handle and log its own errors:

What things should be printed with System.out.println()

What things should be forwarded to a Logger

What things should be both printed with System.out.println() and forwarded to a Logger

Should normal output be considered as being log messages of a low severity level or not at all?

EDIT:

Just to clarify, the app could attempt to download a file, but it's
  not the file what the final user wants, but to see whether or not it
  was accessible and if not, why. The resource could be a server, a
  database, a service or a file. The user doesn't want the app to get
  what the resource offers but to check availability and report the
  cause. That somehow makes failed attempts code errors the output users
  want to get from this app. Hence the thin line between logging or
  printing.

答:
The fact that you are writing a console application doesn't change good UI practices.

Your business logic should be distinct from your UI. The business logic performs the operations and indicates what might have gone wrong. The UI decided how that should be displayed.

If there is information that is useful for tracking the execution of the application after something has happened, it should be written to a log file. This will primarily happen in your business logic classes. The fact that something is written to a log file does not inherently mean that the UI does not need to display it. Things that are important enough to display to the user is likely important enough to log, but it does not need to be in the same  form.

What goes in the log should be more detailed: What exactly went wrong? What were the inputs when that happened? You can also give more fine grained details about what is currently executing. To the user, it might be a single task, but to the code it could be a four step process. The nice thing about logging is the different levels let you have very detailed log messages in your code, but allowing some of them to be omitted from the log file.

Don't write code that is statically configured to only work one way. A command line application will obviously be dealing with standard out a lot. However, that doesn't mean your classes must have System.out.println() everywhere. You classes could write to an OutputStream. By initializing your UI classes with the OutputStreams/InputStreams that they should work with, it will make it much easier to test the code. Being able to use a ByteArrayOutputStream in an automated test is a great way to check if content is being output correctly.

An example of what I am suggesting:

```<code>public class A {
  private final OutputStream _out;

  public A(OutputStream out) {
    _out = out;
  }

  public void Run() {
    _out.println("Write to UI here");
  }
}
</code>```

It is true that System.out is an OutputStream, but there are many classes that implement that interface. If you hard code your classes to use System.out, that is the only way the code can be used. If you pass in the output stream to write to, now you have the option to write to files, network sockets, and other things.

Body:
The fact that you are writing a console application doesn't change good UI practices.

Your business logic should be distinct from your UI. The business logic performs the operations and indicates what might have gone wrong. The UI decided how that should be displayed.

If there is information that is useful for tracking the execution of the application after something has happened, it should be written to a log file. This will primarily happen in your business logic classes. The fact that something is written to a log file does not inherently mean that the UI does not need to display it. Things that are important enough to display to the user is likely important enough to log, but it does not need to be in the same  form.

What goes in the log should be more detailed: What exactly went wrong? What were the inputs when that happened? You can also give more fine grained details about what is currently executing. To the user, it might be a single task, but to the code it could be a four step process. The nice thing about logging is the different levels let you have very detailed log messages in your code, but allowing some of them to be omitted from the log file.

Don't write code that is statically configured to only work one way. A command line application will obviously be dealing with standard out a lot. However, that doesn't mean your classes must have System.out.println() everywhere. You classes could write to an OutputStream. By initializing your UI classes with the OutputStreams/InputStreams that they should work with, it will make it much easier to test the code. Being able to use a ByteArrayOutputStream in an automated test is a great way to check if content is being output correctly.

An example of what I am suggesting:

public class A {
  private final OutputStream _out;

  public A(OutputStream out) {
    _out = out;
  }

  public void Run() {
    _out.println("Write to UI here");
  }
}

It is true that System.out is an OutputStream, but there are many classes that implement that interface. If you hard code your classes to use System.out, that is the only way the code can be used. If you pass in the output stream to write to, now you have the option to write to files, network sockets, and other things.


问:
Re-inventing system design for Scala
Many, many, moons ago, I did my masters in Object Orientated Software Engineering. I covered everything: project initiation, requirements, analysis, design, architecture, development, etc, etc. My favourite IT book of all time was Developing Object Oriented Software, an Experience Based Approach (IBM-1996). A book created by a group of true experts of their time. It describes a work product centric approach to object oriented analysis, design and development methods.

I designed and developed and was happy and at the top of my game, but I started to feel a little dated: Agile movements became fashion of the day and re-branded some well known iterative and incremental approaches with new hip words. Suddenly inexperienced developers started frowning when I said "requirements" or "architecture" as if these things were superseded by magic.

Design and development lost it's fun and I was about to leave the whole IT industry behind me.

Then I discovered Scala. Oh, like soft rain on a dusty road. Everything just became clear, the air became sweet again and the little light of my hard-drive would flicker deep into the night, merrily keeping me company in my world of discovery.

I like system design. I'm an architect at heart, more than a programmer. I love analyzing, designing, thinking, arguing, improving - I just love simple, clean and crisp designs.

How do we design pure Scala solutions?

Surely conventional sequence diagrams, interaction diagrams, object diagrams, etc, could all be replaced or improved for the goodness of blending imperative and functional object orientated systems. Surely there is an opening for something totally different!

I'm not looking for bloated complexity - I'm looking for flexible simplicity. Much like Scala is actually simple and easy (albeit different), but can be extended to fit your requirement like a pair of Yoga pants. There must be a design system for this lovely language that will start simple, and can be extended to fit your requirements and your domain. Surely UML can not be it!

So how do we design pure Scala systems? Imagine for a moment, you have the luxury to design a complete system from scratch, and know that you will only be using Scala - How will your models look? What types of diagrams would you have to describe structure and behaviour? How would you model Options, matches, mixins, singleton Objects, etc. without being drawn into the complexity of extending existing modeling techniques rather than a fresh, light-weight, innovative tool-set.

Does such a design/process/solution exist, or is it time to invent one?

答:
I wouldn't differentiate between languages, I'd do it the same way in java. However I'm from the OO school rather than the functional (algebraic Haskell one or the lisp one). Haskell app design is really different from Scala or Clojure. Also a Scala.js app design is different due to the stateful DOM - it is hard to fight a stateful part of your app that is mandatory. Over time I got used to doing it the OO way, while trying to eliminate state and mutability as much as possible. If I were a typelevel or scalaz fan, my apps would probably look quite different.

Deciding on technology stack and the major design decisions like client/server responsibility, distributed nature - do we really need data persistence? What suits our application the best? (certainly not libraries or frameworks yet)

Starting with just a single App.scala file where I define the key types (traits and case classes) and roles - a lot of contemplating and thinking while being AFK. It is so easy to play with it while it is in one file. Even the prototype might come into being if it is rather a simple application. I dedicate a lot of time to this phase because nothing is more important than having the most correct and mainly transparent and sensible prototype possible. It all helps to make our further contemplating more accurate and it increases probability of success.

Now when we have proven correctness of our solution, we have clear vision and all potential problems are revealed, it is time to think what kind of third party libraries or methodologies to bring in. Do we need play framework or just a few libs? Are we gonna make these stateful actors, do we really need Akka's resilience, .., .. or maybe not? Do we use Rx for these streams? What do we use for UI so we won't go insane after it has 10 interactive features?

split the App.scala file into multiple ones because new traits and classes appeared and got bigger. Their interface should tell about their roles. Now it is also time to think about utilizing type classes and ad-hoc polymorphism where possible. So that whoever calls your interface, it must be flexible for them. The point is to implement only general functionality, leaving the details to the caller. Sometimes what you are trying to implement might be Turing-complete-like so you should provide a way for callers to implement specifics by themselves instead of piling up feature requests on GitHub. This stuff is hard to add later. It must be thought through at the very beginning. As well as designing a DSL.

thinking the design through because the application will grow and it must be ready to withstand new features, optimizations, persistence, UI, remoting, etc. - stuff that was not implemented yet or was somehow mocked or abstracted over. Remember that while it's all in one file it is quite easy to change things. Human brain starts loosing it after it gets spread across 10+ files. And it is like a tumor that grows, that's how overengineering starts. I noticed that my applications end up with a few long partial functions that form some sort of a backbone of it. I find it easy to work with. I guess I became infected by Akka actors.

Now that the first actual features exist, not just the core functioning, it is time to start writing tests. Why so late? Because during this time you probably went through major rewrites and you'd have wasted time maintaining those tests. One should not write tests unless one is really sure there won't be any major redesigns. I prefer integration tests that easily withstand continuous refactoring and I won't spend more time testing that actually developing stuff. It happened to me a few times that I spent way too much time maintaining tests. Fixing potential bugs would certainly pay off more rather than bad tests. Bad tests or tests written from the very first moment can cause major pain. Notice that I'm certainly not a fan of TDD - IMHO it's bullshit.

Refactoring, making and keeping the application design readable, component roles clear. As the application grows there is no way it stays that way unless you are a genius programmer and if you read this answer you're probably not:-) Neither am I. Usually some stateful things exist because you didn't know how to avoid that - that might cause problems, try to eliminate them. Also be sure to eliminate code smells that have bothered you for some time. At this point your project manager (if you have one) probably starts shaking his head. Tell him it will pay off.

Done, is the app well designed? It depends: Do the have components well-defined roles that actually make sense even outside of your head? Could you take some of them and open source them without much effort? Is there clear separation of concern between them? Can you add a new feature without worrying it will crash elsewhere (sign of you know exactly what you are doing)? Generally speaking, it should be readable as a book with straightforward pragmatic solutions to problems. Which is IMHO the major sign of good design.

All in all, it's just a hard work and time you probably won't get from your managers. All I described here takes a lot of time, effort, coffee, tea and especially thinking AFK. The more you give it, the better the design. There is no general recipe for designing applications, common sense, pragmatism, KISS, hard work, experience means good design.

OwnerDisplayName: JacobusR

Title: Re-inventing system design for Scala


答:
Anything that is worth printing at all is worth printing to the logs, since the whole point of logs is to record as much detail as possible about what happened during execution.

As with any other program, by default the user should see only a small subset of the output that's likely to be useful and relevant to him. Due to the nature of your program, you may have lots of options to increase verbosity or change how certain errors are handled, but that principle still applies.

For instance, if the app accepted a command to download some file from some server, I might print out on the console "connecting to website.com", "beginning download", "installing", and not much more, but the logs will contain several additional details like redirects or authorization protocol steps that might be useful in debugging complicated problems someday.

When an error is encountered, typically you'd print a concise summary of the error on the console ("lost connection with server") and tell the user what log file they can look at if they want to see more details.

Should normal output be considered as being log messages of a low severity level or not at all?

Output that the user actually sees should be considered more important, because you're going out of the way to show it to them instead of simply logging it, so it'd better be useful.

A "low severity" error might simply be something your program can workaround ("connection lost, retrying...connection reestablished") or it might be something that implies a possible user error you'd want to warn them about ("http specified, this connection will not be secure"). By itself "severity" isn't a useful indication of whether you should print something to the console or not.

Title: Printing to out vs Logging, given the nature of this app?

Body:
I'm writing a command line application in Java. That app will scan a list of remote resources, do several attempts to access those resources, report failed attempts, and if succesfully accesed, perform some maintenance or diagnosis action and report the outcomes of that action.

As you can imagine, there's a lot of error handling and error reporting. But reporting the errors is a feature. Let me explain: a report with the errors encountered when attempting to access to the remote resource is something the user expects from the app, since those failures are useful for the diagnosis. Such access failures are expected in many cases and the causes should be reported.

As you can see, there's a blurry line between what's an error and what's the expected output of the app, which as every app will have its own errors also.

I'm using the Java Logging API and I'm designing my classes in a way as to be able to add different loggers and swap loggers and/or handlers (to screen, to file, to database, etc), as well as different list of resources to scan (and different types of those resources).

The problem is that I'm tempted to call logger.log() everywhere I was previosly using System.put.println();

Right now I'm now in a position where there's a blury line between what should be printed with System.out.println() and what should be send to the Logger instance.

I believe I'm having a conceptual confusion.

So the questions are, given the fact that errors reporting is a part of the core functionality of the app and that, as any app, it has to handle and log its own errors:

What things should be printed with System.out.println()

What things should be forwarded to a Logger

What things should be both printed with System.out.println() and forwarded to a Logger

Should normal output be considered as being log messages of a low severity level or not at all?

EDIT:

Just to clarify, the app could attempt to download a file, but it's
  not the file what the final user wants, but to see whether or not it
  was accessible and if not, why. The resource could be a server, a
  database, a service or a file. The user doesn't want the app to get
  what the resource offers but to check availability and report the
  cause. That somehow makes failed attempts code errors the output users
  want to get from this app. Hence the thin line between logging or
  printing.


问:
How come the keyword for declaring a class is 'interface'
What is the relationship between a class and an interface in objective-c? How come we declare a class using @interface instead of @class?

答:
The interface keyword such as in Java or C# is used to define a completely abstract model of an object. That is, you can only define a set of methods that an object ought to have, but absent of any kind of implementation detail.

In Objective-C,@interface is used to the same effect. Everything inside the @interface...@end block is also completely abstract. To implement these methods, you must do so within the @implementation...@end block.

In other words, you could say that in Objective-C you are forced to define an interface and also a class that implements it, for every class you need and with the same name. You could do the same thing in Java or C#, were it not for the naming conflict.

Now, this separation seems unnecessary if you ever used Java or C#, but it is enforced because of how the code is compiled (Objective-C is a superset of C, like C++). You must import a class' file in order to compile code that uses it. If every class is defined and implemented in one file each, when you import another class's file you will import all of its imports. This would eventually lead to unsolvable circular dependencies. This is why you must define the interface of a class in a header (*.h) file, and also only import headers.

On a side note, to declare Java/C#-like interfaces in Objective-C, you can use the @protocol block.


问:
Why should I purchase an SSL certificate for custom domain?
After reading Heroku articles, Stack Overflow questions, and the Stripe payments integration guides, the general advice is that I should should purchase an SSL certificate for my custom domain that points to my Heroku app.

Can anyone offer an explanation or other resource to help me understand why I need an SSL certificate?

I understand that SSL encrypts transmitted data, but if Heroku provides SSL, then where am I lacking encryption?

Would a simple explanation be that http://example.com forwards all transmitted data to https://myapp.herokuapp.com, therefore someone could intercept that data on that "leg" of the DNS routing chain?

答:
You pay a certificate authority (CA) to sign a certificate that certifies that a particular public key corresponds to a particular host name that you control.

You don't need a signed certificate to achieve confidentiality between you and some destination server. You only need the public key of your intended communication partner.

The fundamentally hard problem that a signed certificate solves is not confidentiality but identity. Suppose  a customer tries to talk to example.com. The customer connects to some server, and that server supplies a public key for confidential communication. If the key isn't signed by a trusted authority, though, how do you know that the server you're talking to is really example.com?

In order to get a signed certificate, you go to a certificate authority and supply a public key, a host name, and sufficient evidence that you are the operator of the host name. If the CA is satisfied with your evidence, they issue a signed certificate linking your public key to your host name, which anyone can verify. Based on that certificate, the user learns that the CA (whom the user already trusts) asserts a pairing between the received public key and the host name they are trying to talk to.

There's no way for a user's system to know that example.com and myapp.herokuapp.com are the same service. (Comparing IP addresses isn't useful, because multiple sites may be hosted from the same IP, varying content by the Host request header.) The host names are different, so you need separate certification for each name.

It is possible for you to act as you own CA and produce a self-signed certificate. However, anyone can produce a self-signed certificate, so it doesn't provide any identity proof. Your operating system has a list of trusted CAs, whom we generally trust to be discerning when signing certificates. When a user sees a certificate signed by a trusted CA, the user can be reasonably sure that the CA has done due diligence in verifying that the public key is the correct one for that domain.


答: You can generate your own certificate, and it will work perfectly fine.  The reason you buy one instead of making one is that certificates from well-known CA's will not generate an error in the client browser indicating that the signing certificate authority is unknown and not trusted.</p>

Title: Why should I purchase an SSL certificate for custom domain?

Body:
After reading Heroku articles, Stack Overflow questions, and the Stripe payments integration guides, the general advice is that I should should purchase an SSL certificate for my custom domain that points to my Heroku app.

Can anyone offer an explanation or other resource to help me understand why I need an SSL certificate?

I understand that SSL encrypts transmitted data, but if Heroku provides SSL, then where am I lacking encryption?

Would a simple explanation be that http://example.com forwards all transmitted data to https://myapp.herokuapp.com, therefore someone could intercept that data on that "leg" of the DNS routing chain?


问:
How do you take advantage of your whiteboard in your development team?
Today we got our own website design. The theme is the "whiteboard".

I'm a big fan of them. I would like you to share with me how you use it. I'm sure I don't exploit its potential enough.

I will really enjoy answers that will come with pictures of your own whiteboard as an illustration ;)

I use it as an information radiator to support a light version of scrum.

How do you use this essential development tool?

Please note that I'm also interested in people using a virtual whiteboard or even big touchscreen whiteboard emulator.

答:
I write on a whiteboard to communicate during meetings and to visually think through problems. I don't use it as a billboard.

Take the example picture in the question: did you really need to use a whiteboard for that?

Whiteboards yearn to be the dynamic center of interactive communication, not to be static bulletin boards. Using a whiteboard as a bulletin board is a waste of money - blank walls and posterboards are far cheaper.

ContentLicense: CC BY-SA 2.5


问:
Static analysis for finding capitalisation / case inconsistencies in file names
TLDR; I'm looking for ideas on how to flag code containing file names/paths that have inconsistent capitalisation with the actual file/directory.

Situation

I am migrating a significant code base written in an interpreted language from a Windows/OSX dev environment and a Windows prod environment to Linux prod and dev (via vagrant) environment.

The problem is that I've discovered over the years various developers have been sloppy in ensuring references to files have consistent capitalisation with the actual file.

This is not just an issue for including other code files, but also in referencing template names and auto-loading classes from their name. For example someone might render a template by referencing mytemplate but the actual file is called myTemplate.html, or they reference MyClass but the file is called Myclass.

Previously the developers have failed to notice these instances because they're using case-insensitive file systems that hide the issue. Now that the production environment is case-sensitive a heap usually obscure bugs have arisen caused by case inconsistencies.

Questions

What is the best way to identify possible instances of this via static analysis of the code.

I've realised that dealing with this reactively (ie. in response to bug reports) is insufficient - I need to find all the instances where this is possibly an issue and manually review it, but finding every instance is painstaking. I was hoping that there might be an existing static analysis tool for this kind of issue but I couldn't find one.

I was thinking of maybe putting something together that would list all file and directory names, then search the code for any references to these but with a different case. This wouldn't be particularly intelligent but it would probably work (although there would probably be a significant number of false positives from variables names, etc. to work through).

How do I prevent this from happening in future

While developers are now using a Linux dev environment, vagrant shared folders are case-insensitive (on Windows systems at least). In some instances I've been able to add "fast-fail" conditions (so it explicitly checks the case and fails if they don't match, even if the file operation is successful), but I can't do that where file paths are passed directly into a native function for example. Unit testing on a prod environment is one solution, but some of these issues occur within templates (eg. somefile.js vs. someFile.js) which is hard to unit test.

答:
This is a task that defies static analysis. For example the not-unlikely code

```<code>def open_me(dir_path, filename, extension):
    return open(dir_path + filename + extension)
</code>```

would be a tough one to catch. When faced with an insoluble problem, use heuristics. I'd go both directions with this.

Assume that every filename in the tree is a candidate for being referenced in every file. I'd also add to the candidates someFile for every someFile.js. Then search the entire codebase for instances of the candidates and report them as possible defects which must be looked at. I recommend putting eyeballs in the loop because you don't want to catch comments and string literals which may not be filenames. Tedious? Sure.

The second direction is to look at every open() or similar function for filename-like things. This is tedious too.

There is only one way to prevent it happening in the future:

Set a policy and enforce it through code reviews. You went to a new platform which has additional portability constraints. Because of the open_me gotcha above, additional discipline is needed by the development team.

Body:
This is a task that defies static analysis. For example the not-unlikely code

def open_me(dir_path, filename, extension):
    return open(dir_path + filename + extension)

would be a tough one to catch. When faced with an insoluble problem, use heuristics. I'd go both directions with this.

Assume that every filename in the tree is a candidate for being referenced in every file. I'd also add to the candidates someFile for every someFile.js. Then search the entire codebase for instances of the candidates and report them as possible defects which must be looked at. I recommend putting eyeballs in the loop because you don't want to catch comments and string literals which may not be filenames. Tedious? Sure.

The second direction is to look at every open() or similar function for filename-like things. This is tedious too.

There is only one way to prevent it happening in the future:

Set a policy and enforce it through code reviews. You went to a new platform which has additional portability constraints. Because of the open_me gotcha above, additional discipline is needed by the development team.


问:
Is my auto-update standard reasonable?
I'm looking to come up with a standard for how to implement a system that will automatically update software. As such, there is no actual programming (yet), but I still want to make sure my standard is robust before moving on to the stage where I build a proof-of-concept prototype.

Please reference:

The GitHub repo in which I've placed my ideas is

Refine.txt, which outlines all my ideas for the standard

update-response-idea.json, which gives an example of what a server response might look like

As a question, are the implorements, core technologies, and response ideas in my idea complete enough andor reasonable? Also, are there any currently-apparent problems that might arise during implementation and execution of what I've outlined?

答:
The core idea would be to find the difference between the set of files currently installed on someone's computer and the newest set of files that should be installed on that person's specific computer; and (once these differences are determined) download whatever new files are missing and discard whatever old files are obsolete; hopefully in an "atomic" way (that makes it impossible for someone to start the software at the wrong time and get a mixture of old and new).

Note that determining "should be installed on that person's specific computer" may involve an amount of logic. It can depend on which OS the user actually has (32-bit Windows XP, 64-bit Windows 8?), or which CPU they have (with/without AVX?), or which version of DirectX or Java or whatever they have, or whether they're a registered user or not (e.g. only using a free version with restricted features), or whether their video card can handle high detail textures or not, or whether they've enabled various optional features, or...

Also note that the same system could (should?) be used for installing and uninstalling software. For installing software, the set of files currently installed is "nothing" (so the auto-updater knows it needs to download everything in the set of new files). For uninstalling software, you can just pretend that the newest set of files that should be installed is "nothing" and discard the set of currently installed files.

In addition; I'd want some security and/or fault tolerance. For example, maybe the files are encrypted with the provider's private key, and the auto-updater uses the provider's public key to decrypt the files. Maybe every file downloaded has an MD5 checksum and (after decrypting?) the auto-updater makes sure the file's data actually does match the MD5 checksum.

Let's talk about bandwidth. Is the data compressed? If there's a 123 MiB file and the new version of that file only has 12 bytes that are different; do you download the entire 123 MiB file, or do you only download something that describes the differences ("insert 4 bytes here, replace 6 bytes there, then append 2 bytes on the end")?

What does the server store? Does it store plain files only (and compress, encrypt, etc. every single time the file is downloaded); or does the server store pre-compressed and pre-encrypted files, plus store pre-computed descriptions of how to convert old files into new files (so if we're updating that 123 MiB file the server can quickly provide the "insert 4 bytes here, replace 6 bytes there, then append 2 bytes on the end" description)?

Now; let's look at your "refine.txt". Do the technical details within "refine.txt" that describe how it will actually work, cover anything important at all?

Title: Is my auto-update standard reasonable?


问:
Database Handler and SQL injection prevention
I've written a database model class in PHP and have written a controller class that specifically validates the data before sending it to db. I'm getting criticism that I should handle the data in database model class rather than controller class.

I wanted to write a generic db class which can be used anywhere for CRUD operations. Now can you guys please help me out in sorting this out? Whether I should validate the data in db model class or in db controller class?

答:
You should use PDO (PHP Data Objects) for preventing SQL Injection attacks. It supports 12 different database systems.

Your Generic Class for connecting to MySQL using pdo would look like this:

```<code>class Db{
    public function dbConnect(){
        try {
            $conn = new   PDO('mysql:host=host_name/ip;dbname=database_name','user','password');
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }catch(PDOException $e){
            echo $e->getMessage();
         }
    return $conn;
    }
}
</code>```

You can use this class from anywhere just follow the following steps:

include the above php file into your script where you want to use
the Db class. For example:

```<code>include_once 'db_connect.php';
</code>```

Create an object of Db:

```<code>$conn = new Db(); // $conn is object
</code>```

Call to function 'dbConnect' using object($conn):

```<code> $connection =$conn->dbConnect();
 // $connection is variable which will hold the
 // value returned by the 'dbConnect' function.
</code>```

Using this method you can make more functions inside the Db class for CRUD operation and use those function anywhere you want.

To learn more about PDO visit:

http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

http://code.tutsplus.com/tutorials/php-database-access-are-you-doing-it-correctly--net-25338

Body:
You should use PDO (PHP Data Objects) for preventing SQL Injection attacks. It supports 12 different database systems.

Your Generic Class for connecting to MySQL using pdo would look like this:

class Db{
    public function dbConnect(){
        try {
            $conn = new   PDO('mysql:host=host_name/ip;dbname=database_name','user','password');
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }catch(PDOException $e){
            echo $e->getMessage();
         }
    return $conn;
    }
}

You can use this class from anywhere just follow the following steps:

include the above php file into your script where you want to use
the Db class. For example:

include_once 'db_connect.php';

Create an object of Db:

$conn = new Db(); // $conn is object

Call to function 'dbConnect' using object($conn):

 $connection =$conn->dbConnect();
 // $connection is variable which will hold the
 // value returned by the 'dbConnect' function.

Using this method you can make more functions inside the Db class for CRUD operation and use those function anywhere you want.

To learn more about PDO visit:

http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

http://code.tutsplus.com/tutorials/php-database-access-are-you-doing-it-correctly--net-25338


问:
peer review code documentation
We all know that code reviews are generally a good practice, but what about reviewing documentation? Many devs that I work with will put up wiki pages, javadocs, etc, but most of the time, unless someone else needs it right away the docs will go unnoticed and unreviewed.

Are there any good tools or methodologies for peer reviewing code documentation?

答:
Actually, I think your posting contains two different questions, let's start with the simple one first:

are there any good tools or methodologies for peer reviewing code documentation?

I don't think there are "special tools or methodologies", because there is nothing special needed. Peer reviewing documentation works like any other kind of proofreading - you give the documents to the reader, he reads it, adds comments or suggestions for changes and finally you discuss the suggestions. That's all, it works with any kind of documentation technology (of course, some technologies make proofreading and commenting a little bit easier, but that does not change the general methodology).

Many devs that I work with will put up wiki pages, javadocs, etc, but most of the time, unless someone else needs it right away the docs will go unnoticed and unreviewed.

That is actually your second question - in other words "why do lots of people do not take notice of separate code documentation, or don't care for their quality?"

I think this question has been discussed in-depth here on this site, as well as in lots other places. It is a very broad question, but it all boils down to "is additional documentation really worth the effort?" And as long as the answer is not clearly "yes", don't expect to get a different answer to ""is it really worth the effort to review it?"

My personal opinion about this is that any team which is responsible for a certain product has to find the amount of documentation, and the correct abstraction level for the documentation that works for the team and the product. And once you found that, and the team sees a lot of value in that docs, the demand for reviews will arise by itself.

Title: peer review code documentation


问:
Scheduling a Jenkins job to only run integration test
My current company has a Jenkins/DotCi setup. Our current process for CI is when dev pushes to github, jenkins runs unit tests on all branches and reports back to us via email if the unit tests failed.

If on master, we then run a deploy to a UAT environment and we will soon be activating our integration tests after a deploy occurs successfully.

We want to run our integration tests against our Staging environment on a daily basis.

With the "Build Periodically" feature under Config i know we can specify when we trigger it to occur, however is there a way to have it trigger the integration test only rather than having to deploy?

答:
You can create a new job that only runs your integration tests. I always split up jobs like this:

build + unit test

deploy into UAT

run smoke tests

run integration tests / UAT

Take a look at the plugins Build Result Trigger, and the new Build Flow Plugin.

You can also just trigger another job with plain Jenkins without any plugin. In your job, add a Post build step and make it Run anther job.

edit If you need to copy artifacts from one build to another (to create a build+deploy pipeline), you can use the Copy Artifact Plugin.


问:
Appropriate Git workflow for multiple active releases while handling hotfixes
I'm trying to choose a Git workflow that is most appropriate for our product. Here are the parameters:

We do a few major releases a year, let's say 10 at the most

We have multiple versions of our product active at the same time (some people are on v10.1, some on v11.2, etc.)

We need to be able to work on multiple releases at the same time (so we could be working on v12.1, but as we get to the end of the release we start working on v12.2 at the same time)

We need to be able to hotfix releases when critical bugs are found

So far, here's the way I think it could work:

Single remote repo is used

Create branch 12.1 from master

Create feature branches based on 12.1, commit them and merge back into 12.1, push

Once we need to start working on future release, create a new branch 12.2 based on 12.1

From then on, when working on a feature for 12.1, create branch from 12.1, commit changes, and merge into both 12.1 and 12.2, push

If working on a feature for 12.2, create branch from 12.2, commit changes, and merge only into 12.2, push

When release 12.1 is completed, merge it into master and tag master branch with 12.1

If a hotfix is needed, create a hotfix branch from oldest release branch that needs it, commit changes, and merge back into all release branches for that release and future releases that could be affected; if the latest stable release branch was affected, merge it into master.

I have a few concerns:

I'm not sure that merging hotfixes from old branches into new branches will be a smooth process, especially if there have been a lot of overlapping changes; would it be smarter to just hotfix manually in each branch in cases where it looks like there will be conflicts

The workflow models I've seen seem to not keep release branches alive much, once done the release gets merged into master, tagged, and removed. My problem with that is that I don't have a good idea how to manage the state of the release if all I have are tags in master, seems easier to hotfix in a branch and then I have a release I can always go back to that has the latest hotfix (I can even tag the hotfixes in the release). Not sure there's a way I could go back within master and somehow have a copy of the release with hotfixes applied and update that tag.

Comments are appreciated on things I may have overlooked or better ways of accomplishing things given the requirements I've specified.

答:
You mentioned that you are familiar with gitflow. I suggest to addopt it for your scenario. You will need to create branches from your development branch to support older versions. These older versions will also need to have their own release/master branches and hotfix branches. You will need to periodically merge your support branches into the newer support branches and the develop branch.

As the development of the major versions diverges this will keep getting harder. There is no silver bullet for this. Sometimes it will be easier to make changes manually. The cost of maintaining the older versions will increase, and at some point it won't worth it anymore.

It all depends an what kind of changes you are making in your older versions. If only bugfixing, thats relatively easy to merge. If you try adding new features, that will be hard.


问:
Ensuring reliability of cross-compilation
Provided that my code is fully standards compliant with no undefined behaviour, how can I best assure that it will be possible to cross-compile my software for any architecture?

I had some ideas, but I don't if it's wise or possible to implement them. For example, if I could tell the compiler not to assume any paths or architectures when compiling or linking, then any non-cross-compilation would be effectively equivalent to making a cross-compilation build. For example, the compiler shouldn't assume that a DSO that I'm linking with, will be available under that path under runtime (or actually just before that, startup time).

答:
I am assuming that you are already relying on static code analysers to ensure standards compliance.

Now, because of the way systems are built, I'd strongly recommend actually compiling on a machine that resembles the target machines as close as possible.

You can achieve this using a cloud of build servers such as Jenkins or Electric Commander. With these tools you can also tie down the build break down to the actual code check-in via SCM integration.


问:
What was your most difficult bug hunt and how did you find it and kill it?
This is a "Share the Knowledge" question. I am interested in learning from your successes and/or failures.

Information that might be helpful...

Background:

Context: Language, Application,
Environment, etc.

How was the bug identified ?

Who or what identified the bug ?

How complex was reproducing the bug ?

The Hunting.

What was your plan  ?

What difficulties did you encounter ?

How was the offending code finally found ?

The Killing.

How complex was the fix ?

How did you determine the scope of the fix ?

How much code was involved in the fix ?

Postmortem.

What was the root cause technically ? buffer overrun, etc.

What was the root cause from 30,000 ft ?

How long did the process ultimately take ?

Were there any features adversely effected by the fix ?

What methods, tools, motivations did you find particularly helpful ? ...horribly useless ?

If you could do it all again
?............

These examples are general, not applicable in every situation and possibly useless. Please season as needed.

答:
This is from a long time ago (the late 1980s).

The company I worked for wrote a CAD package (in FORTRAN) that ran on various Unix workstations (HP, Sun, Silcon Graphics etc.). We used our own file format to store the data and when the package was started disk space was scarce so there was a lot of bit shifting used to store multiple flags in entity headers.

The type of the entity (line, arc, text etc) was multiplied by 4096 (I think) when stored. In addition this value was negated to indicate a deleted item. So to get the type we had code that did:

```<code>type = record[1] MOD 4096
</code>```

On every machine except one this gave ±1 (for a line), ±2 (for an arc) etc. and we could then check the sign to see if was deleted.

On one machine (HP I think) we had a weird problem where the handling of deleted items was screwed up.

This was in the days before IDE's and visual debuggers so I had to insert trace statements and logging to try and track down the problem.

I eventually discovered that it was because while every other manufacturer implemented MOD so that -4096 MOD 4096 resulted in -1 HP implemented it mathematically correctly so that -4096 MOD 4096 resulted in -4097.

I ended up having to go through the entire code base saving the sign of the value and making it positive before performing the MOD and then multiplying the result by the sign value.

This took several days.

Body:
This is from a long time ago (the late 1980s).

The company I worked for wrote a CAD package (in FORTRAN) that ran on various Unix workstations (HP, Sun, Silcon Graphics etc.). We used our own file format to store the data and when the package was started disk space was scarce so there was a lot of bit shifting used to store multiple flags in entity headers.

The type of the entity (line, arc, text etc) was multiplied by 4096 (I think) when stored. In addition this value was negated to indicate a deleted item. So to get the type we had code that did:

type = record[1] MOD 4096

On every machine except one this gave ±1 (for a line), ±2 (for an arc) etc. and we could then check the sign to see if was deleted.

On one machine (HP I think) we had a weird problem where the handling of deleted items was screwed up.

This was in the days before IDE's and visual debuggers so I had to insert trace statements and logging to try and track down the problem.

I eventually discovered that it was because while every other manufacturer implemented MOD so that -4096 MOD 4096 resulted in -1 HP implemented it mathematically correctly so that -4096 MOD 4096 resulted in -4097.

I ended up having to go through the entire code base saving the sign of the value and making it positive before performing the MOD and then multiplying the result by the sign value.

This took several days.


问:
Periodically polling an API, are there alternatives?
I'm currently working on a service that is supposed to aggregate data from a number of APIs, unify the data, and offer it through another API to the users. I had a couple of ideas for solving this, but I'm not confident my best solution is the best possible solution.

Solutions I considered:

Let the browser poll our API through javascript, which in turn polls the third party APIs. This introduces quite a bit of lag between the request and the user seeing the data, but doesn't waste resources on users that rarely log in.

Let the browser poll the third party APIs and afterwards send the data to our API. This is potentially insecure, and requires me to provide extra API endpoints and a lot more data cleanup.

The option I currently consider the most optimal is letting a service on the server (an actual executable) periodically poll the third party APIs. I would, for example, poll some endpoints every 30 minutes, and others maybe once a day. This is the safest option, and introduces little lag to user requests, and prevents users from reaching the request limit of the API. But data will only be up-to-date right after polling.

Are there any alternatives? If not, is my current optimal solution good enough?

答: Another option is not to poll at all, but to implement a caching solution where, when a request comes in to your API, you use a cached value if you have one that's recent enough, otherwise you update your cache with a call to the external API.</p>


答:
The original poster said:

However, the purpose of this is not to be a package manager, but instead a standard to follow when you want to implement a system that silently, automatically updates your software in the background.

While you can write an auto-upgrader it is hard to get it right without the package-manager ability to check inter-package dependencies.

For example, old (current?) Windows installers would depend upon a certain version of the Visual C RunTime library (msvcrt.dll) so they'd ship with their idiosyncratic version of that core system file put it in the core system directory and break other applications that needed a different version. The Unix equivalent is known as "dependency hell" where upgrading X would entail upgrading Y which might require downgrading Z. Modern distributions strive mightily to prevent this hell and use package managers to do it.

Finally, auto-upgraders are trivial wrappers around package managers: for every installed package, see if the server has a newer version and ask that the package-manager install the new. As @Brendan implied, if you think you can get away with a single, monolithic "total application image" for every machine, you'll be sorely disappointed because different machines will have annoyingly different requirements. You'll also encounter the legacy code requirement of "I need to keep groovy_app.1.1 on this machine because groovy_app.2.1 breaks my mission critical thingy".

Organizations resist change generally. Organizational IT resists change even more because each change is a discrete, jarring jump for most everyone involved. Google Chrome upgrade is a poor model to follow as it is its own complete monolithic system. Yep, new revisions of Chrome will occasionally break existing extensions (including those "by Google") but they simply don't care. They can get away with it because they are the GOOG, you likely can't.

Title: Is my auto-update standard reasonable?

Body:
I'm looking to come up with a standard for how to implement a system that will automatically update software. As such, there is no actual programming (yet), but I still want to make sure my standard is robust before moving on to the stage where I build a proof-of-concept prototype.

Please reference:

The GitHub repo in which I've placed my ideas is

Refine.txt, which outlines all my ideas for the standard

update-response-idea.json, which gives an example of what a server response might look like

As a question, are the implorements, core technologies, and response ideas in my idea complete enough andor reasonable? Also, are there any currently-apparent problems that might arise during implementation and execution of what I've outlined?


答:
However, the purpose of this is not to be a package manager, but
  instead a standard to follow when you want to implement a system that
  silently, automatically updates your software in the background. I'll
  look through apt and rpm!

The problem is that what you want to do is building a package manager whether you like it or not.

Your current proposed system seems to revolve around simply downloading installers at some unknown interval, and running them. There is a lot more you'll have to do.

That model depends on each and every package being able to have a silent installer. While having a silent installer is great, that will not work for a great many software packages. You'll either have to ignore them, making the 'standard' pretty much useless, or have to define exceptions that can be channeled through your software for when the user has to make decisions.

Say some package depends on the .NET framework. For Windows, that's going to be a lot of packages. Since the installers won't know whether .NET is installed, they'll have to include it, every time. Are you going to want the system to download that massive redistributable over and over and over? And if you don't, then you'll have to have a way for softwares to indicate that's what they need, so your system can download it for them. And having the initial software won't save you, as it is not uncommon for a given software product to change .net framework versions between 'updates'.

Pretty soon, different packages will need to have different versions, and so your software will have to keep track of all that.

How is your software going to handle updates that can't be done successfully? It is unacceptable for your auto-update to randomly break an existing software package. You'll have to implement a system for handling that, and rolling back the changes. Windows Installer provides some of that, but not all packages use windows installer to install themselves, and Windows installer is obviously not available on any other popular platforms.

I don't think you realize the complexity this task requires if it is going to solve real problems for many people.

Title: Is my auto-update standard reasonable?


问:
Is it a Good Practice to Catch All Exception?
The snippet below (in java) gives an example of my question.

```<code>try {
                  // code implementation here
                    }
                } catch (Exception ex) {

                }
</code>```

Now, is that a good practice? Does it affect code performance. Is it always better to be specific with the exception you want to catch or just always all exception and do not bother doing something like this?

```<code>try {
                    //code implementation
                } catch (IOException | SQLException | NullPointerException ex ) {

                }
</code>```

答:
I would assume that checking for specific exceptions would have an impact in performance (even if it is minimal) because the program would compare the exception triggered with 3 different values, instead jumping straight to the exception clause. This would increase the number of CPU cycles taken, hence reduce performance.

Listing all exceptions does not improve readability or functionality of the code though, so I would suggest you catch all exceptions by default, unless you need to catch an exact type of an exception.


问:
What changes in .NET software architecture have taken place in the past couple of years?
I've been away from hands on development work for the past couple of years and focusing more on delivery management. I'm looking to get a couple of new projects ASP.NET MVC apps off the group and I'm getting back into doing some hands on work.

My question is around architectural approaches and how they might have changed since I've been away. In the past I would have taken a n-tier approach to the kind of systems I'm looking at so typically that would be made up with:

```<code>Web front end
     |
Web controllers
     |
   Tasks
     |
Domain model
     |
Data access layer
</code>```

The controllers would have been a very thin layer pushing data into the tasks layer which would push things into the data access layer. Everything would have been hooked together using dependency injection and would be as loosely coupled as possible.

Each layer would typically be a separate class library apart from the controllers and the web front end which would both be inside an MVC project.

Is that kind of approach still a standard one or have things shifted in the last couple of years? Any comments/recommendations etc. would be appreciated.

答:
The biggest change is that the web front end (the part that runs in the browser) has gotten more sophisticated.  There are many frameworks that provide enriched functionality at the client; Angular is just one of them.  You can look here to find out more about what frameworks are available and what functionality they provide.

There is the notion of a Single Page Application now, which runs entirely in the browser and is fed data by REST services.

Data stores can now be NoSQL.  Entity Framework even supports them.  Asynchronous programming has become a popular tool; have a look at NodeJS.


答:
It is only good practice to catch a specific exception if it can actually be handled by the catch block.

Very often, programmers assume that the fault can be handled at all, close to the point of occurrence. This is often wrong. To understand why, we need to explore what "handling" means.

Your second snippet:

```<code>try {
    // code implementation
} catch (IOException | SQLException | NullPointerException ex ) {
    // handle exception
}
</code>```

implies that there could be some useful action which could handle the caught exception. But this is often not so. As was noted in the comments, performance is irrelevant if the code gives incorrect results.

About the only thing you can do with a NullPointerException is to log everything salient for debugging and die; any further attempt to continue has a high probability of stomping on the heap and breaking other things down-stream. This exception results from a software defect and cannot be properly handled at all.

I'll assume the code implementation consists of reading a istream. Handling an IOException could be as simple as re-reading the part that threw the exception (if caused by an interrupted system call) but that's the rare case and an over-generalized exception. If the error is FileNotFoundException, you've got an upstream defect which cannot be handled in this context. Who could handle it?  The code which created the istream could have handled the exception if there was a reasonable alternative file to open, but the sample snippet should lack the information. If we were trying to open a file with no reasonable alternate, all the opener can do is throw an exception itself.

Why? Because there is a contract between the opening code and its caller that says "you give me a pathname, and I will open it for you and give you an istream". Upon FileNotFoundException, the opening code has failed to fulfill its contract and will induce failures in the caller and other places where the istream is accessed. It is this violation of contract is the strongest case for exceptions.

Let's assume that the FileNotFoundException was thrown in a long running program like an editor. It would be rude for the application to crash just because you typo'ed a filename. In this case, the exception should be allowed to propagate up to the main loop which actually can handle it: namely by informing the user "file not found" thus giving the user an opportunity to try another filename.

When an Exception implies a contract failure that exception must propagate upwards until there is code that can actually rectify the contract failure. If there is no place that failure can be rectified (as in cat not_a_file) the best you can do is print a meaningful error message and (as in cat not_a_file a_file) skip not_a_file.

Title: Is it a Good Practice to Catch All Exception?

Body:
The snippet below (in java) gives an example of my question.

```<code>try {
                  // code implementation here
                    }
                } catch (Exception ex) {

                }
</code>```

Now, is that a good practice? Does it affect code performance. Is it always better to be specific with the exception you want to catch or just always all exception and do not bother doing something like this?

```<code>try {
                    //code implementation
                } catch (IOException | SQLException | NullPointerException ex ) {

                }
</code>```

Body:
It is only good practice to catch a specific exception if it can actually be handled by the catch block.

Very often, programmers assume that the fault can be handled at all, close to the point of occurrence. This is often wrong. To understand why, we need to explore what "handling" means.

Your second snippet:

try {
    // code implementation
} catch (IOException | SQLException | NullPointerException ex ) {
    // handle exception
}

implies that there could be some useful action which could handle the caught exception. But this is often not so. As was noted in the comments, performance is irrelevant if the code gives incorrect results.

About the only thing you can do with a NullPointerException is to log everything salient for debugging and die; any further attempt to continue has a high probability of stomping on the heap and breaking other things down-stream. This exception results from a software defect and cannot be properly handled at all.

I'll assume the code implementation consists of reading a istream. Handling an IOException could be as simple as re-reading the part that threw the exception (if caused by an interrupted system call) but that's the rare case and an over-generalized exception. If the error is FileNotFoundException, you've got an upstream defect which cannot be handled in this context. Who could handle it?  The code which created the istream could have handled the exception if there was a reasonable alternative file to open, but the sample snippet should lack the information. If we were trying to open a file with no reasonable alternate, all the opener can do is throw an exception itself.

Why? Because there is a contract between the opening code and its caller that says "you give me a pathname, and I will open it for you and give you an istream". Upon FileNotFoundException, the opening code has failed to fulfill its contract and will induce failures in the caller and other places where the istream is accessed. It is this violation of contract is the strongest case for exceptions.

Let's assume that the FileNotFoundException was thrown in a long running program like an editor. It would be rude for the application to crash just because you typo'ed a filename. In this case, the exception should be allowed to propagate up to the main loop which actually can handle it: namely by informing the user "file not found" thus giving the user an opportunity to try another filename.

When an Exception implies a contract failure that exception must propagate upwards until there is code that can actually rectify the contract failure. If there is no place that failure can be rectified (as in cat not_a_file) the best you can do is print a meaningful error message and (as in cat not_a_file a_file) skip not_a_file.


问:
Documentation of interfaces
I know how to document a function:

```<code>/**
 * Prints a greet message to the web page
 */
function greet() {
    echo "Hi!";
}
</code>```

Or describe the usage of a variable:

```<code>/**
 * @type string $name The user's name
 */
$name = "Bas";
</code>```

But I don't know how to document an interface. It requires the classes which implement the interface to have the functions which are inside the interface, and that's it.

Question

How do you document an interface?

答:
Describe the purpose and usage of the interface, and the purpose and usage of the functions in the interface.

Here is an example from the .NET Framework (simplified for brevity).  Note the "statement of purpose," and the specific notes about jitting and internal hacks, things which would not at all be obvious just by looking at the interface code:

```<code>    // Implement this interface if you need to support foreach semantics.

    // Note that T[] : IList<t>, and we want to ensure that if you use
    // IList<yourvaluetype>, we ensure a YourValueType[] can be used
    // without jitting.  Hence the TypeDependencyAttribute on SZArrayHelper.
    // This is a special hack internally though - see VM\compile.cpp.
    // The same attribute is on IList<t> and ICollection<t>.
    public interface IEnumerable<out t=""> : IEnumerable
    {
        // Returns an IEnumerator for this enumerable Object.  The enumerator provides
        // a simple way to access all the contents of a collection.
        /// <include file="doc\IEnumerable.uex" path="docs/doc[@for="IEnumerable.GetEnumerator"]/*">
        new IEnumerator<t> GetEnumerator();
    }
</code>```

It's worth noting that some of the documentation you describe in your question is either unnecessary or redundant.  Don't document things that are obvious.  Instead, make things obvious so that you don't have to document them.

Documentation is just one more thing that you have to maintain and keep in sync, so document for the right reasons.  Allow the code log to speak for itself, but document the relationships between methods and classes, explain obscure things, and in general be helpful without repeating yourself.

Title: Documentation of interfaces

Body:
Describe the purpose and usage of the interface, and the purpose and usage of the functions in the interface.

Here is an example from the .NET Framework (simplified for brevity).  Note the "statement of purpose," and the specific notes about jitting and internal hacks, things which would not at all be obvious just by looking at the interface code:

    // Implement this interface if you need to support foreach semantics.

    // Note that T[] : IList<t>, and we want to ensure that if you use
    // IList<yourvaluetype>, we ensure a YourValueType[] can be used
    // without jitting.  Hence the TypeDependencyAttribute on SZArrayHelper.
    // This is a special hack internally though - see VM\compile.cpp.
    // The same attribute is on IList<t> and ICollection<t>.
    public interface IEnumerable<out t=""> : IEnumerable
    {
        // Returns an IEnumerator for this enumerable Object.  The enumerator provides
        // a simple way to access all the contents of a collection.
        /// <include file="doc\IEnumerable.uex" path="docs/doc[@for="IEnumerable.GetEnumerator"]/*">
        new IEnumerator<t> GetEnumerator();
    }

It's worth noting that some of the documentation you describe in your question is either unnecessary or redundant.  Don't document things that are obvious.  Instead, make things obvious so that you don't have to document them.

Documentation is just one more thing that you have to maintain and keep in sync, so document for the right reasons.  Allow the code log to speak for itself, but document the relationships between methods and classes, explain obscure things, and in general be helpful without repeating yourself.


答:
This state of affairs (when you have to cough up for a cert) will not persist for long. There's a very promising initiative Let's Encrypt which will provide free certificates in an automatic mode. It is bound to launch in mid-2015. It is sponsored by Mozilla, EFF, Akamai, and Cisco. Thus, you'll have the best of two worlds: a non-self-signed, identity-verified certificate that will at the very least work in Firefox, and a gratis, hassle-free one at that.

Identity verification will be based on the ACME protocol.