问:
Is fewer lines of code always better?
Which of these programming styles is better?

```<code>var result = methodOne(methodTwo(a, methodThree(b)), c, d);
</code>```

or

```<code>var result3 = methodThree(b);
var result2 = methodTwo(a, result3);
var result = methodOne(result2, c, d);
</code>```

答:
It depends on how familiar the reader is likely to be with these operators and their problem domain. Even if all the methods are arithmetic functions, it can help to break it up.

Breaking up a larger formula into small steps can quite spoil the readability:

```<code>(let* ((term1 (* b b))
       (term2 (* 4 a c))
       (discriminant (- term1 term2))
       (twoa (* 2 a))
       (top1 (+ b (sqrt discriminant)))
       (top2 (- b (sqrt discriminant)))
       (root1 (/ top1 twoa))
       (root2 (/ top2 twoa)))
  (list root1 root2))
</code>```

versus

```<code>(let* ((root1 (/ (+ b (sqrt (- (* b b) (* 4 a c))))
                 (* 2 a)))
       (root2 (/ (- b (sqrt (- (* b b) (* 4 a c))))
                 (* 2 a)))
  (list root1 root2))
</code>```

Breaking up formulas into small steps is what a compiler does when it generates intermediate code. (Fortran: FORmula TRANslator.)

Breaking up expressions for readability helps, but don't "Fortran it" (go overboard).

Title: Is fewer lines of code always better?

Body:
It depends on how familiar the reader is likely to be with these operators and their problem domain. Even if all the methods are arithmetic functions, it can help to break it up.

Breaking up a larger formula into small steps can quite spoil the readability:

(let* ((term1 (* b b))
       (term2 (* 4 a c))
       (discriminant (- term1 term2))
       (twoa (* 2 a))
       (top1 (+ b (sqrt discriminant)))
       (top2 (- b (sqrt discriminant)))
       (root1 (/ top1 twoa))
       (root2 (/ top2 twoa)))
  (list root1 root2))

versus

(let* ((root1 (/ (+ b (sqrt (- (* b b) (* 4 a c))))
                 (* 2 a)))
       (root2 (/ (- b (sqrt (- (* b b) (* 4 a c))))
                 (* 2 a)))
  (list root1 root2))

Breaking up formulas into small steps is what a compiler does when it generates intermediate code. (Fortran: FORmula TRANslator.)

Breaking up expressions for readability helps, but don't "Fortran it" (go overboard).


答:
Is fewer lines of code always better?

The short is simply no. The longer one, no, because it depends.

How long is the code I want to shorten? If the code doesn't fit the screen, shortening it often makes it more readable

How much is done in single line? If it's an access through 10 objects, it's surely good idea to split it to many lines

What is better? Write long standard version or use single tricky syntax sugar or library function? How much people know that sugar/function? A great example are regular expressions. With single regex you can achieve as much as with many lines of code - but it sometimes takes hours to understand single regex. However, there are some regex that are widely used and google searchable.

Which of these programming styles is better?

Well, the second one is much much better in one aspect. If you need to debug what happens, you have the variables to inspect and more possibilities to place breakpoint.

On the other hand, I don't like using too much local variables, because I must invent the names for them. I hate such names as result1/2/3, because after some time I don't know which is for what. But I don't want to spend too much time on inventing the names... The first example is (for me) actually more readable because of bad variable names in second example.

Usually I start with the first code, and convert it to second first when I need to debug.

However, if the expressions are more complex, I prefer keeping intermediate results in local variables - but those local variable must have self-explaining names. Only then the code is easier to read.

ContentLicense: CC BY-SA 3.0

Title: Is fewer lines of code always better?

Body:
Which of these programming styles is better?

```<code>var result = methodOne(methodTwo(a, methodThree(b)), c, d);
</code>```

or

```<code>var result3 = methodThree(b);
var result2 = methodTwo(a, result3);
var result = methodOne(result2, c, d);
</code>```


答:
You give a bad example.

The solution you give to solve a problem better have a good design so it can be understandable, and good enough to keep the code short.

If you can make code that is more understandable by making it longer, it's something to do, but there is a limit.

I'll always think that code which have both a good design AND is kept short, ensures more understandability the shorter it is.

You should focus on a good design, and then find ways to make the code short enough so that people that will read it can understand it without making them scroll and scroll.

So to sum up, there is no real good answer to this, what is important is how well you divide your code into functions and sections, and how you can make it both short and easy to understand.

The bill gates quote is good, but there's also the quote that talk about a perfect piece of code, which is one where you can't take anything out.

Title: Is fewer lines of code always better?


问:
Should I be learning JavaScript before studying computer science?
So I've done a lot of research and found that Codecademy has been mentioned several times on other forums. I got stuck in and chose JavaScript through Codecademy most probably thinking it was 'Java' and I'm now slightly concerned that I have made a bad choice.. due to the fact that I see posts mentioning JavaScript teaches bad habits and so on...

Should I stop and learn other languages offered on 'Codecademy'?

Should I stop using codecademy altogether?

Or finally should I just wait until I start my degree and pose as a blank canvas?

All opinions wanted, thank you.

P.s I'm not entirely certain what jobs I will be applying for in the future but to give some indication I don't believe it will be website development and more so on the game or application designing side of things

答:
It's also not necessarily true that javascript will be bad for game development, it depends on the types of games you will want to make. I know that recently the Firefox team ported the unreal engine to javascript using something called asm.js, which took C++ code and turned it into a subset of js operations that were gauranteed to run quickly. They then ran some game on Firefox using it. It was a pretty slick demo. Here's a link if you're interested:

asm.js description

Similarly, games like farmville and others that are maybe not blockbuster titles but have their niche and are easily delivered through the browser are probably very heavy users of js in general, either that or the dying flash/actionscript. This is going to likely earn me a downvote, but I would go as far as to claim javascript is one of the most practical languages you can learn today, since it's everywhere and isn't going away in the short term. It doesn't hurt to know it, just keep an open mind that it is definitely not like most other established languages.


问:
Database Schema for Pricing Products (packages, promotions, qty based, limited time offer...)
I'm working on a new point of sale for a company that products for different prices depending on the product mix.

All products have a base price.

To explain my problem, I will use the following info:

```<code>Product         Category        Price
A               1               45
B               1               70
Q               2               20
R               2               27
S               2               15
X               3               17
Y               3               22
Z               3               16
</code>```

The company has Packages, for example Package "Combo": for product A or B, if you choose 1 of Q or R and 1 of X, Y or Z you get a $20 discount.

Case A: Sometimes customers add on to a base product when placing an order, for example:
They wan't one of Product A, and they add Product Q and Product P to that to create a package that has a discounted price. Then they might add that they want 1 of product B with 1 R and 1 Z.

Case B: Sometimes customers will add 1 A and 2 B, 2 Q, 1 S, 2 X and 1 Z. According to the rules set forth by "Combo" Package, only 2 combos would apply because S is not a combo item.

Other promotions are dependent on quantity, so if you buy 2 of B you get 20% off and/or dependent upon time, it is only valid after 5 PM or before 10% off if before 10am. Another promotion might depend on when your last purchase occured or if you have purchase more than $X in Y timeframe.

My Problems:

1) How do I structure the tables so I my create the different packages or promotions in a way that is very flexible to add different types of promotions with different requirements?

2) When they order like Case B (or a mix of Case A and Case B) how do I structure my query so that I can test to see what product mix(es) are in the order, and update the prices/descriptions accordingly? Ultimately, the best result for this query would return which packages and promotions have requirements fulfilled in order of which gives the most benefit to the customer (i.e. maybe what they ordered fulfills requirements for promotion 1 and 3, but promotion 3 is less expensive. This must work with multiple promotions).

Thanks in advance for the help!

UPDATE #1

To better describe the problems at hand and to update the work done thus far to solve them I'm incluiding an ERD of the Product Model limited to the entities and attributes that affect the issue (i.e. inventory is not at play here, so no inventory entities are present).

I'm also including sample data from the entities and attributes that affect this question (to simplify reading the data, I'm putting in name/descriptions in place of Foreign Keys):

Here is a link to a flow chart giving an example of a combo, a fast and visual way to understand the table structure.

