问:
How to justify efforts to make capitalization of class and property names uniform?
In this thread, an Oracle Product Manager (username "Alex Keh") refused to make Oracle's EF provider to conform with .NET's PascalCase coding standard for class names and property names, saying that it is only "cosmetics" without any "functional needs".

I discussed it with my team. One of the key things we want to know is
  why developers are spending so much time changing the case between
  Oracle and EF. Is there a compelling functional need to change from
  upper case to Pascal case, not just a cosmetic one?

On the feature request tool and this thread, people have asked for the
  feature, but not offered a reason why Pascal casing is so important
  that they would be willing to conduct the manual mapping changes.

For me, the main reason is that I don't want to see Oracle's UPPER_CASE name convention mixing in my .NET code, but it seems that this is not enough. How would you justify effort to support PascalCase convention?

答:
How do home builders justify the effort that every wall stud is 16" from each other?  How do aircraft engineers justify that bolts/rivets (whatever they use these day) on an aircraft's wing are all evenly spaced?

Maybe exact spacing doesn't matter and maybe capitalization doesn't matter but outside of software engineering it is very easy to look at these things that don't matter and tell a difference between a well-crafted product and something that was slapped together. Why should software be any different?

Having consistent style throughout your code base allows your engineers to read it efficiently without their brain going, "WTF" every time they open a new source file. Maybe capitalization by itself isn't a major contributing factor, but the key is overall style. More standard and consistent look and feel of all your code makes you use less brain cycles trying to read it and more cycles trying to understand it.

Developers are spending time on Oracle's capitalization because they are trying to clean up the mess and align all those studs/rivets/bolts (whatever software equivalent is).  Maybe it is just aesthetic to a Program Manager but when a developer fixes one of these things, it is one less thing that bugs him about the code base, so next time he has to work on the file, he can avoid one more annoyance/distraction and jump right into the guts.  Good software engineers are generally those that pay a lot of attention to details.  It is important because when you are write a piece of code, it can fail in a 1000+ different ways and paying attention is how you avoid spending 90% of your time looking for bugs. But when a person pays attention to details, they notice ALL details.

One of the well-known authors (can't remember source but either Robert C. Martin or maybe Brooks or DiMarco) once mentioned an analogy that even a product manager should understand: if you need to make a dinner, would you rather do it in a messy kitchen with dirty counters and utensils all over the place? Or would you prefer to enter a spotless, clean environment where everything is exactly where it should be? Sure you can get your work done in both types of environments but a) you'll definitely be more efficient in a clean one and b) if nothing else, it just makes your work day that much more enjoyable.  Sifting through 1000s of lines of code on daily basis is a software engineer's (NOT product manager's) work environment and they should have full right to go in and clean it up.  Because your happy engineer is your productive engineer.  Your engineer whose hands are tied so much that he can't even fix capitalization is an engineer who goes home and works on his resume or his own startup software.

And this last part is mostly a rant that might get me flamed, but here goes... In the last year or so I've head the pleasure of crossing paths with numerous pieces of software produced by Oracle and most of the time I did walk away with a feeling that their official policy is to slap sh#t together.  I don't know any other company at that level who takes more than 6 months to fix a security vulnerability or who defines a class which internally contains the data you need but the only way for you to get that data is to call toString() and then parse what you get back.


问:
Why would anyone invest time in Microsoft "Roslyn"?
I have just been reading through some of the white papers & examples from Microsoft "Roslyn" and the concept seems very interesting.  From what I can tell, it opens up the black box that is the compiler and provides an interface that we can use to get information and metrics about code written in Visual Studio.

Roslyn also appears to have the ability to "script" code and compile/execute it on the fly (similar to the CodeDom) but I have only come across limited uses for that type of functionality in my experience.

Whilst the code analysis & metrics element is an interesting space...it is something that has been around for a very long time and there are numerous providers that have already invested a lot of money into code analysis & refactoring tools (e.g. ReSharper, CodeRush, nCover, etc) and they do a pretty good job of it!

Why would any company go out of their way to implement something that can be provided at a fraction of a cost through buying a license for one of the existing tools?

Maybe I have missed some key functionality of the Roslyn project that places it outside the domain of the mentioned tools...

答: The simple answer for why MSFT is investing in Roslyn is that their existing codebase for the C# compiler is now 5 versions old - 11 years now. That's a long time for any codebase to remain manageable. Plus, since they're rewriting, they decided to invest in doing it so that all of its internals are exposed as API's.

ContentLicense: CC BY-SA 3.0


问:
Are missed deadlines common in programming jobs?
It was my freelancer job at oDesk. I have done several jobs earlier in given time, but is was the first time I missed the deadline. It was a very lengthy job and I tried my best but I still missed the deadline. Now, I am very scared. Because it's my fault that I missed the deadline.

My question is: Is this is a big concern or are missed deadlines common among programming jobs, so I shouldn't worry too much about this?

答:
Missed deadlines should not become common practice if you want to continue to get jobs.

With that said, you typically want to leave yourself some extra "wiggle" room in your estimates in case stuff happens (and it always does).  You don't need to disclose that you've added in extra time, just don't make it unreasonable.  Maybe between 5 - 10% of total time?  The only way you'll find out is to do it a few times.

In order to get really good at estimates, you have to know how long it takes to code a certain type of widget... for example, let's say you have to create an infinite scroll widget for client X.  If it takes you one week to deploy it into production without bugs, you can use that as a baseline for your infinite scroll estimates.


问:
How should I tackle code testing on a solo project?
I am writing a piece of software and I would like to release it open source.

Should I try just getting it stable on my computer (with normal use; no "things a monkey wouldn't even do") before releasing it, or should I take a different approach?

What I am leaning towards doing right now is:

Write it myself during the pre-alpha stage to get it partially usable. Play around with the functions (like a normal person would).

Release it publicly and add some bells and whistles during the alpha stage

Say it's in beta once all features are complete, and then, along with some others (hopefully) do the "monkey testing."

Generate the publicity for my [fairly basic and boring, but still good enough for free and stable] project.

Then keep improving it. This seems to be a usual system (to me, the one who has never really done this whole thing ever before).

Is there something I could do to automatically test for basic errors before I go alpha? Or is this one of the best things I can do? How should I go about testing?

答:
As I am somewhat in your situation (currently developing a PHP-based CMS) I hope that my experience can help you.

Testing is key. Repeat that until you believe. It depends on the programming language though how easy it is. As I am developing in PHP I will give some examples on that.

Developing

The most important point is: You develop the software in the first place for yourself. If you do something in your spare time, do it for yourself, do it for fun. Don't do it in the expectation of "I want that others contribute to the project". If you put up an empty codebase, nobody will contribute. For the first contributors you need a running demo, something that makes your software popular.

For that goal you need to develop the software in the first place.

Create a feature list.

Ask yourself: What should be in the product, what not?

This feature list is not holy. It will change during development and you won't be able to realize everything as planned. But it gives you a general direction, some goals to aim on.

Testing

Create software that is test-friendly. Use dependency injection, prevent singletons and use unit tests. At best use test driven development. That means you create the test first and than the tested class. That way you have to know the specification of your class before you write it. It saves a lot of pain later on and motivates contributors (they just have to test their own classes). Changes of implementation can simply be tested and if they fail, you can immediately resolve the errors.

Release

Announce the software only if it is working and without problems. But use Github or another code hosting site to give early contributors a chance to see the code. If they want, they can contribute. But you are the main developer of the first version.

Once the first version comes close to Beta (all components are mainly written and tested and work together), you can put up a public demo (showing off your product in case of web software). Collect feedback of the general users of the software (What is missing?, What can be done better?). That ensures that you don't miss the customer base. Your initial feature list will be concentrated on features developer focus on. That is natural and OK. But because of that you need this Beta feedback of your potential users.

Then go over the feedback, develop missing features, fix existing bugs, etc. Once everything works (automated tests like unit tests and functional tests will make that a lot easier) you can release your product.

Maintenance

Your job isn't done when it's out. When it's out your real job begins. Now you need to promote your product (both usage and code development) on your product's website. Write good developer documentation (in addition to the API documentation generated from code comments) that explains things that you won't find in API documentation (best practices, do's and don'ts, etc.).


问:
Does modular programming affect computation time?
Everyone says that I should make my code modular, but isn't it less efficient if I use more method calls rather than fewer, but larger, methods? What is the difference in Java, C, or C++ for that matter?

I get that it is easier to edit, read and understand, especially in a group. So is the computation time loss insignificant compared to the code tidiness benefits?

答:
Yes and no.  As other have noted program for readability first, then for efficiency.  However, there are standard practices which are both readable and efficiency.  Most code gets run rather infrequently, and you won't gain much advantage from optimizing it anyway.

