答:
No, the LICENSE file needs to contain the entire GPL. The excerpt provided goes in every single source code file; while you might or might not technically need it, it's best by far to put in every single file a) a copyright notice and b) a statement that the program is under the GPL. That isn't GPL-specific, it just adds significant legal clarity (it makes it explicit that each and every file is licensed under the GPL and puts everyone on notice that each and every file is copyrighted).

In the LICENSE file (where you have the actual terms and conditions), you cannot leave out any part of the GPL, including the "how to apply this to your own program." If you remove the "how to use this license," the result is no longer the GPL; you cannot integrate any code under the GPL with your project under the not-the-GPL (since you can only distribute code under the GPL if you include a full copy of the GPL). Also, the actual GPL is copyrighted and is licensed under restrictive terms allowing only verbatim copying, and you may be violating the copyright if you distribute a modified version.

Here's the correct way to apply the license:

In every source code file, insert the following in a comment (fill in *program name* and *your name* and *years*):

```<code>This file is part of *program name*.
Copyright (C) *years* *your name*

*program name* is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
</code>```

Put a file called LICENSING or COPYING or something like that in the root of the project folder. Put the entire GPL (here is the official text) in that file. The file must contain the verbatim GPL; do not change it in any way.

Title: How to properly apply a license

Body:
Take for example the GPL-3.0 license.

Near the end it states:

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Programs

   ...

So I though that the "correct" way is to use the instructions there and use the small excerpt they provided:

<one line to give the program's name and a brief idea of what it does.>

   Copyright (C) <year>  <name of author>

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program.  If not, see http://www.gnu.org/licenses/.

Replace <year> etc and paste those in a LICENSE file. (but not on top of each file or 80% of my code would be licensing stuff...)

When looking at famous projects however, they seem to have just put the entire license in there with the "HOW TO APPLY..." still added and without even replacing <year>, <name of author> etc.

So I'm starting to wonder: if I remove everything after END OF TERMS AND CONDITIONS or if I actually follow the instructions, is it still the same license...

Body:
No, the LICENSE file needs to contain the entire GPL. The excerpt provided goes in every single source code file; while you might or might not technically need it, it's best by far to put in every single file a) a copyright notice and b) a statement that the program is under the GPL. That isn't GPL-specific, it just adds significant legal clarity (it makes it explicit that each and every file is licensed under the GPL and puts everyone on notice that each and every file is copyrighted).

In the LICENSE file (where you have the actual terms and conditions), you cannot leave out any part of the GPL, including the "how to apply this to your own program." If you remove the "how to use this license," the result is no longer the GPL; you cannot integrate any code under the GPL with your project under the not-the-GPL (since you can only distribute code under the GPL if you include a full copy of the GPL). Also, the actual GPL is copyrighted and is licensed under restrictive terms allowing only verbatim copying, and you may be violating the copyright if you distribute a modified version.

Here's the correct way to apply the license:

In every source code file, insert the following in a comment (fill in *program name* and *your name* and *years*):

This file is part of *program name*.
Copyright (C) *years* *your name*

*program name* is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Put a file called LICENSING or COPYING or something like that in the root of the project folder. Put the entire GPL (here is the official text) in that file. The file must contain the verbatim GPL; do not change it in any way.


问:
How to reuse common code between presenters
In my application there are 2 views both have 70% common fields like name, icon etc. One view is about list( contains 2-3 fields). On clicking the list  , the next view which is the details should be called.

Other functionality in both views is same. e.g while loading , presenter will be called to load data from the url. (The URL for both  views is different).
The common functionality includes
1. Load XML data from URL
2. Set the loading progress bar in activity
3. Removing the progress bar.
3. 50% methods for setting the activity views will be common.
4. Call the xml parser

The differences will be view specific:
1. The fields are only 50% common.
2. the action on button click

My doubt is shall I use 2 presenters or one presenter for both the views. Many methods are different , while many are same in the 2 presenters.

Which is the correct design strategy?:
1. Shall I use helper class
2. Shall both presenters have the same base class.
3. Shall i use the startegy pattern?
 What is the right way to do it in MVP? Or all are correct.

答:
The proper approach for this kind of situation is to have a base presenter and base view, where you can do the common stuff.

```<code>class BasePresenter<T:BaseView>
{
    BasePresenter(T view)
    {
        View = view;
        View.Presenter = this;
    }

    T View { get; private set; }
}

class BaseView<T : BasePresenter> : [base view component such as asp net component]
{
    T Presenter { get; set; }

    protected void ShowProgress()
    {
       ...
    }

    protected void HideProgress()
    {
       ...
    }
}

class ListPresenter : BasePresenter<ListView>
{
    ListPresenter(ListView view) : base(view)
    {

    }

    void FetchData()
    {
        .....
        View.ShowList(data);
    }
}

class ListView : BaseView<ListView>
{
    void ShowList(List<object> data)
    {
        .....
    }
}
</code>```

Without having a look at your code base, I can't say more on how to organize the code.

ContentLicense: CC BY-SA 3.0

Body:
The proper approach for this kind of situation is to have a base presenter and base view, where you can do the common stuff.

class BasePresenter<T:BaseView>
{
    BasePresenter(T view)
    {
        View = view;
        View.Presenter = this;
    }

    T View { get; private set; }
}

class BaseView<T : BasePresenter> : [base view component such as asp net component]
{
    T Presenter { get; set; }

    protected void ShowProgress()
    {
       ...
    }

    protected void HideProgress()
    {
       ...
    }
}

class ListPresenter : BasePresenter<ListView>
{
    ListPresenter(ListView view) : base(view)
    {

    }

    void FetchData()
    {
        .....
        View.ShowList(data);
    }
}

class ListView : BaseView<ListView>
{
    void ShowList(List<object> data)
    {
        .....
    }
}

Without having a look at your code base, I can't say more on how to organize the code.


问:
I believe my solution is better than my boss's, so should I ignore him?
I'm working with php and sql.

I think that my method of implementing functions is better than what my boss proposes. Just now he explained me how to do a check on a list of email addresses, and I do not like his idea. I proposed mine which is better and quicker to implement, but he disagreed.

Now I think I will go ahead and implement my idea, because his idea was not clear enough to me. Do you think he will be mad?

答:
You say your method is "quicker to implement". That rings alarm bells to me.

Code that is quicker to implement can, very often, be hard to maintain.

He is your boss. Unless you stay there for life, he's going to be living with that code for much longer than you are. Perhaps his strategy takes that fact into account.

Short answer: Insubordination is a sure-fire way to get fired.

ContentLicense: CC BY-SA 2.5


问:
Are you allowed to "copy" the GUI/Features of another application
I'm making a app which is based heavily on another application that serves a similar purpose. I'm not actually planning on selling it, but I'm wondering whether it would even be legal for me to sell it.