```<code>PRODUCT
---------
ID  Name
================================
1   Hamburger
2   Cheeseburger
3   Bacon Hamburger
4   Bacon Cheeseburger
5   Orange Juice
6   Apple Juice
7   Coffee
8   Coke
9   French Fries
10  Onion Rings
11  Soup du Jour
12  Hamburger Combo
13  CheeseBurger Combo
14  Bacon Hamburger Combo
15  Bacon Cheeseburger Combo
16  Combo Side
17  Combo Beverage
18  Small Orange Juice
19  Large Orange Juice
20  Small Apple Juice
21  Large Apple Juice
22  Add Extra Patty
23  Add Avocado

PRODUCT COMPONENT
------------------
productFrom                 productTo
===================================================
Hamburger Combo             Hamburger
Hamburger Combo             Combo Side
Hamburger Combo             Combo Beverage
CheeseBurger Combo          Cheeseburger
CheeseBurger Combo          Combo Side
CheeseBurger Combo          Combo Beverage
Bacon Hamburger Combo       Bacon Hamburger
Bacon Hamburger Combo       Combo Side
Bacon Hamburger Combo       Combo Beverage
Bacon Cheeseburger Combo    Bacon Cheeseburger
Bacon Cheeseburger Combo    Combo Side
Bacon Cheeseburger Combo    Combo Beverage

PRODUCT FEATURE
----------------
ID  Description
=======================
1   Combo Side Option
2   Combo Beverage
3   Juice
4   Orange Juice Size
5   Apple Juice Size
6   Extras

PRODUCT FEATURE APPLICABILITY
------------------------------
product                     productFeature  ProductFeatureApplicabilityType
============================================================================
Hamburger Combo             Combo Side      Required
Hamburger Combo             Juice Flavor    Required
Cheeseburger Combo          Combo Side      Required
Cheeseburger Combo          Juice Flavor    Required
Bacon Hamburger Combo       Combo Side      Required
Bacon Hamburger Combo       Juice Flavor    Required
Bacon Cheeseburger Combo    Combo Side      Required
Bacon Cheeseburger Combo    Juice Flavor    Required

PRODUCT FEATURE APPLICABILITY
------------------------------
productFeature  product             ProductFeatureApplicabilityType
============================================================================
Combo Side      Hamburger Combo             Required
Combo Beverage  Hamburger Combo             Required
Extras          Hamburger Combo             Optional
Combo Side      Cheeseburger Combo          Required
Combo Beverage  Cheeseburger Combo          Required
Extras          Cheeseburger Combo          Optional
Combo Side      Bacon Hamburger Combo       Required
Combo Beverage  Bacon Hamburger Combo       Required
Extras          Bacon Hamburger Combo       Optional
Combo Side      Bacon Cheeseburger Combo    Required
Combo Beverage  Bacon Cheeseburger Combo    Required
Extras          Bacon Cheeseburger Combo    Optional

OPTIONAL FEATURE
------------------
productFeatureFrom  Product             ProductFeatureTo
=============================================================
Combo Side Option   French Fries
Combo Side Option   Onion Rings
Combo Side Option   Soup du Jour
Combo Beverage                          Juice
Combo Beverage      Coffee
Juice                                   Orange Juice Size
Juice                                   Apple Juice Size
Orange Juice Size   Orange Apple Juice
Orange Juice Size   Orange Apple Juice
Apple Juice Size    Small Apple Juice
Apple Juice Size    Large Apple Juice
Extras              Add Extra Patty
Extras              Add Avocado
</code>```

So, with the research and support provided by the community up until know, I have been able to solve Problem #1. In fact, I have done so with more flexibility than I thought I could do in the first deployment of the system.

All though there have been advances with Problem 2, it is not solved to satisfaction. There have been some ideas on how to do this, Neil McGuilgan asked a great question leading towards a possible solution using Relational Division (dba.stackexchange.com/questions/45829/what-is-the-name-of-this-type-of-query-and-what-is-an-efficient-example) and this book (www.amazon.com/books/dp/0471380237) helped a lot. However this solution at present, and as I understand it, only works with "one" record (combo) at a time. If a customer Walks up and says he wants 2 cheeseburgers, 1 hamburger, 1 small Apple Juice, 1 Coke, 1 French Fries and 2 onion Rings, I need a way to detect that there is only one combo in the mix and add the other products at base price. If there are multiple combo combinations, I'm looking (ideally for an sql query) that can prioritize combo combinations by largest savings.

One idea I've come up with to solve problem two is to add and attribute to PRODUCT COMPONENT flaggin the main product for the combo (i.e. hamburger). Then when running the pricing process, query what products in the order are main products in a "package", relating the query to the discount given by the PRICE COMPONENT table and ordering by that value (descending), and in that order of packages check to see if you can create a "package" with the remaining non-main products with a query and loop the process until there are no more main products or there are no more non-main products in the remainder.

答:
This could get complicated...

1) How do I structure the tables so I my create the different packages or promotions in a way that is very flexible to add different types of promotions with different requirements?

You could start with a packaged_with table to determine which products can be grouped and packaged together:

```
package
-------
  id (PK)
  name

package_group
-------------
  package_id (FK to package.id)
  name

packaged_with
-------------
  package_group_id (FK to package_group.id)
  product_id (FK to product.id)
  can_be_packaged_with (FK to product.id)
```

package_group refers to a package. packaged_with refers to products and package_groups, so that a row in packaged_with shows which products a product can be packaged with, and a package can be made up of multiple groups.

The data would look like this:

```
package
-------
ID  |  name
------------
1   |  Combo

package_group
------------
ID | name
---------
1  | QR group
2  | XYZ group

packaged_with
-------------
package_group_id | product_id | can_be_packaged_with
----------------------------------------------
1                | A          | Q
1                | A          | R
2                | A          | X
2                | A          | Y
2                | A          | Z
1                | B          | Q
1                | B          | R
2                | B          | X
2                | B          | Y
2                | B          | Z

```

This will help you with the product packages themselves. I have some ideas for the rest of your question, but I don't have time to finish this answer right now...

Promotions

You list many kinds of promotions. You might want to look into some sort of rules-engine, but I'll try to keep things simpler than that, but still... This will get complicated..

Let's start with simple promotions where a price is discounted a certain percentage:

```
percent_discount
----------------
  id (PK)
  name
  percent_amount

product_promotions
------------------
  id (PK)
  product_id (FK to product.id)
  promotion_id (FK to percent_discount.id)
  start_date
  end_date
```

Here we have a table that stores what percentage you get off for product. Another table actually links products to the discount rate, and also includes a start and end date so you know if the discount is applicable on any given date.

Ideas for the other promotions coming later...

Body:
This could get complicated...

1) How do I structure the tables so I my create the different packages or promotions in a way that is very flexible to add different types of promotions with different requirements?

You could start with a packaged_with table to determine which products can be grouped and packaged together:

package
-------
  id (PK)
  name

package_group
-------------
  package_id (FK to package.id)
  name

packaged_with
-------------
  package_group_id (FK to package_group.id)
  product_id (FK to product.id)
  can_be_packaged_with (FK to product.id)

package_group refers to a package. packaged_with refers to products and package_groups, so that a row in packaged_with shows which products a product can be packaged with, and a package can be made up of multiple groups.

The data would look like this:

package
-------
ID  |  name
------------
1   |  Combo

package_group
------------
ID | name
---------
1  | QR group
2  | XYZ group

packaged_with
-------------
package_group_id | product_id | can_be_packaged_with
----------------------------------------------
1                | A          | Q
1                | A          | R
2                | A          | X
2                | A          | Y
2                | A          | Z
1                | B          | Q
1                | B          | R
2                | B          | X
2                | B          | Y
2                | B          | Z

This will help you with the product packages themselves. I have some ideas for the rest of your question, but I don't have time to finish this answer right now...

Promotions

You list many kinds of promotions. You might want to look into some sort of rules-engine, but I'll try to keep things simpler than that, but still... This will get complicated..

Let's start with simple promotions where a price is discounted a certain percentage:

percent_discount
----------------
  id (PK)
  name
  percent_amount

product_promotions
------------------
  id (PK)
  product_id (FK to product.id)
  promotion_id (FK to percent_discount.id)
  start_date
  end_date

Here we have a table that stores what percentage you get off for product. Another table actually links products to the discount rate, and also includes a start and end date so you know if the discount is applicable on any given date.

Ideas for the other promotions coming later...


问:
Verification of requirements in a closed system
I'm on my first real software project following the whole SDLC and am a bit confused. We have a requirement that states something like "The battery will be monitored each second" which needs to be verified. This is something that can't really be checked in the system since it happens "inside", i.e. there's no output that would show that the battery was checked each second. It is my understanding that at this phase the verification is done on a closed system, so you can't just use a debugger to verify something like this.

