答:
The compiler (typically) works in several phases, the first being the "parsing" stage. During the parsing stage, the program is converted to an internal representation, usually referred to as an "Abstract Syntax Tree" (AST), that the remainder of the compiler stages work on.

The parsing step is, essentially, proportional to the amount of source code needed to be read. In this stage, the length of a variable name has (some) impact.

However, the time-consuming parts of the compiler tend to exclusively operate on the AST, where the speed of processing is independent of the length of identifiers.

So while it does have some impact, I'd expect typical (large) programs to have a compilationg time that is essentially-independent of identifier lengths.

Title: What process do typical (the majority) of high level language compilers use when changing a source-code's variable name to a machine code name?

Body:
Do long (very long) variable names slow down the compilation of source code?

I'm aware that the length of variables has 0% impact on interpretation as the compiler changes them to machine code which is always the same length. But my question is, does the speed at which the compiler vary depending on the length of variables?

For example, if I have a variable name which is a million characters long, surely the compiler would struggle as for it to recognise the variable is a variable, it would need to read the entire thing first which would surely take longer depending on its size?

To clarify, what process do typical (the majority) of high level language compilers use when changing a source-code's variable name to a machine code name?

Do they find the start of the variable working from the left and then find the end working from the right, do they read through the entire variable name (one character at a time) until the end is found or do they not even look at the variable name at all and just know that the code requires a variable of type int (for example) and assign it a machine-level name instantly and then completely ignore any user-defined variable names?

Note that I am a complete novice (still a student) so excuse my ignorance if I get my terms mixed up.


问:
Can I run both .Net and Java framework in one computer?
I have .NET 2.5 installed in my computer unit, as a beginner I used VB.net
As I went along I've also installed new .dlls that would help me with my VB.net programming
Now, I want to study java as well, leading to Android programming.

If I install the JDK 7.0, can I still be able to program in VB.net? Will installing JDK overwrite .dlls essential to the .NET framework? Should I get a new developing PC that focuses with JAVA/Android development?

答:
Yes, you can use both the frameworks without any problem as they never affect each other, so just install and start your development.

Also, make sure that you install the latest versions of each framework in order to avoid any problems later.

OwnerDisplayName: anon

ContentLicense: CC BY-SA 3.0


问:
good replacement for commenting out code?
It bothers me to see commented out code and it seems often-times a symptom of developers not being proficient in advanced source control features, but on the other hand source control does not really go all the way in solving the problem that commenting out is intended for.  I've occasionally seen requirements flip-flop in such a way that code that would have been deleted suddenly is needed again.  If the code is really deleted, there doesn't seem to be a clear procedure for locating exactly where to find that deleted code in source control.

Is there a better way out there to save developer work that may be needed again besides the tried-and-true "commenting out"?

答:
My pragmatic approach is to say its fine to comment out code and check it in. This has the benefit of being able to see the previous code immediately present to anyone looking (as we know, bugs are often introduced and found straight away, so if you leave some old code in there, anyone looking for a bug will be much more likely to spot where the offending change might be).

However, I also have the thought that any commented out code can be deleted when you next check it out for editing. So if you get some code and see commented out code, then its now past its usefulness and can safely be deleted. Commented out code should then only live for 1 checkin. (of course, you don't checkin code that only has its commented code removed, only if you change the area around it as you should never see that commented-out code if you never have to look at the code again).

Obviously its a very rough guideline, and I only comment out code I think is a bit hairy anyway.


答:
If you know that the code may be used again, I would refactor it out as an unused method and document the fact that it is available for possible future use.

If it must or should be removed, then I would consider using some form of tagging or a standard comment like REMOVED:, which is searchable later.

Title: good replacement for commenting out code?

Body:
It bothers me to see commented out code and it seems often-times a symptom of developers not being proficient in advanced source control features, but on the other hand source control does not really go all the way in solving the problem that commenting out is intended for.  I've occasionally seen requirements flip-flop in such a way that code that would have been deleted suddenly is needed again.  If the code is really deleted, there doesn't seem to be a clear procedure for locating exactly where to find that deleted code in source control.

Is there a better way out there to save developer work that may be needed again besides the tried-and-true "commenting out"?


问:
Sync / send data between front end and back end systems for an Ecommerce site
A client recently had a new backend .net stock management system developed that hooks into their EPOS and allows their stores to keep track of orders, products, customers, etc from a single central database that utilizes MS SQL Server 2003. The client hopes to use this as an opportunity to renew/re-develop their site to also utilize this centralized back end database.

I have experience with e-commerce, but this is my first time developing a site that needs to work with the companies back end systems.

I had been hoping to use an off the shelf platform such as Magento to make the development process smoother and allow for easy upgrades and the use of plugins/modules in the future. However, having looked at the schema for their new backend systems it is apparent that there could be several problems. Their database has a lot of design issues, the tables are badly normalized, and their approach to the database design seems dated to me.

If I was to use an off the shelf platform like Magento, the only way I can see it working is to re-create all the products/categories/customers in the front end DB, this may have to be done manually because of the differences in schema between the backend (centralized db) and frontend(magento db). That would be a mamoth task, and would create a new problem of how to deal with the replication of data (products, stock levels, prices, orders, order statuses). The client currently manages all the products and order data on their .net system and wants to continue to do so, so there would need to be a way to update the sites db when they make changes to their back end systems (E.G in the case order has been shipped/canceled/etc). Like wise the centralized database would need to be updated from the front-end when a customer makes an order, updating stock levels, etc. These are just two examples of data that will need to be synchronized, but their are countless other scenarios.

Does anyone have experience working with Magento or other platforms in situations similar to the above? How did you deal with data replication and sending data between the back end centralized db and Front end db?

I am having a hard time wrapping my head around the best setup/architecture for a site like this, any pointers in the right direction would be really appreciated.

In retrospect I can't help but feel the best solution would be to create an in-house platform from scratch that can directly connect to their centralized database instead of using an off the shelf platform and worrying about syncing data between backend/frontend. Any thoughts?

答:
I would not allow the front-end to connect to the mission-critical database directly. This is a security-issue. Your front-end normally is in the "wild" (public internet) and therefore target for hackers all the day. If one comes through your productive database gets hacked and the company is standing still.

In such situations I always would introduce a tight backend-API to use from the front-end. The front-end can only access backend-stuff to this API; no other way! The API needs to be type-safe and as small as possible - put in only what is really needed. Make API functions for your use-cases is good start (eg. AcceptOrder(Guid orderno). No generic API's where one can manage to inject general queries and logic. In the backend consider every incoming API-Parameter as potentially hacked. This means for example escape them before sending it to any db-engine etc.

The question if you you need a explicit frontend db aside the backend-API depends mainly on the performance of API / network between front- and backend and if the frontend shows data from only one backend-source. In a e-commerce solution it is likely you need one because of performance. In this case I would look at the frontend database as kind of a server side data-cache. Some of the data is can be cached easely (eg. lookup values like categories etc.) others are more tricky (like how many items on stock). Maybe some of them can not be cached in a front-end db at all.

As a start of evaluating the best synchronization strategy I would analyse every table in combination with the use-cases. How often are they used? How short-living/how often does it change is the data within them? etc. I would not do a general two way sync between the databases. Dumping parts of the backend-db to the frontend-db is ok but never do a dumb dump from frontend- to backend-db (security).

Hope this helps a little bit or at least gives you input for your thoughts. Some hard decisions are ahead of you ;-)

Update on SOAP:
SOAP would not be the worst technique for this but also not the one with the highest performance; at least not out of the box. Designing a SOAP-API needs some extra thoughts as well like authentication-stuff and bundling lot of data into a few SOAP-calls (SOAP calls are "expensive" so don't try to do thousands of them in a second ;-) )

SOAP ia a standardize protocol and therefore can be used in a lot of programming languages on a lot of platforms. If you know your platform and have both end (frontend and backend) and your control you may find a protocol that more native to your technology-stack and therefore faster. You then can even code your own TCP if you like but be careful with this as it will also need a good authentication and security.

I would start with SOAP or a more native one of my programming-stack (eg. .Net: WCF Binary). You can also think about a REST-API (WebAPI in .Net).

Update on pushing data from backend to frontend:
I would consider this only for data that changes a lot and the current value is important. For example the backend can report stock-counts to the front-end. But somehow it feels wrong to me as the backend needs do work for front-end even if there is not one single user on the front-end. So you have permanent work-load on the backend. These things really depends on a lot of details of your project and its use-cases, I would say. Its hard to answer them generally.


问:
Animation in Swing
I have a project written using Swing, and I want to make it more smoothly (like JavaFX is) by adding animation to some components(JButton, JScrollPane, JSplitPane) using javax.swing.Timer.

UPD: That is not a game. I want to use the Timer for short animations like mouseHover events or dropdown, or scroll. But the problem is, a lot of Timer objects should be created.

Question: What action does it perform for JVM? I would start and stop a lot of Timers during app session.

答: Yes if you wanna do the animation yourself, javax.swing.Timer is your best option. It is lightweight and guarantees your code executes on the EDT thread. If you venture into the depths of swing components like JScrollPane you might encounter javax.swing.Timer being used for things like auto scrolling during drag and drop etc. In short animation in swing is quite possible but rare in standard components. Just keep your redraw area to the minimum and repaint wisely. I would advocate looking into timing framework though.

Title: Animation in Swing


问:
When to use repository pattern
I have read recently that it is not good practice to use the repository pattern in conjunction with an ORM. From my understanding this is because the abstraction they provide over the SQL database is too leaky to be contained by the pattern.

I have a couple of questions about this:

What do you do if you want to switch out ORMs? You would have ORM specific code in your application if you do not contain it in a repository.

Is the repository pattern still valid when not using an ORM and you are using ADO.NET for data access and populating object data yourself?

If you use an ORM but not the repository pattern where do you keep commonly used queries? Would it be wise to represent each query as a class and have some sort of query factory to create instances?

答:
1)True, but how frequently do you switch out an ORM?

2)I would say so, because an ORM context is sort of a repository and hides a lot of work involving creating queries, retrieving data, mapping, etc. If you don't use an ORM, that logic still has to reside somewhere. I don't know if that would qualify as the repository pattern in the strictest sense of the word though...