Java can inline smaller function calls, so there is little reason to avoid writing the functions.  Optimizers tend to work better with simpler easier to read code.  There are studies that show shortcuts which should theoretically run faster, actually take longer.   The JIT compiler is likely to work better the code is smaller and frequently run pieces can be identified and optimized.   I haven't tried it but I would expect one large function which is relatively rarely called not to be compiled.

This likely doesn't apply to Java, but one study found larger functions actually ran slower due to requiring a different memory reference model.  This was hardware and optimizer specific.   For smaller modules instructions which worked within a memory page were used.  These were faster and smaller than the instructions required when the function did not fit withing a page.

There are cases where it is worth while to optimize code, but generally you need to profile the code to determine where that is.  I find it is often not the code I expected.


问:
how do design the database tables for file download statistics
I have the web application where i am serving file downloads in php.
All is working fine and i have the download column in file field where i increment it.

But i want to have full statictics of downloads like how many downloads on each day or in month or time of day or from which location

But i am not able o find how to design the mysql tables for that. Do i need to lo every download request in database for that. Any design pattern or example of that in real world

答:
Ordinary, you'll save the date and time and location of each download, given that the table should be optimized for fast insertion, but retrieval may be slow.

Then, you may have an OLAP cube which, based on the original table, will store the number of downloads in a way appropriate for your criteria, i.e. per day or month or location.

You can start by modeling the table which is used to record download hits:

This gives you basic information about the download, i.e. that a download happened at a given date and time from a given geographical location. isProcessed is 0 by default; you'll see how is it used a bit later.

Given the lack of indexes on the table, insertion of data would be fast. Selection, on the other hand, can be really slow, but it doesn't matter: we wouldn't use this table for search.

The data from this table would be transformed into this one on schedule (at night, every hour, once per second, depending on your requirements). Once transferred, the entry is marked as processed by changing IsProcessed to 1.

This table contains indexes to be able to quickly find the information you need, for example count downloads per location like this:

```<code>select sum(CountDownloads) from ProcessedDownload where GeographicalLocation = :location`
</code>```

It may be enough for your needs, or you can go further and do an OLAP cube with specific dimensions depending on the criteria you need.

If you want to go even further, search about snowflake schema. You can implement it for both date-time and location, given that depending on the context, the star schema (the current one) may be more appropriate.

As suggested in the comments, server logs may be another source for the ETL, replacing the database table. I imagine the pros would be:

No database to create in the first place; no connections to the database to manage, etc.

The previous point also means that you don't have to do anything with your web application to be able to report such statistics. Expanding statistics to other web applications is straightforward too, since you don't need to change them.

Server logs are expected to be very fast, very probably faster than the insertion of a row in a table in a database.

Body:
Ordinary, you'll save the date and time and location of each download, given that the table should be optimized for fast insertion, but retrieval may be slow.

Then, you may have an OLAP cube which, based on the original table, will store the number of downloads in a way appropriate for your criteria, i.e. per day or month or location.

You can start by modeling the table which is used to record download hits:

This gives you basic information about the download, i.e. that a download happened at a given date and time from a given geographical location. isProcessed is 0 by default; you'll see how is it used a bit later.

Given the lack of indexes on the table, insertion of data would be fast. Selection, on the other hand, can be really slow, but it doesn't matter: we wouldn't use this table for search.

The data from this table would be transformed into this one on schedule (at night, every hour, once per second, depending on your requirements). Once transferred, the entry is marked as processed by changing IsProcessed to 1.

This table contains indexes to be able to quickly find the information you need, for example count downloads per location like this:

select sum(CountDownloads) from ProcessedDownload where GeographicalLocation = :location`

It may be enough for your needs, or you can go further and do an OLAP cube with specific dimensions depending on the criteria you need.

If you want to go even further, search about snowflake schema. You can implement it for both date-time and location, given that depending on the context, the star schema (the current one) may be more appropriate.

As suggested in the comments, server logs may be another source for the ETL, replacing the database table. I imagine the pros would be:

No database to create in the first place; no connections to the database to manage, etc.

The previous point also means that you don't have to do anything with your web application to be able to report such statistics. Expanding statistics to other web applications is straightforward too, since you don't need to change them.

Server logs are expected to be very fast, very probably faster than the insertion of a row in a table in a database.


问:
How can I look at a GitHub repository and know what version of the code to download?
I am new to GitHub and new to the open source world (coming from .NET). I have a media wiki site and want to install a Google analytics extension:  http://www.mediawiki.org/wiki/Extension:Google_Analytics_Integration

The extension's documentation says to download the code from GitHub.

In the GitHub repo, there are some "reviews" that say master and some that that say branches. I assume that I want a master and not a branch. But how do I pick which master to download? Also, the documentation says that some of the commits will be tagged but this does not seem to be the case. Without tags/documentation is there any easy way to know what commits are stable and what commits are not?

I'd love some general wisdom about how to approach a repo for a project like this.

答:
In a git repository it is mostly very easy to find that out. There will be different branches and master is just one branch of the branches. In tradition you will find on master the stable/approved/current (depends on branch handling) versions. Some people just develop with master.

If such a repository is hosted on Github (the linked is not), you can see the tags fairly easy. The linked repository seems to put the most recent version on the master branch. You should simply use the latest available commit.

What version you should download depends hugely on how the project is maintained. As an example for a Github repository here the Symfony2 Github repository.


问:
Why should a column in a Relational Database have a single purpose?
Consider a table in which a column represents a monetary value in some cases and a link to the value of another record in other cases so that we have the following:

```
TABLE 1
Id Product Composite
1  Apple   False
2  Orange  False
3  Pear    True

TABLE 2
Product  Date        Price
1        2010-01-01  0.45
2        2010-01-01  0.50
3        2010-01-01  1.00
1        2010-01-02  0.46
2        2010-01-02  0.49
3        2010-01-02  2.00
```

The tables above represent the fact that the price for an Apple and Orange are given on each date by the corresponding Price column in Table 2 so that the price of an Apple on 2010-01-01 is 0.45 and the price of an Orange is 0.50 on that same date, however, the price for a Pear on 2010-01-01 is 0.45 and the price for a pear is 0.49 the following day by allowing the Pear's price to be determined by the price of an Apple on the first day and the price of an Orange on the second day.

Please indicate the pros and cons of this approach?

答:
The approach is, frankly, horrible. As I understand it, you want the column 'Price' to be interpreted as a foreign key to Product.Id, and then "redirect" the query for Pear prices to a query for Apple prices or for Orange prices. This requires complicated logic in your SQL code for what should be a straightforward table look-up, and since data base schema don't have comment fields, it is very easy for someone else to overlook this and simply assume that the price is $1.00.

But quite apart from that: you don't even save anything - neither time nor storage. Instead of abusing the Price column as a foreign key, you could just save the actual price in that column at no extra cost! You would end up with a table that has duplicated values, but that is normal and expected in a large data set.

So overall, I can see only cons and no pros here.


问:
Creating a Website Without a Framework
I've been using PHP Frameworks for so long that I've actually forgot the "best practices" for create websites without one.

Usually I will use Symfony, or more recently I've been using Laravel. A client wants a very simple website, but with certain parts of it dynamic. Due to the nature of the site using Wordpress, or a Framework, is out of the question.

I'm a sucker for priding myself on my code, but I feel like I'm asking such a basic question that it's killing me to ask. But, what are the best practices for creating websites without a Framework?

I like to live by the K.I.S.S (Keep It Simple Stupid!) method of thinking. So, my idea was to just create the .php pages that are required, do any page processing or database interaction on that page, then have the HTML below the closing PHP tag. I would have any helpers/functions in a functions.php file. This is what I remember doing way before I was using Frameworks, and to me it seems like a very old school way of doing things.

I've not created a site without a Framework for literally 2+ years, so I've lost my way with the basics.

Any advice would be greatly appreciated.

答:
You have used Symfony. That is perfect for your need. If you used Symfony, than you will know that you don't need to use all it's components. Quite the opposite is the case. You can basically use each of it's components standalone.

That being said I'd recommend you that you stick with what you know. And even if you would do it without a framework, you would end up with recreating all the stuff a framework already does. It has a reason why frameworks use database abstraction and other forms of abstraction. It makes code much more maintainable.

Going back to the very bad style of programming where you put everything in one php file, is not the solution. It has been never the solution and will never be. People believe it might be basic or quick but in the end it is only a messy code that nobody can maintain.

Title: Creating a Website Without a Framework


问:
Law of Demeter causing subclassing indecision and conflict with Single Responsibility
This is my situation:

I have a class called CueList, which is basically a wrapper around ArrayList. I have another class called TimeTicker that alerts all the Tickable (interface) in its list that a certain amount of time has passed. Since I need to tick all of the items in CueList, but I don't want to violate DRY by keeping a copy of all of the CueList items in the TimeTickable class as well (which would make a nightmare when I want to delete a Cue), my immediate instinct was to make CueList a Tickable and have it pass on the "tick" message to all of its items.