Is this assumption wrong? Or can the requirement be considered to be ambiguously defined.

答:
Have your system have log files that it can write to, which can be downloaded later from test versions of the device.  (Make the logs circular, so that you'll always have the last X log lines, and limited memory requirements.)  The requirement now becomes that postprocessing that log file shows that the battery was checked at least once during each second.

Also you should have a simulation of your hardware that you write your software against, which gives all sorts of additional information back to you.  That simulation will be imperfect, but will give you the tools to write proper unit and integration tests that don't require physical devices to be built for every code change.  Make sure that toolchain is there, it will pay off.

(Note, I'm not an embedded system developer, but I have friends who are.  The advice that I'm giving is based on what they've told me worked for them for projects from monitoring heart pumps to launching rockets into orbit.)


问:
How do you educate your customers?
Customers need some education because they think different. Customers think:

changes are not a problem in any time of the project

details are not important (exceptions even less)

time does not cost money (they have a fix price agreed)

one sentence in the specification can be extended/read freely to fit the actual needs - and this does not affect the contract. (here we see often the "common sense" discussion - example: "Of course we need a invoice management screen when we talk about accounting managment - this is common sense!")

the list goes on...

The main problem is that customer (no matter if external or internal/department) do not want or can not understand. It took me many years to understand software creation process and I am still learning, so how can they in just a few months.

What is your experience, what is the best approach to educate customers?

答:
One solution is to put more work into defining what you are agreeing to do before you start working. As you said, one sentence in the contract can easily be read differently by you and the customers. The more detailed the project plan is the easier it is for you to say that the extra they want you to do is not part of the original deal.

It's also important to be consistent. The customer doesn't know how much work there is involved for any given new feature. If you agree to add quickly implementable features for free, it's very hard to later explain to the customer why you can't do this other feature for free as well when the customer's common sense says it shouldn't be any more work.

One trick with fixed price contracts is that even if you do the job with a fixed price put in an estimate on how many hours the job takes. Even though you don't bill by the hour this takes away the illusion that fixed price equals infinite work hours.

ContentLicense: CC BY-SA 2.5

Title: How do you educate your customers?


问:
Demonstration of garbage collection being faster than manual memory management
I've read in many places (heck, I've even written so myself) that garbage collection could (theoretically) be faster than manual memory management.

However, showing is a lot harder to come by than telling.

I have never actually seen any piece of code that demonstrates this effect in action.

Does anyone have (or know where I can find) code that demonstrates this performance advantage?

答:
The rule of thumb is that there are no free lunches.

GC takes away the headache of manual memory management and reduces the probability of making mistakes.  There are some situations where some particular GC strategy is the optimal solution for the problem, in which case you'll pay no penalty for using it.  But there are others where other solutions will be faster.  Since you can always simulate higher abstractions from a lower level but not the other way around you can effectively prove that there is no way higher abstractions can be faster than the lower ones in the general case.

GC is a special case of manual memory management

It may be a lot of work or more error prone to get better performance manually but that's a different story.


答:
There must be some output of the battery monitoring yes? So one possible way to verify would be to attach a test power supply via the battery terminals, changing the test power inputs and looking for a battery monitoring output change within one second.

Where that could get complicated is that battery reporting may be sampled at one second intervals but averaged (or other statistical processing) for reporting on a slower time scale.

Title: Verification of requirements in a closed system

Body:
I'm on my first real software project following the whole SDLC and am a bit confused. We have a requirement that states something like "The battery will be monitored each second" which needs to be verified. This is something that can't really be checked in the system since it happens "inside", i.e. there's no output that would show that the battery was checked each second. It is my understanding that at this phase the verification is done on a closed system, so you can't just use a debugger to verify something like this.

Is this assumption wrong? Or can the requirement be considered to be ambiguously defined.


问:
When to really focus on performance?
We've just finishing up the first release of a database driven web application, which is now in regression testing. The application has an advanced search with many different filtering criteria. When the search is first used with only the 3(of 28) minimum required search criteria it takes like 15-20 secs to calculate and retrieve the data for the page to load.

This happens only the first time the search(uses a stored proc) is run. The search thereafter take 2-6 secs.

The stored procedure has medium complexity around 1500 - 2000 lines. I would like to get it down to run the first time to 6 secs and thereafter like 1-2 secs but I can't seem to find the  time to make it faster.

My question is, is this acceptable for users if it is only slow the first time the search is run? Has anyone else had a similar experience with creating advanced searches? What was your solution?

答:
"Is it acceptable" is not a technical question; it's a product question.  In some products, 2-6 seconds might be considered hideously slow while in others, 15-20 seconds might be pretty zippy.  How fast are competing products?  How fast are similar products?  What percentage of customers will see the long original query vs. the faster cached query?  If you expect ten million queries, one slow one will be trivial.  If you expect ten, then not so much.  Answers to these questions will tell you if you need to optimize.

One technical solution you might try would be to prewarm these queries.  It isn't clear to me exactly how many possible queries there are, but if you have a low enough number of these "slow" queries, just immediately run them after you deploy so no actual customer sees them.  If there are an extremely large number of possible queries, then maybe run those that you find are most common.

Title: When to really focus on performance?


答:
You can do several things:

Create views for performance. A view is a contract of intention that tells the RDBMS "I will be running this query very often". When you do that the RDBMS optimizes the access to this data.

Create views for simplicity and tuning. You create views in order to split the big solution into smaller solutions. This way you can measure exactly where the bottleneck is and try to improve the problematic areas.

Create denormalized tables ( materialized views ). Sometimes it pays back to create summarized tables in order to make certain reports faster, especially of data that is not transactional.

Create a non-transactional database or datawarehouse for queries. Most RDBMS has ways of tuning a special database for queries when this databases is not transactional, ie, it's not being hit continuosly with inserts or updates. The whole set of tuning configurations if different when the database has this purpose. It's more efficient than a general purpose database.

Put most queried tables in faster disks. Move most queried tables in tablespaces located in better, faster disks and better connections (SAN). Move not so important tables to slower, cheaper disks and not so fast connections.

Use structure programming techniques to split your stored procedures into smaller ones, so you can keep complexity at bay. That way you can concentrate better on improving performance once you don't have all the complecity in your face all the time.

Use queries with binding variables avoiding concatenated ones. That way the RDBMS is able to cash them in the query area and they run faster because you save parsing time and planning time.

Remember that your DBA is your friend, and he/she can do a lot to improve database performance. Don't rely solely on your programming skills. You are not alone.

Title: When to really focus on performance?

Body:
We've just finishing up the first release of a database driven web application, which is now in regression testing. The application has an advanced search with many different filtering criteria. When the search is first used with only the 3(of 28) minimum required search criteria it takes like 15-20 secs to calculate and retrieve the data for the page to load.

This happens only the first time the search(uses a stored proc) is run. The search thereafter take 2-6 secs.

The stored procedure has medium complexity around 1500 - 2000 lines. I would like to get it down to run the first time to 6 secs and thereafter like 1-2 secs but I can't seem to find the  time to make it faster.

My question is, is this acceptable for users if it is only slow the first time the search is run? Has anyone else had a similar experience with creating advanced searches? What was your solution?


问:
What exactly is "big O" notation?
From what I've gathered, big O notation is used to describe the length of an operation. However, that's as far as I've gotten. What exactly is big O notation and how do the most common ones (O(n), O(2n), O(n^2), O(log n), etc)?

答:
I can understand where you are coming from here - I am learning this as well, and sometimes it is really helpful to have a more relaxed explanation of something when it is new. Please keep in mind that I am only just learning this as well, but this is how I understand big-Oh:

It is part of asymptotic notation, which is used to describe the running time of an algorithm (i.e. it puts the running time into a range from best-case (Omega) to worst-case (big-Oh) and we can be sure that the algorithm will take at least Omega, and at most Big-Oh to run)

Big-Oh is the upper-bound, i.e. the slowest the algorithm will ever (successfully) run

O(n) is linear time - You can think of it as walking up a set of stairs, left-right-left-right. So you take one step on each stair (or loop through a list once)

O(n^2) is quadratic time - obviously this is much higher (will take longer) than O(n). You could think of this as taking n steps on each stair as you climb (or if there are 8 stairs, you would take 8 steps on each stair)

O(log(n)) is logarithmic time - this is the holy grail for many algorithms (like sorting; being able to sort in O(log(n)) is really good!). Trying to describe this in the stair analogy gets a little tricky, and I don't think I quite understand it well enough to try :) But, the general idea is that as the stairs get longer and longer, you don't have to do much much more work to climb them, because you are actually jumping up them

As to what is the base of the logarithm, it doesn't really matter for asymptotic notation, because with asymptotic notation you are trying to describe what will happen when the size (n) gets really really big (though it is often base 2). All log graphs (base >= 2) start to flatten out at high values, so they are always going to win at the top end.

There is a course on coursera, Design and Analysis of Algorithms, that has just started this week - one of the first lectures gives a high-level description of asymptotic notation, and the last question of week one's problem set made me think about running times and what beats what. It wouldn't take long to cast your eye over these.

Hope this helps a little!

Title: What exactly is "big O" notation?


答:
What about

```<code>var result = methodOne(   methodTwo(    a,
                                        methodThree(b)
                                   ),
                          c,
                          d
                      );
</code>```

This will probably be even further improved by the help of a decend IDE, printing lines that match the braces.

Title: Is fewer lines of code always better?

Body:
What about

var result = methodOne(   methodTwo(    a,
                                        methodThree(b)
                                   ),
                          c,
                          d
                      );

This will probably be even further improved by the help of a decend IDE, printing lines that match the braces.


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

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

Do they really violate the three-tier separation ?

答:
Tier actually means different machine, layer means different logical separation. With stored procedures you have the data layer and (at least part of) the business logic layer in the same tier. Putting the business logic in the stored procedures violates the 3-tired architecture but is questionable whether it violates a 3-layered architecture; one sure thing is that it sure isn't a good example of separation of concerns.

A layer is a logical structuring mechanism for the elements that make up your software solution; a tier is a physical structuring mechanism for the system infrastructure. (Reference)

In my opinion there are two major problems with building business logic in the database:

Code and libraries: you will find fewer programmers being able to program in SQL, PL/SQL, TSQL etc. than in C#, Java etc. Programming languages also have the advantage of great IDEs, great libraries and frameworks.

Horizontal scalability: the only way you can scale your system is by changing the physical server on which the database with a more powerful one, which is rather expensive (a server with 64 GB RAM); relational databases scale horizontally very bad, and even at greater expenses. While, with business logic in OO-built server you can scale horizontally pretty well by putting the server on many nodes (in Java many applications servers support this).


答:
It should be considered that GC is not just a memory management strategy; it also makes demands on the entire design of the language and runtime environment, that impose costs (and benefits).   For example, a language that supports GC has to be compiled into a form where pointers can't be hidden from the garbage collector, and generally where they can't be constructed except by carefully managed system primitives.   Another consideration is the difficulty of maintaining response time guarantees, as GC imposes some steps that have to be allowed to run to completion.

Consequently, if you have a language that is garbage collected, and compare the speed with manually managed memory in the same system, you still have to pay the overhead to support garbage collection even if you're not using it.

Title: Demonstration of garbage collection being faster than manual memory management

Body:
I've read in many places (heck, I've even written so myself) that garbage collection could (theoretically) be faster than manual memory management.