3)Encapsulating queries is something I see frequently, but that's usually more for testing/stubbing purposes. Other than that, I would be careful when reusing a query across different parts of an application, because then you risk creating a dependency on something which could change n-times (n being the number of places where you use the query).

Title: When to use repository pattern


问:
Etiquette for editing someone's pull request
I own a repository on GitHub to which someone sent a pull request with one single commit. I only want to implement his solution partially, and use about half of the code changes the user made. What should I do in this situation?

Make a branch of his version, then go back and copy and paste the "old" code that I want to preserve from the original version into a second commit. This may make the diff between commits look larger than it really is, and throw off things like git blame.

Copy and paste the code I want to keep from his commit into a new, different commit. This means that he does not receive credit for his valuable contribution to the code.

Same as the above, copy some of his code into a new commit, but change the author of the commit to him instead of me. He technically didn't write the exact code that was committed, so I'm not sure if this is frowned upon. But at least he gets attribution for those lines that are used.

答:
I'd go with option 4: explain to the contributor why his pull request doesn't fit the project's goals (and in the process give the contributor a chance to explain why he thinks it does) and ask him to resubmit a new version containing only the changes which fit the project.

This has three benefits:

You don't have to do the work ;-)

The contributor will get a better understanding of your goals, making it more likely that future contributions don't need any changes

In addition to retaining a sense of ownership, the contributor is acknowledged and recognized as having made a useful contribution. All of which makes them more likely to continue to contribute


问:
Business rule to display data in all uppercase - how to handle?
Part of a system I am working on manages some securities information (stocks, bonds, etc...) and business rules specify certain fields be displayed only in all CAPS (stock symbols and CUSIPs for example). Users will have to look at data displayed on the screen as well as perform create/edit data-entry operations.

Where is the best place to deal with this?

1. Presentation layer only

user enters "ibm" as stock symbol, stored in database as "ibm", converted to uppercase when displayed in app ("IBM")

2. Convert to CAPS before storing in DB

user enters "ibm", model class converts to uppercase and sends to database, stored as "IBM"

Something like a custom setter:

```<code>private string _StockSymbol;
public string StockSymbol
{
    get { return _StockSymbol; }
    set
    {
        if (value != null)
            value = value.ToUpper();
        _StockSymbol = value;
    }
}
</code>```

3. Convert to CAPS at DB

user enters "ibm", database insert query converts to "IBM" (for example, using the UPPER function in SQL)

The end result is the same for the users - they see their data in all CAPS and the system doesn't care if their data input is in the proper case or not. The most "MVC compliant" answer seems to be #1, but if this data will never be used in any other format other than all CAPS, I would argue it should be validated as such before being stored in the database. That then becomes more of a controller or view model concern, right?

I've heard people speak about accomplishing this client-side with Java (and even CSS), but that seems like a very poor solution.

I think the question is language/system-agnostic, but if it matters, I'm using MS SQL with Entity Framework/ASP.Net MVC.

What I'm scratching my head over is whether or not a presentational business rule like this should influence how the data is stored in the DB (CAPS vs no CAPS). The application doesn't care if the stock symbol IBM is input as "iBm" or "ibM" but it seems wrong to store the data like that (it will only ever be used/displayed in CAPS).

Would you consider this a data validation issue to be handled at the controller/model level, or a presentational detail to be handled only at the view?

答:
I think it's good to have the same data always formated the same way in the database.

There are many cases where an application might care about whether something is formatted as "iBm" or "ibM". After all "iBm"!="ibM"

A developer who asks the database for the name of a stock can reasonably expect that the same stock is always formated the same way. Especially if a lot of data is stored in uppercase, his application might have bugs if a few examples don't come formatted as expected. That might introduce bugs.

The database therefore shouldn't allow you to add data that isn't correctly formatted, so you should solve the problem at the database layer.


问:
Choosing the right resources
Once I heard that a good book on any programming language cannot be short, so the number of pages is the first criterium when choosing a tutorial.

The statement was half a joke, but it has some truth in it. There are tens and hundreds of books available for most popular programming languages, frameworks and technologies, and it is hard to choose one. So that dummy condition is the first one to check.

Are there any criteria to help choose the "right" tutorials? What is the first (or probably the second) thing to pay attention on when choosing a technical tutorial?

答:
I look for:

The ones that build programming languages obviously have the information and a vested interest and sometimes publish books.

For example, If it's C, then look for the authors Dennis Ritchie and Ken Thompson.

If it's a Microsoft programming language such as C#, look for books by Microsoft.

Well known publication houses.  For example, I generally like the O'Reilly books.

Sites like codeacademy.com and khanacademy.org.

Title: Choosing the right resources


答:
There are various metrics that can be helpful:

Does the resource make absurd promises? If the title is “Learn X in Y days”, it is probably crap.

Does the community of that technology maintain an index of especially good (or bad) resources? It is worth listening to such opinions.

Is the author well known in that field? If so, this can be a positive indicator, but be aware that brilliant people aren't necessarily good teachers.

Is the layout and formatting of that resource professional and geared towards easy understanding? I shit you not, I have seen language tutorials that don't even use code indenting. If a website looks like it's from the 90s, there is a chance the content may not be up to date either.

If there are many orthographic and grammatical errors then the resource probably wasn't reviewed. On the other hand, the content may be excellent, but the author just isn't a native speaker.

Does the resource ignore or embrace best practices of that technology? Does it use deprecated functionality? Of course, these questions can only be answered when you already know that technology.

How old is the resource? Best practices evolve constantly. Some resources have a timeless quality, but more often anything > 5 years old will be out of date in some respect. This is a proxy indicator for the previous point, not an absolute rule.

Title: Choosing the right resources

Body:
Once I heard that a good book on any programming language cannot be short, so the number of pages is the first criterium when choosing a tutorial.

The statement was half a joke, but it has some truth in it. There are tens and hundreds of books available for most popular programming languages, frameworks and technologies, and it is hard to choose one. So that dummy condition is the first one to check.

Are there any criteria to help choose the "right" tutorials? What is the first (or probably the second) thing to pay attention on when choosing a technical tutorial?


答:
I think it pretty much comes down to whether the uppercase-ness is a display requirement or a property of the data itself.

To take a different example, if it was necessary to display a name with the surname uppercase for emphasis, I would capitalise it in the output UI, as in your (1). This is a display requirement as surnames are not 'naturally' uppercase - other views might use the original capitalisation.

To get back to your case, although I'm not an expert on stock symbols but as far as I understand it they are always uppercase. That is, a stock symbol is inherently uppercase, and so I would check this as part of the input validation, as in your (2).

Title: Business rule to display data in all uppercase - how to handle?

Body:
Part of a system I am working on manages some securities information (stocks, bonds, etc...) and business rules specify certain fields be displayed only in all CAPS (stock symbols and CUSIPs for example). Users will have to look at data displayed on the screen as well as perform create/edit data-entry operations.

Where is the best place to deal with this?

1. Presentation layer only

user enters "ibm" as stock symbol, stored in database as "ibm", converted to uppercase when displayed in app ("IBM")

2. Convert to CAPS before storing in DB

user enters "ibm", model class converts to uppercase and sends to database, stored as "IBM"

Something like a custom setter:

```<code>private string _StockSymbol;
public string StockSymbol
{
    get { return _StockSymbol; }
    set
    {
        if (value != null)
            value = value.ToUpper();
        _StockSymbol = value;
    }
}
</code>```

3. Convert to CAPS at DB

user enters "ibm", database insert query converts to "IBM" (for example, using the UPPER function in SQL)

The end result is the same for the users - they see their data in all CAPS and the system doesn't care if their data input is in the proper case or not. The most "MVC compliant" answer seems to be #1, but if this data will never be used in any other format other than all CAPS, I would argue it should be validated as such before being stored in the database. That then becomes more of a controller or view model concern, right?

I've heard people speak about accomplishing this client-side with Java (and even CSS), but that seems like a very poor solution.

I think the question is language/system-agnostic, but if it matters, I'm using MS SQL with Entity Framework/ASP.Net MVC.

What I'm scratching my head over is whether or not a presentational business rule like this should influence how the data is stored in the DB (CAPS vs no CAPS). The application doesn't care if the stock symbol IBM is input as "iBm" or "ibM" but it seems wrong to store the data like that (it will only ever be used/displayed in CAPS).