I don't borrow graphics from the other application, but I have a very similar color scheme, virtually the same features (I added a few, but not really significant), and a very similar interface layout. Obviously, I'm not borrowing any code (It's written in Objective-C and mines written in Java).

Again, I'm not actually planning on selling it, I was just wondering in the hypothetical. I'm not sure whether it's just the code that's copyrighted or the actually design itself.

答: Well twitter has a patent on the pull to refresh functionality so in theory you could get sued if you chose to copy that feature. That is just one example. There are tons of software patents out there, so no. You can't always copy a feature.</p>


问:
Should static analysis be integrated with code review?
I want to integrate various static analysis tools, and then add the results as comments on a file within code review tools, such as Stash or Review board.

I am exploring the feasibility of writing such a tool, I have a prototype working for python, using pylint and pep8. But have not integrated it with a code review tool yet.

Additionally it should be relatively easy to add support for other languages, for example C++, via something like CPPCheck, or any static analysis tool that can be run/outputs to the console.

Should it be integrated? Or is there a better place for the results of those tools?

答:
The tools you list have nothing to do with code reviews. They are there exactly to let the reviewers to focus on more useful subjects.

Code reviews are for important things which cannot be automated: using a design pattern when another one matches better, over-documenting clear code or under-documenting unclear one, not using language features which can make code shorter and more readable. All those things are “too smart” for a machine: a program, no matter how sophisticated is it, won't be able to tell whether your application of abstract factory pattern is a good idea in a given context or not. That's why code reviews are done by persons, often more experienced developers.

Subjects mentioned during code reviews are also often subjective. One developer will tell that this specific method should be split in two. Another equally experienced one will consider that the method is fine and does exactly one thing. One reviewer will find a goto statement terrible; his colleague may find that in this particular case, goto is fine and can't be removed without leading to less readable code.

Style tools, on the other hand, are the archetype of automation of purely objective, basic, even sometimes dumb rules. Line 273 is too long. You've forgotten a capital letter. And here, there is a space missing. And here, I've found two empty lines instead of one. Boooring.

Don't waste anyone's time for that during code reviews. If there is a style guide in your project, use style checker (like pep8) but run it automatically through pre-commit hook. Space missing? No commit for you, sir. An empty line contains whitespace? Please remove it if you want your code in version control.

In fact:

Since the rules are objective and straightforward, there is nothing to discuss during a code review. There is whitespace in an empty line. So remove it. What would you like to tell about it during a code review?

Worse, it can lead to discussions which are all but constructive. For some, code reviews would become an opportunity to discuss the merits of their preferred style, because, frankly, everyone knows that two spaces are better than four, and now, the code review is focused on “Should we change our code style and rewrite our entire code base to use two spaces instead of four”. Avoid this at all costs.

The remaining—the stuff which is too complicated for a machine—is for code reviews, letting the reviewers to focus on things that actually matter.

Automated checking, would it be style checking, compiling, tests, static analysis or formal proof, should be, well, automated. Where should it be in continuous integration process is a different subject. Short and fast checks, such as style checking, can be put directly in a pre-commit hook to avoid any non-compliant code in the code base. Long checks, such as static analysis, will usually be done during the build.

Remember, if you have a subject which:

Doesn't have a straight answer, the answer being based on personal experience and educated guesses,

Results in non-binary "well, it can be A, but B can be accepted here, while C seems a bit problematic, but will be an excellent solution if this were that"-style answers,

Cannot possibly be automated even with most sophisticated applications,

Cannot easily be ported to another context,

Is focused on code quality, readability, expressiveness and maintainability,

code reviews may be a good place for it. On the other hand, if the subject:

Is purely objective and without ambiguity,

Results in a binary answer, often based on a metric,

Can be automated (sometimes requiring a lot of work and research),

Applies to every situation in the same group,

Is focused on code quality, readability, expressiveness and maintainability,

pre-commit hooks or the build are much better places than a code review.

Further reading:

How to set up something like an integration server that measures the quality of code and reject the code if the score is below a certain number?

Linters rock, but they are slow


答:
Being a great developer is not just being a good coder! Part of the job is to work well with others, and collaborate with your teams and bosses. If you think that your way is better, try and explain that to him, showing him "data" of why it is better.

If he claims that his way is actually better, than try to keep an open mind for the case that he might be right. If he is not, and is just pulling authority over you, then you have one bad boss... (because part of being a great boss as well is collaborating with your team and managing it properly). In which case, it might not be such a bad idea to start looking around.

Title: I believe my solution is better than my boss's, so should I ignore him?

Body:
I'm working with php and sql.

I think that my method of implementing functions is better than what my boss proposes. Just now he explained me how to do a check on a list of email addresses, and I do not like his idea. I proposed mine which is better and quicker to implement, but he disagreed.

Now I think I will go ahead and implement my idea, because his idea was not clear enough to me. Do you think he will be mad?


问:
When designing a replacement application, how can I compare its performance to the original, if there are no existing statistics?
I don't believe there are any performance statistics kept for the application I'm being asked to replace, and don't want to ask the individuals doing the work to manually record things like how long it takes them to perform a given task.  However, the main objective of my project is to make it easier for the users to get their work done.  If I don't know how difficult or time consuming it is for them now, how can I objectively show that the new system fulfills that objective?

Would adding a few high-level logging statements and analyzing the logs be straightforward enough?  I'm not sure how much effort it would take to do that much, let alone setup anything more sophisticated.  Or, are there existing tools out there for this scenario?  It seems like something that would be relatively (if not quite) common.

答:
I've been faced with this, and the answer is:

For someone experienced in performance tuning, the new code can be tuned so almost no code can go faster.
Here's an example.

The reason is, there is a minimum length of time the task can take, and it's greater than one cycle. There are many, many programs that can do the task, and one or more of them take less time than all the others, so they are optimal, by definition.

The old code might possibly be just as fast or even faster, but if it hasn't been tuned by someone with that experience, it's not likely.

So if there are no measurements of the old code, all you can do is apply the expertise to make sure the new code is as nearly optimal as possible, so it is almost certain to be faster than the old.

A simpler way to put it:

Software is like a wet towel.
Most of the time it has not been wrung out.

You don't know how wet the old one was,
but if you really wring out the new one, you can be pretty sure it is no wetter than the old one was, and possibly quite a lot drier.


问:
What is a context object in relation to a web application?
I've seen the term "context" used in a few web application frameworks but I'm not sure what it's actually about. It seems pretty important and seems to be related to holding session information, but I've also seen it used for URL related things.

Is there a clear, concise and agreed upon definition of the term when used in web application programming? It seems like something I would need to make use of but I can't find anything explaining what it should (and shouldn't) be.

答:
An application context object usually allows access to the configuration of the application instance, things like:

What is the application's hostname and path?

How is dependency injection configured, i.e. what implementation is to be used for a given interface?

OS environment variables

In a properly designed OO system, the access will be via methods of the context object that do things like convert relative URLs to absolute ones or return fully configured implementation objects for a given interface or name, and that can involve session information since DI configuration may define objects to be session-scoped (i.e. there is one implementation object per user session).

This description may be colored by my experience on the Java platform, but the concept as such is not platform-specific.


答:
This answer is based on two assumptions. First, you are using a static analysis tool that is more than a style checker (PMD and/or FindBugs instead of Checkstyle, for example). Second, the tool has been properly configured with regards to the errors detected and the severity of the error for the given process or product.

Yes, static analysis tools that are designed to find errors should be part of the code review process. More generally, a static analysis tool should be run and the results reviewed as part of a code review, before committing code into a branch that other developers use.

Prior to code review, the developer should execute and correct issues found by the static analysis tool, with any findings reviewed and any important findings corrected. Then, they should be rerun over the code to produce remaining errors. This list should be part of the code review. This will allow the human code reviewers to focus on issues that they can't find, or perhaps pay special attention to areas of the code flagged by the tool (double checking false positives).

Ideally, you have been using the tool since the inception of the project. If not, however, and there are a large number of findings, these would need to be reviewed and dispositioned, which would not be done as part of a code review. At this point, I would make the execution of the tool part of the build or continuous integration process and each build should reduce the number of errors. The developers should use this information to help leave the code they touch in a better state than they found it during refactoring or development. Of course, using the list during a code review would also be useful to identify potential problems that should be corrected to ensure the code is better than it was before.

Title: Should static analysis be integrated with code review?

Body:
I want to integrate various static analysis tools, and then add the results as comments on a file within code review tools, such as Stash or Review board.

I am exploring the feasibility of writing such a tool, I have a prototype working for python, using pylint and pep8. But have not integrated it with a code review tool yet.

Additionally it should be relatively easy to add support for other languages, for example C++, via something like CPPCheck, or any static analysis tool that can be run/outputs to the console.

Should it be integrated? Or is there a better place for the results of those tools?


问:
How should I distribute a login key?
Our application currently generates "invitation" emails containing an encrypted personId in the query string of an https link. When the recipient clicks the link, the application validates the personId, returns the home page, and sets a never-expires cookie that will identify and authenticate the user for all future visits.

Can we make this process more secure without sacrificing the ease of use? We think the weak point is the use of the query string. The secure token, because its passed in the query string, will be stored in the browser history, server logs, and possibly firewall logs if they do man-in-the-middle https inspection. We could put the same details in a form with hidden inputs, but I read that forms in emails cause the panic reaction in email clients.

The resources being secured aren't super precious. Are there obvious improvements that I've overlooked?

答:
emails containing an encrypted personId in the query string of an
  https link

Firstly, encryption isn't really what you want in this scenario - you really want entropy. Your login token should be entirely independent of your personId, instead it should be a random string generated using a cryptographically secure method.

Of course you will need to store the random token in your database, and you may choose to hash+salt that value, but the value emailed to them should not be the hashed value.

Can we make this process more secure without sacrificing the ease of
  use? We think the weak point is the use of the query string.

I don't think the issue is so much that your token is in the query string, but rather that your tokens aren't single use.

Single use tokens would resolve browser history and server logs because once it's been accessed the links in the logs/history wouldn't work any more.

With regard to:

if they do man-in-the-middle https inspection

If they have installed a malicious CA on the machine then they can inspect any of the traffic, so regardless of where you put the value (in the Request URL header or in the request body) they could access it.

Overall I'd consider this to be a pretty low threat, it's not easy to install a malicious CA and if someone malicious has managed to do so then you probably can't trust anything whatsoever on that machine.

You could of course also make them manually type the code rather than using a link - which would mitigate some of these threats. At the least you might be able to have some separate and easier to type code (eg. a 4 digit value) and an appropriate failed attempt lockout in addition to the link containing the main token.

Title: How should I distribute a login key?


问:
Custom serializer or create base class which implements IXmlSerializable?
I am working on a project where I have very specific xml serialization specifications, that is:

Some properties are elements, some are attributes

Some properties are required others aren't

Some properties are required just in some context of the overall
object state

Not required properties must not be serialized

Properties of same type can be serialized differently

Some double properties should have rounding, maybe even custom
rounding

And the list goes on...

I am currently implementing these rules using Attribute which is the only sane way.