However, showing is a lot harder to come by than telling.

I have never actually seen any piece of code that demonstrates this effect in action.

Does anyone have (or know where I can find) code that demonstrates this performance advantage?


问:
TFS merging - how to track what changes go into MAIN?
I'm new to TFS branches, and have opted to set up a \Dev and \Main branch (ultimately there will be release branches too). I'm using TFS2012. My understanding is that I will work on the \Dev branch on a day to day basis. When a bug is fixed or a user story is completed, I will merge \Dev to \Main, build, and give that to the tester.

In \Dev I have a policy to ensure that check-ins are associated with a work item. However when I merge from \Dev to \Main, and check-in that merge, what would I associate that check-in with, if anything?

The reason I ask is because I'm wondering how someone could find out what changes went into a particular \Main build? It's obvious in \Dev, as you'll see the associated work items in the build output. But there will be no such history in \Main, unless I associate the merge check-in with some sort of work item. The tester needs to know what's gone into a particular \Main build, but how? Is it a manual process, where the developer simply gives him a list of changes that have been merged into \Main?

I've read the MS branching/merging guidance, but it doesn't really shed light on this kind of thing.

答:
As Max said, you could create a task specifically devoted for the merging Dev into main process and then track which changesets have been associated with that task.

Also, you can read on every build journal the list of the changesets used for the build.


答:
Such an example necessarily has a bad manual memory allocation scheme.

Assume the best garbage collector GC. It internally has methods to allocate memory, determine what memory can be freed, and methods to finally free it. Together these take less time than all of GC; some time is spent in the other methods of the GC.

Now consider a manual allocator that uses the same allocation mechanism as GC, and whose free() call just sets aside the memory to be freed by the same method as GC. It doesn't have a scan phase, nor does it have any of the other methods. It necessarily takes less time.


问:
Career advice: stay with PHP or start a new career in something else ( .Net?)
I'm planning on moving to NY in 6-12 months tops, so I'm forced to find a new job. When I'm planing to start my life in another city it's also probably a good time to think about career changes.

I've found a lot of different opinions about PHP vs .Net vs Java and this is not the topic here. I don't want to start a new fight about which language is better. Knowing a programming language is not the most important thing for being a software developer. To be a really good developer you need to know OOP, design patterns, testing... and a language is just a tool to make things happen.

So back to my question. I have mixed experience in IT - 1 year as an IT support guy (Windows administration and support), around 2 years of experience in embedded programming (VB.Net 2005) and for the last 2 years I'm working with PHP/MySQL. I have worked with Magento web shop, assisted in some projects in Symfony, modified few Drupal sites.

My main concerns are the following:

Do I continue to improve my skills in PHP e.g. to start learning some major PHP framework like Zend, Symfony maybe get some PHP certification.

Or do I start learning .NET or Java. I'm more familiar to .NET so I'll probably choose it if choice falls between .NET and Java ( or you could convince me to choose Java :).

Career-wise, I don't know what is the best choice. Learning a new framework and language is more time consuming then improving my existing skills in PHP. But with .NET you have a lot of possibilities (Windows 7 Phone development, Silverlight, WPF) and possibly bigger chances to find better jobs.