Would you consider this a data validation issue to be handled at the controller/model level, or a presentational detail to be handled only at the view?


答:
If some values are always in upper case I would store them in upper case for the following reasons:

To reduce the number of conversions in the code.

To decrease the
possibility that future updates to the code will not take the
Business Rule into account.

To make troubleshooting easier. If
    somebody in the industry is used to see certain things in upper
    case, it will make her live easier when debugging/troubleshooting if
    values show up in familiar format.

Having said that, I would convert on entry and validate/convert if necessary on the backend before saving to the database.


答:
DISCLAIMER: What follows is based on my understanding and brief experience of said pattern (Repository that is). I might be doing it wrong...in fact, I'm pretty positive that I'm doing it wrong :). So, while this is an attempt for an answer, it is also a question in disguise.

I'm using the Repository pattern to abstract away the data access layer, which is in most cases an ORM. It is a generic interface, with methods for Create, Read, Update, Delete and implementation classes for LINQ to SQL and EF so far. I could make an implementation that writes to XML files on disk (just a wild example of what I could do with it). I'm not implementing Unit of Work since it's supported by the ORM's. If need be, I could probably implement it. I like it this way because, so far, it has given me a nice separation. I'm not saying that there aren't better alternatives.

To answer your questions:

Whether you like it or not, change will occur. And if you've written a bunch of applications and time has come to maintain them, but feel that is a pain to work with the current ORM and want to change it, you'll praise yourself for making such an abstraction. Just use anything that you feel comfortable with, be it Repository or other pattern/concept.

Yes it is, as long as you use it to separate data access. Like I mentioned earlier, you can make an implementation that writes data in flat files.

I use the Repository to keep my commonly used queries and Query Objects for when I have queries that I want to tweak (which aren't that many).

To give you another example, the guys at Umbraco have abstracted away the DI container, just in case they might want to be switching over to something else.

Title: When to use repository pattern

Body:
I have read recently that it is not good practice to use the repository pattern in conjunction with an ORM. From my understanding this is because the abstraction they provide over the SQL database is too leaky to be contained by the pattern.

I have a couple of questions about this:

What do you do if you want to switch out ORMs? You would have ORM specific code in your application if you do not contain it in a repository.

Is the repository pattern still valid when not using an ORM and you are using ADO.NET for data access and populating object data yourself?

If you use an ORM but not the repository pattern where do you keep commonly used queries? Would it be wise to represent each query as a class and have some sort of query factory to create instances?


问:
How to design (just the outline) an enterprise class PHP application
For the last year or so, I have been working on a very large application. I am currently on version 17 of it, and every time, I start over with some of the code from before. But now, this is starting to become unmanageabley large.

When I do the design for the application, I generally start with a Word document, outlining all the classes, with the functions, descriptions for each, their dependencies, default configuration data, and how each component augments the rest of the application. But with that method, within a few hours, I can easily reach 20-30 pages of documentation, and the nice simple outline of the software because so complex in itself, using that as the template to write the code to becomes difficult.

So, now, I am trying to describe the application in an XML format, built on an XSD that contains the structure of how the classes will be laid out. But, this is also demonstrating its problems.

At this stage, everything ahead of the base application has been designed (the database er diagrams, the functionality, etc), but the main problems lies in the design of the underlying software that runs it all.

So, can anyone recommend what path I should go down, either with specific ways to lay out a Word document for easy reading, an XML pattern that would do the same, or some other software package that can do this for me and help guide me through the development?

Any help would be greatly appreciated, mainly because once this part has been cracked, my application can finally be built and completed.

Thanks

答:
What is the main purpose of the document you are creating. Are you the only developer working on the app or there is a team working with you?

Don't underestimate the power of visual presentation. A picture is
worth a thousand words. You could use some of the available UML
tools or a basic diagram tool.

Use naming conventions - this will reduce the need to document. For example, with DAO for all Data Access Classes. Then it will be self evident that UserDAO does all the operations pertaining to saving and retrieving user information from database.

Document in detail only what is not obvious.

A quick Google search found PHPDoc. This could help document implemented code


答:
I would store them always in lower case. This way you can assume you are always looking in DB for lower case word (in this particular case). The key is to be uniform in the DB. This avoid the issue Christian described.

This kind of thing are display issue only so you should format when you show the data to the user (#1 in your question). This offer more flexibility, if for X reason somewhere you would need to display those value with a different format then you could easily.


答:
1) What do you do if you want to switch out ORMs, you would have
  specific ORM code in your application if you do not contain it in a
  repository.

I haven't yet been in a position where company all of a sudden decided to switch data access technology. If this does happen, some work will be required. I tend to abstract data access operations through interfaces. Repository is one way to solve this.

I would then have a different assembly for concrete implementation of my data access layer. For example, I might have:

Company.Product.Data and Company.Product.Data.EntityFramework assemblies. First assembly would be used purely for interfaces, when another would be a concrete implementation of Entity Framework's data access logic.

2) Is the repository pattern still valid when not using an ORM and you
  are using ADO.net for data access and populating object data yourself
  ?

I think that it's up to you to decide which pattern is valid or not. I've used a repository pattern in the presentation layer. One thing to keep in mind is that people like to throw responsibilities into repositories. Before you know it, your repository class will be dancing, singing and doing all sort of things. You want to avoid this.

I've seen a repository class that started off by having GetAll, GetById, Update and Delete responsibilities, which is fine. By the time the project was complete, that same class had dozens of methods (responsibilities) which should have never been there. For example GetByForename, GetBySurname, UpdateWithExclusions and all kinds of crazy stuff.

This is where queries and commands come into play.

3) If you use an ORM but not the repository pattern where do you keep
  commonly used queries. Would it be wise to represent each query as a
  class and have some sort of query factory to create instances ?

I think it's a very good idea to have use queries and commands instead of repositories. I do the following:

Define interface for a query. This will help you unit test. E.g. public interface IGetProductsByCategoryQuery { ... }

Define concrete implementation for a query. You will be able to inject these through IoC framework of your choice. E.g. public class GetProductsByCategoryQuery : IGetProductsByCategoryQuery

Now instead of polluting repository with dozens of responsibilities, I simply group my queries into namespaces. For example, an interface for the above query may live in: Company.SolutionName.Products.Queries and the implementation may live in Company.SolutionName.Products.Queries.Implementation

When it comes to updating or removing data, I use command pattern in the same manner.

Some might disagree and say that before the project is complete you will have dozens of classes and namespaces. Yes you will. In my mind it's a good thing as you can browse through the solution in IDE of your choice and instantly see what kind of responsibilities certain component has. If you have decided to use a repository pattern instead, you will have to look inside each repository class trying to work out its responsibilities.

Title: When to use repository pattern


问:
How large non-OO code bases are managed?
I always see abstraction is a very useful feature the OO provides for managing the code-base. But how are large non-OO code bases are managed? Or do those just become a "Big Ball of Mud" eventually?

Update:

It seemed everyone is thinking 'abstraction' is just modularization or data-hiding. But IMHO, it also means the use of 'Abstract Classes' or 'Interfaces' which is a must for dependency-injection and thus testing. How non-OO code bases manage this? And also, other than abstraction, the encapsulation also helps a lot to manage large code bases as it define and restrict the relation between data and functions.

With C, it is very much possible to write pseudo-OO code. I don't know much about other non-OO languages. So, is it THE way to manage large C code bases?

答:
You seem to think that OOP is the only means of achieving abstraction.

While OOP is certainly very good at doing that, it’s by no means the only way. Large projects can also be kept manageable by uncompromising modularization (just look at Perl or Python, both of which have excelled at that, and so do functional languages like ML and Haskell), and by using mechanisms such as templates (in C++).

ContentLicense: CC BY-SA 2.5


答: https://stackoverflow.com/questions/15040989/issues-creating-a-very-accurate-swing-timer  Shows swing timer being off dead accurate time by 10ms to 200ms using it to trigger frames of animation won't work well.  Using it to trigger the start of an animation should be OK.  The way swing timers work is one thread manages the timeouts and the actual event callback happens on the EDT so it shouldn't matter if you have a large number of timers they don't use that many resources, just make sure the EDT can keep up.</p>

Title: Animation in Swing

Body:
I have a project written using Swing, and I want to make it more smoothly (like JavaFX is) by adding animation to some components(JButton, JScrollPane, JSplitPane) using javax.swing.Timer.

UPD: That is not a game. I want to use the Timer for short animations like mouseHover events or dropdown, or scroll. But the problem is, a lot of Timer objects should be created.

Question: What action does it perform for JVM? I would start and stop a lot of Timers during app session.


答:
I think that instead of searching for tutorials and buying book, reading language specification is your best shot at gaining a complete understanding of that language.

For example:

C# http://www.microsoft.com/en-gb/download/details.aspx?id=7029

EcmaScript http://www.ecma-international.org/publications/standards/Ecma-262.htm