But I wonder, what is the best way to serialize these objects? Certainly the approach that makes the most sense is to have a serializer which knows all these rules and how to handle them just as XmlSerializer, although it seems IXmlSerializable was created for this reason.

So, what would you do? Custom serializer or IXmlSerializable?

答:
Using IXmlSerializable

There are some things to take into consideration when implementing this interface and you should check to see if your intended use is compatible with this. Big advantage of this approach is that you can serialize what are otherwise private or protected fields, and the fairly straightforward usage of serialization (method on the object itself). This approach might validate SRP depending on the nature of the serialized object.

Using a Serializer

Using a serializer allows you to take advantage of DI (Dependency Injection), so you can have re-usable XML serialization classes injected with DI. This makes writing tests a lot simpler as using new to create new objects makes it significantly harder to write tests(1) Disadvantage is that you have to carry around serializers to use thoughout your code and will probably need some degree of wiring code to obtain the correct serializer for a given object.

In the end, it boils down to what advantages matter more and what disadvantages would seriously hamper your development.

1) If two objects contain the same type of child object, the serialization of that object can be split off into a separate class with separate tests. The tests on the parent serializer would only need to verify the child serializers are called. Without DI you'd probably need to duplicate the tests for the children across the parents.


答:
You are critizing him by thinking you are better than him, instead of critizing his ideas.

You need to change that inappropriate behavior in the first place.

Take the opportunity to challenge his ideas positively by asking "why?" enough times. If the idea is so stupid, he will eventually discover it himself by answering your questions.

This technique has the advantage help you understand. His idea is probably more intelligent than you think.

Also seeking to understand before trying to be understood will help your boss disarm himself against you. When you propose someone something, its lizard brain will try to determine if it's a treat. His lizard brain want to him to be safe. Seeking to understand him will re-insure his archaic brain.

Now if you have a better proposal, I'm sure he will be more than happy to listen to you. Be prepared to be asked "why?" enough times until he is convinced.

After all, you are the professional, that's why he hired you at the first place. He should listen to you.

If he is not interested by your ideas at all, there is only one thing to do: quit.


问:
How to show link between a java class which gets JSON data from PHP script
I am trying to show the relationship that a java class has with a PHP script. The PHP script gets data from a database and then converts it into JSON format. This is then read by the java file.

In my UML diagram, is there a way to show the relationship between the database and the java class? Should I even bother with this?

答:
It depends if this relationship makes sense in the context of your diagram and what the focus is.

It feels to me as if this PHP script acts as a service of some kind (provides access to data the java class cannot get directly from the database) so I would probably model the script as a component on the diagram. A component provides an abstraction of where the data comes from as the java class does not really care about this, it simply sees the script as a provider of a certain kind of data.


问:
Is my usage of explicit casting operator reasonable or a bad hack?
I have a big object:

```<code>class BigObject{
    public int Id {get;set;}
    public string FieldA {get;set;}
    // ...
    public string FieldZ {get;set;}
}
</code>```

and a specialized, DTO-like object:

```<code>class SmallObject{
    public int Id {get;set;}
    public EnumType Type {get;set;}
    public string FieldC {get;set;}
    public string FieldN {get;set;}
}
</code>```

I personally find a concept of explicitly casting BigObject into SmallObject - knowing that it is a one-way, data-losing operation - very intuitive and readable:

```<code>var small = (SmallObject) bigOne;
passSmallObjectToSomeone(small);
</code>```

It is implemented using explicit operator:

```<code>public static explicit operator SmallObject(BigObject big){
    return new SmallObject{
        Id = big.Id,
        FieldC = big.FieldC,
        FieldN = big.FieldN,
        EnumType = MyEnum.BigObjectSpecific
    };
}
</code>```

Now, I could create a SmallObjectFactory class with FromBigObject(BigObject big) method, that would do the same thing, add it to dependency injection and call it when needed... but to me it seems even more overcomplicated and unnecessary.

PS I'm not sure if this is relevant, but there will be OtherBigObject that will also be able to be converted into SmallObject, setting different EnumType.

答:
It is... Not great. I've worked with code that did this clever trick and it led to confusion. After all, you would expect to be able to just assign the BigObject into a SmallObject variable if the objects are related enough to cast them. It doesn't work though - you get compiler errors if you try since as far as the type system is concerned, they're unrelated. It is also mildly distasteful for the casting operator to make new objects.

I would recommend a .ToSmallObject() method instead. It is clearer about what is actually going on and about as verbose.


问:
Are there any good reasons to use ER Diagrams instead of UML Class Diagrams for data modeling? Is ERD the COBOL of data modeling?
Are there any good reasons to use ER Diagrams instead of UML Class Diagrams for data modeling, given the fact that class diagrams subsume ER diagrams? Or is it just for historical reasons because database people are used to ER modeling and are not familiar with UML? So, is ERD the COBOL of data modeling?

UML and ERD are two languages that can do the same thing: model entity (or object) types and their relationship types (or associatons).

答:
When I am working on a new feature, I always use ERDs. To me, the data structures are more important than the classes that will be used to interact with them, and it is important to remember that the two are not necessarily identical. At some point in the future, it may become important for me to split a class into multiple classes, or to combine the object representation of multiple tables into a single class. I may also write programs that rely on the same database using a different language, like Clojure or Haskell, where representing the result of a query as an object is unnatural.

To my mind, UML is the "COBOL of data modeling," because it represents a period of object orientation triumphalism, where it was assumed that a single object model was at the same tier as the database. It isn't—and shouldn't be. This, along with Rails-influenced use of software-level data integrity constraints, has led to a lot of pain, in my experience.

Some relevant quotes:

“Show me your flowcharts and conceal your tables, and I shall continue to be mystified. Show me your tables, and I won’t usually need your flowcharts; they’ll be obvious.” – Fred Brooks

“I will, in fact, claim that the difference between a bad programmer and a good one is whether he considers his code or his data structures more important.” – Linus Torvalds

“Rule 5. Data dominates. If you've chosen the right data structures and organized things well, the algorithms will almost always be self-evident. Data structures, not algorithms, are central to programming.” – Rob Pike

“Fold knowledge into data so program logic can be stupid and robust.” – esr


问:
Help putting together an Open Source Friendly contract but does not allow day job work to be Open Sourced
So I just was hired at a place that had only one Developer and that was the co owner. Their employee handbook had something to the effect of the following.

All IP, inventions or software you develop while at X company is the
  property of the company. Additionally you will have to provide a list
  of all prior inventions, software or IP developed prior to working for
  company x.

This is an issue for me because I have both side projects and occasionally contribute to open source stuff and would like to continue to have the ability to to both.

I talked about it with the owner and he agreed to making changes and asked me for an outline that is fair for both parties. He would take that to a lawyer and they would go over it and apply it. So with that I'm looking for some wording I could submit to that effect to helping me put this together in such a way that I and any other software developers are protected as well as company x and its software. That or a resource or guideline for this sort of thing.

To clarify, the company's software isn't allowed to be made open but the employees will be allowed to work on side project both of an open-source and private nature as long as they don't come to compete with the company's best interest. If it helps we are in the USA.

答:
While I agree with the warnings to be careful here, they fail to address two very important issues:

Your boss is a nice guy and is acting in a spirit of helpfulness and cooperation.

Since a lawyer is going to be asked anyway, why ask us?

Presumably you and your boss can agree on something like "things done on company time, or at company request, belong to the company and the rest belongs to you" - or whatever you both find acceptable.

Have the lawyer translate that into five dollar words and wrap it in a non-complete clause & that should do it.


答:
Different modeling languages (Entity-Relation, Unified Modeling Language, and others) are simply notations for communicating a design to stakeholders. Communicating a design is technical communication, and one of the principles of good technical communication is to communicate the information clearly and concisely. Choosing a modeling notation that is understood by your audience and can communicate the desired information clearly is the first step to achieve this principle.

In his article A Comparison of Data Modeling Techniques, David Hay identifies a number of modeling notations and provides the same example model as expressed in each notation, including ER diagrams, Information Engineering, Barker's notation, IDEF1X, Object Role Modeling, and UML. Hay discusses the difference between analysts (who need clear and easy to read diagrams that can be reasoned about) and designers (who need complete, rigorous, and expressive diagrams to use for implementation).

Scott Ambler also has some principles of Agile Modeling are relevant to this:

Travel Light. Every artifact that you create, and then decide to keep, will need to be maintained over time. If you decide to keep
  seven models, then whenever a change occurs (a new/updated
  requirement, a new approach is taken by your team, a new technology is
  adopted, ...) you will need to consider the impact of that change on
  all seven models and then act accordingly. If you decide to keep only
  three models then you clearly have less work to perform to support the
  same change, making you more agile because you are traveling lighter.
  Similarly, the more complex/detailed your models are, the more likely
  it is that any given change will be harder to accomplish (the
  individual model is "heavier" and is therefore more of a burden to
  maintain). Every time you decide to keep a model you trade-off agility
  for the convenience of having that information available to your team
  in an abstract manner (hence potentially enhancing communication
  within your team as well as with project stakeholders). Never
  underestimate the seriousness of this trade-off. Someone trekking
  across the desert will benefit from a map, a hat, good boots, and a
  canteen of water they likely won't make it if they burden themselves
  with hundreds of gallons of water, a pack full of every piece of
  survival gear imaginable, and a collection of books about the desert.
  Similarly, a development team that decides to develop and maintain a
  detailed requirements document, a detailed collection of analysis
  models, a detailed collection of architectural models, and a detailed
  collection of design models will quickly discover they are spending
  the majority of their time updating documents instead of writing
  source code.