PHP jobs are less well payed then .NET, at least, according to my research (correct me if I'm wrong). But if I start now with .NET I'm just a beginner and my salary will be low. I need at least 2+ years of experience in some language to even try to find some job that is paying higher than $50-60k in NY. My main goal in the next 2-3 years is to try to find a job in the $60-80k category. Don't get me wrong, I'm not just chasing money, but money is an important factor when you're trying to start a family.

I'm 27 years old and I feel that there isn't a lot of room for wrong decisions regarding my career, so any advice will be very welcome.

Update

Thank you all for spending time to help me with my problem. All of the answers and comments have been very helpful. I have decided to stick with PHP but also to learn C# and Silverlight 4. We'll see where the life will take me.

答:
Learn as many languages as you can, preferably at least one from each major area of development.

Scripted programming languages (you have PHP already, try Ruby, Python or something else)

Compiled to virtual machine languages with rich frameworks: .Net, Mono, Java

Compiled to bare-metal: C/C++

Functional languages: Lisp, F#, Haskell

Each one of these will teach you something about the fundamentals of software development. Of course, on top of that you'll need to experience different design approaches (OO, functional, data-driven), different team working methods (agile, tdd, compared to more rigid types), different platforms, different deployment mechanisms (native, framework based, web). The list goes on. Language fluency is just one tiny part of the whole.

For all these things, you need to make at least one real product using them to be proficient.

Some people will tell you you need to specialise in one technology (PHP, .Net, Java) and build a career largely around that one to make progress. I don't agree with this at all. I'll take a developer who has been around the block a few times with different platforms and
technologies over one that has spent 10 years doing one thing any day of the week. The reason is that technology changes every year, and the developer who is capable of picking up a new tech, reading the API and applying their experience in more general ways than just knowing the library functions off by heart, will be far more productive in the long term. Ok, so that 10-year .Net veteran will be off the starting blocks in .Net faster, but that early lead is lost in about a month. It's irrelevant compared to the wider picture of being experienced in a range of approaches and technologies.


问:
log4cxx: is it a stable option to include as part of distributed library?
We are porting our Java API library to C++. (Our target platforms are Linux and Windows.)  Since we have minimal C++ experience, the learning curve has been pretty steep, but overall we have been able to make a clean port so far.

In Java we use log4j, and are looking at to use log4cxx in the C++ version.  It took us a few hours to get log4cxx to build on Windows (due both to our inexperience, and also build documentation seems out of date). We haven't yet tried to build on Linux.

To my uninformed eye, log4cxx seems messy and somewhat outdated. Is there any consensus on whether this is a good logging framework to go forward with?  (Log4j also seems to have been superceded by SLF4J and Logback.)

I looked also at boost logging, but that does not appear to be part of the main distribution, so I wasn't sure if I was provided a more standard option with that or not.

One other piece of information to add into the evaluation - the first client we are providing this to is already using log4cxx.

答:
One thing you need to understand, coming from Java to C++, is that it does not have a single, monolithic, standard library. It's a key weakness of C++, and something that the language committee is very keen on addressing, but time - and plenty of it - will tell whether that can be improved.

This means that you need to become comfortable with finding and evaluating third-party libraries on your own. This doesn't mean that C++ doesn't have high-quality libraries though! A lot of third-party libraries are very good, and are used by many projects. It's just that without a central authority to put their seal of approval over it, you have to do the investigation yourself. Note that there have been many bugs in the standard libraries of Java, C# and so on, so not being a part of the "standard" library doesn't automatically mean it's untrustworthy.

A few points that may help you:

Boost is a very safe choice; it is used by a lot of people, and parts of it are so good that they eventually make it into the C++ language and standard libraries. Be aware however that its quality is not uniform; stick to the commonly used parts and away from the fringes and you'll be fine. This is not meant as a jab at Boost; it's a common symptom of any large library to have unstable fringes.

Any library that is used by many people, and is actively and well maintained, stands a good chance of being high quality. Speak to your peers to find out which libraries they recommend, or do your own investigation. I don't know if log4cxx falls into this category; ask those familiar with it.

Sometimes you need a library that does something very obscure, or for whatever reason there's no impetus for anyone to make a good library for it. Then you have to make some tough decisions, such as finding some flaky open-source library and getting it up to scratch, writing your own, or paying some vendor to do it.


问:
Is there a concept of a variable with phases of initialization: uninitialized, initializing, immutable?
I was looking at this thread on Stack Overflow and thinking about the functional programming I've been learning, and how immutability is so key there, and it occured to me that maybe some language has gotten the idea to have variables start out "null", then go to a "building" state, and finally become the same as any other immutable when initialization is done.

Is this a valid concept and/or has it been tried or experimented with at the language level?

It might look something like this:

```<code>string s new String(); // empty strings start out mutable
for x = 1 to 10
  s = s + "z"
s.Freeze() // now it's immutable
</code>```

It's just a thought.. maybe it's not a good one, but it seems like a hybrid of two things that seem to be opposing one another.

答:
The problem with your approach is static type safety:

```<code>string s new String(); // empty strings start out mutable
for x = 1 to 10
  s = s + "z"
if (rand()==0) s.Freeze() // now it might be immutable
</code>```

And the explicit solution to this is a pair like String/StringBuilder. One is immutable and long-lived, the other is used in construction and shortlived. Your "Freeze()" becomes the assignment from the builder to the immutable object.

Body:
The problem with your approach is static type safety:

string s new String(); // empty strings start out mutable
for x = 1 to 10
  s = s + "z"
if (rand()==0) s.Freeze() // now it might be immutable

And the explicit solution to this is a pair like String/StringBuilder. One is immutable and long-lived, the other is used in construction and shortlived. Your "Freeze()" becomes the assignment from the builder to the immutable object.


问:
Is it good practice on server/client systems to automatically install updates?
I'm working on an automated update system for a legacy server/client software package written in Delphi. The way I'm designing it is so the client's (customer's) server machine runs a service which...

periodically checks online for new versions

automatically downloads files

hosts latest version information for all client machines

hosts files for client machines to update

Once this service has downloaded update files, it raises a flag in the database alerting all client machines that updates are available. BUT, the thing is, the server must be installed first. So, an administrator would see this message and approve the update. However, the administrator must schedule a time for it to install. At that scheduled time, the server will update its self. If everything was successful, it will raise another flag in the database for all client machines to also update. If anything happened, it will restore the backup which was made before the install.

My question is... Is this good practice? Of course automated updates is a very good thing... if done right. This software is used in real-time in retail and wholesale environments, so if anything goes wrong during this scheduled installation, people could come to work the next morning to a broken system. The point is, no matter how automated I make this, an administrator still needs to ensure everything went smooth.

Further issues...

client machines must know not only the database server info, but also their update server info.

server machine might be at another location which might require firewall configuration

database changes may give unforeseen results, which aren't known until something bad happens

client machines may be shut down and need to update once it starts

a list full of possible scenarios which may go wrong

So in this situation, would you feel comfortable making a 100% automated updating system for a sensitive software? Because some of our clients have up to 50 client computers which need to be updated to match their server's database.

答:
The answer of Auto Update or Manual Update depends on two basic parameters.
1. How Important/Urgent is the Update?
2. How Big is the Update?

For Enterprise software, first priority is 'Security', second is 'System Availability' , new features or cool features are last things to care about.

I work for Fortune 500 INCs and my experience is that many companies use older versions of software because newer version are likely to have some bugs and older versions are likely to be bug free(bugs have been fixed science 1st release).

Hence you need to pool lots of small non security updates, trivial bug fixes, features that clients don't need together and let the system admin decide on update date-time.
Incase there are update related to security, you can still raise some flag in system so that Admins will install the features ASAP.

So IMO, you must NOT have automated updates. Planned updates are always better than unplanned one.


答:
I think the primary point is, eventually a software engineer should get to the state where the language is largely immaterial to the task at hand, except in its limitations.

Whether you know a language or not should not make a difference, providing you have a manual, only to speed for the first day or so while you find your bearings.

Having said that, proprietary languages tend to have less documentation and examples spread around the web, and thus are harder to become accustomed to and pose a problem if you wish to take your work home with you.

Title: Career advice: stay with PHP or start a new career in something else ( .Net?)

Body:
I'm planning on moving to NY in 6-12 months tops, so I'm forced to find a new job. When I'm planing to start my life in another city it's also probably a good time to think about career changes.

I've found a lot of different opinions about PHP vs .Net vs Java and this is not the topic here. I don't want to start a new fight about which language is better. Knowing a programming language is not the most important thing for being a software developer. To be a really good developer you need to know OOP, design patterns, testing... and a language is just a tool to make things happen.

So back to my question. I have mixed experience in IT - 1 year as an IT support guy (Windows administration and support), around 2 years of experience in embedded programming (VB.Net 2005) and for the last 2 years I'm working with PHP/MySQL. I have worked with Magento web shop, assisted in some projects in Symfony, modified few Drupal sites.

My main concerns are the following:

Do I continue to improve my skills in PHP e.g. to start learning some major PHP framework like Zend, Symfony maybe get some PHP certification.

Or do I start learning .NET or Java. I'm more familiar to .NET so I'll probably choose it if choice falls between .NET and Java ( or you could convince me to choose Java :).

Career-wise, I don't know what is the best choice. Learning a new framework and language is more time consuming then improving my existing skills in PHP. But with .NET you have a lot of possibilities (Windows 7 Phone development, Silverlight, WPF) and possibly bigger chances to find better jobs.