The same goes for understanding certain technologies. I know dozens of web developers who have never read HTTP1.1 specification (https://www.rfc-editor.org/rfc/rfc2616)

Title: Choosing the right resources


问:
Is it practical to write exit codes in a script where the outcome is more complex than success/fail?
Where I work, we're in the process of automating a lot of tasks that currently need to be run manually by an IT person to determine if the next task can be performed (the second task depends on certain outcomes of the first task). We're ending the first phase of our script automation process, having reworked the first task to have better support for logging, error handling and even emailing a report, but we will not be able to get to reworking the second task right away so it will remain in its current state of manual use.

In the meantime, it has been suggested that we implement exit codes into the first task so that we can simply chain the second task, in its current state, on a successful first task. The only issue here is that the first task is a little more complicated than just success/fail. There are many different parts that can pass that will allow the second task to be run a certain way. Now I know none of this is impossible with exit codes. We could take the time to implement the first task to return all these different exit codes so that the second task can be run in a semi-automated fashion based on these exit codes as a temporary solution to making the entire process automated until we have the time to go in and rework the second task the correct way.

My question is, is it practical to take the time to implement exit codes into a script as a temporary solution to a larger problem where the script is more complex than success/fail?

Note: The exit codes will take some time to implement as our rework of the first task was not designed to return exit codes (it is a self-contained script that handles its own logging and error reporting).

Edit: It is a given that we have to go back and rework the second task in a way that the two tasks can be run independently of each other (their outcomes/state will be shared through a database).

Edit: In general, I know it is useful to have exit codes, but my current situation involves spending a considerable amount of development time to go back and implement the exit codes properly (again because the outcome of the script is quite complex with many different levels of success/fail), when they aren't part of the overall solution, but a temporary hack to our new system in order to "fake" it as a completely automated system until we can actually complete the rework. I guess it's more of a "Is the time spent to implement this hack, while not a complete solution, worth it if we have to go back and undo the hack later?" question.

答:
Multiple values for exit codes is a pretty common practice within the world of application programming.  Take a look at errno.h as an example.

The key part is to coordinate on the meaning of the exit codes so that callers & senders are able to correctly communicate their exit status.

To address some of the particulars of your question:

The only issue here is that the first task is a little more complicated than just success/fail.

Which would be a perfect use case for implementing multiple exit codes as you suggest.  Perhaps one of the codes you need is TRY_AGAIN_LATER, which would let your calling routine know that the immediate call had failed, but there's a good chance it would work after a timeout and then retry.

My question is, is it practical to take the time to implement exit codes into a script as a temporary solution to a larger problem where the script is more complex than success/fail?

Absolutely practical and advisable.  You're not guaranteed that you'll have the time to fix the 2nd script.  And it may actually be easier to just wait and retry once the error condition has passed.  "Good enough" may be exactly that in this case - why spend inordinate amounts of time fixing a script when you can just wait out the problem?  Granted, that may not be your exact case, but having multiple values in the exit codes buys you that flexibility.

"Is the time spent to implement this hack, while not a complete solution, worth it if we have to go back and undo the hack later?"

Most likely yes, it will still be worth your while.

You're not guaranteed to be given the time later to properly fix the 2nd script.

You're not guaranteed you'll be able to properly fix the 2nd script.  Underlying technical issues may prevent your code from working the way you want to.

If you don't implement the "hack" then consider how much you and your team may suffer in the interim keeping the two scripts running.

Properly implemented, the hack shouldn't need to be backed out.  Those sections of the first script simply won't get called.  And I'm having a hard time seeing how there would be that much work in the 2nd script - you'll be fleshing out the error paths that would have previously returned a more nuanced exit code.

Your scripts are in version control, right? Create a new branch and put the "hacked" scripts in there with the additional exit codes.  When you're ready to fix the 2nd script go back to your main branch and work from there.

But take some rough swags at cost to implement the "hack" and costs to undo all of it.  Compare that to how much your team will suffer until you have the time to completely fix the 2nd script.  That evaluation would end up being your final answer.


问:
Reconciling contradictory programming advice: get something working and iterate vs. really think it through before coding
I am an intermediate programmer with a few years of professional experience who is halfway through a masters degree. In learning to program I've often heard two pieces of seemingly contradictory advice.

The first piece of advice was get something working quickly, see how it works (either through prototyping or informal testing), improve the version , see how it works again, improve it again...and then repeat the cycle until you're done. This is sometimes called "spiral development" or phrased as "release early, release often."

The second piece of advice was: really think a project through before ever writing any code.

I've had success with both methods and I would say that I agree with each philosophy.

But now I'm starting to tackle much more complex projects that I have no idea how to complete (like distributed applications and performance-driven graphics programming).

How do I go about these projects?

Do I just start coding SOMETHING and learn (platforms/methods/languages/architectures) as I go -- or do I hold off from coding and do a ton of research/reading before I even open the IDE?

How do I reconcile these contradictory pieces of programming advice?

答:
My rule of thumb: if you don't fully understand any part of the problem you need to step back and fully think it through (I include prototyping and throw-away code to understand APIs etc. as part of "think it through"). If it's basically a collection of problems that you've solved before and you just need to figure out the best way to fit everything together in this particular instance, then iterate.

Honestly though, that's not a hard and fast rule. I really think you need to do a mix of both for any given project. How much of each you do is probably going to mostly depend on how close the project is to one you have already completed in the past.


问:
What process do typical (the majority) of high level language compilers use when changing a source-code's variable name to a machine code name?
Do long (very long) variable names slow down the compilation of source code?

I'm aware that the length of variables has 0% impact on interpretation as the compiler changes them to machine code which is always the same length. But my question is, does the speed at which the compiler vary depending on the length of variables?

For example, if I have a variable name which is a million characters long, surely the compiler would struggle as for it to recognise the variable is a variable, it would need to read the entire thing first which would surely take longer depending on its size?

To clarify, what process do typical (the majority) of high level language compilers use when changing a source-code's variable name to a machine code name?

Do they find the start of the variable working from the left and then find the end working from the right, do they read through the entire variable name (one character at a time) until the end is found or do they not even look at the variable name at all and just know that the code requires a variable of type int (for example) and assign it a machine-level name instantly and then completely ignore any user-defined variable names?

Note that I am a complete novice (still a student) so excuse my ignorance if I get my terms mixed up.

答:
Yes, it will change the compilation speed by a few nano to a few milliseconds.

It will obviously take longer to process a 10MB source file than 10 line hello world type source file.

Will the length of variable names change the compilation speed in any way that's perceptible to a human being? No.


问:
Why do large IT projects tend to fail or have big cost/schedule overruns?
I always read about large scale transformation or integration project that are total or almost total disaster. Even if they somehow manage to succeed  the cost and schedule blow out is enormous. What is the real reason behind large projects being more prone to failure. Can agile be used in these sort of projects or traditional approach is still the best.

One example from Australia is the Queensland Payroll project where they changed test success criteria to deliver the project.

See some more failed projects in this SO question (on Wayback Machine)

Have you got any personal experience to share?

答:
The main reason is an increase in scope, which the book "The Pragmatic Programmer" describes as:

feature bloats

creeping featurism

requirement creep

It is an aspect of the boiled-frog syndrome.

The idea of the various "agile" method is to accelerate feedback and - hopefully - correct the evolution of the project in time.

But the other reason is release management: if you aren't geared toward releasing the project (however imperfect it may be), chances are it will fail (because released too late, with too many buggy features, and harder to fix/update/upgrade).

That does not mean you have to have a fixed release date, but that means you must be able at all time to build a running version of your program, in order to test/evaluate/release it.

The blog post "Late projects are late one day at a time" contains many more examples:

I know the ‘Getting Real’ thing to do would be to Flex the scope and keep the launch date fixed, but that doesn’t work if there is agreed upon functionality that cannot be completed in time.

That’s why we don’t advocate specs or “agreed upon functionality.” That’s the root of the problem — saying you know everything about what you need and how its going to be implemented even before the first pixel is painted or line of code is written.

When you predict a rigid future on a flexible present you’re in trouble. Rigid futures are among the most dangerous things. They don’t leave room for discovery, emergence, and mistakes that open new doors.


问:
Determine file type and then decompile to edit source
I'm new to this type of programming, but proficient in web development... looking to expand my palette a little.

I have this file. In Windows 7 the file properties window claims its a 'system file', my assumption is that this is a generic description and isn't particularly useful, no file extention. This file resides on a usb drive which Windows machines can boot to to run various scripts and applications.

How can I determine what type of file this is and is it possible to de-compile it to view its code or even if that's possible? Sorry for two separate questions, a point in the right direction would be very helpful!

Thanks!

答:
File extensions normally tell the end user and the operating system what type of file it is. In your case, maybe the file extension was hidden by windows(in this case, it is a SYS file), or maybe it was flagged with a "System" File Attribute(Thanks to Hellion for the added info). If your case was the former, Here is a description for the SYS File Format for windows devices. Although to be fair, There are also cases where the file type doesn't necessarily speak the truth of the file's file type as mentioned by FrustratedWithFormsDesigner. i.e. You can change the file extension of an XML file and fool the computer and probably other users, but it does little to hide that its still an XML file when you open it with a text editor nor does it magically turn your XML file into an executable or C file etc. (Thanks to FrustratedWithFormsDesigner for the example.) This isn't always the case, but it does happen.

Decompiling executables and binaries are normally ill advised as they don't produce a 100% copy of the original source code. It might give you a hint on what the code does if documen1tation doesn't already exist but there also lies a chance that the output will just confuse you especially if you are not proficient in the source language you are decompiling the binary to.

So in case you wanted to study system programming, I would suggest looking for opensource applications and binaries instead of trying to decompile the internals of your flash drive's driver files. Probably try using linux as well, being an opensource OS, you can take a look at how everything was built from the source instead of trying to pull your hair out trying to figure out how to get a decompiler to give you more readable code. Not to mention that linux is also well documented so that should save you a lot of time trying to understand what a line of code means and/or does.


答:
I think don't think you should operate under the premise that; We may need it. If we don't have it and need it there will be this disproportionate amount of time to recreate the solution. This solution is so great no one will ever think of it again.

If possible, write a unit test that passes based on this line(s) of code being excluded. Something about the test should tell you why it is no longer a good idea to have this code in there.

Now, you have it documented in: source control, testing and anything other documentation, project or request tracking.

The goal isn't to find the most convenient way to add back, but to rely on and review all the resources about a particular area of the application before making any changes. Just using memory alone or unnecessary prompts in your code is not enough. Who knows if something else changed that makes the saved code useless.

YAGNI


问:
Why would I learn C++11, having known C and C++?
I am a programmer in C and C++, although I don't stick to either language and write a mixture of the two. Sometimes having code in classes, possibly with operator overloading, or templates and the oh so great STL is obviously a better way. Sometimes use of a simple C function pointer is much much more readable and clear. So I find beauty and practicality in both languages. I don't want to get into the discussion of "If you mix them and compile with a C++ compiler, it's not a mix anymore, it's all C++" I think we all understand what I mean by mixing them. Also, I don't want to talk about C vs C++, this question is all about C++11.

C++11 introduces what I think are significant changes to how C++ works, but it has introduced many special cases, exceptions and irregularities that change how different features behave in different circumstances, placing restrictions on multiple inheritance, identifiers that act as keywords, extensions of string literals, lambda function variable capturing, etc.

I know that at some point in the future, when you say C++ everyone would assume C++11. Much like when you say C nowadays, you most probably mean C99. That makes me consider learning C++11. After all, if I want to continue writing code in C++, I may at some point need to start using those features simply because my colleagues have.

Take C for example. After so many years, there are still many people learning and writing code in C. Why? Because the language is good. What good means is that, it follows many of the rules to create a good programming language. So besides being powerful (which easy or hard, almost all programming languages are), C is regular and has few exceptions, if any. C++11 however, I don't think so. I'm not sure that the changes introduced in C++11 are making the language better.

So the question is: Why would I learn C++11?

答:
You should learn C++11 because the features added allow you to write better code. Some people have mentioned type safety of NULL pointers and lambdas, which are very nice. But I want to draw attention to what I think is the most dramatic change in C++11, especially in a large production environment: move semantics.

C++11 supports separate notions of 'moving' and 'copying'. In regular C++, we just have the = operator which basically does both of these. But really, we are expressing two separate ideas with one operator, which is hazardous.

The most obvious example of where this is useful is the new unique_ptr. It has all the best features of the old auto_ptr and scoped_ptr. Suppose we want to have a pointer that is guaranteed to be the only pointer pointing to an object. How do we deal with a = b? Well, before, we were stuck, you could either disallow it completely (as scoped_ptr), or we could do what auto_ptr does where a=b steals ownership from b. This behavior of auto_ptr is very confusing because a = b actually changes b. unique_ptr handles this: a = b is not allowed, but you have a = std::move(b) to steal ownership. How is this useful? Where, there is a separate (overloaded) version of swap that uses move semantics rather than copy semantics. This means that that unique_ptr can be swapped, no problem. This means that unique_ptr, unlike auto_ptr, is safe to use in a container and then say sort. unique_ptr is basically the be all and end all of safe memory management when you don't need multiple pointers on the same object.

Another great example: suppose you have an object that is uncopyable. This is useful in a number of situations. You can never return this object from a function, because when the function ends it copies out whatever you are returning. The ironic thing is that usually the compiler actually optimizes this out (i.e. nothing actually gets copied at the end, the return value is created at the address of eventual assignment). But this has nothing to do with why we made it uncopyable; returning from a function is really just moving the object from inside function scope to outside. You can now write objects that are uncopyable but ARE movable, and these objects can be returned from functions.

Move semantics make it much easier to write code that won't leak and is thread safe.


问:
Can I use a @font-face of "Courier New"?
I currently have my font stack:

```<code>font-family: "Courier New", Courier, monospace;
</code>```

In all browsers that I test in I see the font displayed in the Courier New font except for my android devices - my nexus and my kindle. And although they have a monospace fallback I would rather have my site displayed the same across these devices.

Do I violate any licenses when I add the font using @font-face?  If so, how do I resolve this?

```<code>@font-face {
  font-family: "Courier New";
  src: url(/fonts/cour.ttf) format('truetype');
}
</code>```

答:
Legal questions should be answered by a lawyer. The question of licensing, however, can be addressed.

To answer this properly, we need to look at the intellectual property holdings around both fonts - copyright, trademark and possibly design patent. Realize that all of this comes from my layman's understanding of IP law (that I have delved into some, but I'm still not a lawyer).