This seems to violate the Single Responsibility principle, which says that CueList should not worry about both keeping track of all the cues AND Ticking them.

So what I did was create a CueManager class that is itself Tickable and links everything up (and ticks all of the CueList elements).

But now, because of the law of demeter, I have a bunch of duplicate methods in the CueManager that just mirror the TimeTicker and CueList class.

Doesn't that mean that the CueManager class has multiple reasons to change? Doesn't that mean it violates the Single Responsibility principle.

Also, since most of the methods in CueManager mirror TimeTicker and CueList, doesn't that really mean that it IS a TimeTicker and CueList. Therefor shouldn't it INHERIT from CueList and TimeTicker! (Obviously you can't do multiple inheritance in Java, but I feel like it sort of makes sense to Inherit from CueList, but then that would violate Single Responsibility)

So in summary:

Law of Demeter makes me make a bunch of methods that merror two other classes, but that makes me think that it really should just inherit from both of those classes, but that would mean that one class handles multiple responsibilities (even if it is through its superclass).

答:
What you are describing is the Observer pattern and Java has already two nice things for that in store. There is the interface Observer and the abstract class Observable. If you use these two, then your TimeTicker does not handle the observer. TimeTicker extends from Observable and does only the stuff it needs to do. When a certain amount of time has passed, it calls the method setChanged and notifyObservers.

Your TimeTicker does know 0 Tickables (Observer). The Observable abstract class does only know them via the interface Observer. Every Tickable can now register itself as an observer to the TimeTicker without a problem.

That being said you don't even need CueList anymore as the list of observers is handled by the abstract class Observable.


问:
Best books on Managing a Software Development Team?
The canonical books on software development is fairly well established. However, after reading through a dreadful book full of bad advice on managing programming teams this weekend I am looking for recommendations for really good books that focus on the management side of programming (recruiting, performance measurement/management, motivation, best practices, organizational structure,  etc.) and not as much on the construction of software itself.

Any suggestions?

答: The Mythical Man-Month. This is essential reading.</p>

ContentLicense: CC BY-SA 2.5


问:
Unit testing and coupling
As a developer I should strive for low coupling between classes.

But low coupling doesn't mean "No coupling" so sometimes I have to allow some code flexibility and use "new" inside a domain model. (I'm sure everybody does this in real production code)

If I use "new" inside a method to create an object and I have to unit test this method I got a problem. Because I can't mock the objects I can't test the method in isolation. I know I can use dependency injection or I can send objects as parameters but I'm not talking about this clear cases.

Is this acceptable in practice?