Multiple Models. You potentially need to use multiple models to develop software because each model describes a single aspect of your
  software. “What models are potentially required to build modern-day
  business applications?” Considering the complexity of modern day
  software, you need to have a wide range of techniques in your
  intellectual modeling toolkit to be effective (see Modeling Artifacts
  for AM for a start at a list and Agile Models Distilled for
  detailed descriptions). An important point is that you don't need to
  develop all of these models for any given system, but that depending
  on the exact nature of the software you are developing you will
  require at least a subset of the models. Different systems, different
  subsets. Just like every fixit job at home doesn't require you to use
  every tool available to you in your toolbox, over time the variety of
  jobs you perform will require you to use each tool at some point. Just
  like you use some tools more than others, you will use some types of
  models more than others. For more details regarding the wide range of
  modeling artifacts available to you, far more than those of the UML as
  I show in the essay Be Realistic About the UML.

Content Is More Important Than Representation. Any given model could have several ways to represent it. For example, a UI specification
  could be created using Post-It notes on a large sheet of paper (an
  essential or low-fidelity prototype), as a sketch on paper or a
  whiteboard, as a "traditional" prototype built using a prototyping
  tool or programming language, or as a formal document including both a
  visual representation as well as a textual description of the UI. An
  interesting implication is that a model does not need to be a
  document. Even a complex set of diagrams created using a CASE tool may
  not become part of a document, instead they are used as inputs into
  other artifacts, very likely source code, but never formalized as
  official documentation. The point is that you take advantage of the
  benefits of modeling without incurring the costs of creating and
  maintaining documentation.

He also has some practices for Agile Modeling to help achieve these principles:

Apply The Right Artifact(s). Each artifact has its own specific applications. For example, a UML activity diagram is useful for
  describing a business process, whereas the static structure of your
  database is better represented by a physical data or persistence
  model. Very often a diagram is a better choice than source code -- If
  a picture is worth a thousand words then a model is often worth 1024
  lines of code when applied in the right circumstances (a term borrowed
  from Karl Wieger's Software Requirements) because you can often
  explore design alternatives more effectively by drawing a couple
  diagrams on whiteboards with your peers than you can by sitting down
  and developing code samples. The implication is that you need to know
  the strengths and weaknesses of each type of artifact so you know when
  and when not to use them. Note that this can be very difficult because
  you have Multiple Models available to you, in fact the Agile Models
  Distilled page lists over 35 types of models and it is by no means
  definitive.

Iterate To Another Artifact. When you are working on a development
  artifact -- such as a use case, CRC card, sequence diagram, or even
  source code -- and find that you are stuck then you should consider
  working on another artifact for the time being. Each artifact has its
  strengths and weaknesses, each artifact is good for a certain type of
  job. Whenever you find you are having difficulties working on one
  artifact, perhaps you are working on a use case and find that you are
  struggling to describe the business logic, then that's a sign that you
  should iterate to another artifact. For example, if you are working on
  an essential use case then you may want to consider changing focus to
  start working on an essential UI prototype, a CRC model, a business
  rule, a system use case, or a change case. By iterating to another
  artifact you immediately become "unstuck" because you are making
  progress working on that other artifact. Furthermore, by changing your
  point of view you often discover that you address whatever it was that
  causing you to be stuck in the first place. See the essay Iterate to
  Another Artifact for more thoughts.

Single Source Information. Information should be stored in one place and one place only. In other words, not only should you apply the
  right artifact you should also model a concept once and once only,
  storing the information in the best place possible. When you are
  modeling you should always be asking the questions "Do I need to
  retain this information permanently?", "If so, where is the best place
  to store this information?" and "Is this information already captured
  elsewhere that I could simply reference?". Sometimes the best place to
  store information is in an agile document, often it's in source code.
  Read here for more details.

First need to identify who you are communicating with and what information they need. You should choose the appropriate modeling notation and models to communicate that information to them. Once the models are created, you should use them. They should be reviewed for consistency, they should be transformed into other models, they should be included in documents, or they should be used to guide an implementation.

If you need to, consider investing in training. If you're working with Systems Engineers who use SysML, maybe consider training everyone to read SysML models. If the software team finds the UML notation easier, consider training everyone in UML. It doesn't have to be a formal training class - it could be passing around links to useful websites, buying a few copies of a book for a company library, lunch and learn sessions, or external training (either off-site or a trainer brought in for a session). This may make it easier to reduce the need to have multiple modeling notations used.

Second, don't be afraid to throw away models. Perhaps the first iteration of a model could be an ER diagram. That could be used to understand the data and to create your database. However, in order to add more detail, you may choose to evolve that into a different model type, such as a class diagram. Depending on stakeholder needs, you may need to maintain both models. If you don't, though, throw the first model away so you don't need to maintain it or risk someone finding it and working off of an incorrect model. Future updates to the database could be driven through changes to the class diagram. At the end of the day, though, you don't want the same information captured in multiple places.

To very clearly answer your question: yes, there are reasons to use an ER diagram over a UML model. That reason is that the ER diagram is more useful to your stakeholders than a UML model. However, using an ER diagram once doesn't mean that you will keep it for the life of a project or product or that you won't be creating another model in parallel or from your ER model.

I'd also recommend checking out Scott Ambler's Agile Data site for more articles and information. It is connected to the Agile Modeling site and is part of the complete Disciplined Agile Delivery process, but it does have some good ideas regardless of the methodology you are following.

Title: Are there any good reasons to use ER Diagrams instead of UML Class Diagrams for data modeling? Is ERD the COBOL of data modeling?

Body:
Are there any good reasons to use ER Diagrams instead of UML Class Diagrams for data modeling, given the fact that class diagrams subsume ER diagrams? Or is it just for historical reasons because database people are used to ER modeling and are not familiar with UML? So, is ERD the COBOL of data modeling?

UML and ERD are two languages that can do the same thing: model entity (or object) types and their relationship types (or associatons).

ContentLicense: CC BY-SA 4.0


问:
Picking m number in the best possible time
Imagine we want to pick m numbers from n numbers so that the difference of the maximum and minimum of the m numbers be minimum, for example if

m = 4

  n =6

  numbers: 10 12 10 7 5 22

The minimum difference is 5, picking 5, 7, 10, 10 from the numbers.

the first thing that pops into mind is to sort the numbers and pick the n number which has the minimum difference through looping on an m sized window on the n numbers.

I was wondering if there would be a way to do this in a time order less than O(nlogn), maybe through dynamic programming?

EDIT : The m numbers doesn't matter, the only thing the problem wants is the minimum difference (e.g. 5 for the provided example)

答:
To do this on a list that has not been sorted would require an algorithm that is worse than O(n log n), which is the best you can hope for to sort the list in the first place, meaning on an unsorted list O(n log n) is the best.

However, it should be said that the sorting is an operation which must only be performed once, thus you could sort the list and later directly add successive items in its sorted place in order to maintain a sorted list which is an operation that only requires O(n) time.  Alternatively, if elements are initially inserted in such a way as to maintain a sorted array, you won't have to perform a sort later.

So the real question here is:  What is the best possible time to pick m numbers from an array of n numbers such that the set of m numbers has a minimal difference between max and min given the array n is sorted?

As it turns out, this can be done in O(n) time.  The pseudoalgorithm is as follows:

```<code>Given array of size n called A_n containing input
Init values currentMin and currentMax
Init values bestDifference and bestDifferenceIndex

for i = 0, i <= n - m
   currentMin = A_n[i]
   currentMax = A_n[i + m - 1]

   if i = 0 or currentMax - currentMin < bestDifference
       bestDifference = currentMax - currentMin
       bestDifferenceIndex = i
</code>```

At the end of this using as input your example, bestDifference should show 5 and bestDifferenceIndex will be 0 (sorted A_n would be {5, 7, 10, 10, 12, 22}, meaning it grabbed {5, 7, 10, 10}).

It is a little misleading to call this O(n log n) because this isn't due to the algorithm itself but rather the sort necessary for the algorithm to work properly, and performing sort each and everytime while guaranteed to always work will certainly be slower than if you worked with a pre-sorted array and avoided the call to sort it altogether.

Hope that helps!

Body:
To do this on a list that has not been sorted would require an algorithm that is worse than O(n log n), which is the best you can hope for to sort the list in the first place, meaning on an unsorted list O(n log n) is the best.

However, it should be said that the sorting is an operation which must only be performed once, thus you could sort the list and later directly add successive items in its sorted place in order to maintain a sorted list which is an operation that only requires O(n) time.  Alternatively, if elements are initially inserted in such a way as to maintain a sorted array, you won't have to perform a sort later.

So the real question here is:  What is the best possible time to pick m numbers from an array of n numbers such that the set of m numbers has a minimal difference between max and min given the array n is sorted?

As it turns out, this can be done in O(n) time.  The pseudoalgorithm is as follows:

Given array of size n called A_n containing input
Init values currentMin and currentMax
Init values bestDifference and bestDifferenceIndex

for i = 0, i <= n - m
   currentMin = A_n[i]
   currentMax = A_n[i + m - 1]

   if i = 0 or currentMax - currentMin < bestDifference
       bestDifference = currentMax - currentMin
       bestDifferenceIndex = i

At the end of this using as input your example, bestDifference should show 5 and bestDifferenceIndex will be 0 (sorted A_n would be {5, 7, 10, 10, 12, 22}, meaning it grabbed {5, 7, 10, 10}).

It is a little misleading to call this O(n log n) because this isn't due to the algorithm itself but rather the sort necessary for the algorithm to work properly, and performing sort each and everytime while guaranteed to always work will certainly be slower than if you worked with a pre-sorted array and avoided the call to sort it altogether.

Hope that helps!


答:
While I can see why you would need to have a SmallObject, I would approach the problem differently.  My approach to this type of issue is to use a Facade.  Its sole purpose is to encapsulate BigObject and only make available specific members.  In this way, it is a new interface on the same instance, and not a copy.  Of course you may also want to perform a copy, but I would recommend that you do so through a method created for that purpose in combination with the Facade (for instance return new SmallObject(instance.Clone())).

Facade has a number of other advantages, namely ensuring that certain sections of your program can only make use of the members made available through your facade, effectively guaranteeing that it cannot make use of what it shouldn't know about.  In addition to this, it also has the enormous advantage that you have more flexibility in changing BigObject in future maintenance without having to worry too much about how it is used throughout your program.  So long as you can emulate the old behavior in some form or another, you can make SmallObject work the same as it did before without having to change your program everywhere BigObject would have been used.

Note, this means BigObject does not depend on SmallObject but rather the other way around (as it should be in my humble opinion).

Title: Is my usage of explicit casting operator reasonable or a bad hack?

Body:
I have a big object:

```<code>class BigObject{
    public int Id {get;set;}
    public string FieldA {get;set;}
    // ...
    public string FieldZ {get;set;}
}
</code>```

and a specialized, DTO-like object:

```<code>class SmallObject{
    public int Id {get;set;}
    public EnumType Type {get;set;}
    public string FieldC {get;set;}
    public string FieldN {get;set;}
}
</code>```

I personally find a concept of explicitly casting BigObject into SmallObject - knowing that it is a one-way, data-losing operation - very intuitive and readable:

```<code>var small = (SmallObject) bigOne;
passSmallObjectToSomeone(small);
</code>```

It is implemented using explicit operator:

```<code>public static explicit operator SmallObject(BigObject big){
    return new SmallObject{
        Id = big.Id,
        FieldC = big.FieldC,
        FieldN = big.FieldN,
        EnumType = MyEnum.BigObjectSpecific
    };
}
</code>```

Now, I could create a SmallObjectFactory class with FromBigObject(BigObject big) method, that would do the same thing, add it to dependency injection and call it when needed... but to me it seems even more overcomplicated and unnecessary.

PS I'm not sure if this is relevant, but there will be OtherBigObject that will also be able to be converted into SmallObject, setting different EnumType.


问:
Android. HTTP Communcation, and GCM
I have an app that sends/receive data via HTTP POST, and communicates with PHP/SQL on the backend.

I however wanted to integrate GCM to I can tell the app to "check for an update" to query the server. I wanted to sell the app, and the user has to run the server themselves (the PHP backend). However, I assume I can't publicly list my Google API key. Am I correct in saying that? That throws GCM out the window.

I'm new to sockets, but can I create a TCP connection between the device and server, and send requests back and forth. Or does there need to be two sockets, one to send request, and one to listen?

Thanks.

答:
No struggle, you can create a small sample code using your favorite language (PHP, Java or C#) and give it as integration sample of GCM into your clients, of course on this sample you can hide your Google API Key and ask them to create theirs..

If they do not know how to create one, well you can create a small how to..
I am not Guru but the TCP and sockets idea seems to me will cost a lot for something that exists.. good luck

Title: Android. HTTP Communcation, and GCM


答:
Isn't the version of the app tied to the version of the server? Let's say you implement some new features, doesn't your app have to be updated as well as the server component? In that case I would have the app make a request to the server when it starts. The server can simply send an indication to apps making this starting request that it is outdated. The app would flat-out refuse to function if it's version does not match the servers.

(This also takes away much of the headaches of having to deal with old apps calling newer servers or newer apps calling old servers.)

Title: Android. HTTP Communcation, and GCM

Body:
I have an app that sends/receive data via HTTP POST, and communicates with PHP/SQL on the backend.

I however wanted to integrate GCM to I can tell the app to "check for an update" to query the server. I wanted to sell the app, and the user has to run the server themselves (the PHP backend). However, I assume I can't publicly list my Google API key. Am I correct in saying that? That throws GCM out the window.

I'm new to sockets, but can I create a TCP connection between the device and server, and send requests back and forth. Or does there need to be two sockets, one to send request, and one to listen?

Thanks.


问:
Is there a name for refactoring technique that turns hardcoded values into configurable parameters?
What is that technique called when you take values in the code that are hardcoded and make them variable, possibly constructing elaborate OO constructs to make that variable properly configurable?

For example you are printing labels, and you are specifying a value of labels to print per page, like say 4.

Later you realize you have different label sizes, and shapes.  You construct a label factory, which calls proper label files, which also configure themselves and know their own size in relation to the page which is then returned via a function call using polymorphism, and that value is then used instead of the hardcoded 4.

In my own words I can describe it as

Refactoring in effort to increase configurability and flexibility of the software.

but as far as naming specific technique, no..

答: The antipattern is usually called magic numbers, but the refactoring doesn't have quite such a well-known name. My IDE calls the process of turning literals into parameters externalizing (e.g. "Externalize Strings").


问:
When it makes sense to implement C# explicit operator?
Follow-up of Is my usage of explicit casting operator reasonable or a bad hack?

One of the users commenting on that question said that it's really bad if the casting operator creates a new object under the hood, as it ceases to be an actual cast. It is of course very valid point.

When one would use the ability of defining custom type conversion? Especially: between two types that are not related by inheritance in any way.

With related objects it makes (some) sense:

```<code>class Animal {
    public string Name {get;set;}
    public int Age {get;set;}
}

class Dog : Animal {
    public void Bark(){}
    public void Fetch(){}
}

class Cat : Animal {
    public void Meow(){}
    public void Sleep(){}
}
</code>```

Although normally casting Cat to Dog wouldn't be possible, it makes sense to explicitly allow it - they share all their data, just the behaviour is different.

Even when there would be some difference in fields:

```<code>class Parrot : Animal {
    public int WingSpan {get;set;}

    public void Screech(){}
}
</code>```

casting still might be desired (Parrot to Cat for example, as Cat doesn't have MORE data than Parrot).

But what about two types that are not related? It is possible to do:

```<code>class Rock{
    public int Age {get;set;}
}
</code>```

and

```<code>public static explicit operator Rock(Cat cat){
    return new Rock{Age = cat.Age};
}
</code>```

but why? As pointed out in related question it would cause quite strange behaviour:

```<code>var cat = new Cat{Name = "Fluffy", Age = 8};
var rock = (Rock) cat;
rock.Age = 100000000;
Console.WriteLine(rock.Age); // 100000000
Console.WriteLine(cat.Age); // 8
</code>```

Can anyone give a good example of when implementing explicit operator between unrelated types makes sense and how to do it?

答:
Can anyone give a good example of when implementing explicit operator between unrelated types makes sense and how to do it?

I will argue that it never makes sense to overload the explicit conversion operator. That operator has a well defined behavior, and using it for a different behavior will always fall into the realm of "clever". Just use a function.

That said, I've used the implicit conversion operator a few times, and I think that it can be used in a net-positive way.

For example, I have a small programming language I'm working on. It has an object to represent an Identifier token in the syntax tree, which is just a wrapper for a string to give it a concrete type (like this recent question asked about). So instead of writing new Identifier("blah") or if(identifer == new Identifier("class")) everywhere, I have an implicit conversion from string to Identifier. It simplifies the code while keeping the behavior clear.

Yes, it does create a new object during conversion. Yes, it requires me to make sure that Identifier has value-style equality and be sure that my class design won't cause horrible problems. But it's is one of those fairly dangerous tools you can use in a few situations to make things a lot more elegant if you know what you're doing.

Explicit conversion overrides have no such upside. They add verbosity to code anyways, so you're always better off using more conventional approaches.


问:
Where to store hashes, salts, keys in Desktop Applications
I am trying to figure out where or how i should store application secrets and keys inside a desktop application.
For example a facebook app key or dropbox key and secret.

So I've read that i should hash, salt, encrypt etc etc these values. This is to prevent someone from reverse engineering my code and seeing the keys.

The is all good and well, but with all these methods, i'm just storing a salt or hash value somewhere instead of the key itself, in the end. Surely if a hacker can get to the salt/hash and possibly the source code, they will be able to decrypt the encrypted key and get my password/key/secret anyway?

One option I've read about that seems the most secure is to not store this value in the desktop app at all, but to call a web service to obtain the key (probably encrypted). But my question is, even in this case, a decent hacker will surely just do a memory dump or something to see what the value returned from the web service is, and then we're back at square 1.

The next best alternative seems to be obscurity.

Am I missing something completely?

On a side note, what use will a facebook/twitter/dropbox/etc key/secret be to a hacker anyway? Surely they would still need a user's credentials or access token to be able to use it anyway?

Any advice or suggestions will be appreciated.

答:
You should use a cryptographic hash function: a hash function which is considered practically impossible to invert, that is, to recreate the input data from its hash value alone.

To authenticate a user your application will:

hash the password presented;

compare the value with the stored hash.

This way, if the password file is compromised, you haven't a massive security breach: the application asks for a password, not for a hash-key and the hacker cannot retrieve the password (the one-way function prevents the original password from being retrieved even if forgotten or lost).

Reverse engineering the hash function / application is not meaningful as there is nothing hidden in your code. The passwords are protected by the complexity of reversing the hash function.

Anyway the hacker could try a dictionary attack using a large list of pre-computed hashes for commonly used passwords.
Usually even a small dictionary (or its hashed equivalent, a rainbow table) has a significant chance of cracking the most used words.

So the access to hashed data should be restricted (e.g. see Shadow file for Unix-like operating systems).


问:
Why does C provide language 'bindings' where C++ falls short?
I recently was wondering when to use C over C++, and vice versa? Fortunately someone already beat me to it and although it took a while, I was able to digest all the answers and comments to that question.

However one item in that post keeps being addressed again and again, without any kind of example, verification or explanation:

"C code is good for when you want to have multiple language bindings for your library"

That's a paraphrase. I should note that several people point out that multiple language bindings are possible in C++ (via some extern functioning), but nevertheless, if you read that post in its entirety, it's pretty obvious that C is ideal for portability/language binding. My question is: why?

Can someone please provide concrete reasons why writing libraries in C allows for easier bindings and/or portability in other languages?

答:
There are two major axes when interfacing with another language:

the concepts that the interface can carry over: just values? references? generics?

how the interface is implemented in "binaries" (called ABI)

C has an advantage over C++ on those two fronts:

C only has mostly simple concepts, which appear in most every other language1

The ABI of C binaries is decided by the OS2

Now, why do most languages have a similar set of concepts than C may be due to it either being "simple" or "pre-existing"; it does not matter though, the point is that they do.

On the contrary, C++ has complex concepts, and the ABI is decided by each compiler (though many adhere to the Itanimum ABI, except on Windows...). There was actually a proposal by Herb Sutter to have OSes fix a C++ ABI (on a per OS basis) to partially address this issue. Also, one should note that a C++ FFI is possible, D is attempting it3.

1 Except variadics (...), those are not simple

2 Does C have a standard ABI?

3 Interfacing D to Legacy C++ code


问:
Reuse already fetched data for request
I have action that fetches user model from db to check access.

Then I have method that in some cases requires same model.

```<code>function checkAccess(req, res, next) {
    var data = Data.fetch(req.params._id);
    if (data.userId === req.user._id) {
        return res.sendStatus(401);
    }
    return next();
}

Router()
    .get('/:_id',
        checkAccess,
        function (req, res, next) {
            var data = Data.fetch(req.params._id);
            update(data);
            return res.json(data);
        });
</code>```

Question isn't about how to reuse data in exactly that case (the simplest solution I found is use res.local).

My confusion is about fetching same data from db twice, when it theoretically can be reused.

It isn't heavy request, so caching layer unlikely increase access speed in comparison with access to db. But using cache can introduce many headache with invalidation.

I found that using request-related (res.local) cache can particularly solve the problem, but it makes my code more verbose and complex. I check every piece of data whether it was fetched, and also should make decision is it possible that this data outdated. Also I pass arguments through several methods to reuse it, so it pollutes my internal API (e.g. when I send email I reuse data needed for rendering email template, so I can't just use mailService.sendInvite(userId), but mailService.sendInvite(userId, {user: user, event: event})).

Should I worry about fetching small pieces of the same data from db multiple times per request?

答:
It looks like you could integrate CheckAccess into a higher-level data-fetching function.

```<code>var GetSomeData = function(req) {
  var data = Data.fetch(req.param_id);
  if (data.userId === req.user._id) {
    return {'error': 401};
  }
  return {'success': data};
}

// ...
// in client code

var reply = GetSomeData(req);
if (reply.error) {
  res.sendStatus(reply.error);
  return res;
}
else {
  return res.json(reply.success);
}
</code>```

I see how attractive and reusable methods like checkAccess() could be. But these need certain information to actually check access. You can either haul this security context around as an argument, or pass it into a constructor / factory method.  Consider:

```<code>var securityContext = getSecurityContext(request);  // fetches security data
var mailService = new MailService(securityContext);
var orderProcessor = new OrderProcessor(securityContext);
try {
  var orderId = orderProcessor.createOrder(request);
  mailService.sendConfirmationEmail(orderId, ...);
} catch (error) {
  // report the details of the error
}
</code>```

With securityContext passed in constructor, any of your services can reuse it without re-fetching. getSecurityContext() should fetch enough security-related data to avoid more round-trips for it, or at least make them improbable.

Title: Reuse already fetched data for request

Body:
It looks like you could integrate CheckAccess into a higher-level data-fetching function.

var GetSomeData = function(req) {
  var data = Data.fetch(req.param_id);
  if (data.userId === req.user._id) {
    return {'error': 401};
  }
  return {'success': data};
}

// ...
// in client code

var reply = GetSomeData(req);
if (reply.error) {
  res.sendStatus(reply.error);
  return res;
}
else {
  return res.json(reply.success);
}

I see how attractive and reusable methods like checkAccess() could be. But these need certain information to actually check access. You can either haul this security context around as an argument, or pass it into a constructor / factory method.  Consider:

var securityContext = getSecurityContext(request);  // fetches security data
var mailService = new MailService(securityContext);
var orderProcessor = new OrderProcessor(securityContext);
try {
  var orderId = orderProcessor.createOrder(request);
  mailService.sendConfirmationEmail(orderId, ...);
} catch (error) {
  // report the details of the error
}

With securityContext passed in constructor, any of your services can reuse it without re-fetching. getSecurityContext() should fetch enough security-related data to avoid more round-trips for it, or at least make them improbable.


答:
There is no 100% secure solution.  What ever you implement must be executable by a deterministic computer, so someone and substitute that and unpick what ever technical barriers you put in their way. You can make it more technically challenging and a more involved and slower process, but in time if the incentives are there, someone will break it.

If you are implementing this in .NET then, by default it is trivial for someone to obtain C# style source code to your application, and then to step through their C# code in a debugger.  It is a little more complex in C/C++, but again not impossible.  I do not know how much of a challenge this is with JAVA, but I would not expect it to be a significant hurdle.

There are processes that can be applied to make the code harder for a human to read, but do very little to make it harder for a computer to single step through the code.  Someone can put a breakpoint in the system library and then back track up the call stack to see if this call to a network socket is of interest without having to understand your code base.

I have also seen encryption techniques used, where a program decrypts the actual code during run time.  However, again, a determined hacker can just run this part of the code, obtain the decrypted code and then reverse engineer this into source code.

The best solution is to assume it will become compromised, and then ensure that the process for changing the sensitive data is trivial for you, and to process to compromise the sensitive data is as hard as possible for everyone else.  That's why some systems require a web call to obtain the data.  You can then block calls from IP's or from client certificates that you no longer trust, and give everyone else 'this months' application key.

In the end, you need to consider the consequences for having the data publicly known, and then decide how far you need to go, to make the process for obtaining it more skilled and and more time consuming.

Title: Where to store hashes, salts, keys in Desktop Applications

Body:
I am trying to figure out where or how i should store application secrets and keys inside a desktop application.
For example a facebook app key or dropbox key and secret.

So I've read that i should hash, salt, encrypt etc etc these values. This is to prevent someone from reverse engineering my code and seeing the keys.

The is all good and well, but with all these methods, i'm just storing a salt or hash value somewhere instead of the key itself, in the end. Surely if a hacker can get to the salt/hash and possibly the source code, they will be able to decrypt the encrypted key and get my password/key/secret anyway?

One option I've read about that seems the most secure is to not store this value in the desktop app at all, but to call a web service to obtain the key (probably encrypted). But my question is, even in this case, a decent hacker will surely just do a memory dump or something to see what the value returned from the web service is, and then we're back at square 1.

The next best alternative seems to be obscurity.

Am I missing something completely?

On a side note, what use will a facebook/twitter/dropbox/etc key/secret be to a hacker anyway? Surely they would still need a user's credentials or access token to be able to use it anyway?

Any advice or suggestions will be appreciated.


问:
is OOP the dominant programming model in real world?
Objects Never? Well, Hardly Ever

In the VIEWPOINT section of Communications of The ACM, I found an
interesting article entitled "Objects Never? Well, Hardly Ever".
It’s a radically different perspective than objects-first or objects-late. He suggests "objects-never" or maybe "objects-graduate school".

The author talked about OOP and made a question about how OOP is used
in real world programming environments. He thinks that OOP is not the
dominant programming model. For example, he claims, 70% of
programmings are done for Embedded Systems where OOP is not really
suited.

When some professors in universities wants to talk about the benefits
of OOP, they talk about code-reuse. As another example, again, he
claims, this is not the real case in real world. code-reuse is harder
than what's claimed in universities:

I claim that the use of OOP is not as prevalent as most people believe, that it is not as successful as its proponents claim, and, therefore, that its central place in the CS curriculum is not justified.

It's interesting for me to know how people in stack-overflow think
about this? Is OOP the dominant programming model from programmers'
point of view?

If I should choose/learn/use just one approach, is it OOP or not? why?

答:
If OOP is the only paradigm you know, maybe you should learn more. But really, what's OOP actually mean? Does it mean Java or C++? Does it mean Smalltalk? Does it mean settable value slots and closures? (Hi, Scheme!) Does it mean message sending? (Hi, Erlang!)

In short, it seems an uninteresting question to ask. "Is OO useful?" is a better question. And, well, it seems that way. (Certainly it is for me.)


答:
The casting operator is an operator, and like all operators you shouldn't overload it unless that overloading preserves the accepted meaning of the operator in the environment you work in. One of the reasons Scala confuses so many people is that it's libraries tend to hijack operators for DSL creation, making it very hard to understand the library and write code that uses it just from reading the API. Don't do that.

The same operators might have different accepted meanings in different languages - e.g. << and >> usually mean shift, but in C++ they also mean send-to/read-from stream. The accepted meaning can also come from the domain - for example many libraries that deal with paths like to use the division operator / for joining paths - because that's what used in the shell.

But the cast operator has the same general meaning everywhere - when I cast type X to type Y, I'm saying "a Y is essentially a X, only ...". The part after the only can make a world of difference - but I'd argue that any overload of cast that can't be translated to this template is an abuse of the case operator.

(string) 10 - a string is essentially a integer, only represented as text.

(int) 5.4 - an int is essentially a float, only without the fraction

(string) ['a', 'b', 'c'] - a string is essentially a collection of characters, only concatenated to each other.

(Rock) cat - a cat is essentially a rock, only... well...

It doesn't work in the last example - because a cat is not a rock, not matter how you put it. You are getting a weird behavior because what you are trying to do is weird. Just because both rock and cat have an age doesn't mean that a cat is essentially a rock with the same age - that kind of thinking is worse than Weak Typing - not only are you breaking the abstraction that strong typing provides to you that says that 1069547520 is different than 1.5 even though they are have the same representation in the memory - you are creating brand new conversions that make no sense neither in the high abstraction level nor in the low memory level.

So, to your question("Can anyone give a good example...") - the answer is no. Noone can give a good example, because there aren't any good example. Casting doesn't make sense when X and Y are unrelated, because the only cases where a cast operator makes sense is then you can say "a X is essentially a Y, only ...", and if you can say this - that's the relation between X and Y.

Title: When it makes sense to implement C# explicit operator?

Body:
Follow-up of Is my usage of explicit casting operator reasonable or a bad hack?

One of the users commenting on that question said that it's really bad if the casting operator creates a new object under the hood, as it ceases to be an actual cast. It is of course very valid point.

When one would use the ability of defining custom type conversion? Especially: between two types that are not related by inheritance in any way.

With related objects it makes (some) sense:

```<code>class Animal {
    public string Name {get;set;}
    public int Age {get;set;}
}

class Dog : Animal {
    public void Bark(){}
    public void Fetch(){}
}

class Cat : Animal {
    public void Meow(){}
    public void Sleep(){}
}
</code>```

Although normally casting Cat to Dog wouldn't be possible, it makes sense to explicitly allow it - they share all their data, just the behaviour is different.

Even when there would be some difference in fields:

```<code>class Parrot : Animal {
    public int WingSpan {get;set;}

    public void Screech(){}
}
</code>```

casting still might be desired (Parrot to Cat for example, as Cat doesn't have MORE data than Parrot).

But what about two types that are not related? It is possible to do:

```<code>class Rock{
    public int Age {get;set;}
}
</code>```

and

```<code>public static explicit operator Rock(Cat cat){
    return new Rock{Age = cat.Age};
}
</code>```

but why? As pointed out in related question it would cause quite strange behaviour:

```<code>var cat = new Cat{Name = "Fluffy", Age = 8};
var rock = (Rock) cat;
rock.Age = 100000000;
Console.WriteLine(rock.Age); // 100000000
Console.WriteLine(cat.Age); // 8
</code>```

Can anyone give a good example of when implementing explicit operator between unrelated types makes sense and how to do it?


问:
Software pattern for combining properties
I have two classes that read distinct files. As an examples, two classes, sourceA or Client, and sourceB or Resources:

```<code>public class Client()
{
    public string ClientName {get; set;}
    public int ClientNumber {get; set;}
    public string Address {get; set;}
    //...
}

public class Resources()
{
    public int ClientNumber {get; set;}
    public decimal Resources {get; set;}
    //...
}
</code>```

Let's say that I need to merge booth classes into a new one, but I just need some fields from class Client and Resources. Is there any software pattern motivated by something like this, to compose a class like ClientReport?

The new class should be something like this:

```<code>public class ClientReport()
{
    public string ClientName {get; set;}
    public int ClientNumber {get; set;}
    public string Address {get; set;}
    public decimal Resources {get; set;}

    public int CalculateRating()
    {
        //...
    }
}
</code>```

These new classe will have some properties of Client and Resources, and copying code from them in order to create ClientReport seems to be a repetition, and I think it should be a away to compose this class and only use the needed properties from Client and Resources.

答:
The definition of your client class should not be tied to how you acquire the data to construct the class.  You should review your business requirements of your client class and define it based on that only.

From what you have shown so far, it looks like you need two file processing classes which both are provided a collection of client objects to work on, whether that is for creation or update.

The key thing is that the client class needs to be freestanding from the processing needed for the files.  Tomorrow you may need to read from a database, or a web service, or something else, but that certainly doesn't change the definition of a client in your business domain.


答:
Here are (at least) two objects client and report involved.
From what you write so far, a report seems best to be composed of a client and ressources:

```<code>public class ClientReport()
{
    public Client client;
    public decimal ressources;

    public getClientName(){ return this.client.getName(); }
    // ...
    public setRessources(decimal ressources){ this.ressources=ressources; }

    public ClientReport(Client client){
        this.client=client;
    }
}
</code>```

Instead of copying the fields of the Client you should wrap the Client into the ClientReport (pass it via constructor) and delegate incoming calls of the report to the Client itself (see getClientName()). So you are free to hide/show (= encapsulate), whatever part of the Client you want. It makes sense to hide the creation of the ClientReport behind a Builder. The Builder reads first SourceA to generate the List<Clients>. After that it reads SourceB to map the ressources to the respective client. The Builder itself has only one method getClientReports(), which does all that transparently to the consumer.

You should further clean up your object design. Perhaps it makes sense in your domain to have an Address-object, which is wrapped by the Client object.

Title: Software pattern for combining properties

Body:
I have two classes that read distinct files. As an examples, two classes, sourceA or Client, and sourceB or Resources:

```<code>public class Client()
{
    public string ClientName {get; set;}
    public int ClientNumber {get; set;}
    public string Address {get; set;}
    //...
}

public class Resources()
{
    public int ClientNumber {get; set;}
    public decimal Resources {get; set;}
    //...
}
</code>```

Let's say that I need to merge booth classes into a new one, but I just need some fields from class Client and Resources. Is there any software pattern motivated by something like this, to compose a class like ClientReport?

The new class should be something like this:

```<code>public class ClientReport()
{
    public string ClientName {get; set;}
    public int ClientNumber {get; set;}
    public string Address {get; set;}
    public decimal Resources {get; set;}

    public int CalculateRating()
    {
        //...
    }
}
</code>```

These new classe will have some properties of Client and Resources, and copying code from them in order to create ClientReport seems to be a repetition, and I think it should be a away to compose this class and only use the needed properties from Client and Resources.

Body:
Here are (at least) two objects client and report involved.
From what you write so far, a report seems best to be composed of a client and ressources:

public class ClientReport()
{
    public Client client;
    public decimal ressources;

    public getClientName(){ return this.client.getName(); }
    // ...
    public setRessources(decimal ressources){ this.ressources=ressources; }

    public ClientReport(Client client){
        this.client=client;
    }
}

Instead of copying the fields of the Client you should wrap the Client into the ClientReport (pass it via constructor) and delegate incoming calls of the report to the Client itself (see getClientName()). So you are free to hide/show (= encapsulate), whatever part of the Client you want. It makes sense to hide the creation of the ClientReport behind a Builder. The Builder reads first SourceA to generate the List<Clients>. After that it reads SourceB to map the ressources to the respective client. The Builder itself has only one method getClientReports(), which does all that transparently to the consumer.

You should further clean up your object design. Perhaps it makes sense in your domain to have an Address-object, which is wrapped by the Client object.


答:
There is a very strong convention that casts on mutable reference types are identity-preserving.  Because the system generally does not allow user-defined casting operators in situations where an object of the source type could be assigned to a reference of the destination type, there are only a few cases where user-defined casting operations would be reasonable for mutable reference types.

I would suggest as a requirement that, given x=(SomeType)foo; followed sometime later by y=(SomeType)foo;, with both casts being applied to the same object, x.Equals(y) should always and forevermore be true, even if the object in question was modified between the two casts.  Such a situation could apply if e.g. one had a pair of objects of different types, each of which held an immutable reference to the other, and casting either object to the other type would return its paired instance.  It could also apply with types that serve as wrappers to mutable objects, provided that the identities of the objects being wrapped were immutable, and two wrappers of the same type would report themselves as equal if they wrapped the same collection.

Your particular example uses mutable classes, but does not preserve any form of identity; as such, I would suggest that it is not an appropriate usage of a casting operator.


答:
I have not facts to follow it up, but OOP isn't the dominant programming model. Just imagine all those in-house apps developed by someone who took a visual basic course, or did some macro programming in Excel.

A lot of applications are just doing imperative programming where all logic is stacked up in a single class or view. This is probably the vast majority of internal simple applications running all over enterprises.

There is nothing wrong with that, there are several ways to solve the same problem. Some better suited than others.

Also as you pointed out, OOP not usefull for all scenarios. There are other models as well.

Title: is OOP the dominant programming model in real world?

Body:
Objects Never? Well, Hardly Ever

In the VIEWPOINT section of Communications of The ACM, I found an
interesting article entitled "Objects Never? Well, Hardly Ever".
It’s a radically different perspective than objects-first or objects-late. He suggests "objects-never" or maybe "objects-graduate school".

The author talked about OOP and made a question about how OOP is used
in real world programming environments. He thinks that OOP is not the
dominant programming model. For example, he claims, 70% of
programmings are done for Embedded Systems where OOP is not really
suited.

When some professors in universities wants to talk about the benefits
of OOP, they talk about code-reuse. As another example, again, he
claims, this is not the real case in real world. code-reuse is harder
than what's claimed in universities:

I claim that the use of OOP is not as prevalent as most people believe, that it is not as successful as its proponents claim, and, therefore, that its central place in the CS curriculum is not justified.

It's interesting for me to know how people in stack-overflow think
about this? Is OOP the dominant programming model from programmers'
point of view?

If I should choose/learn/use just one approach, is it OOP or not? why?


问:
Should I use inheritance to differentiate objects even if they have the same fields?
Consider this simple class that models a real world mobile device:

///
///     Model that represents a device.
///
public class Device
{
    public DateTime CreationDate { get; set; }

    public bool Enabled { get; set; }

    ///
    ///     Gets or sets the device's hardware identifier.
    ///
    /// <remarks>Commonly filled with data like device's IMEI.</remarks>
    public string HardwareId { get; set; }

    public int Id { get; set; }

    public DateTime? LastCommunication { get; set; }
}
```

<p>Now suppose a new requirement arrived and I need to start differentiating a device by platform, like <code>Windows Phone</code>, <code>Android</code> and <code>iOS</code>. The most common option I think would be to create an enumeration class:</p>

<pre class="lang-cs prettyprint-override"><code>/// <summary>
///     Defines a type of device.
/// </summary>
enum PlatformType
{
    /// <summary>
    ///     Device is an Android.
    /// </summary>
    Android,

    /// <summary>
    ///     Device is an Windows platform.
    /// </summary>
    Windows,

    /// <summary>
    ///     Device is an iOS platform.
    /// </summary>
    Ios,
}
</code>```

and then add a new property to the device class:

public class Device
{
    ...

    public PlatformType Platform { get; set; }

    ...
}
```

<p>Another approach would be to create a inheritance hierarchy on the device class itself:</p>

<pre class="lang-cs prettyprint-override"><code>public class AndroidDevice : Device { }

public class IosDevice : Device { }

public class WindowsPhoneDevice : Device { }
</code>```

When should I choose one of those approaches over the other? Should I always choose the second one or is there a reason not to?

答:
I would make this choice based on how much of the implementation is shared between platforms.

If 99% of the code is the same on all platforms, then have a private enum, and in the one or two places where it matters just use a switch(Platform) block and you're done.

But if you have to make dozens of platform-dependent system calls inside this class, each with different parameters and semantics and error handling conventions, then you're better off with completely separate classes that merely inherit from a common interface.

The example interface you've shown would almost certainly end up in the latter category.


答:
The OOP answer is to do the inheritance. I guess the reasoning is to avoid conditional blocks of code such as :

```<code>if(type==PlatformType.Android) { ..}
else ....
</code>```

Which can be replaced with overridden methods on the specific class

However if you just have a data struct with no logic, as may be the case if you have no requirement for extra fields, or are passing to a DB or service. I think the type property is ok.

Title: Should I use inheritance to differentiate objects even if they have the same fields?

Body:
Consider this simple class that models a real world mobile device:

///
///     Model that represents a device.
///
public class Device
{
    public DateTime CreationDate { get; set; }

    public bool Enabled { get; set; }

    ///
    ///     Gets or sets the device's hardware identifier.
    ///
    /// <remarks>Commonly filled with data like device's IMEI.</remarks>
    public string HardwareId { get; set; }

    public int Id { get; set; }

    public DateTime? LastCommunication { get; set; }
}
```

<p>Now suppose a new requirement arrived and I need to start differentiating a device by platform, like <code>Windows Phone</code>, <code>Android</code> and <code>iOS</code>. The most common option I think would be to create an enumeration class:</p>

<pre class="lang-cs prettyprint-override"><code>/// <summary>
///     Defines a type of device.
/// </summary>
enum PlatformType
{
    /// <summary>
    ///     Device is an Android.
    /// </summary>
    Android,

    /// <summary>
    ///     Device is an Windows platform.
    /// </summary>
    Windows,

    /// <summary>
    ///     Device is an iOS platform.
    /// </summary>
    Ios,
}
</code>```

and then add a new property to the device class:

public class Device
{
    ...

    public PlatformType Platform { get; set; }

    ...
}
```

<p>Another approach would be to create a inheritance hierarchy on the device class itself:</p>

<pre class="lang-cs prettyprint-override"><code>public class AndroidDevice : Device { }

public class IosDevice : Device { }

public class WindowsPhoneDevice : Device { }
</code>```

When should I choose one of those approaches over the other? Should I always choose the second one or is there a reason not to?

Body:
The OOP answer is to do the inheritance. I guess the reasoning is to avoid conditional blocks of code such as :

if(type==PlatformType.Android) { ..}
else ....

Which can be replaced with overridden methods on the specific class

However if you just have a data struct with no logic, as may be the case if you have no requirement for extra fields, or are passing to a DB or service. I think the type property is ok.


问:
I believe my solution is better than my boss's, so should I ignore him?
I'm working with php and sql.

I think that my method of implementing functions is better than what my boss proposes. Just now he explained me how to do a check on a list of email addresses, and I do not like his idea. I proposed mine which is better and quicker to implement, but he disagreed.

Now I think I will go ahead and implement my idea, because his idea was not clear enough to me. Do you think he will be mad?

答: I don't think you have the right attitude here. Thinking you are better than your boss or just thinking you are better than somebody else never helps matters. Did you tell him why you didn't like his idea or did you just say, "I have a better way of doing things". Why is your idea better exactly? Is it a less convoluted algorithmically? Does it have better run-time? Is it easier to maintain? Does it use easier to understand design patterns?</p>


答:
I think there are two distinct problems here

1: Can I stop a user who has access to the client source code from getting at a hardcoded or configigured key /password the client needs to access a service

2: Can I stop a hacker who gains access to the users pc from accessing the users cached username/password my app is using.

so with 1, you shouldn't have this kind of shared key used by all your clients. ensure each user has their own credentials for the service. This makes then responsible for their own information only and allows you to ban abusers

with 2, as in @ptolemy's answer, dont store their username/password store a hash, or better yet use the username/pass once to get an api key and store that. Invalidate after a period of time or when you detect suspect behaviour such as multiple concurrent connections etc