As a preface, I'm assuming that curr.ttf is the true type font for Courier and not Courier New (those tend to be named courier new.ttf or something to that effect - it is important for IP that it be named properly (if the IP holders of Courier New started naming their font file Courier instead, things become hazy)).

If, you are willing to accept wikipedia as a source of some legal information - from Courier typeface

Although the design of the original Courier typeface was commissioned by IBM, the company deliberately chose not to secure legal exclusivity to the typeface and it soon became a standard font used throughout the typewriter industry. Since IBM deliberately chose not to seek any copyright, trademark, or design patent protection, the Courier typeface cannot now be trademarked or copyrighted and is completely royalty free.

This information can be found in multiple locations (not just Wikipedia). One can find a more recent release of the Courier typeface at http://www.ctan.org/tex-archive/fonts/psfonts/courier which includes the IBM/MIT X Consortium Courier Typefont agreement which reads:

You are hereby granted permission under the terms of the IBM/MIT X Consortium
  Courier Typefont agreement to execute, reproduce, distribute, display, market,
  sell and otherwise transfer copies of the IBM Courier font to third parties.

The legal bit on the 'Courier' name is the trademark - not copyright or patent (its the trademark dilution that one would be concerned with). As stated, there is deliberately no trademark protection on the Courier name (which has allowed other companies to use it as the basis for their font names - such as 'Courier New'. Compare with Helvetica which is a registered trademark of Linotype-Hell, and thus when Macintosh was implementing screen fonts couldn't use that name as its basis so named the corresponding font Geneva - note the bitmap version of the font was not protected while the name Helvatica was.. and Apple likely had good lawyers for anyt that wanted to discuss that).

(There is much more about this if one wants to delve into the realm of copyright law (and intellectual property) on typefaces - which varies by country. In the US it has been established several times that typefaces are not protected by copyright. The copyright protection declined on Courier mentioned above would have been on the wheel and hammers in the typewriter, this wasn't sought after. Design patents can also protect fonts (such as the Cocacola font) - this wasn't done. Furthermore, the name of the font can be protected by trademark - this wasn't done. Note that all of this pertains to Courier font, not others where there may be trademarks on it. The actual implementation of a font can be protected (the cour.ttf file), but one may be able to reimplement the font from scratch and not infringe upon copyright... though all of this gets murky if one is in the US and the font designer is in the UK (where one can copyright a typeface) - in which case talk to a lawyer again.)

On the other hand... 'Courier New' name from Microsoft Typography Courier New - Version 5.10 shows a "Courier New is a trademark of The Monotype Corporation in the United States and/or other countries."

You would likely be better off defining the Courier font name rather than Courier New. 'Courier' won't raise the ire of IBM, 'Courier New' might raise the ire of The Monotype Corporation and given that this is their business, they likely do care. Defining the Courier New font family using the Courier true type font dilutes The Monotype Corporation's trademark and something that becomes an issue.

If one wants to instead license the font Courier New...

As has been pointed out in comments, following the link on the Microsoft Typography for licensing page takes you to fonts.com web fonts which has (I haven't delved into it) various licensing for the fonts for defining a font face (the lowest tier has 25k pageviews/30 days for free though you need a badge on the page - the next tier is $10/month and 250k pageviews/30 days with no badge on the page). By properly licensing the fonts, you shouldn't have any problems at all.


问:
How best to implement a Dashboard from data in HDFS/Hadoop
We have a bunch of data (several TB) in Hadoop HDFS and it's growing.
We want to create a dashboard that reports on the contents in there e.g counts of different types of objects, trends over time etc.

Our first thought was to use something like Oracle Tableau or d3.js and
to use Hive queries. But Hive is just too darn slow for these "precanned" queries.

Now we're thinking of using Hive to extract data regularly from HDFS and store the output in a "more real time" database e.g. HBase or an RDBMS (e.g. MySQL).

That'll work but I'm worried we're missing a simpler / easier solution (if there is one) that requires less ETL / extracts and duplicate data storage mechanisms (HDFS + something else)

答:
I'd recommend keeping the data in HDFS and converting it to the Parquet file format. Parquet uses a concise, columnar representation of nested data and will reduce the I/O required for many of your queries.

Once your data is in the Parquet format, I'd use Impala to issue SQL queries against the data. Impala implements a highly efficient execution engine for SQL queries over data stored in HDFS. Impala queries will return results to your dashboard with low latency. Unlike Hive, the Impala execution engine doesn't rely on Hadoop's MapReduce implementation.

If you have text data that you'd like to view on the dashboard, I'd recommend Cloudera Search for indexing it. Cloudera Search is a version of Solr Cloud that stores and serves partitioned Lucene indices out of HDFS.

It's quite trivial to install Impala and Search with Cloudera Manager. Cloudera Manager is a free software tool that provides an in-browser GUI for installing and managing Cloudera and related third-party software. If you install and manage your cluster with Cloudera Manager, you don't have to worry about tuning your configuration or ensuring cross-version compatibility between HDFS, Parquet, and Impala.

To try out your new cluster, you may want to use Cloudera Manager to install Hue as well. Hue provides a web-based GUI for end users of Cloudera and related third-party software. From Hue you can explore the data in HDFS and issue SQL or keyword search queries over your data.

For an example of an interactive dashboard built with D3 that uses Cloudera Impala and Search on the backend, check out Zoomdata. This video is a wonderful demonstration of the interactive capabilities of Impala and Search.

If you'd like to use Tableau, Cloudera makes a connector for Tableau available that works with Impala.

Note that the already exceptional performance of Impala for small data sets will be aided by the upcoming in-memory cache that's being added to HDFS with our next release.


问:
Can a team that uses Scrum achieve Co-Dev and domain expertise if it handles many SW domains?
I've worked in a team that developed and gave support for SW practices tools. Those tools were written (and will be written) in many programming languages.

According to Scrum, a given story, can be implemented by several team members (according to what I know).

When organized in a team that is oriented to a specific SW domain/framework (.NET for example), this seems possible and even reasonable.

But if your team needs to write in Python, C#, Java etc. for several tools, some with different orientation (DB/UI), is this possible? How does the "division of labor" should be made in  this case?

Thanks.

答:
I understand the 'all team members' are equal in scrum as an ideal.

Practically, you'll always have people better at some jobs than others. But it's all about reducing the bus factor: voluntarily assigning work to someone who's not the best at it so should a bus happen, or should your expert be overloaded with other things, work can still happen.

The non expert will of course require help/assistance from the expert. But it is better to lower your velocity and take advantage of the help when it is available rather than be stuck when it's not (hospital/overwork case).


问:
How can I make sure that I'm actually learning how to program rather than simply learning the details of a language?
I often hear that a real programmer can easily learn any language within a week. Languages are just tools for getting things done, I'm told. Programming is the ultimate skill that must be learned and mastered.

How can I make sure that I'm actually learning how to program rather than simply learning the details of a language? And how can I develop programming skills that can be applied towards all languages instead of just one?

答:
I think, as with anything, practice makes perfect. Just don't pigeonhole yourself into always doing the same thing or always using the same language and keep continuing to learn things on every project.

I think you can easily draw a parallel to something like learning to play a guitar. Any good musician can learn to play a new song in a very short period of time, because they already know all the chords and all the theory behind why the chords are played the way they are. How do they get that good? They just have played so many songs that all the patterns have just blended together, while at the same time supplemented their knowledge with actual documented theory that those patterns subscribe too.

So maybe you can play a few songs very well, but you can't deviate or pick up new songs quickly. This is probably the equivalent of a .NET programmer that continues to make the same CRUD application over and over, at some point try something new, add in some web service calls or an advanced UI, or writing it in a whole new language. When you hit a snag look into why things happen the way they do, ask questions on Stack Exchange, etc. Eventually, you will see all the patterns that continually come up and know some of the underlying theory and learning a new language won't seem nearly as daunting.


答:
I think, if you can think analytically, you have a good start.

Learn any language you want and work yourself trough a series of examples e.g. as presented in nearly ever book that teaches programming.

Next try to solve your own problems. Try to find different solutions and compare them. Speed and memory-usage are commonly used factors that matter. Discuss your solutions with other programmers.

Read code of other programmers and try to understand why they solved the problem this way.

You should also read some books about algorithms to get an overview over standard approaches. New problems are often modifications of old problems.

A lot of practice and working with code also in teams will help you to increase your skills step by step.

I hope my opinion answers you question at least partial.

Body:
I often hear that a real programmer can easily learn any language within a week. Languages are just tools for getting things done, I'm told. Programming is the ultimate skill that must be learned and mastered.

How can I make sure that I'm actually learning how to program rather than simply learning the details of a language? And how can I develop programming skills that can be applied towards all languages instead of just one?


答:
There's the theoretical approach. Learning about how computers actually work under the cover. How the basic processor instructions are stringed together to make the more complex operations and structures that we take for granted in high-level programming land.

Then there's the more practical programming approach. The main sticking point that plague people usually labeled as "not good programmers" is that they only really know one language. And even if they know others, they program in them in the same way they do with their native language. That's a cycle one must break if they really want to learn how to program. The default answer to that is to learn at least one language from each programming paradigm. So learn an OOP language, a functional language, a scripting language ... etc. And by learning I don't mean learning the syntax. You learn a language by actually using it to create something.

Personally, when I want to learn a new language I use Project Euler puzzlers. I go to a puzzle that I have already solved in an OOP language (as an example) and try to solve it using a functional one while trying to follow the best practices of the new language. When you solve the same problem using two fundamentally different approaches you not only see what the real differences are, but they also show you where the common areas are. These common areas that are shared by all languages is the real programming, the differences are just different ways to achieve it.

Title: How can I make sure that I'm actually learning how to program rather than simply learning the details of a language?


问:
Where in computer science education does "reuse and integration" find comprehensive coverage?
This intro is only my naive attempt at a mile-high snapshot helping me to position my question. Any user trying to answer my question, that tries to nail down one aspect of programming, will have to overcome my naive understanding, simply because of my idiosyncratic education. So here I'm placing my subject in the array of topics outlining programming and software activities:

Fundamentals of programming (software design patterns, idioms, models)

Code reuse and integration (libraries, frameworks, apis)

Continual development (documentation, commenting, version control)

Maintenance best practices (systems administration)

I'm interested to focus my programming skills on code reuse and integration topics. This topic may certainly begin with software programming languages and the differences between functional and object-oriented programming. However, what I wish to focus on in detail and at some length are the variety of uses of libraries, frameworks, and apis.

My programming education comes from what I can readily find on the internet and in books. Earlier this year I enrolled in a class on fundamentals at Coursera, Programming Languages, by professor Daniel Grossman, which attempts to prepare students for programming in any language. Reuse was mentioned only as a property of functions and object. You can start your search for 'reuse and integration' in fundamentals and not get close.

Since I started learning some Ruby, php I've put together a better understanding of 'reuse and integration', but its all cobbled and patchwork. Published materials are mostly #1 and then some idiosyncratic mix of #2-4. You can read a lot of books and still not understand how all of these abstractions fit together.

I've even participated in a discussion here at p.se on the pedagogical problem of cargo-cult programmer students who "...copy-paste code from previous, similar-looking assignments..." While my own answer to this reflects my appreciation for the OP's concern, and yet my imagination can't help envying these students who can draw with such ease from previous projects just a little bit.

I've not read the book or participated in a class or heard a discussion which attempts to survey the reuse and integration paradigms in their totality.

Where in computer science education does “reuse and integration” find comprehensive coverage?

答:
What you described as "reuse and integration" is mostly embodied in a practical way using the concept of modularity.

Modularity takes a number of forms.  In some languages there are actually modules, and in many others there are concepts of modularity that take the form of individual files, namespaces and other similar organizational mechanisms.  Object-oriented classes are a form of modularity, as are simple functions.

To achieve reusability and ease of integration with various systems, software must be generic enough to be applicable to a wide variety of programmer scenarios.  This is achieved by high cohesion and loose coupling.  Generics allow collections to be used with arbitrary objects.

In short, reuse and integration are achieved by understanding fundamental programming principles, and how these concepts can be applied to develop software that is easily reused and integrated.  You have to know the fundamentals first, in other words.


答:
Pick a language, and start coding.  Python is a good choice for a beginner, and there are tutorials available online, so that you can learn how to do it properly.

Everything follows from that.  Your interests will lead you to frameworks and design concepts that will add sophistication to your programs.  You will discover that there are online courses you can take that will ground you in the fundamentals and the theory, and that there are different programming paradigms you can explore, and so on.

And yes, you will discover languages like Haskell that will teach you something new, once you have a firm grounding in the fundamentals.

Some programmers probably think all languages are the same because they haven't been exposed to any that make them think differently. All of the most commonly used languages are derived from Algol (they are essentially procedural languages), and of those, most are curly-brace languages similar to C. All of them do essentially the same things, albeit some with more sophistication than others.


答:
In my case, I learn how to actually program through the following:

Learn from the masters. Listen to programming podcasts, read professional blogs in your programming topic of choice, read/watch wonderful tutorials done by gurus that are scattered all over the web and lastly, reading epic books like The Pragmatic Programmer. This book has a lot of programming gems that have been accumulated throughout the career of the authors. One sure fire way to learn how to actually code is to know how other successful programmers do it.

Experience by doing. Reading about it and knowing is one thing, actually putting it into practice and getting it to work is another. There is no better teacher than experience, so put your coding cap on and get started.

Ask someone who knows. Just like you're doing now, don't be afraid to ask about best practices or better ways to do things from seniors in your team, or if you're unfortunate enough to not have access to the said seniors or mentors or gurus, then there's still the rest of stackexchange and the internet to ask.

Also, as your commenters have mentioned, don't forget to master your tools as well. Learning all the best practices and greatest theories are all for naught or will be poorly implemented if you don't know enough about your tool, in this case, a programming language.


答:
Don't worry about meeting some ridiculous concept of "skill" so commonly heard in such statements like:

All programming languages are basically the same.

Once you pick up one language well you can pick up any other language quickly and easily.

Languages are just tools, there's some overarching brain-magic that actually makes the software.

These statements are all based on a flawed premise and betray a lack of experience across a broader spectrum of programming languages. They are very common statements and strongly believed by a great swath of programmers, I won't dispute that, but I will dispute their accuracy.

This is proved simply: Spend one week (or really any amount of time greater than a couple days) trying to learn the fundamentals of Haskell, Prolog, or Agda. You will soon after start hearing the old Sesame Street song play in your head "One of these things is not like the others...".

As it turns out, there is a whole swath of programming languages, techniques, and approaches which are so foreign from what 95% of us do or have ever done. Many are completely unaware that any of these other concepts even exist, which is fine and these concepts aren't necessary to be an employed and even effective programmer.

But the fact remains: These techniques and approaches do exist, they are good for many different things and can be very useful, but they are not just like what you're used to and people cannot simply pick them up with an afternoon of fiddling.

Furthermore, I would say the majority of cases where people claim they have or can learn such complex things as programming languages so quickly as a week, they are suffering from a bit of Dunning Kruger Effect, Wikipedia (emphasis mine):

The Dunning–Kruger effect is a cognitive bias in which unskilled
  individuals suffer from illusory superiority, mistakenly rating their
  ability much higher than average. This bias is attributed to a
  metacognitive inability of the unskilled to recognize their
  mistakes.

I would refer people to this more experienced perview on the concept of learning to program by Peter Norvig: Learn to program in ten years.

Researchers (Bloom (1985), Bryan & Harter (1899), Hayes (1989), Simmon
  & Chase (1973)) have shown it takes about ten years to develop
  expertise in any of a wide variety of areas, including chess playing,
  music composition, telegraph operation, painting, piano playing,
  swimming, tennis, and research in neuropsychology and topology. The
  key is deliberative practice: not just doing it again and again, but
  challenging yourself with a task that is just beyond your current
  ability, trying it, analyzing your performance while and after doing
  it, and correcting any mistakes. Then repeat. And repeat again.

Surely, there is a set of overarching principles that will make all languages easy to learn!

Perhaps, but I would argue this set of principles is so large that there will almost always be languages outside of your one-week reach. As you add new concepts to the list you're familiar and comfortable with, this list of languages outside your immediate reach may shrink, but I have a hard time believing it will ever go away. The list of conceptual computing approaches to things is so broad it's baffling, from concatenative languages to vector based languages to languages specializing in AI or metaprogramming (or languages which exist entirely to support regular expressions).

After ten years you will be able to generally program. This means you can write somewhat decent code in some language or style of languages. So after 10 years you are ready to start tackling these countless broad cross-cutting concepts for the rest of your life, and short of being Edsger W. Dijkstra, Donald Knuth or John D. Carmack, you're not going to get to all of them.


问:
What is a Ruby on Rails way to save images?
I develop on iOS, and I'm switching from a PHP backend to Ruby on Rails. The interchange format is JSON.

A quick Google search for 'save images in Rails' has nearly every result talking about saving image data as blobs to the database. I might be mistaken, but I'm under the impression that saving image data in a database is a huge waste of time and space (as opposed to saving a link to the file location ('/img/subcat/4656.png').

In PHP, it's pretty standard to receive the data, generate a filename, save that file to disk, and update the database with the image's location on disk. Is this the same for Ruby on Rails, or is there some built-in ActiveRecord image functionality I'm not aware of?

答:
What I've done in the past is use PaperClip with Amazon S3 and CloudFront CDN for faster delivery. PaperClip supports S3 storage very nicely out of the box: see their documentation for S3 storage configuration options.

Set up a CloudFront distribution to forward image requests to your S3 bucket and other requests for static assets to your Ruby on Rails application (alternatively, you can upload those to S3 as well, but that's outside the scope of this question).

CNAME a domain you control (such as assets.example.com) to point to your CloudFront distribution.

In the PaperClip configuration, set s3_host_alias: assets.example.com. This will cause generated URLs to saved image resources to use your CloudFront distribution host.

In your Ruby on Rails configuration, you can then do config.action_controller.asset_host = http://assets.example.com. Ruby on Rails asset URLs will then also use your CloudFront distribution, for caching/faster delivery.

That's pretty sketchy, but it hopefully points you in the direction of some useful resources. Of course, that's just one solution, but it's one that has worked for me in a situation where I was dealing with hundreds of thousands of image attachments in the database.

(As a possible advanced step that may not be necessary or useful for your case, you can also set up multiple CNAMEs for your CloudFront distribution, such as assets0.example.com and assets1.example.com. Both paperclip s3_host_alias and action_controller.asset_host can then take lambdas that will allow you to deterministically (based on the asset) generate URLs that use different hosts, for better parallelization if you're downloading a bunch of them on the same page, as browsers will limit the maximum simultaneous connections to the same host.)


答:
No, it is not legal. The font is protected by copyright. And it would be pointless to use a font like Courier New instead of the native monospace font of Android, which is typographically much better.

Technically, using @font-face on a copyright-protected font isn’t illegal as such. It could be used to refer to a font in the user’s system. But distributing the font without permission, or using an illegal distribution, is illegal.

Title: Can I use a @font-face of "Courier New"?

Body:
I currently have my font stack:

```<code>font-family: "Courier New", Courier, monospace;
</code>```

In all browsers that I test in I see the font displayed in the Courier New font except for my android devices - my nexus and my kindle. And although they have a monospace fallback I would rather have my site displayed the same across these devices.

Do I violate any licenses when I add the font using @font-face?  If so, how do I resolve this?

```<code>@font-face {
  font-family: "Courier New";
  src: url(/fonts/cour.ttf) format('truetype');
}
</code>```


问:
Architecting multi-model multi-DB ASP.NET MVC solution
I have an ASP.NET MVC 4 solution that I'm putting together, leveraging IoC and the repository pattern using Entity Framework 5. I have a new requirement to be able to pull data from a second database (from another internal application) which I don't have control over.

There is no API available unfortunately for the second application and the general pattern at my place of work is to go direct to the database.

I want to maintain a consistent approach to modeling the domain and use entity framework to pull the data out, so thus far I have used Entity Framework's database first approach to generate a domain model and database context over the top of this.

However, I've become a little stuck on how to include the second domain model in the application.

I have a generic repository which I've now moved out to a common DataAccess project, but short of creating two distinct wrappers for the generic repository (so each can identify with a specific database context), I'm struggling to see how I can elegantly include multiple models?

答:
I think at some point you are going to have to write two adapters.  Interfaces are  a great way to tie things together, but each model needs to access its own data.

I think you are on the rigjt path by seperating out the data access.  If you have both models interact through an interface, adding more models in the future will be easier.

What objects knows the context on the information being saved?  I can see where you could have a couple of objects som type of SQL statement object to write to the database.  Even then you still need to translate to/from the domain models.

Good luck.


答: I think you're confusing computer science with software engineering.  Computer science is more concerned with theories, algorithms, data structures and proofs.  Software engineering is the discipline that studies software architecture and construction.  A computer science degree program may have software engineering courses, but they're not necessarily part of computer science per se.</p>

Title: Where in computer science education does "reuse and integration" find comprehensive coverage?

Body:
This intro is only my naive attempt at a mile-high snapshot helping me to position my question. Any user trying to answer my question, that tries to nail down one aspect of programming, will have to overcome my naive understanding, simply because of my idiosyncratic education. So here I'm placing my subject in the array of topics outlining programming and software activities:

Fundamentals of programming (software design patterns, idioms, models)

Code reuse and integration (libraries, frameworks, apis)

Continual development (documentation, commenting, version control)

Maintenance best practices (systems administration)

I'm interested to focus my programming skills on code reuse and integration topics. This topic may certainly begin with software programming languages and the differences between functional and object-oriented programming. However, what I wish to focus on in detail and at some length are the variety of uses of libraries, frameworks, and apis.

My programming education comes from what I can readily find on the internet and in books. Earlier this year I enrolled in a class on fundamentals at Coursera, Programming Languages, by professor Daniel Grossman, which attempts to prepare students for programming in any language. Reuse was mentioned only as a property of functions and object. You can start your search for 'reuse and integration' in fundamentals and not get close.

Since I started learning some Ruby, php I've put together a better understanding of 'reuse and integration', but its all cobbled and patchwork. Published materials are mostly #1 and then some idiosyncratic mix of #2-4. You can read a lot of books and still not understand how all of these abstractions fit together.

I've even participated in a discussion here at p.se on the pedagogical problem of cargo-cult programmer students who "...copy-paste code from previous, similar-looking assignments..." While my own answer to this reflects my appreciation for the OP's concern, and yet my imagination can't help envying these students who can draw with such ease from previous projects just a little bit.

I've not read the book or participated in a class or heard a discussion which attempts to survey the reuse and integration paradigms in their totality.

Where in computer science education does “reuse and integration” find comprehensive coverage?


答:
Elaborating a bit on VonC's answer:

This big projects tend to have an "all or nothing" mentality. The project as defined has to be released in one go - often as it's a change over from an existing system.

This means that the problems of feature/requirement creep are harder to address so when the project comes to fruition it's often seen as no longer meeting requirements. This can be exacerbated if the existing system has been updated or technology has moved on in the meantime.

What's the solution to this?

I don't really know as no one wants to have two systems running in parallel with a changing set of functions split between the two.

Title: Why do large IT projects tend to fail or have big cost/schedule overruns?

Body:
I always read about large scale transformation or integration project that are total or almost total disaster. Even if they somehow manage to succeed  the cost and schedule blow out is enormous. What is the real reason behind large projects being more prone to failure. Can agile be used in these sort of projects or traditional approach is still the best.

One example from Australia is the Queensland Payroll project where they changed test success criteria to deliver the project.

See some more failed projects in this SO question (on Wayback Machine)

Have you got any personal experience to share?


答:
Well, most of the things I wanted to say has already been said. What I would like to add is a very simple analogy.

If programming languages are considered mere tools, even then there is absolutely no logic in being good at one makes being good at the other a cakewalk.

Just consider a bunch of reputed master swordsmen, suddenly put down their swords and went off to battle with spears after 7 days training.
  What would happen? They would be massacred.

Languages are often not difficult to learn but it takes patience and exercise to be good at it. Additionally, there is no right way to learn programming.

Learning a programming is like playing an RPG game. Sometimes you use swords, sometimes spears, sometimes a shield. Each enemy you kill, you get experience points. Once you have enough experience points, you level up.
  Now mastering a sword will not make you excellent with bows and arrows. But a portion of  the experience you gained previously will increase your stamina and speed.

Here's a couple of things you might want to do when learning a language.

Read about the language. if it sound interesting try out the hello world app(s) by yourself.

Read some tutorials, tricks, blogs.

Make simple apps in it just for fun.

Test different features.

If you really like it, buy some books and/or video tutorials.

Search for good libraries.

Search for answers, ask only if you can't find the answers.

Help others asking for answers (where better than here?)

Make something useful. Making a calculator app may be a good exercise but if you make a TO-DO list app and actually you use on your PC/Phone, the feeling is 100 times satisfactory.

Experience new languages, explore new libraries, learn new tricks on your free time. Before you know it you'll surprise yourself with your own skill.


问:
structure problem in Relational DBMS creation
For learning and understanding purpose, I currently want to try to make a small relational DBMS with simple features like (for now) only sequential reading/writing and CREATE TABLE, INSERT, SELECT, UPDATE and DELETE management.

I am currently on the "think" part of the project and I am stuck on the way to store the read data in memory. First I was thinking of putting them properly on a structure, but the problem is that tables are all different, know the type of each column is not an issue, but I am not sure C provide a way to make fully dynamic structure.

My second and current idea is to make a simple char array of the required length and just get the data by order with cast. But I am not sure if it is the good way to do that part, so I wanted to ask for your opinion and advices about that.

Thanks in advance for your help.

nb: I hope my question is enough clear and understandable, I still lack of pratice in english

答:
It has been a long time since I programmed in straight C, but I think I can point you in the right direction.  There are 2 things you can use together.  First somthing like:

```<code>union data {
    // all the data types you will support
}
</code>```

You will need a way to identify each element.  That is where struct can come in:

```<code>struct dataNode {
   data *value;
   // some type id system with either enum or ints
}
</code>```

A row of data then becomes a linked list & a result set a linked list of linked lists.  You will probably need to straighten out the syntax, but it is a start.

Body:
It has been a long time since I programmed in straight C, but I think I can point you in the right direction.  There are 2 things you can use together.  First somthing like:

union data {
    // all the data types you will support
}

You will need a way to identify each element.  That is where struct can come in:

struct dataNode {
   data *value;
   // some type id system with either enum or ints
}

A row of data then becomes a linked list & a result set a linked list of linked lists.  You will probably need to straighten out the syntax, but it is a start.


答:
... how can I develop programming skills that can be applied towards all languages instead of just one?

The key to this question is to transcend the language and think in not the language you are coding in.

WAT?

Experienced polyglot programmers think in the abstract syntax tree (AST) of their own mental model of the language. One doesn't think "I need a for loop here", but rather "I need to loop over something" and translates to that to the appropriate for, or while, or iterator or recursion for that language.

This is similar to what one sees in learning a spoken language. People who speak many languages fluently think the meaning, and it comes out in a given language.

One can see some clue of this AST in the pair of eyetracking videos Code Comprehension with Eye Tracking and Eye-Tracking Code Experiment (Novice)  where the movements of the eye of a begineer and experienced programmer are watched. One can see the experienced programer 'compile' the code into their mental model and 'run' it in their head, while the beginner has to iterate over the code keyword by keyword.

Thus, the key to the question of developing programming skills to apply to all languages is to learn multiple languages so that one can distance themselves from having the mental model of one language and develop the ability to generate the AST for a problem on their own in a head language that is then translated to a given language.

Once one has this ability to use the AST in the head, learning another language within a similar school of thought (going to Befunge is a bit of a jump from Java, but not as much from Forth) becomes much easier - it's 'just' translating the AST to a new language which is much easier the 3rd, 4th and 5th (etc...) time it's done.

There is a classic article, Real Programmers Don't Use Pascal. Part of this reads:

... the determined Real Programmer can write Fortran programs in any language

There are also bits for which you can't just use the mental AST - you need to think in the language too. This takes a bit of time to accomplish (I'm still accused of writing Perl code in Python and my first Lisp code was reviewed saying "This is a very good C program.").

To this, I must point out an article published by the ACM, How Not to Write Fortran in Any Language. The third paragraph of the article (that isn't leading quotes) directly addresses the question at hand:

There are characteristics of good coding that transcend all general-purpose programming languages. You can implement good design and transparent style in almost any code, if you apply yourself to it. Just because a programming language allows you to write bad code doesn’t mean that you have to do it. And a programming language that has been engineered to promote good style and design can still be used to write terrible code if the coder is sufficiently creative. You can drown in a bathtub with an inch of water in it, and you can easily write a completely unreadable and unmaintainable program in a language with no gotos or line numbers, with exception handling and generic types and garbage collection. Whether you're writing Fortran or Java, C++ or Smalltalk, you can (and should) choose to write good code instead of bad code.

It isn't just enough to have the AST - it's necessary to have the AST that one can translate into other languages. Having a Fortran AST in your head and writing Fortran code in Java isn't a good thing. One must also be familiar enough with the language and its idioms to be able to think in the language (despite what I said at the very top).

I've seen Java code written by someone who hadn't stopped writing C code. There was one object with a main method. In this object were a bunch of static methods called by main, and private inner classes that had public fields (and thus looked a lot like struts). It was C code written in Java. All that was done was translating the syntax of one language to another.

To get past this point, one needs to continue to write code in multiple languages, not think in those languages when designing the code, but think in them when translating the design into the code to work with the language idioms correctly.

The only way to get there - being able to develop programming skills that can be applied to all languages - is to continue to learn languages and keep that mental programing language flexible rather than linked to one language.

(My apologies to ChaosPandion for borrowing heavily from the idea he presented.)


问:
What are the alternate models for remote desktop software?
A coworker and I were trying to brainstorm and list the different ways an application developer can write a program enabling a user on one computer to run remotely on another computer while being displayed on their own computer. She suggested all possibilities would fall into only three categories:

remote desktop software

hosted service

appliance

I think I understand how an application developer might approach this using the first model (for example, by writing an application that uses a service on the server via a protocol.) I'm unsure how the second model would be different than the first, and I don't understand what the term 'appliance' would mean in this case.

What I would like to know is how should an application developer compare these alternatives when designing a strategy for a new application -  that will be used remotely?

答:
The best way to understand what your coworker meant would be to ask her, rather than assuming these names refer to standard concepts shared by others. Ask her.

If I were to try and decipher those terms, I would say that the first is using Terminal Services/Remote Desktop (on Windows) in which a thin client application (the Remote Deskto Client) acts as a window to a process running on the server, where the actual process is executing. A similar concept is the X Windowing System on Unix machines, where the application runs in one process or server (the X Server) and it sends commands (like Open Window, Show UI, etc) to an X Client process which only renders the UI.

The second option, I would guess, is what you suggested for #1. You write an application that runs locally on your machine, but which is relatively thin in logic - it accesses a remote service where the business logic and heavy lifting is performed, getting the results, and displaying them locally. In this scenario there is more work done locally, rather than just being a UI puppet in the hands of the server, the client is responsible for asking for the data and showing it. Still, the brains of the operation is on the remote machine.

And as for #2, the term "appliance" is used mainly to refer to 3rd party software that you buy (say, a Mail server or database) which, instead of having to install yourself on your machines, comes already pre-configured on its own machine (either physical server or virtual machine). I'm not sure how it related to your question.