PHP jobs are less well payed then .NET, at least, according to my research (correct me if I'm wrong). But if I start now with .NET I'm just a beginner and my salary will be low. I need at least 2+ years of experience in some language to even try to find some job that is paying higher than $50-60k in NY. My main goal in the next 2-3 years is to try to find a job in the $60-80k category. Don't get me wrong, I'm not just chasing money, but money is an important factor when you're trying to start a family.

I'm 27 years old and I feel that there isn't a lot of room for wrong decisions regarding my career, so any advice will be very welcome.

Update

Thank you all for spending time to help me with my problem. All of the answers and comments have been very helpful. I have decided to stick with PHP but also to learn C# and Silverlight 4. We'll see where the life will take me.


问:
What is the ideal length of a method for you?
In object-oriented programming, there is of course no exact rule on the maximum length of a method , but I still found these two quotes somewhat contradicting each other, so I would like to hear what you think.

In Clean Code: A Handbook of Agile Software Craftsmanship, Robert Martin says:

The first rule of functions is that they should be small. The second
  rule of functions is that they should be smaller than that. Functions
  should not be 100 lines long. Functions should hardly ever be 20 lines
  long.

and he gives an example from Java code he sees from Kent Beck:

Every function in his program was just two, or three, or four lines
  long. Each was transparently obvious. Each told a story. And each led
  you to the next in a compelling order. That’s how short your functions
  should be!

This sounds great, but on the other hand, in Code Complete, Steve McConnell says something very different:

The routine should be allowed to grow organically up to 100-200 lines,
  decades of evidence say that routines of such length no more error
  prone then shorter routines.

And he gives a reference to a study that says routines 65 lines or long are cheaper to develop.

So while there are diverging opinions about the matter, is there a functional best-practice for you?

答:
IMHO, you shouldn't have to use scrollbar to read your function. As soon as you need to move scrollbar, it take a few more time to understand how work the function.

Accordingly, it depends of usual programming environment of your team work (screen resolution, editor, font size, etc...). In 80's, it was 25 lines and 80 columns. Now, on my editor, I display nearly 50 lines. Number of columns I display did not change since I split my screen in two to display two files at times.

In brief, it depends of setup of your coworkers.

OwnerDisplayName: iPhoneDeveloper


问:
DB table with column for each datatype
I need to design a DB for storing key-value data. List of Key names isn't fixed and should expand at later point.
I don't want to create a table with a column for each key, because I'll need to add columns frequently and it might grow too big, and I understood that the Entity-Attribute-Value design isn't efficient.
I thought of the following type of table design, and I'm asking if it makes any sense and does anyone can come up with any drawbacks related to efficiency, table size or any other issue -

Each column in the table is of a different data type;
irrelevant columns for a key are NULL:

```<code>ID |DataType |KeyName |ValInt |ValSmallInt|ValBool |ValStr  |ValText  |ValDate
-------------------------------------------------------------------------------
1  |1 (int)  |Width   |100    |NULL       |NULL    | NULL   | NULL    | NULL
2  |1 (int)  |Height  |200    |NULL       |NULL    | NULL   | NULL    | NULL
3  |2 (bool) |IsActive|NULL   |NULL       |false   | NULL   | NULL    | NULL
4  |3 (text) |URL     |NULL   |NULL       |NULL    | NULL   | w.com   | NULL
5  |1 (int)  |Size    |4      |NULL       |NULL    | NULL   | NULL    | NULL
6  |4 (date) |Created |NULL   |NULL       |NULL    | NULL   | NULL    | 2/2/2012
</code>```

Number of columns will be as the number of all datatypes (about 30?).

The DataType column is a flag of type int which is used for the caller - it tells him what column to take the value from.

Each row is actually a property of some object in other table. A set of rows makes a set of properties for that object and usually a SELECT will get the whole set.

答:
You're correct that representing different keys as columns in a table is a bad idea. The right thing to do is to represent them as different rows.

That leaves the problem of storing values of different types uniformly. The alternatives are

(a) storing them in different tables, at the cost of having to perform different queries for looking up values of different types, and having to use JOIN for retrieving all values. Depending  on what your usage pattern will be, this may be a good idea. For instance, if you normally look up individual values rather than the entire set, and if the caller knows what type every key represents, then this is the superior solution.

(b) storing them all in the same table, at the cost of having to use the least common denominator for the type of the value column. This means having to cast or transform the value every time you retrieve it, and probably also storing a type flag in each record. This would be a horrible idea in an object-oriented programming language, because they have better options for polymorphic collections, but it can be the best solution for a database schema if you want efficient retrieval, or the caller doesn't necessarily know the type of each key.

Note that your solution would require more columns for the same data, and also require the caller to know which type to retrieve (or to check all the alternative fields to find out which one is not NULL). Therefore I would go with (a) or (b) instead, depending on what your typical usage pattern will be.

Title: DB table with column for each datatype


答:
My advice is to find a job doing what you are interested in, and enjoy doing. If you enjoy PHP, why not continue to develop your PHP skills. It is much easier to learn and develop skills doing something that you are interested in.

Have you ever looked at .NET or Java before? If not, that might suggest that you aren't interested in those languages, but perhaps you could spend a week or so looking at each and see for yourself whether you are interested in either.


问:
Model-View-Controller: who caches the data?
I am building a GUI to interface an embedded device to a PC host. The GUI provides control over the device parameters and displays some feedback from it. The GUI also has to emulate some of the device functionality and present it to the user.

I have been advised to use a Model-View-Controller pattern, so that if the device does not acknowledge some command, the the user knows about the ineffectiveness of his actions.

Trouble is, I cannot decide which component(s) should cache data. Example: when a value is printed on the screen, the view clearly has to know it. However, the model also has to know it, as it uses it to calculate other values. Furthermore, the controller also has to know it as, for example, the value change could be proportional to a logarithm of the user action.

How do I pull this off properly?

答:
The view has to know it only in a way of how to show the information to the user. It doesn't really know whether it is a weather temperature, some random text, or anything else. It doesn't interpret data in any way.

The model is the one that stores and process data. And it knows whether to enable or disable a control. In your case, you need to cache data in the model.

The controller controls model and view layers. It is the one that can enable or disable a control in the view by using the value from the model. And it sets all the values in the view by just passing them from the model.


问:
Are there strategies for discovering REST services using HATEOAS?
When building a REST service with the HATEOAS constraint, it's very easy to advertise the existence of resources through linking. You make a GET to the root of my site and I respond with the root document listing all the first-tier resources:

```<code>{
    users: { href: "/users" }
    questions { href: "/questions" }
}
</code>```

Clients which understand how to read these href values could perform GET requests on those and discover all the current resources available in the application.

This works well for basic lookup scenarios, but doesn't indicate whether a resource is queryable. For example, it may be reasonable to perform:

```<code>GET /users?surname=Smith
</code>```

Are there any formats that could express this query ability with enough information that a client could form a coherent query without needed prior knowledge of the resource?

Additionally, is there any way to express that a client is allowed to perform a POST to a given location with an expected location. For example, it could be expected that a client perform the following to create a new question resource:

```<code>POST /questions

{
    title: "Are there strategies for discovering REST services using HATEOAS?",
    body: "When building a REST service with the HATEOAS constraint, it's very..."
}
</code>```

When using HTML as the format for human consumption, we can express a lot of this through use of forms and written prompts to allow a human to discover the operations they are allowed to perform on a service.

Are there formats which are capable of similar things for clients?

答:
You can publish details on your services through a "WADL"

http://en.wikipedia.org/wiki/Web_Application_Description_Language

It's optional and not every backend REST technos supports this. Jersey, the "official" java implementation of jax-rs, supports it for example - it can be automaitcally generated for you.

It's quite rare though, to see it used.

I don't know of big ones using it. In general you have a web page describing the api.


问:
Is there an industry standard for systems registered user permissions in terms of database model?
I developed many applications with registered user access for my enterprise clients. In many years I have changed my way of doing it, specially because I used many programming languages and database types along time.

Some of them not very simple as view, create and/or edit permissions for each module in the application, or light as access or can't access certain module.

But now that I am developing a very extensive application with many modules and many kinds of users to access them, I was wondering if there is an standard model for doing it, because I already see that's the simple or the light way won't be enough.

答:
As you said there are many kinds of users that you need to support. There are different types of systems that implement this feature, for example you ask for a database model, but there are also systems based on files, LDAP, web services.

The best you can do is to abstract properly the needs of your application regarding the user permissions and then adapt the implementations to support the needed frameworks.

I would start with something as simple as

```<code>public interface UserPermissionsManager{
     void addUser(String userId);
     List<String> listUsers();
}
</code>```

Your first implementation could use a file or a database. If you discover that another database schema is better you can migrate it without affecting your code. Your code will not change even if you migrate to LDAP (except the UserPermissionsManager).

Body:
As you said there are many kinds of users that you need to support. There are different types of systems that implement this feature, for example you ask for a database model, but there are also systems based on files, LDAP, web services.

The best you can do is to abstract properly the needs of your application regarding the user permissions and then adapt the implementations to support the needed frameworks.

I would start with something as simple as

public interface UserPermissionsManager{
     void addUser(String userId);
     List<String> listUsers();
}

Your first implementation could use a file or a database. If you discover that another database schema is better you can migrate it without affecting your code. Your code will not change even if you migrate to LDAP (except the UserPermissionsManager).


答:
How would you know what kind of inputs are acceptable? That is to say, if your client has no prior knowledge, how would you define the semantics of "surname"? You're starting to get into the territory of needing something like OWL.

I think it's more practical to expect your clients to understand the semantics of well-known mime-types; say, for example, "text/vcard" for people.

Body:
When building a REST service with the HATEOAS constraint, it's very easy to advertise the existence of resources through linking. You make a GET to the root of my site and I respond with the root document listing all the first-tier resources:

```<code>{
    users: { href: "/users" }
    questions { href: "/questions" }
}
</code>```

Clients which understand how to read these href values could perform GET requests on those and discover all the current resources available in the application.

This works well for basic lookup scenarios, but doesn't indicate whether a resource is queryable. For example, it may be reasonable to perform:

```<code>GET /users?surname=Smith
</code>```

Are there any formats that could express this query ability with enough information that a client could form a coherent query without needed prior knowledge of the resource?

Additionally, is there any way to express that a client is allowed to perform a POST to a given location with an expected location. For example, it could be expected that a client perform the following to create a new question resource:

```<code>POST /questions

{
    title: "Are there strategies for discovering REST services using HATEOAS?",
    body: "When building a REST service with the HATEOAS constraint, it's very..."
}
</code>```

When using HTML as the format for human consumption, we can express a lot of this through use of forms and written prompts to allow a human to discover the operations they are allowed to perform on a service.

Are there formats which are capable of similar things for clients?


问:
What is the most inspiring speech from a developer you ever watched?
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)