Is there a better way? (I can't always inject)

Is this a unit test or an integration test?

PHP example:

```<code>class Car {
   protected $objDoor;
   public function createComponents() {
       $this->objDoor = new Door();
   }
}
</code>```

答:
Dependency Injection

I think is strongly depends on what object you are creating. If you create object that you then return, it is somewhat part of the specification of the method. In that case it would be basically possible to do a unit test.

As you would do a unit test for the class in question (the one you use new on) as well, this shouldn't be the main problem. But if you create an object and do some stuff with that object (produce side-effects), you should use injection. This is true even more if you get all the parameters for the constructor call as parameters of your method. Simply create the object before calling the method and give the reference instead.

But of course that would imply that the method in which the object is created, would be doing the same thing now.

That being said you will need some kind of central mechanism that handles the dependency injection. Symfony provides a Dependency Injection component that handles that stuff.

Code coverage

It is important to have code coverage. It depends strongly on your project how well that can be done. Whenever possible unit tests should be written. On top of that you should use functional tests that test a certain function (and thereby the interaction of needed classes). All in all that should fit your need.

Title: Unit testing and coupling


问:
What to use in UML for included module in ruby?
I like to create simple class diagrams for my projects. Most of the time I just use composition, inheritence and associations.
IBM's basic UML resource tells all about this.

However I'm using ruby so I got the option to define a module with some methods. I can just include this module in every class where I want to use these methods. This could be interpreted as an inheritence, however some of my classes are already child classes of an other class and I don't want to mix the meaning of a symbol used in my diagrams.

How should I display an included module in my class diagrams in UML?

答:
UML does not have this kind of module concept, so it aso does not have a defined way to represent them in a diagram.

A few possibilities are:

Don't show the module inclusion in your UML diagrams. UML does not require all details to be present in the diagrams and you can just decide that the fact that some of the methods are actually provided through Ruby's module mechanism is one such hidden detail.

Model the Ruby modules as UML packages/classes and use a simple dependency to indicate the inclusion.

Model the Ruby modules as a special kind of base class (you can mark them as special by using a stereotype for them, for example <<module>>)

ContentLicense: CC BY-SA 4.0


问:
OwnCloud App Licensing
I'm a bit confused about the OwnCloud licensing model. OwnCloud is an AGPL licensed product (at least the open source version is). Does that mean that the only license I can use for an OwnCloud app I write using the API would be AGPL as well?

The way I understand it, the AGPL license is so restrictive that no app can be written without it having to be released under the AGPL, which would include custom apps for customers who don't want to spend a small fortune on the OwnCloud Enterprise edition. Somehow that feels wrong, so I might have gotten it all wrong and would be happy if somebody with a clear understanding of this topic could shed some light on this.

答:
The AGPL version 3 is compatible with the GPL version 3 and the LGPL version 3 is also compatible to GPL version 3. That being said you can publish the app under the AGPL v3, the GPL v3 or other compatible licenses.

These licenses allow you to sell the app but the buyer is allowed to publish the app for free. That is the goal of the General Public Licenses. The licensed software is and will always be free software and all software that use parts of it will always be free software.

But you do not need to sign a contributer agreement of OwnCloud as that is only required if you want to contribute to the core.

In the end there is nothing wrong with that.

Title: OwnCloud App Licensing


答:
Frameworks are there to make your life easier. And so, like most things, your approach should be determined by the needs of the client.

TL;DR Use a framework, especially if the project is going to grow, otherwise use the simplest and quickest way forward.

If most of your sites are simple sites, with a little bit of dynamic, then I suppose there's compelling reason to use a framework. However as your project grows, having a good framework is invaluable. I've had the unfortunate privilege of working on some complicated software for an insurance firm that was built without a framework. They figured "lets build our own framework, since this project is so small". Years later it caused headaches.

Personally, I use frameworks for everything. I've moved from php to python and use a 'micro framework' called flask. Its super quick to get the basics up and running, yet adds structure should a project go. In my php days I used cakePhp and it worked really well for the simple projects I did back then.

Title: Creating a Website Without a Framework

Body:
I've been using PHP Frameworks for so long that I've actually forgot the "best practices" for create websites without one.

Usually I will use Symfony, or more recently I've been using Laravel. A client wants a very simple website, but with certain parts of it dynamic. Due to the nature of the site using Wordpress, or a Framework, is out of the question.

I'm a sucker for priding myself on my code, but I feel like I'm asking such a basic question that it's killing me to ask. But, what are the best practices for creating websites without a Framework?

I like to live by the K.I.S.S (Keep It Simple Stupid!) method of thinking. So, my idea was to just create the .php pages that are required, do any page processing or database interaction on that page, then have the HTML below the closing PHP tag. I would have any helpers/functions in a functions.php file. This is what I remember doing way before I was using Frameworks, and to me it seems like a very old school way of doing things.

I've not created a site without a Framework for literally 2+ years, so I've lost my way with the basics.

Any advice would be greatly appreciated.


答:
As it was suggested in another answer, it might be worthless to include the module in your diagram.

If you do it anyway, I think you could do the following (some were suggested in another answer):

You can consider the methods and variables in a module as static. you should thus underline them.

You can create a specific stereotype for the modules to qualify them better.

You should only use depency relationships (such as << use >> )

Title: What to use in UML for included module in ruby?

Body:
I like to create simple class diagrams for my projects. Most of the time I just use composition, inheritence and associations.
IBM's basic UML resource tells all about this.

However I'm using ruby so I got the option to define a module with some methods. I can just include this module in every class where I want to use these methods. This could be interpreted as an inheritence, however some of my classes are already child classes of an other class and I don't want to mix the meaning of a symbol used in my diagrams.

How should I display an included module in my class diagrams in UML?


问:
Display error message with jQuery without reloading page
I created login form. When user clicks on login button this form shows up with some fade effect (jQuery). What I want to do is to display error message in this form when user inputs invalid data. Before showing any messages, PHP must read data from database, therefore page must be reloaded and when page is reloaded this form fade away. How can I display error message in this login form without reloading page?

(I have lots of code so if you need any part of code I will provide)

答:
What you are looking for is JQuery's ajax methods.

They can get data from the server and update your dom on the fly without a page reload.

This is pretty straightforward using Get or Post

JQuery also has some other ajax methods which may be useful as well.


答:
If the repository is following the usual patterns (which is slightly more likely for Git repos than other VCS, in my experience) then you want the master branch for stable releases. In theory, if it's in master then it should be tested and working, so the most recent commit to master should be the most recent stable release.

Looking at the repo you linked, I go straight to the "branches" section, and see "master". Clicking on that, I see that this commit is tagged REL1_21, which I assume means release 1.21, which I'm guessing corresponds to the name for this version used within their documentation. That's a good place to start.

Quickly scanning up from there, I see mostly commits by a bot, updating localisation. Probably nothing breaking in there. There's also one commit that mentions a change. If they're doing things properly, this should be a fix, and definitely not a breaking change, because it's a commit to master without a version tag. Checking the comment on this commit, I see that it mentions steps taken to preserve backwards compatibility.

Now that I'm happy that nothing bad has been pushed to master since the last release, I simply grab the latest commit: at time of writing, that's this one. If I have problems with this version, or if I wasn't convinced that the change was safe, I'd get the last tagged commit, and stick with it until they add a version to master tagged with something higher than 1.21, (which, based on a quick guess at their versioning system, would be either REL1_22 or REL2_0).

Of course, one would hope that the project's documentation would point you to the correct version, rendering this process of figuring it out yourself unnecessary, but sadly that isn't always the case. When you find yourself in this situation, the process I used here works for most repositories, Git or otherwise, provided a vaguely sensible branching strategy has been used:

Find a branch called "main", "master", "stable" or something similar

Find the last version-tagged commit to that branch

Check nothing odd has been added to that branch - anything that might introduce breaking changes

If there's nothing, grab the latest commit

If there is a potentially problematic change, grab the tagged commit

Either way, if you have problems with the version you have, move back to the previous tagged commit.

When you find a version that works, stick with it until they release a new tagged version, then get that. If it doesn't work, move back to the one you were on before and wait for a new version.

Title: How can I look at a GitHub repository and know what version of the code to download?

Body:
I am new to GitHub and new to the open source world (coming from .NET). I have a media wiki site and want to install a Google analytics extension:  http://www.mediawiki.org/wiki/Extension:Google_Analytics_Integration

The extension's documentation says to download the code from GitHub.

In the GitHub repo, there are some "reviews" that say master and some that that say branches. I assume that I want a master and not a branch. But how do I pick which master to download? Also, the documentation says that some of the commits will be tagged but this does not seem to be the case. Without tags/documentation is there any easy way to know what commits are stable and what commits are not?

I'd love some general wisdom about how to approach a repo for a project like this.


问:
How to implement multi-theme PHP application
I am developing an application which will handle many virtual stores and I would like to have many themes that the user could choose anytime. I would to know what's the main ideia to implement it. I will be developing it using Symfony 2.

I was thinking about implementing own views and assets for each theme

Resources

views

theme 1

Product

List.html

Detail.html

...

theme 2

Product

List.html

Detail.html

...

theme 3

Product

List.html

Detail.html

...

public

theme 1 assets

js

css

images

...

theme 2 assets

js

css

images

...

theme 3 assets

js

css

images

...

And in the database each user would have own preferences(theme name, color, etc...).

I am looking for an implementation which will allow me to add any kind of theme. For exemple, one theme, in main page the cart icon will go cart page and another theme, cart icon will pop up a window showing products.

What's the best approach to implement multi theme web application? What I am missing?

答:
Maybe I am misunderstanding what you mean with theme, but a theme is a style for me. So the structure itself remains the same but the visual style can change. To have an idea what I mean, here a few links to the same site with the same content, just with different styles:

default style

battlefield style

creative 3d layout

freedom of life style

For that goal you don't need different views just different CSS. If you want to change the behaviour of the application though, you would basically need to recreate code (which increases duplication). In case of code change (JS is part of a web application as well), you would need to change the connected code of all themes.

Your shown approach fits best for a multi-behaviour application that offers different forms of interaction with it. For such a goal you will need different JS and different views (as the HTML will be different too).

Since you basically put function and style together in a theme, I recommend you to split it up. Have different style possibilities by CSS changes only (use a lot of css classes in the HTML so that you can change the visual appearance). For the functional changes you should allow an option in the application to choose which function shall be used.


问:
Why don't companies ship multiple modules within a mobile app? Are there concerns about tight coupling?
Preface: My question does not exclusively pertain to Google and it doesn't exclusively pertain to iOS. I'm only using Google and iOS as examples because they are familiar to many. I could have just as easily used 'Company X', apps 'A', 'B', 'C', 'D', and 'E', and 'Android', but I wanted to keep my question rooted in the real world with a tangible example.

In the iOS app store, Google has many apps. At a glance, I can see 'Google Search', 'Google+', 'Google Maps', 'Google Earth', and 'Gmail'.

But I wonder - Why didn't Google simply create a 'Google' app which can provide all of the functionality that these five apps provide? The black menu bar at the top of each Google webpage makes this possible on the web; so why don't they make this possible by way of a menu button at the bottom of one "global" Google app?

Is Google concerned about tight coupling between the apps?

Is Google concerned about tight coupling between the teams that develop the apps?

Is Google concerned about app size?

Is Google concerned about the memory footprint or CPU load that such a monolithic app might incur when it is loaded?

[Not a rant. Merely playing devil's advocate.]

In spite of many advantages, some iOS critics say that multiple pages of apps leave the iPhone and the iPad feeling "cluttered". This is particularly relevant to my question because it seems a bit much to expect a user to know about (and manage) so many Google mobile offerings. From a product standpoint, and arguably a usability standpoint, it seems like it would be wise to ship a single app.

If you're curious, I own an iPhone and a Nexus 7; so I'm not wedded to either of the two major mobile platforms.

And I have a real problem to solve here - Whether to bundle multiple apps inside of one large app, or to distribute separate bits of functionality in multiple apps.

EDIT: In response, to @MichaelT's comment

While there is indeed a 2GB size limit for apps, the size of your sandbox is only limited by the remaining capacity on the device.

答:
Can't say what Google are concerned about, but what I think:

Is Google concerned about tight coupling between the apps? - Having the apps together means you can't update them separately. Every minor update in a single (sub)app would result in an update in the app. This means many small updates frequently or few larger updates rarely (which is not good for bug fixes).

Is Google concerned about tight coupling between the teams that develop the apps? - The teams can work separately but there must be coordination between them. Especially for build and integration of the apps together. A positive side is that fewer build/architecture engineers might be needed as only one app is built (there is no need for such members in each team)

Is Google concerned about app size? - The size is a valid concern in mobile environment. But I think the app's size itself is not a big issue as it's downloaded once. I am more concerned about the frequent updates, sometimes not desired by the user (if a subapp that he/she's not using is updated). Slow networks and data charges are the main reasons - imagine having to wait for an update that you don't need, because it updates a part of the app you don't use. And you have to pay for it...

Is Google concerned about the memory footprint or CPU load that such a monolithic app might incur when it is loaded? - Depends on how the app is structured it might not need so much memory/cpu compared to when it's separated. But the size of the app/resources would be bigger. There are various constraints like methods/classes count in an application. It might occupy too much space on the built-in storage.


问:
Why is #include <iostream.h> bad?
I was reading another thread where a guy asked about C++ books for beginners, and one of the programmers answering wrote this:

Some warnings: avoid all books that present an "hello world" stating with

```<code>#include <iostream.h>
</code>```

I opened my C++ book and sure enough it included the iostream header like the example above.

Why is that bad? What other pointers should I keep in mind when learning C++?

Background: I am proficient with C and I'll start to learn C++ this next semester.

答:
Maybe this comes a bit late but for what it's worth, on a unix/linux box do ls /usr/{local/,}include/c++/* or similar, according to your layout and paths. You could pipe to grep looking for the header in question, like:

```<code>ls /usr/{local/,}include/c++/* | grep iostream
</code>```

This entails a look-up for iostream.h as well as any other superstrings.

Or run find / -type f -name iostream 2> /dev/null | grep include or locate iostream | grep include (provided the database is current, otherwise prepend with a call to updatedb)--these, however, will print also non-system-wide includes, so please adjust appropriately.
The actual C++ include path is easily found with something like:

```<code>g++ -v 2>&1| sed -rn 's/.+gxx-include[^=]+=([^ ]+).+/\1/p' # adjust iff empty
</code>```

Equivalently on Windows and other machines. I guess the idea is clear--such a file as iostream.h doesn't exist in the system include path by default any longer, you still, however, can find legacy libc++ distributions with iostream.h either soft-linked to iostream or as its copy. So this is not a matter of style but rather of the circumstances. You could ship your own iostream.h with your project just make sure it's contained in the include path where your compiler looks up for the <...> headers.

Title: Why is #include <iostream.h> bad?

Body:
Maybe this comes a bit late but for what it's worth, on a unix/linux box do ls /usr/{local/,}include/c++/* or similar, according to your layout and paths. You could pipe to grep looking for the header in question, like:

ls /usr/{local/,}include/c++/* | grep iostream

This entails a look-up for iostream.h as well as any other superstrings.

Or run find / -type f -name iostream 2> /dev/null | grep include or locate iostream | grep include (provided the database is current, otherwise prepend with a call to updatedb)--these, however, will print also non-system-wide includes, so please adjust appropriately.
The actual C++ include path is easily found with something like:

g++ -v 2>&1| sed -rn 's/.+gxx-include[^=]+=([^ ]+).+/\1/p' # adjust iff empty

Equivalently on Windows and other machines. I guess the idea is clear--such a file as iostream.h doesn't exist in the system include path by default any longer, you still, however, can find legacy libc++ distributions with iostream.h either soft-linked to iostream or as its copy. So this is not a matter of style but rather of the circumstances. You could ship your own iostream.h with your project just make sure it's contained in the include path where your compiler looks up for the <...> headers.


问:
Is the database the bottleneck or not? High Scalability talk
I found an interesting article on high scalability web site where it talks about EBay scalability and especially a specific passage struck me:

"(Ebay strategies)...Move work out of the database into the
  applications because the database is the bottleneck. Ebay does this in
  the extreme. We see it in other architecture using caching and the
  file system, but eBay even does a lot of traditional database
  operations in applications (like joins)."

and the above is no mistake because again in the same article:

"Move cpu-intensive work moved out of the database layer to
  applications applications layer: referential integrity, joins, sorting
  done in the application layer! Reasoning: app servers are cheap,
  databases are the bottleneck."

Any explanation on this? If the above were true then I should only use the database for retrieving data and do all other operations in the programming logic.

I was always told the opposite: "databases are optimized for operations on data and complex selects so use them".

Any insight?

答:
Memory is fast and non-durable, while drives are slow and durable. If you pull data out of a database and pop it into memory, its access will always be significantly quicker the downside is that if the server fails, you'll lose the data.

Databases are a great fit for most applications out there. Only a small percentage of applications have the scale of google, twitter etc, and while its always fascinating on how those companies have overcome their challenges, it would be naive to try implement their solutions from the word go.


问:
Data transfer between "main" site and secured virtual subsite
I am currently working on a C# ASP.Net 3.5 website I wrote some years ago which consists of a "main" public site, and a sub-site which is our customer management application, using forms-based authentication. The sub-site is set up as a virtual folder in IIS and though it's a subfolder of "main", it functions as a separate web app which handles CRUD access to our customer database and is only accessible by our staff.

The main site currently includes a form for new leads to fill in, which generates an email to our sales staff so they can contact them and convince them to become customers. If that process is successful, the staff manually enter the information from the email into the database.

Not surprisingly, I now have a new requirement to feed the data from the new lead form directly into the database so staff can just check a box for instance to turn the lead into a customer.

My question therefore is how to go about doing this? Possible options I've thought of:

Move the new lead form into the customer database subsite (with authentication turned off).

Add database handling code to the main site. (No, not seriously considering this duplication of effort! :)

Design some mechanism (via REST?) so a webpage outside the customer database subsite can feed data into the customer database

How to organise the code for this situation, preferably with extensibility in mind, and particularly are there any options I haven't thought of?

答: I would think option 3 would be the better option. You would pass the data via a service to insert the data to your database. You should of course check what is calling your service maybe a client side cert, ip address range check, sanity check the data.</p>


答:
"Measure. Don't Guess".

We can't assume that Ebay's bottlenecks are the same as our own. For the specific applications that I work on, when a bottleneck exists it is rarely the database (or if it is, it's because of poorly optimized queries). I know this because we've reviewed the instances of poor-performance and profiled the performance of normal performance of our application.

Title: Is the database the bottleneck or not? High Scalability talk

Body:
I found an interesting article on high scalability web site where it talks about EBay scalability and especially a specific passage struck me:

"(Ebay strategies)...Move work out of the database into the
  applications because the database is the bottleneck. Ebay does this in
  the extreme. We see it in other architecture using caching and the
  file system, but eBay even does a lot of traditional database
  operations in applications (like joins)."

and the above is no mistake because again in the same article:

"Move cpu-intensive work moved out of the database layer to
  applications applications layer: referential integrity, joins, sorting
  done in the application layer! Reasoning: app servers are cheap,
  databases are the bottleneck."

Any explanation on this? If the above were true then I should only use the database for retrieving data and do all other operations in the programming logic.

I was always told the opposite: "databases are optimized for operations on data and complex selects so use them".

Any insight?


答:
Yes, relational databases are bottlenecks when it comes to horizontal scalability; in order to scale your RDBMS server in most cases you need a more powerful machine and this leads to a limit. This is one of the main reasons why NoSQL databases have appeared as an alternative to RDBMS, by trading off ACID transactions. The bottleneck is even bigger if you put application logic in the database, in the form of stored procedures.

By shifting the processing power in the application tier, your whole application can scale out more easily, since a well written application server can be deployed on multiple machine servers. An alternative to this is using the above mentioned NoSQL data stores for achieving scalability; NoSQL data stores can also be easily deployed onto multiple nodes.

Note, that this only makes sens in a high-scalability talk, as you have pointed out in the question. In most cases, when used properly, databases represent no  real bottleneck and do their job very well as they have done it for decades.


问:
Decoupling Components - Design
I have created a a number of non-trivial scripts in Python that do some long running reporting. At first these reports started off as scripts with a config file. Then I added in the a database component to persist data. Now I'm building a GUI to sit on top of all of them.

My question relates to design. Each time I add an additional requirement, I find myself wishing I had decoupled the components of these scripts more than I did. When I consider how to recfactor my code to be more modular, I find that I need to pass quite a few references around the code, to the point that class initializers and function signatures have a ton of parameters. Also I find myself having parameters that are simply "pass-through", in that one object needs them only to pass to another object, doing nothing with them.

What is the best way to approach modularity in Python while minimizing the need to pass references all over the place?

I understand this is very conceptual and will vary by design, but I'm looking for guiding principles.

答:
You have correctly realized that modularization is key for a well maintained software. Without a specific problem I will have to limit it to a general answer.

Structure

Each module has one function. That being said there are a few classes that represent the external interface for the module and others that are only used internally. Those that serve as an interface need to get everything they require for an action via parameter. If the parameters are non-trivial types, you should use an interface for the parameter type. That way the class only knows about a certain public interface of the objects it receives but nothing about the specific class.

Some modules need other modules. There is a simple approach to this. You have tools, services, materials and values (see tools and materials approach). Tools can use every type of class. A service can only use other services, materials and values. A material can only use materials and values and finally a value can only use values.

The values represent immutable values in the subject matter. In the banking area this might be an amount of money. Though the amount itself might be variable (you can have 100, 200, x bucks), the value is not. You don't change 100 to 200. You simply take the value representation of 200.
The materials represent things in the subject matter (like a bank account).

Services are used to change materials and operate subject matter operations (e.g. a lending service that is used to lend out movies). They also contain the business logic to determine if a certain operation is valid.
The tools are the interaction point with the user. They mostly work on one material or service. There can be sub-tools. The tools are the interface to the GUI (be it desktop based of web based).

That being said you can ensure that each module contains only one kind of classes and one responsibility.

Dependency Injection

But how does Dependency Injection now work without polluting other classes? It is allowed to use new statements within tools classes to create sub-tools. As tools are mostly technology oriented, it is not very easy to test it automatically (as they require other classes to do the heavy work). Important is that every dependency to another module (be it services, materials or values) is given via parameter.

In the end you need one class that ties the modules together, initializes the services needed in the software and gives them to the appropriate classes via parameter injection (be it in constructor or setter method).

The tools by the way get their needed object references (if not via parameter) from the GUI, so there is not much relaying of references through the system.

Title: Decoupling Components - Design


问:
Do JAX WS implementation classes come as part of the Java 5/6 package or only as part of an application server libraries?
Do JAX WS implementation classes come as part of the Java5 package, as part of the Java6 package or only as part of an application server libraries like WAS?

I read that it comes as part of Java EE? What does that mean? Java 5?

答:
JAX-WS is an API which is part of both JavaEE 5 and JavaEE 6 APIs. The implementation of JAX-WS is not part of the JavaEE API. There are multiple implementations of the JAX-WS; noticeable ones are:

Metro - the reference implementation, and part of the Glassfish application server (it is open-source so you can easily find sources)

CXF - part of an Apache open-source project (easily found sources)


问:
Under what conditions should I rebase rather than merge?
Here is, roughly, our structure of work using git, for web development. We have a master branch, and individual or groups of work are done seperately in branches, then merged in.

A ticket (or several) comes in.

We create a branch on our local development repository, and push it to origin.

We fix the tickets in code, commit the work and push to origin.

Once we're happy with our work, we pull the branch down to a repository on our UAT / Staging server and check it out for the client to review.

The client approves the work.

We go back to our local development repository, we check out master, merge the branch, and push to origin.

We create a tag from master afterwards.

We then go on the live server, pull master and move/update the tag to the new one.

There are 7 of us, working on about 15 projects or so throughout the year. Generally, one person is sufficient to work on a project at any one time, but sometimes two people might work in separate branches with a view to merging into the master branch around the same time.

Generally we think merging is best because it, as I understand, preserves a development history with regard to what was merged and when. Whereas rebase seems to completely destroy this and linearize the master log.

Why would, if this assumption is correct, someone want to use rebase? Is it only for extremely busy projects that are constantly being branched and merged and there needs to be a guarantee that merges are successful - so developers can test out adding master to their work and resolve conflicts before merging back in?

答:
rebase may only be used on work in progress that was not merged anywhere yet (not even into your colleagues. Once the work was merged, you must not rebase (or amend) it. If you try, you'll create unbelievable mess.

For work in progress however rebasing is often appropriate. It is used to keep merges out of the work in progress and to keep the work in progress organized in logical rather than historical steps. Which is useful if:

Somebody will be reviewing the changes before integrating. Larger changes are much easier reviewed in series of logical steps, but they must be logical steps.

You want to similarly review the changes yourself to be sure you didn't do any unrelated or inappropriate changes.

You have some experimental changes among changes you need to integrate (the rebase -i lets you reorder the changes).

(Linux development always included reviews that required the changes presented in patch series, which is what inspired git rebase, especially the interactive one)


问:
Does dealing with legacy code help one evolve as a programmer?
I'm a Java developer with a bit more than a year of experience which places me somewhere above a junior, but not among mid-level developers yet. Recently I was offered a long-term project which is about studying an existing banking application code for 4 months and then introducing changes when needed. As a not-so-experienced programmer I'm looking for ways to develop and I wonder what such a project might give.

Would you consider dealing with a big and probably not-so-well written application a good practice for a beginner?

答:
It very much depends on how you define "legacy" in this context. Let me give you an example from C and C++. Many C++ programmers call it a bad practice to use C strings in C++ applications, others demand no mixing, while others, in turn, claim that it be sheer and utterly pointless to use any bits of C code because they are old, i.e., "legacy" code. Some go further and avoid using pre-C++X (replace the 'X' with the appropriate number) standard idioms, style--that is syntax, for it's "legacy" style.

Leaving aside performance issues of C++ streams and strings and a few STL peculiarities, it sure is a great practice to have a look at what's inside your so much beloved preprocessor directive #include <string.h>. If you follow the path to the implementation and find yourself on a unix/linux machine at /usr/include/string.h (and get libc implementation sources, for example, from gnu.org) and read strcmp.c or strlen.c or strtok.c, I bet you're gonna hear "What a beautiful world" phasing in.

There is, however, a caveat to this prose--namely, deprecated classes and methods. In Java quite a lot of legacy stuff is still accessible from within a recent environment, but if I recall correctly, not everything. In the IB sector, from my own experience, well, not all software is written by good programmers. Lots of graduates had had virtually zero exposure to real-world programming before they started out at an analyst/developer position. But don't generalize this statement. I know lots of folks who employ Java and C# at the core of high-throughput, low-latency environments. I don't agree with them, but well, this is fortunately their business. Had they gone real HFT though, they'd get pushed way behind in the line. But again, easily inferred from this sentence is the assumption (and in many cases the fact) that Java code is highly optimizable. And if you can excel at optimizing, if required, not only fixing this or that, you'd become invaluable as a dev. It's very satisfying by the way to realize how much you have contributed. I'd go for it.


答:
If you REALLY don't want to use an out of the box framework, then design your app using some of the principles you have already learnt from your experience with frameworks.

You could follow the Symfony style, having an Entity represent your objects and acting as a basic abstraction for your DB, then a series of Controller classes which handle the routing and interactions with the view. Then finally, pick a templating language and use that within your view.

As stated, throwing all the code together in a few files is taking a step backwards.

Title: Creating a Website Without a Framework


问:
Are missed deadlines common in programming jobs?
It was my freelancer job at oDesk. I have done several jobs earlier in given time, but is was the first time I missed the deadline. It was a very lengthy job and I tried my best but I still missed the deadline. Now, I am very scared. Because it's my fault that I missed the deadline.

My question is: Is this is a big concern or are missed deadlines common among programming jobs, so I shouldn't worry too much about this?

答:
Yes. Missed deadlines are common in software development.

Many freelancers meet deadlines by incurring in technical debt or hiding the dirt under the rug.

Paraphrasing Frederick Brooks' The Mythical Man Month:

Deadlines are often missed because project leaders continue to estimate software tasks the same way they do civil engineering tasks, which is a flawed approach because software is a novel, handicraft industry with no clear body of norms. This is so true that you cannot revoke a programmer's "permit" to code for malpractice, nor you can sue someone for programming without a title.

Software development has inherent complexity that other disciplines lack. A big program can have more components than a car, and these components can interact in more, different ways.

Software is hard to visualize, so different kinds of diagrams are used to see different aspects of a project, and these aspects may not be orthogonal. Civil engineering, on the other hand, has blueprints allowing you to see plumbing, wiring etc. all in the same chart (or layers) in an orthogonal way.

It's not common, after a bridge or building is half built, for the client to completely change the scope of the project. This is often the case in software projects.

The state of the art in software development hasn't reached the point where software projects are repeatable and almost risk free. Even the largest software companies like Microsoft can miss deadlines by months or years.

Most vaporware is nothing but software projects that were cut because of these kinds of problems.

In conclusion:

Bad estimates and underestimation of complexity, due to the handicraft nature of the software development process, mean it remains an immature discipline.


答:
Missing deadlines isn't uncommon in software development. It is almost impossible to accurately estimate how long a software project will take.

Professionalism is shown in how you deal with it. When you know you will miss a deadline, inform your client as early as possible about it so they can plan accordingly.

Title: Are missed deadlines common in programming jobs?

Body:
It was my freelancer job at oDesk. I have done several jobs earlier in given time, but is was the first time I missed the deadline. It was a very lengthy job and I tried my best but I still missed the deadline. Now, I am very scared. Because it's my fault that I missed the deadline.

My question is: Is this is a big concern or are missed deadlines common among programming jobs, so I shouldn't worry too much about this?


答:
I'd second what Jim Martens writes. Unfortunately I can't leave a comment yet due to too few rep points over here.

Let me add this, though:

A few years back, some 10 years, actually, I emulated the CMS project from which joomla was forked from the ground up, with several features of my own like a completely multilingual interface or a hugely simplified code base with less generalization. To simplify the themes backend, I used different CSSs without changing the interface file--the layout, it was in my index.php. I did over time, however, have to add some small-scale functionality to dynamically generate the CSS. The structure remained the same.

If you are using some database for your project, which I assume you do, you could add on a per-page basis a field stating which theme to use for it. Or you could categorize the tree by telling, instead of which theme to use, the page's parent page to inherit that value from there. The base node of a branch of pages must then--as a database entry--have the field with the theme name.

An easily maintainable approach would be to keep a separate layout file per branch of pages and let them inherit the style and the layout from their respective parent node, so in effect you would only replace the content in that files. The layout would be fixed, the style too. Should you, however, need a dynamically adjustable style, that is, without reloading the page, do it with JavaScript.

You could also have a single file with the basic layout, write specific layout generators, and rewrite the paths to GET via .htaccess on an Apache httpd or in the nginx config. But this is obviously more demanding, albeit easily to scale up.

Title: How to implement multi-theme PHP application

Body:
I am developing an application which will handle many virtual stores and I would like to have many themes that the user could choose anytime. I would to know what's the main ideia to implement it. I will be developing it using Symfony 2.

I was thinking about implementing own views and assets for each theme

Resources

views

theme 1

Product

List.html

Detail.html

...

theme 2

Product

List.html

Detail.html

...

theme 3

Product

List.html

Detail.html

...

public

theme 1 assets

js

css

images

...

theme 2 assets

js

css

images

...

theme 3 assets

js

css

images

...

And in the database each user would have own preferences(theme name, color, etc...).

I am looking for an implementation which will allow me to add any kind of theme. For exemple, one theme, in main page the cart icon will go cart page and another theme, cart icon will pop up a window showing products.

What's the best approach to implement multi theme web application? What I am missing?


答:
One option would be to extend UML. That's what Schärli et al did when they invented traits, which are close relatives to mixins. The simply invented an addition to UML that allowed them to represent traits. Of course, such mixin-extended UML can no longer be produced or processed by existing UML tools, you would have to extend those tools, too.

An alternative is to look at what a mixin really is at its core: a mixin is a class that is parameterized over its superclass. (Think: class MyMixin<T> extends T.) In Ruby, that's even how it's actually implemented: include creates a new class which shares its method, constant and module/class variable tables with the mixin, gets the current superclass of the class it is included into as its superclass and then becomes the mixed-into classes' superclass.

Compared to multiple inheritance: with multiple inheritance, a class may have multiple superclasses but only appears once in the inheritance graph. With mixins, a mixin class may appear multiple times in the inheritance tree but at each occurrence has only one superclass (which may be different from the other occurrences).

So, you could represent a mixin as a superclass in the inheritance chain of every class it is being mixed into, with some additional relationship between those classes to indicate that those are actually the same mixin, just with different superclasses. For example, represent them as template instantiations (<<bind>>) of a MyMixin<T> template which has T as its superclass (if that's possible). Or just make up your own relation, such as <<same mixin>> or something.


问:
Sending exactly one notification n seconds after the event
I have a system that checks the status of a number of systems, such as, is http up, does the system respond to ping, that sort of thing.

I check all of these systems every 5 minutes. If something is broken, I send out an e-mail with a notice. If the problem is cleared I send out an "all clear, problem resolved" notice too.

I want to send out a notice 30 minutes after a problem is detected and the problem is still ongoing and then at failure +1h, +2h, +4h, etc. I do not want to flood the user with messages every time the event "problem still ongoing" occurs which is every 5 minutes.

I could store a "last notification sent at" somewhere and just work with that but I would rather just solve it in the code itself. Am I missing something very obvious or is this the only feasible way?

答: I think the most straight forward way of achieving what you want is to store the state of the monitored systems as well as whether a notification was sent at the point in time that your process runs. Depending on how many systems and metrics you are monitoring this could be as simple as writing a few entries to a flat text file. </p>


答:
IANAL and this is not a legal advice. Furthermore the copyright laws and exceptions differs from country to country.

In US the API cannot be copyrighted. Therefore technically if you use the API you can use any licence you want for your application. I don't know about any interpretation in this respect in other parts of world.

However even if you distribute your application separately it might have an effect on the joined product. Depending on how the "work as a whole" is interpreted if it is server side the joined work might be binding on AGPL or it cannot be run. So you may need a licence which is compatible with AGPL and is 'upgraded' to AGPL. So while the source code is theoretically on weaker licence you de-facto use AGPL (unless user have implementation of API on another license). This is similar to definition of 'derived work' discussion with GPL and I am not aware of any binding interpretation one way or another.

If your application is not joined with server (communicates by network) my interpretation (after very quick look on AGPL) is that it can be on any license.

PS. As others pointed out you are allowed to charge for application on AGPL.

Title: OwnCloud App Licensing

Body:
I'm a bit confused about the OwnCloud licensing model. OwnCloud is an AGPL licensed product (at least the open source version is). Does that mean that the only license I can use for an OwnCloud app I write using the API would be AGPL as well?

The way I understand it, the AGPL license is so restrictive that no app can be written without it having to be released under the AGPL, which would include custom apps for customers who don't want to spend a small fortune on the OwnCloud Enterprise edition. Somehow that feels wrong, so I might have gotten it all wrong and would be happy if somebody with a clear understanding of this topic could shed some light on this.


问:
Creating a Website Without a Framework
I've been using PHP Frameworks for so long that I've actually forgot the "best practices" for create websites without one.

Usually I will use Symfony, or more recently I've been using Laravel. A client wants a very simple website, but with certain parts of it dynamic. Due to the nature of the site using Wordpress, or a Framework, is out of the question.

I'm a sucker for priding myself on my code, but I feel like I'm asking such a basic question that it's killing me to ask. But, what are the best practices for creating websites without a Framework?

I like to live by the K.I.S.S (Keep It Simple Stupid!) method of thinking. So, my idea was to just create the .php pages that are required, do any page processing or database interaction on that page, then have the HTML below the closing PHP tag. I would have any helpers/functions in a functions.php file. This is what I remember doing way before I was using Frameworks, and to me it seems like a very old school way of doing things.

I've not created a site without a Framework for literally 2+ years, so I've lost my way with the basics.

Any advice would be greatly appreciated.

答:
While there is nothing inherently wrong with the idea of rolling a custom framework, the reality is that most 'frameworkless' PHP programmers are not really creating interesting content, they are just naive about what comprises a production ready application and repeating the same common security errors over and over again.  Consider the following resources just on the security aspect of web applications:

The OWASP Top Ten Project  (note: that is only the top ten)

Security issues in similar frameworks: Symfony, Zend

PHP Security Patches

Browser updates (ie, chrome, firefox, android, ios, etc...)

You should be aware of all of these things even if you use a known framework, the difference is that without a framework, you are solely responsible for implementing and maintaining these changes alongside the ones for your specific application.  With a framework, you have help with most of these issues.

It's hard for me to buy the idea that a lone programmer can solve these problems any better without spending years of time, and while having a specific application to build aside from the web framework.  It is not impossible, but usually those that succeed release their work as another framework, so unless that is your intention, it is not advised to down the custom framework path.

Also see this answer for more detail.

Title: Creating a Website Without a Framework


答:
You could first of all store the status of all systems connected with a given recipient, e.g.

```<code>[ {
    recipient: 'lserni@gmail.com',
    situation: [
        { 'system': 'alnitak',
          'failed': [
              { 'subsystem': 'http',
                 'failures': [
                     { 'code': '80701',
                       'text': 'SYN unacknowledged',
                       'timestamp': 1375189804,
                       'alertno': 1,
                       'nextalert: 1375193404 },
                     ...
              },
              ...
          ]
        },
        ...
    ]
  },
  ...
]
</code>```

Every five minutes you save each recipient's extant block, and generate a new one.

You now need a function that will walk two such blocks, and divide all items in three blocks with the same structure as the "status block":

present in new only: add new issue to "NEW ISSUES" block.

present in old only: add old issue to "RESOLVED" block.

present in both: checks the nextalert, and alertno. If nextalert has not expired, do nothing. If it has expired, the item is added to the "UNRESOLVED" block, alertno is incremented, and its value is used to decide how much to add to current timestamp to get the new value for nextalert.

The important thing is the do nothing in the above loop. This ensures that if nothing happens, no alert will be sent even if there are ongoing issues.

This architecture allows little tweaks - for example: if there are no new nor resolved issues (this is important, for both might require timely decisions, such as to inform a customer of a service being back on line), you can do an additional walk of the status blocks and approximate the "next alert" time in the new block to the nearest multiple of, say, 15 minutes, before calling the function that builds the unresolved block.

This has the effect of posticipating all alerts so that they come together at intervals of 15 minutes. In this example:

```<code>10:05 alert 1 goes out, and is scheduled for 15 minutes from now: 10:20
10:10 alert 2 goes out, and is scheduled for 15 minutes from now: 10:25
10:15 nothing happens
10:20 alert 1 is sent ("Still unresolved") and rescheduled for 10:50
10:25 alert 2 is sent ("Still unresolved") and rescheduled for 10:55
</code>```

what would happen is that both alerts would be sent at the exact time the first time, and then both would be sent together at 10:30, thereby sending three emails instead of four. The alert 1 rescheduling is delayed by 10 minutes in this example.

(Other time-tweaking tricks can be played). Notice: if you snooze the nextalert value, remember that this value being different does not count when comparing old and new status blocks.

Now that we have the three (possibly empty) blocks, a third function can compose an email by walking the three blocks and spewing out text -- or just returning if all three blocks are empty:

```<code>Dear mr. Serni,
The following issues are now marked SOLVED:

    System: albutain
    Reason: fail to respond to PING
    Alert : 27 Jul 2013, 20:27:33 UTC

The following issues are NEW and require your attention:

    ...

The following issues are still unresolved:

    ...
</code>```

Possibly, if all three blocks are "{}" for a given period, you may want to send an email all the same -- just to remind that the checking system is alive and well. A subject line might suffice. This periodic email could be sent also to deal with unresolved issues, which otherwise would only be sent upon resolution of an issue or creation of a new one, and "starve" otherwise.

Title: Sending exactly one notification n seconds after the event

Body:
I have a system that checks the status of a number of systems, such as, is http up, does the system respond to ping, that sort of thing.

I check all of these systems every 5 minutes. If something is broken, I send out an e-mail with a notice. If the problem is cleared I send out an "all clear, problem resolved" notice too.

I want to send out a notice 30 minutes after a problem is detected and the problem is still ongoing and then at failure +1h, +2h, +4h, etc. I do not want to flood the user with messages every time the event "problem still ongoing" occurs which is every 5 minutes.

I could store a "last notification sent at" somewhere and just work with that but I would rather just solve it in the code itself. Am I missing something very obvious or is this the only feasible way?

Body:
You could first of all store the status of all systems connected with a given recipient, e.g.

[ {
    recipient: 'lserni@gmail.com',
    situation: [
        { 'system': 'alnitak',
          'failed': [
              { 'subsystem': 'http',
                 'failures': [
                     { 'code': '80701',
                       'text': 'SYN unacknowledged',
                       'timestamp': 1375189804,
                       'alertno': 1,
                       'nextalert: 1375193404 },
                     ...
              },
              ...
          ]
        },
        ...
    ]
  },
  ...
]

Every five minutes you save each recipient's extant block, and generate a new one.

You now need a function that will walk two such blocks, and divide all items in three blocks with the same structure as the "status block":

present in new only: add new issue to "NEW ISSUES" block.

present in old only: add old issue to "RESOLVED" block.

present in both: checks the nextalert, and alertno. If nextalert has not expired, do nothing. If it has expired, the item is added to the "UNRESOLVED" block, alertno is incremented, and its value is used to decide how much to add to current timestamp to get the new value for nextalert.

The important thing is the do nothing in the above loop. This ensures that if nothing happens, no alert will be sent even if there are ongoing issues.

This architecture allows little tweaks - for example: if there are no new nor resolved issues (this is important, for both might require timely decisions, such as to inform a customer of a service being back on line), you can do an additional walk of the status blocks and approximate the "next alert" time in the new block to the nearest multiple of, say, 15 minutes, before calling the function that builds the unresolved block.

This has the effect of posticipating all alerts so that they come together at intervals of 15 minutes. In this example:

10:05 alert 1 goes out, and is scheduled for 15 minutes from now: 10:20
10:10 alert 2 goes out, and is scheduled for 15 minutes from now: 10:25
10:15 nothing happens
10:20 alert 1 is sent ("Still unresolved") and rescheduled for 10:50
10:25 alert 2 is sent ("Still unresolved") and rescheduled for 10:55

what would happen is that both alerts would be sent at the exact time the first time, and then both would be sent together at 10:30, thereby sending three emails instead of four. The alert 1 rescheduling is delayed by 10 minutes in this example.

(Other time-tweaking tricks can be played). Notice: if you snooze the nextalert value, remember that this value being different does not count when comparing old and new status blocks.

Now that we have the three (possibly empty) blocks, a third function can compose an email by walking the three blocks and spewing out text -- or just returning if all three blocks are empty:

Dear mr. Serni,
The following issues are now marked SOLVED:

    System: albutain
    Reason: fail to respond to PING
    Alert : 27 Jul 2013, 20:27:33 UTC

The following issues are NEW and require your attention:

    ...

The following issues are still unresolved:

    ...

Possibly, if all three blocks are "{}" for a given period, you may want to send an email all the same -- just to remind that the checking system is alive and well. A subject line might suffice. This periodic email could be sent also to deal with unresolved issues, which otherwise would only be sent upon resolution of an issue or creation of a new one, and "starve" otherwise.


问:
Unit-Tests and databases: At which point do I actually connect to the database?
There are answers to the question on how test classes that connect to a database, e.g. "Should service test classes connect ..." and "Unit testing - Database coupled app".

So, in short let's assume you have a class A that needs to connect to a database. Instead of letting A actually connect, you provide A with an interface that A may use to connect. For testing you implement this interface with some stuff - without connecting of course. If class B instantiates A it has to pass a "real" database connection to A. But that means B opens a database connection. That means to test B you inject the connection into B. But B is instantiated in class C and so forth.

So at which point do I have to say "here I fetch data from a database and I will not write a unit test for this piece of code"?

In other words: Somewhere in the code in some class I must call sqlDB.connect() or something similar. How do I test this class?

And is it the same with code that has to deal with a GUI or a file system?

I want to do Unit-Test. Any other kind of test is not related to my question. I know that I will only test one class with it (I so agree with you Kilian). Now, some class has to connect to a DB. If I want to test this class and ask "How do I do this" many say: "Use Dependency Injection!" But that only shifts the problem to another class, doesn't it? So I ask, how do I test the class that really, really establishes the connection?

Bonus question: Some answers here boil down to "Use mock objects!" What does that mean? I mock classes that the class-under-test depend upon. Shall I mock the class-under-test now and actually test the mock (which comes close to the idea of using Template Methods, see below)?

答:
The point of a unit test is to test one class (in fact, it should usually test one method).

This means that when you test class A, you inject a test database into it - something self-written, or a lightning-fast in-memory database, whatever gets the job done.

However, if you test class B, which is a client of A, then usually you mock the entire A object with something else, presumably something that does its job in a primitive, pre-programmed way - without using an actual A object and certainly without using a database (unless A passes the entire database connection back to its caller - but that's so horrible I don't want to think about it). Likewise, when you write a unit test for class C, which is a client of B, you would mock something that takes the role of B, and forget about A altogether.

If you don't do that, it's no longer a unit test, but a system or integration test. Those are very important as well, but a whole different kettle of fish. To begin with, they are usually more effort to set up and run, it isn't practicable to demand to pass them as a precondition to check-ins, etc.


答:
The Template Method Pattern might help.

You wrap the calls to a database in protected methods. To test this class you actually test a fake object which inherits from the real database connetion class and overrides the protected methods.

This way the actual calls to the database are never under unit tests, that's right. But it's only these few lines of code. And that is acceptable.

Title: Unit-Tests and databases: At which point do I actually connect to the database?

Body:
There are answers to the question on how test classes that connect to a database, e.g. "Should service test classes connect ..." and "Unit testing - Database coupled app".

So, in short let's assume you have a class A that needs to connect to a database. Instead of letting A actually connect, you provide A with an interface that A may use to connect. For testing you implement this interface with some stuff - without connecting of course. If class B instantiates A it has to pass a "real" database connection to A. But that means B opens a database connection. That means to test B you inject the connection into B. But B is instantiated in class C and so forth.

So at which point do I have to say "here I fetch data from a database and I will not write a unit test for this piece of code"?

In other words: Somewhere in the code in some class I must call sqlDB.connect() or something similar. How do I test this class?

And is it the same with code that has to deal with a GUI or a file system?

I want to do Unit-Test. Any other kind of test is not related to my question. I know that I will only test one class with it (I so agree with you Kilian). Now, some class has to connect to a DB. If I want to test this class and ask "How do I do this" many say: "Use Dependency Injection!" But that only shifts the problem to another class, doesn't it? So I ask, how do I test the class that really, really establishes the connection?

Bonus question: Some answers here boil down to "Use mock objects!" What does that mean? I mock classes that the class-under-test depend upon. Shall I mock the class-under-test now and actually test the mock (which comes close to the idea of using Template Methods, see below)?


问:
How to create better OO code in a relational database driven application where the database is poorly designed
I am writing a Java web application that consists mainly of a bunch of similar pages in which every page has several tables and a filter that applies to those tables. The data on these tables comes from an SQL database.

I am using myBatis as ORM, which may not be the best choice in my case, since the database is poorly designed and mybatis is a more database oriented tool.

I am finding that I am writing a lot of duplicate code because, due to the database's poor design, I have to write different queries for similar things as those queries can be very different. That is, I cannot easily parametricise the queries. This propagates into my code and instead of populating rows on columns in my table with a simple loop I have code like:

get A Data (p1, ..., pi);

get B Data (p1, ..., pi);

get C Data (p1, ..., pi);

get D Data (p1, ..., pi);
...

And this soon explodes when we have different tables with different columns.

It also adds to the complexity the fact that I'm using "wicket", which is, in effect a mapping of objects to html elements in the page. So my Java code becomes an adapter between the database and the front end, which has me creating a lot of wiring, boilerplate code with some logic intermingled in it.

Would the correct solution be wrapping the ORM mappers with an extralayer that presents a more homogeneous interface to the db or is there a better way to deal with this spaghetti code I'm writing?

EDIT: More info about the database

The database holds mainly phone calls information. The poor design consists of:

Tables with an artificial ID as primary key that has nothing to do with the domain knowledge.

No unique, triggers, checks or foreign keys whatsoever.

Fields with a generic name that match different concepts for different records.

Records that can be categorised only by crossing with other tables with different conditions.

Columns which should be numbers or dates stored as strings.

To sum it up, a messy / lazy design all around.

答:
My suggestion:

Create database views that:

Give meaningful names to columns

Do the "crossing with other tables with different conditions" so you can have that complexity hidden away.

Convert numbers or dates stored as strings to numbers and dates respectively.

Create uniqueness where there is none, according to some criteria.

The idea is create a façade that emulates a better design on top of the bad one.

Then make the ORM relate to that façade instead of the real tables.

This doesn't simplify insertions though.