答: Integration Tests are a scam made me realize how unit tests are supposed to be written.</p>


问:
Regaining my spark on a project
So I'm in a little bit of a pickle. I suppose some people have gotten in my situation at some point, I know but at least as many have kept going for various reasons. To put the problem shortly; I am stuck in a project which I have after several attempts of "new fresh attitude" ended up drained out of energy and creativity and been less productive than I wish I were.

The scenario is this; I had earlier been handed a, in my opinion, half done project made in Drupal. At first it had really terrible code, but I managed to get them to clean it up a bit first. Needless to say, a poorly constructed house full of used clothes and thrash is still a poorly constructed house even without the used clothes and the thrash.

My hope currently is to regain that spark I have for all of my other projects that lets me work effeciently and mainly gets things done. In this case, I have little to none interest in working with this project. Here are some reason:

The code have quite some room for improvements. The only things that I find acceptable are the things contributed from Drupal, which are simply implemented into this project. Most custom things made in it is nothing I cherish.

I can't push myself to endure it, because I know this project will be something I'm forced to work with in the long term. In the same way I can't push myself to run the last mile of a marathon faster if I know I have to walk the entire way home afterwards.

I've read up quite a bit regarding people's opinion upon Drupal, and have came to the conclusion that Drupal is great if you have the right mindset for it. I don't have that mindset.

I prefer to create as much as possible myself and simply let a framework such as CodeIgniter worry about the process. It helps me be more confident with my code and less dependent on a module fetched from somewhere.

I generally don't believe in the project. It already takes silly long time to load, weird bugs appears from time to time that I can't even solve through google effeciently. It feels like the best thing I can do with the project is to patch it up, but I strive to do great websites, not make bad ones less bad.

Drupal has a long learning process, and I've been put in the middle of a half made project and am supposed to implemented more advanced features. Usually I have no problem to add these things in my other projects, but in Drupal it feels close to impossible often.

Apart from this, I might add that I'm currently economicly independent and don't fear loosing my job for that reason. I generally have nice colleagues but I work alone as a developer and would prefer to have at least someone whom I could discuss technical solutions with.

This project isn't something that will go away from my understanding, I've sat down with my boss, explaining how I feel regarding this project but all I get in reply is "We've spend too much time and money on this project. It needs to get completed." From my point of view, we're currently throwing money into a pit, hoping that the money will reach the surface sooner of later.

Question:

How can I regain the spark for this project? The creativity simply isn't there for me. This project won't give me much knowledge that I will have use of in the future (I have maintained lots and lots of code for 3 years) and it doesn't lead me towards my goal; to create "the perfect website".

If I can't regain the spark, what other alternatives should I consider?

Note:

I am aware that this question can seem too localized, but I think my main question can help many in a similiar position. I'm sorry if I sound like a spoiled developer who only wants to take on specific tasks, but I work so much better with project I'm comfortable with and I also like being productive.

答: I have experienced the same thing, it came to a point where I had this feeling same This project won't give me much knowledge that I will have use of in the future. But I when look more into it, it's not the project that is the problem but me. It gave more insight into my personality as a developer. Usually when things like this happen I talk to my lead or the management and discuss my concerns, if they won't take me off the project I simply rewrite the components that get in my nerves.

Title: Regaining my spark on a project


问:
Is fewer lines of code always better?
Which of these programming styles is better?

```<code>var result = methodOne(methodTwo(a, methodThree(b)), c, d);
</code>```

or

```<code>var result3 = methodThree(b);
var result2 = methodTwo(a, result3);
var result = methodOne(result2, c, d);
</code>```

答:
This is one of those issues I think were you get to decide which way that works for each separate case. Deciding if a particular result should be stored in an intermediate variable is part of being a programmer, part of the craft. You use the skills you have acquired together with coding standards at your workplace.

In the two contrived examples below, I would probably go with 1A and 2A, because of readability (too much noise and redundancy in 1B, too long and indirect usage of an anonymous array in 2B). But you can't really come up with any exhaustive list of patterns where you can stipulate one way over the other - new situations arise all the time as the art of programming progresses.

```<code>1A:
startManufacture(loadProductName(), isProductOk(loadProductState()));

vs.

1B:
String productName = loadProductName();
ProductState state = loadProductState();
boolean productIsOk = isProductOk(state);
startManufacture(productName, productIsOk);

2A:
boolean antennaCount = storage.getCount(currentDealer, items[ANTENNA_INDEX]);
boolean chassisCount = storage.getCount(currentDealer, items[CHASSIS_INDEX], EXTERNAL_SHIPPING);
orderManufacture(RADIO, antennaCount, chassisCount);

vs.

2B:
orderManufacture(RADIO, storage.getCount(currentDealer, items[ANTENNA_INDEX]), storage.getCount(currentDealer, items[CHASSIS_INDEX], EXTERNAL_SHIPPING));
</code>```

Title: Is fewer lines of code always better?

Body:
This is one of those issues I think were you get to decide which way that works for each separate case. Deciding if a particular result should be stored in an intermediate variable is part of being a programmer, part of the craft. You use the skills you have acquired together with coding standards at your workplace.

In the two contrived examples below, I would probably go with 1A and 2A, because of readability (too much noise and redundancy in 1B, too long and indirect usage of an anonymous array in 2B). But you can't really come up with any exhaustive list of patterns where you can stipulate one way over the other - new situations arise all the time as the art of programming progresses.

1A:
startManufacture(loadProductName(), isProductOk(loadProductState()));

vs.

1B:
String productName = loadProductName();
ProductState state = loadProductState();
boolean productIsOk = isProductOk(state);
startManufacture(productName, productIsOk);

2A:
boolean antennaCount = storage.getCount(currentDealer, items[ANTENNA_INDEX]);
boolean chassisCount = storage.getCount(currentDealer, items[CHASSIS_INDEX], EXTERNAL_SHIPPING);
orderManufacture(RADIO, antennaCount, chassisCount);

vs.

2B:
orderManufacture(RADIO, storage.getCount(currentDealer, items[ANTENNA_INDEX]), storage.getCount(currentDealer, items[CHASSIS_INDEX], EXTERNAL_SHIPPING));


问:
ado.net or EF for a point-of-sale system
We have a point-of-sale system that was developed using ado.net, our current concern is to make the application real fast in creating transactions (sales). Usually there are no performance concerns with high end PCs but with with low end PCs, the transactions take really slow.

The main concern is on saving transactions which usually calls a lot of stored procedures for inserting records within a single transaction. This usually takes time on low end PCs. We need to improve the performance since most clients will only use low end PCs to act as cashier machines. One solution we are thinking is to use entity framework for data access. The entire project is written using ado.net and development time if we shift to entity framework would be alot. Any suggestions?

答: If you are looking for performance stay away from EF. It is the slowest ORM out there and uses a lot of memory to keep the database metadata. Most benchmarks out there show that - </p>


答:
Blog About Your Experience

You could blog about how best to use drupal. You have more than enough examples on how you would convert crappy drupal code to great drupal code. This would accomplish a few things...

You would have an updated, well functioning application in the end

You would be educating the masses on what to do and what not to do in drupal

You would create a drupal following

You would stay engaged

I got burned out on writing code... any code. I was so burned out I wouldn't even check my email when I came home at night. After 9 years I started to get back into writing code. A lot changed in 9 years. The language I used grew by leaps and bounds. Screen resolution went from 640 X 480 to almost endless. Google replaced bookstores. I found myself in a completely different environment.

It's like I had to learn all over again. It's like I was given an opportunity to go back and do it over again. So I embraced it. I'm having fun and I'm doing it for me... if others benefit then great. Here's my blog

Similar but different situation

Title: Regaining my spark on a project

Body:
So I'm in a little bit of a pickle. I suppose some people have gotten in my situation at some point, I know but at least as many have kept going for various reasons. To put the problem shortly; I am stuck in a project which I have after several attempts of "new fresh attitude" ended up drained out of energy and creativity and been less productive than I wish I were.

The scenario is this; I had earlier been handed a, in my opinion, half done project made in Drupal. At first it had really terrible code, but I managed to get them to clean it up a bit first. Needless to say, a poorly constructed house full of used clothes and thrash is still a poorly constructed house even without the used clothes and the thrash.

My hope currently is to regain that spark I have for all of my other projects that lets me work effeciently and mainly gets things done. In this case, I have little to none interest in working with this project. Here are some reason:

The code have quite some room for improvements. The only things that I find acceptable are the things contributed from Drupal, which are simply implemented into this project. Most custom things made in it is nothing I cherish.

I can't push myself to endure it, because I know this project will be something I'm forced to work with in the long term. In the same way I can't push myself to run the last mile of a marathon faster if I know I have to walk the entire way home afterwards.

I've read up quite a bit regarding people's opinion upon Drupal, and have came to the conclusion that Drupal is great if you have the right mindset for it. I don't have that mindset.

I prefer to create as much as possible myself and simply let a framework such as CodeIgniter worry about the process. It helps me be more confident with my code and less dependent on a module fetched from somewhere.

I generally don't believe in the project. It already takes silly long time to load, weird bugs appears from time to time that I can't even solve through google effeciently. It feels like the best thing I can do with the project is to patch it up, but I strive to do great websites, not make bad ones less bad.

Drupal has a long learning process, and I've been put in the middle of a half made project and am supposed to implemented more advanced features. Usually I have no problem to add these things in my other projects, but in Drupal it feels close to impossible often.

Apart from this, I might add that I'm currently economicly independent and don't fear loosing my job for that reason. I generally have nice colleagues but I work alone as a developer and would prefer to have at least someone whom I could discuss technical solutions with.

This project isn't something that will go away from my understanding, I've sat down with my boss, explaining how I feel regarding this project but all I get in reply is "We've spend too much time and money on this project. It needs to get completed." From my point of view, we're currently throwing money into a pit, hoping that the money will reach the surface sooner of later.

Question:

How can I regain the spark for this project? The creativity simply isn't there for me. This project won't give me much knowledge that I will have use of in the future (I have maintained lots and lots of code for 3 years) and it doesn't lead me towards my goal; to create "the perfect website".

If I can't regain the spark, what other alternatives should I consider?

Note:

I am aware that this question can seem too localized, but I think my main question can help many in a similiar position. I'm sorry if I sound like a spoiled developer who only wants to take on specific tasks, but I work so much better with project I'm comfortable with and I also like being productive.


问:
Synchronization in the given Code
I had an interview few weeks back, and I was asked to write a code with Setters and Getters. I had written the following code;

```<code>// Just an example

Class ABC{
    private int num;

    public void setNum(int givenNum){
        this.num = givenNum;
    }

    public int getNum(){
        return num;
    }

    public ABC(){
        num = 0;
    }

    public static void main(String [] args){
        ABC object1 = new ABC();
        ABC object2 = new ABC();

        object1.setNum(5);
        System.out.println(object1.getNum());
        System.out.println(object2.getNum());
    }
</code>```

}

Now I was told, that "object1" can change the value for "object2.Num".
But I was not in agreement with this, I believe another thread which has access to object2 can change the value of object2.Num but not object1.

In the above case, I would have synchronized the setter method, or use the synchronized block inside the setter method while setting/changing the value, but I could not understand the concept of object1 changing the value of object2.Num.

I was just curious if I was missing on something. If so I would really appreciate any help regarding the same.

答:
If all you have is a reference to object1, then no, you can't change object2.num.

The only thing that comes somewhat close to what you describe would be things like this:

```<code>public void swap(ABC other) {
  int num = this.num;
  this.num = other.num;
  other.num = num
}
</code>```

Suche a code could modify two ABC objects: this (i.e. the object on which it's called) and other (the parameter). But this doesn't have anything to do with multithreading either.

Title: Synchronization in the given Code

Body:
If all you have is a reference to object1, then no, you can't change object2.num.

The only thing that comes somewhat close to what you describe would be things like this:

public void swap(ABC other) {
  int num = this.num;
  this.num = other.num;
  other.num = num
}

Suche a code could modify two ABC objects: this (i.e. the object on which it's called) and other (the parameter). But this doesn't have anything to do with multithreading either.


答:
Synchronization is not the relevant concept here. You synchronize things to prevent errors caused by the unforeseen order of actions caused by interleaving different threads. The classical example is decreasing the balance of one bank account and increasing another by the same amount, which can lose information (money) if not done atomically. But this code merely assigns an integer, which is already atomic, so the point is not inconsistency.

They were probably talking about access control and the somewhat surprising fact that private means "private to all instances of the class" and not "private to to the owning instance only" in java. object2 can change the value of a field in object1 if it has a reference to object1. But this has nothing to do with synchronization.

Title: Synchronization in the given Code

Body:
I had an interview few weeks back, and I was asked to write a code with Setters and Getters. I had written the following code;

```<code>// Just an example

Class ABC{
    private int num;

    public void setNum(int givenNum){
        this.num = givenNum;
    }

    public int getNum(){
        return num;
    }

    public ABC(){
        num = 0;
    }

    public static void main(String [] args){
        ABC object1 = new ABC();
        ABC object2 = new ABC();

        object1.setNum(5);
        System.out.println(object1.getNum());
        System.out.println(object2.getNum());
    }
</code>```

}

Now I was told, that "object1" can change the value for "object2.Num".
But I was not in agreement with this, I believe another thread which has access to object2 can change the value of object2.Num but not object1.

In the above case, I would have synchronized the setter method, or use the synchronized block inside the setter method while setting/changing the value, but I could not understand the concept of object1 changing the value of object2.Num.

I was just curious if I was missing on something. If so I would really appreciate any help regarding the same.


答: It looks as if you are looking for reasons to quit and you have quite a few of them already. I'd say quit. Do it. If you have to work on an inherited, crappy project that you don't want to improve and it doesn't teach you anything you really want to know and it's also for the long term, I'd say just be good to yourself and treat yourself to a new job. Preferably one that has interesting projects and a better pay :)</p>

Title: Regaining my spark on a project


问:
One web service multiple sites
I don't know whether this is even possible or I imagine (according to my habit of over thinking) will bring through numerous issues but let me give it a go.

I have an idea where I would like a single web service which a user will send a request to, for example logging in. The response back dictates a URL where they get redirected too so essentially this means for me less maintenance in updating web services etc as its all in one place.

What I am trying to do is have a single service that routes people to the correct server to get data from instead of having the end user to have knowledge of the endpoint address etc.

For example, I have a system on the web and want it visible to my windows, android and apple devices but there is a specific site for each client. Ideally, I only want the user to enter their login credentials and the web service does the rest, i.e. fetches data from the correct data source.

I imagine this is common practice for many systems but I guess is there a risk factor in that a user being sent data from another request if they happen at the same time? Obviously this is a huge flaw and perhaps I am going completely the wrong route here.

I would appreciate any resources to links, books etc. I was unsure of what to search for on the web so thought this is the best place for such questions.

This is a system I am developing to help me understand web services better in general. A little project I am working on to help me explore different techniques and approaches towards development :)

答: What you are describing is a service oriented architecture, but your requirements are a bit vague. Is it possible to create a centralized authentication service for multiple applications that returns redirect URLs? Of course.Your concern about one request receiving the data of another person's (or application's) request is unlikely to become an issue. Your web server will make sure the correct response stays tied to the correct request. </p>

Title: One web service multiple sites