问:
OOP (php) for beginners - some unclarities
I started reading some tutorials about OOP, because I want to learn the basics.

I have a question about it. I understand how you can have a object "Car" and give it a color like this $oCar->setColor("white");

But there are some things unclear to me. Let's say I have a database with all kinds of cars. What is the best way to create the object "car"? A SQL-query instead the class?

And the other question is: how can I output a list of all cars? Do I need to create a object called "Garage" with has only one method within that selects all the cars from the database? Or does this kind of method belong in the "Car" object?

答:
You still need to understand what the Object is and what does it represent.

What is the best way to create the object "car"? A SQL-query instead the class?

Firstly, an SQL query doesn't help you to create objects, you can use
its output to create objects.

OBJECTS RESIDE IN MEMORY. You must be aware that what represent the
Objects are their STATES. Now what are the states ? It's nothing but
the values that object is having.

Say for example

Car Object --> name='bmw', color='black' // values of the both the
  variable is state of car object.

I think you are clear enough about the objects now.

So think of your problem again.

You need to access list of cars. But the data that represents the cars is in the database.

ONE DB ROW = CAN CREATE ONE CAR OBJECT.

How we will create objects from the database output ? Simple. Fire
query against the database, get the output and CONSTRUCT OBJECTS from
that data.

Now about LIST of the CARS. As you are having all your objects in the memory you can create list which will include all the objects in it. Again this list is also an object and its state is its values.

Hope this clears your understanding of Objects.


问:
Distributed system command and control
I have an application that consists of a set of Java and C++ of processes running on one or more systems and need to ability to monitor and control the components as if they were one complete system.

My requirements:

runtime statistics (messages per second etc..)

log of events

control: "service X set rate to 1000 mps" or "all services stop"

ambient configuration so all services can start up and discover the working mode (etc..)

Since data plane messaging is 0MQ based, I am currently doing this with 0MQ based messaging and a message distributor to fan out the control messages.

However, I am interested in how others have tackled the problem.

Thanks.

答:
I'm not sure about controlling them, but SNMP is typically used for monitoring of a distributed system like this.

0MQ is awesome however, so there's no reason why one of its configurations can't be used too.

ContentLicense: CC BY-SA 3.0

Title: Distributed system command and control


问:
Where should authentication be handled, in the server's code, or in the application's server-side code?
I'm developing a simple web application in node.js.  Users can log in from any page in the application, so I handle authentication in the server's code and logic, and the application's server-side code checks to see if a couple session variables are set.  If they are, the application continues with user-specific information.

I'm unsure if this is the best way to handle the authentication logic.  Should I move all authentication completely over to the application's code and only have the server listen and pass requests along, or, since the server is setting the session anyway, should I have it control back-end authentication logic as I'm handling it now?

In the end, what I'm really asking is: Conceptually, where should authentication be handled?  In the server's code, or in the application's server-side code?

Edit: To be more specific, it's a public application on the internet.  The logic that I'm questioning is entirely the server-side logic.  Thank you for pointing that out to me.  I edited my title to make it a little more accurate.

答:
When you say "web application logic" you mean on the client side, in the JavaScript on the client's browser?  If so, the answer is simple.  You can't trust what happens on the client's browser, or even that the client is using a browser.  It could be a hacking tool that makes your code think it's running in a browser.  Heck, some standard browsers even let you edit JavaScript in a loaded page.

You can do checks on the client side to provide quick user-feedback.  But any actual security constraints need to be enforced on the server - even though this sometimes means duplicating code.

Your "couple of fields" are your login tokens.   If you store them in cookies, those tokens need to be created on the server in a cryptographically secure way so that someone (or some script) can't guess one in a few million tries.  Hope that helps.


问:
Training old timey fortran programmers to better code design. hints?
I need to quickly train Fortran 90 developers into object oriented design, good coding, and general coding practices to make code maintenance easier and accessible to everybody. Their current style is the usual:

long routines that do too much

modules are aggregated in "family mode" (routines that have something to do with different kind of objects who share a common use are all in one module, instead of having different modules for different type)

huge globals module with hundreds of variables

general un-greppability of identifiers

This is just out of my head. I did a course to one of them explaining OO and modularization in terms of a Pen (with methods such as uncap(), and members like inkLevel) and I was very successful in diverting his point of view. I also gave him the exercise to code in OO style a very simple textual adventure, where the player can move around rooms. I also introduced the concept of patterns and antipatterns.

I would like to know any hints and suggestions on how to perform this task at best.

Thanks

答:
Do a simple Animal, Cat, Dog example demonstrating inheritance without writing a single line of code at first.  Make sure they understand the concept of Object Oriented Programming before you even begin syntax.

It's easy to try to relate old concepts to new concepts if you try to let them understand on their own, so I would avoid that until you think they understand why they're doing it in that particular way.  If you explain it to them in terms in which they can see the advantages of doing it that way, they'd have a reason not to use their old pattern of Fortran.

As for the length of methods, take a long method as an example and then replace pieces of it with bitesize methods with proper naming conventions so you can both demonstrate that long methods are ugly and how they can go about improving the situation.

ContentLicense: CC BY-SA 2.5


答: Any time you rely on anything coming from the client it can be spoofed. You definitely want to do some kind of hashing with some kind of server side "salt" which is stored securely on the server so you can encrypt / decrypt your client validation tokens without relying on anything "originating" from the client. </p>

Title: Where should authentication be handled, in the server's code, or in the application's server-side code?

Body:
I'm developing a simple web application in node.js.  Users can log in from any page in the application, so I handle authentication in the server's code and logic, and the application's server-side code checks to see if a couple session variables are set.  If they are, the application continues with user-specific information.

I'm unsure if this is the best way to handle the authentication logic.  Should I move all authentication completely over to the application's code and only have the server listen and pass requests along, or, since the server is setting the session anyway, should I have it control back-end authentication logic as I'm handling it now?

In the end, what I'm really asking is: Conceptually, where should authentication be handled?  In the server's code, or in the application's server-side code?

Edit: To be more specific, it's a public application on the internet.  The logic that I'm questioning is entirely the server-side logic.  Thank you for pointing that out to me.  I edited my title to make it a little more accurate.


问:
setSoftInputMode versus InputMethodManager
I have seen and used both of the methods to hide the on screen keyboard while coding Android:

```<code>getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
</code>```

and:

```<code>InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
</code>```

I have read through the documentation for both and I am still unclear as to how each is different, the same, which is a better method or practice to use, and which one should be used in which situations.

Here is an excerpt from the .setSoftInputMode documentation:

Specify an explicit soft input mode to use for the window, as per WindowManager.LayoutParams.softInputMode. Providing anything besides "unspecified" here will override the input mode the window would normally retrieve from its theme.

And here is an excerpt from the InputMethodManager documentation that seems to say nearly the same thing:

You can also control the preferred soft input state (open, closed, etc) for your window using the same windowSoftInputMode attribute.

More finer-grained control is available through the APIs here to
  directly interact with the IMF and its IME -- either showing or hiding
  the input area, letting the user pick an input method, etc.

So what is the difference in these two options to hide the Android soft keyboard, and does one have a benefit over the other? Is one more efficient? What are specific uses for each?

答:
I think is very clear in InputMethodManager documentation when it says:

The input method manager as expressed by this class is the central point of the system that manages interaction between all other parts. It is expressed as the client-side API here which exists in each application context and communicates with a global system service that manages the interaction across all processes.

An input method (IME) implements a particular interaction model allowing the user to generate text. The system binds to the current input method that is use, causing it to be created and run, and tells it when to hide and show its UI. Only one IME is running at a time.

What I mean is that the InputMethodManager is "bigger" and has a lot of more responsability than setSoftInputMode. The first one is a

Central system API to the overall input method framework (IMF) architecture, which arbitrates interaction between applications and the current input method.

and in the other hand, the second is just a setter method.


问:
Is it poor programming practice to pass parameters as Objects?
So, we've got a guy who likes to write methods that take Objects as parameters, so they can be 'very flexible.' Then, internally, he either does direct casting, reflection or method overloading to handle the different types.

I feel like this is a bad practice, but I can't explain exactly why, except that it makes it more difficult to read. Are there other more concrete reasons why this would be a bad practice? What would those be?

So, some folks have asked for an example. He has an interface defined, something like:

```<code>public void construct(Object input, Object output);
</code>```

And he plans to use these by putting several in a list, so it sort of builds bits and adds them to the output object, like so:

```<code>for (ConstructingThing thing : constructingThings)
    thing.construct(input, output);
return output;
</code>```

Then, in the thing that implements construct, there is a rickety reflection thing that finds the right method that matches the input/output and calls it, passing input/output.

I keep telling him, it works, I understand it works, but so does putting everything into a single class. We're talking about reuse and maintainability, and I think he's actually constraining himself and has less reuse than he thinks. The maintainability, while probably high for him right now, will likely be very low for him and anyone else in the future.

答: It takes away the type checking that the compiler does and can lead to more runtime exceptions when the object is cast to the concrete type.  Thus, the end-user will see the unhandled exception, unless the invalid casts are all caught and properly handled.</p>

OwnerDisplayName: Risser

OwnerDisplayName: edtheprogrammerguy


答:
From a practical point of view I see these problems:

A bloat of possible run type errors -- unless a lot of dynamic type checking which could be avoided with the Java included strong type checker.

A lot of unnecessary casts

Difficulty understanding what a method does by its signature

From a theoretical point of view I see these problems:

A lack of contracts of the interface of a class. If all parameters are of Object type then you aren't declaring anything informative to the client classes.

A lack of overloading possibilities

The incorrectness of override. You are able to override a method and change its parameter types thus breaking everything which is inheritance related.

Title: Is it poor programming practice to pass parameters as Objects?

Body:
So, we've got a guy who likes to write methods that take Objects as parameters, so they can be 'very flexible.' Then, internally, he either does direct casting, reflection or method overloading to handle the different types.

I feel like this is a bad practice, but I can't explain exactly why, except that it makes it more difficult to read. Are there other more concrete reasons why this would be a bad practice? What would those be?

So, some folks have asked for an example. He has an interface defined, something like:

```<code>public void construct(Object input, Object output);
</code>```

And he plans to use these by putting several in a list, so it sort of builds bits and adds them to the output object, like so:

```<code>for (ConstructingThing thing : constructingThings)
    thing.construct(input, output);
return output;
</code>```

Then, in the thing that implements construct, there is a rickety reflection thing that finds the right method that matches the input/output and calls it, passing input/output.

I keep telling him, it works, I understand it works, but so does putting everything into a single class. We're talking about reuse and maintainability, and I think he's actually constraining himself and has less reuse than he thinks. The maintainability, while probably high for him right now, will likely be very low for him and anyone else in the future.

OwnerDisplayName: Jack


答:
I'd consider the following direct implications:

Readability

I guess working with him is not exactly the most pleasant experience in the world. You never know what the type is going to be in the end or what happens to the parameters. I doubt you appreciate wasting your time with that.

Type Signature

In Java everything is an Object. So what does that method do in the end?

Speed

Reflection, casts, type checks etc all contribute to a slower performance. Why? Because in his opinion it makes things flexible.

Against nature

Java has been strongly typed since birth. Tell him to start writing JavaScript or Python or Ruby if he wants a dynamically typed dialect. His background is probably strongly based on one of them.

Flexibility

To use the same term as the colleague in question, Java has already figured out flexibility long ago. There is no point to look at it with the horse glasses put on by a dynamically typed language.

Interfaces, polymorphism, covariance & contra-variance, generics, inheritance, abstract classes and method overloading are just a few of the things that contribute to the so called "flexibility". Flexibility is given by the fact that it is trivial to specialise virtually anything from any given type to another.(The usual case meaning specialising a direct upper type or lower type).

Documentation

One of the main goals of programming is to write reusable and stable code. How does the documentation of your example look like? What is the learning time for another developer before being able to use that stuff? I would suggest your guy to write self-modifying assembler code and stay responsbile for it.


答:
yes. java is supposed to be strictly typecasted  . But having Object as parameter will virtually break this rule. Moreover, it will make your program more bug prone.

And that's the one of the top reasons, why generics were introduced.


答:
First, if you pass the parameters as the concrete object, any error of using the wrong object (instance of a non expected class) will be detected in compile time, so will be faster to fix. In the other case, the error will be shown at runtime and will be harder to detect and fix.

Second, the code of checking the real class of the instance, reflection, etc, will be slower than a direct call

OwnerDisplayName: Evans


答:
There are a lot of good answers here already. I want to add a secondary thought:

This pattern is most likely a "code smell."

In other words, if you need to pass an Object to your method for "ultimate" flexibility, you most likely have a very poorly defined method.  Having strongly typed parameters indicates a "contract" to the caller (I need things that look like "this"). Being unable to specify such a contract most likely means that your method does too much or has a poorly defined scope.

OwnerDisplayName: jtahlborn


问:
Languages with graph data structures and algorithms in standard library
I am trying to improve my knowledge and ability with graphs and graph algorithms and have noticed something curious: as far as I can tell no "mainstream" language contains support for graphs in its standard library. Trees yes, graphs no. The only language that comes even remotely close is C++ with Boost (which isn't technically a "standard library")

I'm not sure exactly why this is, but it's got me wondering: are there any programming languages out there that come with solid support for graphs as part of their standard library?

Edit: To clarify: by "graph" I mean a network of nodes and edges; the sort of thing you'd run Dijkstra's algorithm on, not a "graph" in the sense of "graphical display of data".

答:
One way of looking at this is that any time you have a data structure that references another data structure, you have some form of object graph.  On that level, any object-oriented language supports a graph.  Some languages are not object oriented and instead use a map to store related data structures.  This also creates graphs of related maps, so any language with an associative array (PHP) or hashMap (Clojure, perl, etc) can make graphs with maps.

But I think you are asking why there aren't more tookits that have something like

```<code>Node {
    Iterator<Node> getAdjacentNodes();
}

Graph {
    void putNode(Node n);
    Iterator<Node> getAllNodes();
}
</code>```

Look at Datomic.  Also triple-stores use something like this.  Similarly, cross-reference (xref) tables in relational databases can be used to create arbitrary graphs of relationships.

Having said that, I might restate your question as "Why don't more programming languages and tool-kits take a graph-based approach to problem decomposition?"

I think the answer is that efficient generic graph traversal is an NP-Hard problem lacking both a universal, efficient way to process graphs, and also a universal, efficient way to prove that a single solution is the most efficient one (e.g. the Travelling Salesman problem).

Graphs are absolutely essential for every CS student to learn because they deal with the most general relationships between data.  Yet for that same reason, they should be your last choice for how to represent relationships.  Most relationships are more specific.  A car should only have one driver and one position on a given road at a time.  There is generally no reason to join all cars with all possible drivers and all possible roads.  Doing so would invite unnecessarily difficult problems.  The more specific you can make the relationships between your objects or functions in your program design, the more you can optimize those relationships and the easier it is to understand and test them.

Finally, how do you traverse graphs?  There is depth-first and breadth-first.  Most programming languages make breadth-first traversal easy:

```<code>select * from passenger where car_id = 3;

myCar.getCurrentPassengers();
</code>```

When you look at depth-first search, there is no one right way to do it.  What's the best road from New York to San Francisco?  It's solvable, but only by a fairly brute-force approach.  If intersections are nodes and roads are edges, that doesn't help you solve this problem.  Far better is it to know something about the roads - which ones are interstates, have traffic lights or stop-signs, are under construction, are prone to traffic, are closed, or not built yet?  Your NYC to San Fran route search might start with just interstates, then examine the angles of intersection where you change roads, or the maximum distance from a straight (well, curved around the globe) line.  These are footholds to finding an optimal solution efficiently.  They hint at places to check for more local roads that work around a less-than-ideal interstate solution.  The details of the problem are exactly what makes real-time, real-world route finding possible.  Yet the details are precisely the aspect of graph traversal that a generic API would not capture.

There could be myNode.setWeight(double d) and myNode.getWeight() methods, but they still don't define an iteration order in a way that's any better than you just adding a weight entry to your hashMap or weight field on your object.  Also, there might be different weights for bicycle routes or public transit, or whatever.  Would you have a set or hash of weights for every node?  I guess I don't see the use of a generic graph data structure because only the non-generic aspects of your data can make a graph traversable in anything close to polynomial time.

Body:
One way of looking at this is that any time you have a data structure that references another data structure, you have some form of object graph.  On that level, any object-oriented language supports a graph.  Some languages are not object oriented and instead use a map to store related data structures.  This also creates graphs of related maps, so any language with an associative array (PHP) or hashMap (Clojure, perl, etc) can make graphs with maps.

But I think you are asking why there aren't more tookits that have something like

Node {
    Iterator<Node> getAdjacentNodes();
}

Graph {
    void putNode(Node n);
    Iterator<Node> getAllNodes();
}

Look at Datomic.  Also triple-stores use something like this.  Similarly, cross-reference (xref) tables in relational databases can be used to create arbitrary graphs of relationships.

Having said that, I might restate your question as "Why don't more programming languages and tool-kits take a graph-based approach to problem decomposition?"

I think the answer is that efficient generic graph traversal is an NP-Hard problem lacking both a universal, efficient way to process graphs, and also a universal, efficient way to prove that a single solution is the most efficient one (e.g. the Travelling Salesman problem).

Graphs are absolutely essential for every CS student to learn because they deal with the most general relationships between data.  Yet for that same reason, they should be your last choice for how to represent relationships.  Most relationships are more specific.  A car should only have one driver and one position on a given road at a time.  There is generally no reason to join all cars with all possible drivers and all possible roads.  Doing so would invite unnecessarily difficult problems.  The more specific you can make the relationships between your objects or functions in your program design, the more you can optimize those relationships and the easier it is to understand and test them.

Finally, how do you traverse graphs?  There is depth-first and breadth-first.  Most programming languages make breadth-first traversal easy:

select * from passenger where car_id = 3;

myCar.getCurrentPassengers();

When you look at depth-first search, there is no one right way to do it.  What's the best road from New York to San Francisco?  It's solvable, but only by a fairly brute-force approach.  If intersections are nodes and roads are edges, that doesn't help you solve this problem.  Far better is it to know something about the roads - which ones are interstates, have traffic lights or stop-signs, are under construction, are prone to traffic, are closed, or not built yet?  Your NYC to San Fran route search might start with just interstates, then examine the angles of intersection where you change roads, or the maximum distance from a straight (well, curved around the globe) line.  These are footholds to finding an optimal solution efficiently.  They hint at places to check for more local roads that work around a less-than-ideal interstate solution.  The details of the problem are exactly what makes real-time, real-world route finding possible.  Yet the details are precisely the aspect of graph traversal that a generic API would not capture.

There could be myNode.setWeight(double d) and myNode.getWeight() methods, but they still don't define an iteration order in a way that's any better than you just adding a weight entry to your hashMap or weight field on your object.  Also, there might be different weights for bicycle routes or public transit, or whatever.  Would you have a set or hash of weights for every node?  I guess I don't see the use of a generic graph data structure because only the non-generic aspects of your data can make a graph traversable in anything close to polynomial time.


答:
Being flexible and able to handle multiple types of data is exactly what method overloading and interfaces were created for.  Java already has the features that make handling these situations simpler while guarenteeing compile time safety via type checking.

Also, if it is impossible to narrowly define what data the method operates on, then that method may be doing too much and needs to be decomposed into smaller methods.

I like a rule of thumb I've read about (in Code Complete I think).  The rule states that you should be able to tell what a function or method does just by reading its name.  If it is really difficult to clearly name a function\method using that idea (or have to use And in the name) then the function/method is really doing too much.


问:
Does 'consider returning Null Object' apply to a DAO read method?
I was looking for an answer to the question of what a DAO should return when a search ends up to be for an entity that does not exist.

There are some generic previous questions related to returning null, but I am looking for an answer specifically in the context of the DAO retrieve scenario.

To be clear, when I say Null Object I am referring to the Null Object pattern. In the Java space, Josh Bloch recommends an empty collection solution in the book Effective Java (See Item 43) which provides an very good introduction to the problem/solution.

Despite being aware of Bloch's advice when I first wrote this question I considered returning null appropriate in a read/retrieval scenario. I'm in good company making a mistake with nulls.

答:
In "Effective Java" item 43 p. 201, Joshua Bloch says, "There is no reason ever to return null from an array- or collection-valued method."  He recommends returning a zero-length array or an empty collection (Collections.emptyXxx) when there are legitimately no results.  For one thing, it's a pain for the client to double-check everything:

```<code>if ( (retVal == null) || (retVal.size() < 1) ) {
    ...
}
</code>```

Before returning null, ask yourself if the null return value is a result of a programming error on the part of the calling code.  Such a check is generally done in the first few lines of a procedure as a defensive check for invalid input values and could legitimately result in throwing an unchecked exception instead of returning null.  For my reasoning on this, please see the Checked vs. Unchecked Exceptions entry in my blog.

Scala and Haskell avoid returning null with an Option class.  I don't immediately see how this is better than null (other than being type-safe just for the sake of it), but I thought I should mention it as another point of view:

```<code>val nameMaybe = request getParameter "name"
nameMaybe match {
  case Some(name) =>
    println(name.trim.toUppercase)
  case None =>
    println("No name value")
}
</code>```

Bloch suggests that null is an appropriate return instead of an empty collection in C because array lengths are stored separately from arrays and there is no advantage to allocating an empty array.  But a null is not the right answer all the time in all languages.

Body:
In "Effective Java" item 43 p. 201, Joshua Bloch says, "There is no reason ever to return null from an array- or collection-valued method."  He recommends returning a zero-length array or an empty collection (Collections.emptyXxx) when there are legitimately no results.  For one thing, it's a pain for the client to double-check everything:

if ( (retVal == null) || (retVal.size() < 1) ) {
    ...
}

Before returning null, ask yourself if the null return value is a result of a programming error on the part of the calling code.  Such a check is generally done in the first few lines of a procedure as a defensive check for invalid input values and could legitimately result in throwing an unchecked exception instead of returning null.  For my reasoning on this, please see the Checked vs. Unchecked Exceptions entry in my blog.

Scala and Haskell avoid returning null with an Option class.  I don't immediately see how this is better than null (other than being type-safe just for the sake of it), but I thought I should mention it as another point of view:

val nameMaybe = request getParameter "name"
nameMaybe match {
  case Some(name) =>
    println(name.trim.toUppercase)
  case None =>
    println("No name value")
}

Bloch suggests that null is an appropriate return instead of an empty collection in C because array lengths are stored separately from arrays and there is no advantage to allocating an empty array.  But a null is not the right answer all the time in all languages.


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答:
a thorough understanding of foundation concepts e.g. datatypes, interfaces

a medium to high level understanding of the tool they are using e.g. specific .net/java knowledge

a reasonable idea of 'the other technologies your stuff interfaces with' e.g. how databases work

roughly where their technology base is headed e.g. what is cloud computing and what impact it will have on their current skillset


问:
I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?
My day job is  java/web developer. I have been using eclipse for ~5years. I think its excellent and I also use Webstorm for javascript and html/jsp.

I do on occasion need to ssh into server and mess around with config files; for this I use vi and it pains me. I have to get up a webpage listing the syntax/commands : press escape, then asterix, turn around three times and the text will be entered two lines above your cursor. Its so unintuitive to me, and I imagine anyone who grew up in the late eighties nineties.

Here are the main reasons I think eclipse is brilliant(and I assume other IDE's), and do not switch to emacs and/or vim.

Error highlighting with no need to
recompile project.

Code assist.

Refactoring.

Opening call hiearchy/Opening
declaration.

Fully integrated with source control.

Debugger is included.

availablity of 3rd party plugins - eg
findbugs/checkstyle.

One of the arguments I hear is that with emacs/vim you can create your own plugins - well OK, but you can do that in eclipse too. But you don't need to as everything is already there!  Its like saying buy this half built car, you can build the rest yourself.

Why are people using emacs/vim ? Do people who use it actually work on complex object-oriented projects in large organisations ?

What are the reasons to switch to vim/emacs. How would my productivity increase if I did switch?

答:
If you're happy with Eclipse, then don't switch.

If you can use Eclipse everywhere you need, don't switch.

If your project/company pretty much exclusively uses Eclipse, don't switch.

If you only rarely need something else, print out a cheat-sheet for one of the editors and pull it out of the drawer when you need it, and then go back to using Eclipse.

See the (same) question over at SO: https://stackoverflow.com/questions/1346820/what-are-the-efficiencies-afforded-by-emacs-or-vim-vs-eclipse

As far as answering, "Do people who use it actually work on complex object-oriented projects in large organisations?" - Hold onto your hat sonny, but the answer is "yes".  I've worked on projects with tens of millions of lines of code used in the critical path of designing the very CPU running the computer you're using to ask this question.  And people tried Eclipse but found it to be too slow and clunky (though, admittedly, we were not using Java).


答:
The method violates the Liskov substitution principle.

If a method accepts a parameter of type Object, I should expect that any object I pass to the method will work.

What it sounds like is that only certain subclasses of Object are allowed. The only way to know which types are allowed is to know the details of the method. In other words, the method is less flexible than advertised.


答:
To give something a type give:

Users an interface to code to with a semantic description.

Compilers an interface to parse from to allow their optimizers to increase code execution time or shrink code size more easily.

Early(static) binding which catches code errors early in the development cycle.

Using just an object conveys almost no information, thus removing all of these features that were put into the language for the reasons listed above.

Also, the type system was designed for flexibility with its is-a relationships allowing for all of these conditions.  So use it to your advantage.  Don't waste it by making unmaintainable code.

There may be a particular reason to do something like this at a particular time, but to do this it this generically all the time is poor practice.  If you are doing it, get others to look over the problem and see if it can be done another way.  In the majority of cases (99.999%) it can be.

In that 0.001% that it can't be, at least you are all on board and know what is happening (though you probably just need some fresh eyes on the problem).


答:
I agree with the other responses that this is generally bad practice.

There is one specific case where I find passing an Object may be superior: when you are eventually dealing with Strings, e.g. if you are creating XML or JSON.  In that case, instead of something like:

```<code>public void addAttribute(String s) {
  //... add s to the XML
}
</code>```

I prefer:

```<code>public void addAttribute(Object o) {
   String s = String.valueOf(o);  // perhaps check for null explicitly
   // now add s to the XML
}
</code>```

This saves endless String.valueOf's in the calling code.  Also, it works nicely with vararg's.  And, with autoboxing, you can pass ints, floats, etc...  Since all Objects have a toString(), this, arguably, does not violate Liskov etc...

Body:
I agree with the other responses that this is generally bad practice.

There is one specific case where I find passing an Object may be superior: when you are eventually dealing with Strings, e.g. if you are creating XML or JSON.  In that case, instead of something like:

public void addAttribute(String s) {
  //... add s to the XML
}

I prefer:

public void addAttribute(Object o) {
   String s = String.valueOf(o);  // perhaps check for null explicitly
   // now add s to the XML
}

This saves endless String.valueOf's in the calling code.  Also, it works nicely with vararg's.  And, with autoboxing, you can pass ints, floats, etc...  Since all Objects have a toString(), this, arguably, does not violate Liskov etc...


答:
The rule that I follow is... parameter definitions should be as specific as needed by the method, and no more and no less.

If all I need is to iterate an enumerable, the param is defined as an enumerable, not an array or a list. This allows any type of enumerable to be used, avoiding converting to a specific type.

I also will not define it as an object because I need an enumerable.  Any object that is not an enumerable will not work in this method.  It's confusing to read a method signature and not know what it means, and only run-time testing can find the error.


问:
Rules of thumb regarding breaking into sub-projects
We are building a Game Client and Server, our system is broken into four major projects: (Client and Server, Shared Interfaces, Source Art). In addition, both client and server have a set of libraries where we put shared code for client and server respectively. As you can imagine this leads to a lot of projects, I count 12 projects in the entire source.

My questions are; What are the good rules of thumb regarding when to keep code in one project versus breaking it into sub projects. No one likes a large monolithic project but lots of small projects also add a lot of overhead.

Should all projects be branched and released in lock-step to keep things simple (one current version number for all) or should library projects be branched and released separately only when they change. This will lead to complex map of compatible versions.

I know there is no absolute answer for these questions but what are the known best practices when deciding and/or good reference material to read up on this subject?

答:
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

This lists the SOLID principals as well as principals for what goes in a package and how packages reference each other.


问:
Way to allow inspection of java data model after exporting to file
I've refactored a program to remove its dependency on an sql database by storing all the state in a memory model.  However the manager liked the ability to easily inspect the domain state just by doing an sql join/filter on the database at any time; and he wishes to maintain some similar domain inspection ability.  We discussed having a call that dumps the model state to a file that can be inspected.  There isn't that much state--it can all fit into memory--but the state is large enough that we need some mechanism to allow us to 'fetch' the child if a given parent better then manual inspection of the files.

I need the best tool to make this doable.  They are thinking of exporting everything to CSV to be read into a DB, which could work, but it seems off to be using a DB only for doing joins on data types.  Plus, their old approach used Strings for joins that weren't guaranteed to be unique, and, with my addition of extra objects, thought would have to put into how to lay out the database fields to represent the new model objects (particularly child objects of parents).

I've toyed with other ideas for this.  One idea was to a CSV file and having some other program read in the CSV file and do 'sql like' joins, but haven't found a program that does this easily.  I've also toyed with an interactive java interpreter so we can read things into our model and do calls against the model, even using linux base commands to write 'joins' with awk or similar.  I'm not sure I like any option though.  Does anyone have suggestions for a good way of doing this?

p.s. We can SSH to the maintained systems at any time, but we can't copy files to or from them without permission when maintaining live systems.  Any tool used to inspect memory has to be packaged with our release as its own jar with justification as to why we are including it.

答:
Any tool used to inspect memory has to be packaged with our release as it's own jar

We've got a restriction to use Java... This makes some things easier, and some things harder.

Consider having something that serializes the state out to xml and then a separate program to do xpath queries against it.  This gives you some forms of queries, but doesn't quite do the joins (if you don't really need them, this might be the easiest approach).

Failing being able to run xpath queries, one could instead serialize the data to something and bring it into another program that uses an embedded database. Something like HSQLDB or H2 or Derby or Sqlite.  Then you have two most obvious options...

If the database is exposed, you could use your favorite sql tool and run against it

You could run the query from the command line in the application itself.

Another option of just do a memory dump of the running application and use OQL to analyze the memory.  The tool for this is the Memory Analyzer. This gets into it a bit, though there quite a bit more information needed when approaching this problem.


问:
If a fluent coder disregards good practices, doesn't his fluency work against him?
I am working on a fairly large and buggy application - and due to the way it's written (I'll spare you details, but it violates rules in most areas you can think of), it is next to impossible developing it without major refactoring.

Significant part of the app was authored by interns, n00bs etc.; but there has also been a programmer in the rank of Master Developer, and with all humility, the code he left behind is dubious as well, in a different way perhaps but still.

Granted, his code tends to get the job done - most of the time - but it's typically cryptic, reinventing the wheel (eg. a big custom method accomplishing a rather ordinary SQL db backup) etc. Basically, needless confusion plus lots of overengineering

And it got me thinking that being a highly skilled coder (I deliberately don't use the word "developer", assuming that it indicates a wider set of skills), if not accompanied by other qualities, can actually be sort of poisonous.

Assuming that it's true, some of the reasons I could think of are:

if you're coding with ease, it feels (or actually is, in short run) just quicker to snap out your own solutions on the spot, without turning to libraries, preexistent functionality etc.

if one is experienced enough to easily maintain a mental image of a complex program, one is less inclined to split it into modules, layers etc.

So my point is that if a fluent coder happens to be a bad developer, their fluency not only doesn't compensate for the latter, but it actually does even more harm instead.

What do you think of that? Is it true (to what extent if so)?

答:
Having been both in your situation and having caused similar situations I understand your frustration, but I think the answer to your question is a flat "no".  Fluency doesn't guarantee that a programmer is going to produce maintainable code.  Often organizations force programmers to deliver poorly designed and implemented software due to ridiculous budget and time constraints.  It's possible that the fluent programmer is cutting corners only programmers care about to deliver something that customers do care about.  Obviously this isn't good in practice, but sadly a reality most every programmer has to deal with at some point in their career.  There is also the chance that fluent programmer is just being lazy or complacent.  I can speak perfect English, but it's easier and more fun to use slang.

As for the using other's code or rolling your own argument, I think it really comes down to what gets the job done best.  Sometimes "best" doesn't account for things like style and maintainability if "best" means deliver a six week project in two weeks.  This is why we refactor and refine.  Also, the developer has to be aware of what's available in terms of third-party code and they have to know how to use it and trust that it will work and be properly supported/maintained.  Given that there are thousands of optional frameworks, libraries, and APIs for any popular development paradigm using such things can end up costing more time, energy, and stress than just rolling your own.  Also, I do find cases where third-party code just doesn't do exactly what I need it to do - which is when it's highly beneficial to be fluent.


问:
Useful Scripts for CM?
I'll be forming a remote team, and I want to be able to use scripts (or something) to make sure that people's code is checked in every night.  I currently use some BASH scripts that are kindof wonky and aren't customizable easily.

Does anyone have any useful tools, tips, or resources for this?

Are there any pitfalls to doing this that I'm not seeing, or can I do it better another way?

(cross-posted to super-user)

答:
Why do you want to force people to check in code ? Doesn't seem like a good idea to me; if the developer is not ready to commit changes, there is probably a good reason.

What is the benefit to be gained from being forced to check in everyday ?

I have half built stuff that I wouldn't wish on anyone.

Every place I have worked the checked in code is assumed to work, or has passed tests and compiles correctly etc.

I'd set up a continuous integration server, hudson, in conjunction with subversion or cvs.

(backing-up should be different to checking in, imho)

Title: Useful Scripts for CM?


答:
Great in-depth answers so far, I really have to say that before even getting into high level philosophy and methodology, they are being lazy, short and simple.

They are not providing good information in their code for others to maintain and understand, and they are going against the design of the programming language at hand.  I love PERL, I love Objective-C.  I do not however make efforts to bend Java, C#, or C++ for that matter, toward my preferences at the expense of having maintainable, readable, and efficient code.

Yes, if they need to change how a function works, or what the inputs are, they saves a few line changes here and a few refactoring steps.  However, the cost to others having to maintain the code is greater, not to mention most modern IDEs such as eclipse and Xcode can handle doing the refactoring automatically with a simple right click command.  Furthermore, as others have mentioned, the processing cost is increased with each cast, with each unknown object type that's passed, and I imagine basic built in speedups that runtime would perform by knowing the proper classes are also thrown out the window.

Syntax sugar is always better than salt for the developer, but a balanced diet of both ensures the health of the project and others involved (customer, application, other developers, etc.)


答:
Don't forget that this is a good pattern for languages like JavaScript which don't support passing parameters by name. Consider a function

```<code>function dialog( message, cancelButton, okText, notOkText ) { ... }
</code>```

which has to be called like

```<code>dialog( "...", true, "...", "..." );
</code>```

When you study the client code, it's not easy to remember the meaning of, say, the third parameter of the call. The readability of the client code suffers. Therefore, it is better to declare it with a param object

```<code>function dialog( options ) { ... }
</code>```

which enables you to call it with named parameters:

```<code>dialog({
  message : "...",
  cancelButton: true,
  okText: "...",
  notOkText: "..."
  })
</code>```

Principle: We should reduce the number of parameters of a function (zero is excellent, one is frequent, two and more should be rare)!

Body:
Don't forget that this is a good pattern for languages like JavaScript which don't support passing parameters by name. Consider a function

function dialog( message, cancelButton, okText, notOkText ) { ... }

which has to be called like

dialog( "...", true, "...", "..." );

When you study the client code, it's not easy to remember the meaning of, say, the third parameter of the call. The readability of the client code suffers. Therefore, it is better to declare it with a param object

function dialog( options ) { ... }

which enables you to call it with named parameters:

dialog({
  message : "...",
  cancelButton: true,
  okText: "...",
  notOkText: "..."
  })

Principle: We should reduce the number of parameters of a function (zero is excellent, one is frequent, two and more should be rare)!


问:
Why retrieves a native app data faster than one with PhoneGap?
I know that an app developed with PhoneGap is slower than a native one because at PhoneGap the whole code must be interpreted at runtime into a native one.

But could someone explain or has a good in-depth website which explains why a native app retrieves data (a picture or text) from a web ressource faster than an app with PhoneGap? Do both apps handle internet connections in another way, or is there more data retrieved by an PhoneGap app?

答:
It's a totally different application event process.

PhoneGap uses JavaScript event callbacks that are designed to be generic across multiple devices, whereas Android is activity based which is native to the OS. iOS has something simular but I can't comment on that.

Android knows which activity to start when the application is loaded, and execution of that activity happens relatively quickly even for large applications. Whereas, PhoneGap requires a HTML5 browser to finish loading, then all the HTML5 JavaScript files have to load from the device and the JavaScript has to be executed at least once to initialize all the code. As a result there is a visible delay in starting PhoneGap applications. That's why PhoneGap includes a splash screen feature while the app loads.

After a PhoneGap application has started the entire user interface is a rendered HTML page, which is subject to performance issues relative to the device it's on. Whereas, native Android applications often use the OS to render their activity view. So improvements in the speed of the OS translate to faster apps. HTML rendered by a browser is limited to the speed of the processor and GPU.

Performance Should Be The Same When

Applications can take advantage of local storage, caching and SQL.

Communication with the web server is done via AJAX (JSON, XML or HTML).

Performance Should Be Different

Javascript is used to perform large calculations.

The user interface displays data from a large data source.

Read/Write operations to local storage are in large amounts (i.e. camera images)

All visual elements that involve animation or large graphics would be faster done natively.

Hybrid PhoneGab

There is no good reason for a PhoneGap developer to complain about performance. PhoneGap allows you to develop code for each device that runs natively, and can be executed via a plugin to PhoneGap. The native plugin is exposed to the PhoneGap app as a Javascript extension. Any time performance is an issue the developer has the option to move that code to a native plugin.

While JavaScript is slower than native code. What is it the code is doing that makes it so slow? Most likely it's bad Javascript then a fault in the design of PhoneGap.

Why PhoneGab?

PhoneGab is not Android development. It's HTML5 and personally the Android SDK can allow you to achieve results often faster than implementing the same thing in HTML. I think people who have strong skills in HTML/Javascript have very specific user interface expectations, and recoil at the idea of the OS imposing standards.


答:
A search suggests that there will be multiple results which is an easy case - always return a collection. If there
are no results, then the collection will simply have no items.

If there can be 0 or 1 result, it depends on the semantics of the search. Can there only be a 1 result because
you are artificially limiting the search results to 1? I would go with a collection
with 0 or 1 items, the limit could probably change at some point.

If there can truly only be 0 or 1 result, you are probably trying to "search" by an unique identifier or such. In normal
application usage, this "search" will never fail. It is not really a search. Your application doesn't generate links with invalid ids or whatever.

However, in exceptional situations such as:

A page with links has been loaded and been sitting idle for a while. Some of the resources behind the links have been deleted in the meanwhile. Now when you click such a link, the "search" would fail.

The user manually "circumvents" the application and uses the address bar directly to enter arbitrary id numbers.

...

All of the above are exceptions. So it is very easy, throw an exception. Probably a NotFoundException that doesn't need to be caught
anywhere that can just bubble to the top for an automatic 404 error page.

Title: Does 'consider returning Null Object' apply to a DAO read method?

Body:
I was looking for an answer to the question of what a DAO should return when a search ends up to be for an entity that does not exist.

There are some generic previous questions related to returning null, but I am looking for an answer specifically in the context of the DAO retrieve scenario.

To be clear, when I say Null Object I am referring to the Null Object pattern. In the Java space, Josh Bloch recommends an empty collection solution in the book Effective Java (See Item 43) which provides an very good introduction to the problem/solution.

Despite being aware of Bloch's advice when I first wrote this question I considered returning null appropriate in a read/retrieval scenario. I'm in good company making a mistake with nulls.


答:
There is no problem with this. In languages that do not have typed variables, this is what happens in every function.  Formal parameters are just values, and the type is in the object that is passed, not in the formal parameter.

People Get Stuff Done (TM) in Lisp, Python, Ruby, ...

Though you benefit less from compile time type checking, you also suffer less from compile time type checking.

The real solution is to use some dynamic language that targets the Java virtual machine, instead of writing ugly Java code in which every third identifier is the word Object.

I does make sense to have a completely generic function called construct which takes arbitrary objects.

I think I would enjoy collaborating with this programmer. It would take some of the sting out of using a bletcherous programming language.

Note that this type of code occurs in C in the implementation of the run-time support for dynamic languages implemented in C. E.g. you might see something like this in a Lisp implemented in C:

```<code>/* Map each object in a list through a function, in order to produce
   a list of the return values. */

val mapcar(val function, val list)
{
   val iter = car(list);
   val out = nil;  /* nil is really a null pointer */

   for (iter = car(list); iter; iter = cdr(iter))
      push(funcall_1(function, car(iter)), out);  /* push is a C macro */

   return nreverse(out); /* destructively reverse list */
}
</code>```

The val type is actually something like:

```<code>typedef struct object *val;
</code>```

and struct object is a complicated structure that overlays various kinds of type information for various kinds of objects.

I developed a very nice little programming language, whose internals are all done in this style, which I deliberately kept as clean as possible: more so than in the internals of some other language implementation which take a similar approach.

In this style, amazing things are possible in a small amount of C code.

Body:
There is no problem with this. In languages that do not have typed variables, this is what happens in every function.  Formal parameters are just values, and the type is in the object that is passed, not in the formal parameter.

People Get Stuff Done (TM) in Lisp, Python, Ruby, ...

Though you benefit less from compile time type checking, you also suffer less from compile time type checking.

The real solution is to use some dynamic language that targets the Java virtual machine, instead of writing ugly Java code in which every third identifier is the word Object.

I does make sense to have a completely generic function called construct which takes arbitrary objects.

I think I would enjoy collaborating with this programmer. It would take some of the sting out of using a bletcherous programming language.

Note that this type of code occurs in C in the implementation of the run-time support for dynamic languages implemented in C. E.g. you might see something like this in a Lisp implemented in C:

/* Map each object in a list through a function, in order to produce
   a list of the return values. */

val mapcar(val function, val list)
{
   val iter = car(list);
   val out = nil;  /* nil is really a null pointer */

   for (iter = car(list); iter; iter = cdr(iter))
      push(funcall_1(function, car(iter)), out);  /* push is a C macro */

   return nreverse(out); /* destructively reverse list */
}

The val type is actually something like:

typedef struct object *val;

and struct object is a complicated structure that overlays various kinds of type information for various kinds of objects.

I developed a very nice little programming language, whose internals are all done in this style, which I deliberately kept as clean as possible: more so than in the internals of some other language implementation which take a similar approach.

In this style, amazing things are possible in a small amount of C code.


答:
Why do you want to be sure that everyone's code is checked in overnight?

You don't want your build to fail and having to check code in implies that one will have to commit code that won't necessarily be right.

This leads to broader questions about what version control tools you're using and your general "philosophy" for version control.

Certainly you want to make sure that your developers work is backed up and you almost certainly want them committing changes early and often but equally you want, no, need a build server and you therefore want committed code to build (and pass its tests).

A lot of the answer may come from using a Distributed VCS (or teaming local DVCS with a central server based system) in that you can require "local" commits (pushed to a mirror for backup) - hence need for more detail or more questions...

Title: Useful Scripts for CM?

Body:
I'll be forming a remote team, and I want to be able to use scripts (or something) to make sure that people's code is checked in every night.  I currently use some BASH scripts that are kindof wonky and aren't customizable easily.

Does anyone have any useful tools, tips, or resources for this?

Are there any pitfalls to doing this that I'm not seeing, or can I do it better another way?

(cross-posted to super-user)


问:
Are there any industry standards that define code quality?
Our specific situation is that we are creating an agreement between ourselves and another team for shared control or use of a PHP based web application that we have been building.    We have a set of standards and conventions documented in our technical specs.  However, I have been asked to define them in terms of an industry standard.

I am aware of different terminology for coding conventions. Hungarian notation, CamelCase, for example. And some defined standards for very specific things, PSR-0 for example covers namespaces in PHP.

It seems the point is to try to give us stronger ground in the agreement, by pointing to industry standards rather than an arbitrary standard we set forth.  They're looking for things like the PSR-0 or an ISO#### or IEEE#### that we can point to.

My personal concern is that I've spent the time working with the team to show them the standards we have and to get buy in on the bigger parts of it. So I'm worried we'll either end up having to conform to some standard that doesn't match how we like to program, or the better case will be picking and choosing pieces of standards if they exist, to fit our current conventions.

Anyway, the core of the question is, Are there any industry standards regarding code quality, coding processes, or other areas that would help us keep their programmers from making disruptive or difficult to maintain code?  I realize we can't prevent it, but if we can point to the agreement, at least we have recourse other than refactoring or recoding it ourselves.

Any other thoughts or suggestions would be helpful.

答:
Well, there are the standards put forth by the PHP Framework Interoperability Group.

Then there are the standards put up in reaction to the PHP Framework Interoperability Group: The Difinitive PHP Style Guide.

And then there's Apache's style guide.

So, no.  Nothing that's been agreed on by the industry.


问:
Is this solution RESTful and secure?
Our product registers new players on our service, and we've chosen to host it on Azure (we're using .NET) and we wanted it to be stateless (for scalability) and relatively secure.

Since this is the first REST WS I'm writing, I wanted to get some feedback on whether or not it's a solid solution.

Some presumptions to know about our app:

Users are logged into the service anonymously, without requiring a password from a user

The WS must be completely stateless to allow horizontal scaling

We're connecting using HTTPS (SSL) to prevent 3rd party snooping

EDIT:

We target for native iOS/Android devices

Our main concern is making sure only non-tampered clients are able to send requests

And the abstract authentication process:

The client creates a simple hash (UDID:Timestamp) and encrypts it using the timestamp with some basic algorithm (for example, secret key is every 2nd character from the hash)

The client sends his UDID, Timestamp & hash to the server

The server rebuilds the hash and decrypts the encrypted hash sent from the user

If the two are equal - we know that it was actually sent from our client (and hopefully not from a malicious sender)

Any input/suggestions would be great - obviously since it's the first time I'm handling this issue I might have designed it incorrectly.

Thanks!

2nd update:

Reading the security specs for OAuth, it seems that there is no real answer to my question - since the client and server must know the secret keys and the client is locally stored on our users' mobile devices (as opposed to a web app).

From the OAuth security guide (http://hueniverse.com/oauth/guide/security/):

When implementing OAuth, it is critical to understand the limitations of shared secrets, symmetric or asymmetric. The client secret (or private key) is used to verify the identity of the client by the server. In case of a web-based client such as web server, it is relatively easy to keep the client secret (or private key) confidential.

However, when the client is a desktop application, a mobile application, or any other client-side software such as browser applets (Flash, Java, Silverlight) and scripts (JavaScript), the client credentials must be included in each copy of the application. This means the client secret (or private key) must be distributed with the application, which inheritably compromises them.

This does not prevent using OAuth within such application, but it does limit the amount of trust the server can have in such public secrets. Since the secrets cannot be trusted, the server must treat such application as unknown entities and use the client identity only for activities that do not require any level of trust, such as collecting statistics about applications. Some servers may opt to ban such application or offer different protocols or extensions. However, at this point there is no known solution to this limitation.

答:
This is somewhat off on a tangent but, from a security point of view any secret that is on a client is not a secret. You state in your question that.

Our main concern is making sure only non-tampered clients are able to
  send requests.

As someone who has worked in the gaming industry this is a lost cause. If there is enough value to be able to send arbitrary requests users will figure out how to send those requests. You can never rely on being able to tell whether a request is from a trusted client. Here are some tips from my experiences.

Keep the canonical copy of game state on the server

Figure our what changes to the state each user can make and have server side checks for violation.

Have rate limits on how fast users can level up or earn currency/items to catch scripts.

If the cheater cannot grief other players do not ban them. A lot of cheaters are also spenders.

Have social controls on cheaters i.e. so that cheaters become obvious to their friends. If you can have matching logic than cheaters will be removed from playing against their friends.

Title: Is this solution RESTful and secure?


答:
What he does is throwing away all advantages of having a static type system.

Simply: It's much less clear to what such methods do, both to a compiler and to people reading the code.

One of the biggest reasons for a static type system is to have compile-time guarantees about what a program does. The compiler can check that a piece of code is used correctly and if not, issue a compiler-time error. Methods like you're colleague is writing are much more prone to run-time errors, because compiler-time checks are missing. Be prepared run-time errors and for writing a lot more tests.

Another big problem is that it's not at all clear what a method does. Reading such a code, maintaining it, or using it is a big pain.

Java added generics to give stronger compile-time guarantees about code, Scala is going even further with its functional approach, and sophisticated type system with covariant and contra-variant types. Your colleague is going backwards  against this line of development, throwing away all its advantages.

If he used properly typed, overloaded methods instead, he (and you all) would gain:

Compiler time checking for correct usage of those methods.

Clear indication what combinations of arguments are allowed and what aren't.

The possibility to properly and separately document each of these combinations.

Code readability and maintainability.

It would help him to split his methods into smaller parts, which are easier to debug, test and maintain. (See also How to convince your fellow developer to write short methods?.)


问:
To design pattern, or not to design pattern
Design patterns are good, but complex. Should we use them in small projects? Implementing design patterns needs more sophisticated developers, which in turn raises project costs. On the other hand, they make code neat and clean. Are they necessary for small projects?

Update: Should we insist on using design patterns when the team is not efficient at working with them?

答:
A basic understanding and recognition of standard creational, behavioral, and structural design patterns can only increase a developer's understanding of OOD and gives them the ability to communicate complex concepts with less words.

Also, knowledge of concurrency patterns can make life easier when dealing with threaded execution. Easier is not harder!

Understanding patterns also gives developers a toolbox of ready-made solutions to very common software design problems.  I would recommend instead of thinking of patterns as a skill to be used or not used, think of them as an advantage any developer should exploit.


问:
Monitoring C++ applications
We're implementing a new centralized monitoring solution (Zenoss). Incorporating servers, networking, and Java programs is straightforward with SNMP and JMX.

The question, however, is what are the best practices for monitoring and managing custom C++ applications in large, heterogenous (Solaris x86, RHEL Linux, Windows) environments?

Possibilities I see are:

Net SNMP

Advantages

single, central daemon on each server

well-known standard

easy integration into monitoring solutions

we run Net SNMP daemons on our servers already

Disadvantages:

complex implementation (MIBs, Net SNMP library)

new technology to introduce for the C++ developers

rsyslog

Advantages

single, central daemon on each server

well-known standard

unknown integration into monitoring solutions (I know they can do alerts based on text, but how well would it work for sending telemetry like memory usage, queue depths, thread capacity, etc)

simple implementation

Disadvantages:

possible integration issues

somewhat new technology for C++ developers

possible porting issues if we switch monitoring vendors

probably involves coming up with an ad-hoc communication protocol (or using RFC5424 structured data; I don't know if Zenoss supports that without custom Zenpack coding)

Embedded JMX (embed a JVM and use JNI)

Advantages

consistent management interface for both Java and C++

well-known standard

easy integration into monitoring solutions

somewhat simple implementation (we already do this today for other purposes)

Disadvantages:

complexity (JNI, thunking layer between native C++ and Java, basically writing the management code twice)

possible stability problems

requires a JVM in each process, using considerably more memory

JMX is new technology for C++ developers

each process has it's own JMX port (we run a lot of processes on each machine)

Local JMX daemon, processes connect to it

Advantages

single, central daemon on each server

consistent management interface for both Java and C++

well-known standard

easy integration into monitoring solutions

Disadvantages:

complexity (basically writing the management code twice)

need to find or write such a daemon

need a protocol between the JMX daemon and the C++ process

JMX is new technology for C++ developers

CodeMesh JunC++ion

Advantages

consistent management interface for both Java and C++

well-known standard

easy integration into monitoring solutions

single, central daemon on each server when run in shared JVM mode

somewhat simple implementation (requires code generation)

Disadvantages:

complexity (code generation, requires a GUI and several rounds of tweaking to produce the proxied code)

possible JNI stability problems

requires a JVM in each process, using considerably more memory (in embedded mode)

Does not support Solaris x86 (deal breaker)

Even if it did support Solaris x86, there are possible compiler compatibility issues (we use an odd combination of STLPort and Forte on Solaris

each process has it's own JMX port when run in embedded mode (we run a lot of processes on each machine)

possibly precludes a shared JMX server for non-C++ processes (?)

Is there some reasonably standardized, simple solution I'm missing?

Given no other reasonable solutions, which of these solutions is typically used for custom C++ programs?

My gut feel is that Net SNMP is how people do this, but I'd like other's input and experience before I make a decision.

答:
I am not super familiar with the c++ side of things but in Java we extensively use CodaHale metrics in conjunction with Graphite. CodaHale stores metrics on a per instance basis in the local memory of the instance then uses a background thread to flush metrics to a graphite server every minute (configurable). In graphite we can aggregate across instances as well as identify faulty instances. If you do not want the complexity of maintaining a graphite cluster you can use HostedGraphite.

This setup means no single point of failure for metrics aggregation or reporting as (time based aggregation happens on the nodes themselves and the reporting aggregation across happens in a distributed graphite cluster (or hosted graphite).

Lastly, you can use Seyren to provide alerts on top of the monitoring data.

Title: Monitoring C++ applications


答:
Yes, this is poor practice because it makes no guarentee that the method will be able to do what it needs to for any particular input passed in.  The goal of making a method that is widely useable is not a bad goal, but there are better ways to accomplish it.

For this particular case, it sounds like a perfect situation for the use of interfaces.  An interface would ensure that objects being passed to the method provide the needed information and allows the casting to be avoided.  There are some situations where this won't work well (like if it has to work with either sealed or base classes that you can't add an interface implementation to), but overall a method should only take input that is valid for it as parameters.


答:
Assume for a minute that "Object guy" has reason for using a generic "loosely" typed object.  We do not know his reasons, but it reminds me of the value of using inheritance and Generics (Templates).  In the off chance that Object-guy is actually trying to make sense, this is the sense he might be trying to make:

I always base my objects on a single base object.  This base object handles additional duties like exception handling, logging, profiling, and garbage collection.

I always base mathematical objects (those that might support mathematical operators) on a single base class.  This helps provides utilities to handle exceptions in the event a derived class does not handle a certain operation.  For example, using a Taylor series in the event an explicit representation for a function is not available.

So I do not know Object-guys reasons are: perhaps they are just because he like dynamic typing offered by other languages.  But perhaps he is trying to appreciate the value of inheritance.

He may also want to explore Generics (Templates).  I used them in C++ to define two, three, and four dimensional images, where the pixels can be bytes, ints, floats, complex, or spectra.  I had to do a fair bit of casting, but the pay-off was significant in terms of separating the geometry of images from the computation of pixels.


问:
Extending Composite Structure model generally/in Enterprise Architect
I'm currently on a project, which integrates domain specific techniques in the modelling tool Enterprise Architect through UML Profiles.

The domain specfic model almost matches the structure of the composite structure model, with a couple of restrictions though, so I'm trying to use the model as a foundation for my restrictions.

The questions:

1) How can I generally extend models (like composite structure models) which themselves lie in the M1-layer of Meta-Object Facility?

2) Is the element "Part" of composite structure diagrams a metaclass itself, which can be extended by stereotypes in UML profiles?

Since the literature on these topics is not very exhaustive, I'm also looking for suggestions, too.

答:
To answer your first question, from my own experience with MagicDraw UML (MDUML), you can build a Profile on the DSL Profile, if you do not want to directly modify the DSL you have or it is not editable.

Your classes should utilise the same Stereotypes found in the profile, if any or you can make your own and apply them to the new classes you want to add.

Open the profile as a project, if you can. You should be able to thoroughly analyse the building blocks involved and replicate them in a separate project, so as to maintain the integrity of the original UML Profile. The caveat here is that I do not know what exactly you are doing, but following this methodical way of decomposing the UML Profile to build your own will ensure you can extend the models and use them in your project.

I would not recommend building on the Metaclass level if you can help it. If you are building a whole new meta-model then this could be the approach, else from experience, you only need to model classes that constitute the extensions you seek to add (Use Stereotypes and Tags). Then export your project as a module for use by the implementing project - as in MDUML.

Part is NOT a Metaclass in itself. If you have looked and not found it, it is because it is a classifier (for example, a class, collaboration, component) property owned by a composition. I found this document on the EA site, if you have not already seen it.

If I understood your second question, you should be able to extend Part by additional Tags and Property Stereotypes - although it would depend on the features you are looking to add here. Again you do not have to go down to the Metaclass and edit, that would be too extreme in my opinion. If you do though, I would hope you share your insights.

Finally, I have never found EA appealing enough to commercially do these advanced tasks for my projects. In the MagicDraw UML world, where I have consistently documented and customised profiles specific to my domain of interest these steps have been relatively easier and well documented.


问:
How to genericize foreign key references in table?
I am trying to design a table to store references to multiple tables as a "target" of the item in each row.

An example should clarify what I am trying to do:
Imagine you have 4 tables (images, videos, comments, likes)

with likes being similar to

```<code>CREATE TABLE `likes`
`target` int(11),
`user_id` int(11),
`created_at` timestamp
</code>```

How do you make it so the "target" could be a row of images, videos or comments (eg, you like an image, video or comment)

Also how would you go about representing this within your code? (abstract class Like and concrete classes for LikeImage, LikeImage, LikeComment?) or maybe have an interface ILikeable  and then the Like object has a ILikeable object on hand?

I'm running into this pattern more and more often making things such "like" (like an object) or "subscribing" (subscribe to changes on an object) to various targets and generating "notifications" (notify a user of a change on an object) that are generically able to target objects.

Thanks for sharing your knowledge.

Update:: Is there a nosql way to easily achieve this?

答:
TLDR;

In my experience if you are going to have relationships between tables, they should be proper foreign keys, enforced with constraints. If you go for a weak reference such as the one you describe you'll eventually run into trouble.

You can do this by using inheritance in your object model, and represent it in your database with 1-to-1 foreign keys from the 'superclass' table to the 'subclass' tables, and a foreign key from your 'likes' table to the 'superclass' table. Read on for a more full explanation.

The full story
The way that Entity Framework does this would be to use inheritance in your object model (ie Post, and subclasses Image, Comment, Video). In the databases there would then be a table called Post, with all the fields common to all types, and tables Image, Comment, Video for the fields specific to each type. The primary key of each subclass tables is also foreign keyed of the primary key of Post (so there is a 1-to-1 mapping between Post.Id and Image.Id etc, it they are the same id). Your likes table then foreign keys to Post.

Psuedo-SQL below:

```<code>table Post (
    Id int not null PK,
    UserId int not null REFERENCES User.Id
)

table Image (
    Id int not null PK REFERENCES Post.Id,
    ImageUrl varchar(250) null
)

table Likes (
    Id int not null PK,
    UserId int not null REFERENCES User.Id,
    PostId int not null REFERENCES Post.Id
)
</code>```

I have also come across an example where there is a table called something like 'LikeableType' which has an Id, and the name of the table that type in question references (so you would have a row for each of Image, Comment and Video). Your 'Likes' table then has a 'LikeableType' field, and a 'LikeableId' field. Your lookup process would then be something like:

LiekableType = 1 therefore table = 'Image'

Select from table where Id = LikeableId

The problem here is twofold: firstly, you can't enforce this with a foreign key constraint, because it is a meta-relationship, rather than a real relationship at the database level. Secondly - and this occurred in the example I have seen - is that the key types might be different for each table you want to reference (ie Image has an int key, but Video has a varchar key), and so casting to varchar etc is necessary so that you can deal with keys in a common format.

Body:
TLDR;

In my experience if you are going to have relationships between tables, they should be proper foreign keys, enforced with constraints. If you go for a weak reference such as the one you describe you'll eventually run into trouble.

You can do this by using inheritance in your object model, and represent it in your database with 1-to-1 foreign keys from the 'superclass' table to the 'subclass' tables, and a foreign key from your 'likes' table to the 'superclass' table. Read on for a more full explanation.

The full story
The way that Entity Framework does this would be to use inheritance in your object model (ie Post, and subclasses Image, Comment, Video). In the databases there would then be a table called Post, with all the fields common to all types, and tables Image, Comment, Video for the fields specific to each type. The primary key of each subclass tables is also foreign keyed of the primary key of Post (so there is a 1-to-1 mapping between Post.Id and Image.Id etc, it they are the same id). Your likes table then foreign keys to Post.

Psuedo-SQL below:

table Post (
    Id int not null PK,
    UserId int not null REFERENCES User.Id
)

table Image (
    Id int not null PK REFERENCES Post.Id,
    ImageUrl varchar(250) null
)

table Likes (
    Id int not null PK,
    UserId int not null REFERENCES User.Id,
    PostId int not null REFERENCES Post.Id
)

I have also come across an example where there is a table called something like 'LikeableType' which has an Id, and the name of the table that type in question references (so you would have a row for each of Image, Comment and Video). Your 'Likes' table then has a 'LikeableType' field, and a 'LikeableId' field. Your lookup process would then be something like:

LiekableType = 1 therefore table = 'Image'

Select from table where Id = LikeableId

The problem here is twofold: firstly, you can't enforce this with a foreign key constraint, because it is a meta-relationship, rather than a real relationship at the database level. Secondly - and this occurred in the example I have seen - is that the key types might be different for each table you want to reference (ie Image has an int key, but Video has a varchar key), and so casting to varchar etc is necessary so that you can deal with keys in a common format.


答:
I see three different solutions from a DB design point of view. I am not sure how your ORM layer (entity framework) will look based on these designs, but I like to approach these things from a DB design first.

Option One

The one that you mentioned - but to enforce referential integrity you'd need to add another column:

```<code>CREATE TABLE 'likes' (
'target' int(11),
'targetTypeID' int(11),
'user_id' int(11),
'created_at' timestamp
)
</code>```

So you'd then need a targetType table, which has 3 entries in it; Video, Image and Comment. Based on this table you can then write a trigger to enforce referential integrity - you would check the targetTypeID value and then check the corresponding target value. . A bit messy, but it'd work. If you wanted to make this easier you could add TargetTypeID as a column onto your Video, Image and Comment table, and then you can query it like so:

```<code>Select  l.*
from    Likes l
left outer join image i on l.target = i.imageid and l.targettypeid = i.targettypeid
left outer join video v on l.target = v.videoid and l.targettypeid = i.targettypeid
left outer join comment c on l.target = c.commentid and l.targettypeid = i.targettypeid
</code>```

which will help you avoid accidently joining a "Video Like" row in the Like table to the wrong table, eg like a "Image" row. And yes if this is possible, it will definitely happen.

Option Two

Create your table like so:

```<code>CREATE TABLE 'likes' (
LikeID int primary key,
ImageID int null,
VideoID int null,
CommentID int null,
'user_id' int(11),
'created_at' timestamp
)
</code>```

You can then put in a constraint (or trigger) that says either "ImageID" or "VideoID" or "CommentID" must be populated. The main benefit of this design is that you can fully enforce referential integrity using the DB. Downside of course is that you're "wasting" two columns which will always be null. The other downside is that your queries will look like this:

```<code>Select  l.*
from    Likes l
left outer join image i on l.imageid = i.imageid
left outer join video v on l.videoid = v.videoid
left outer join comment c on l.commentid = c.commentid
</code>```

which is somewhat annoying. But maybe you won't need to do that kind of thing very often, especially if you put the common stuff (Eg, name, description) into the likes table.

Option Three

Using "inheritence" or a base table. Create a new table named "ItemLike":

```<code>create table ItemLike (
    ItemLikeID int,
    TargetTypeID int,
    ImageID int null,
    VideoID int null,
    CommentID int null,
)
</code>```

and change your like table to be like this:

```<code>CREATE TABLE 'likes' (
    LikeID int primary key,
    ItemLikeID int foreign key,
    'user_id' int(11),
    'created_at' timestamp
)
</code>```

very similar to the second answer but just adding another level of abstraction and might make your entity framework classes nicerer. Kind of pointless from a DB design perspective unless you want to make ItemLikeID nullable (can't see why you would) - but it might make your table partitioning easier if you get lots and lots of data in your like table. Your joins then look like this:

```<code>Select  l.*
from    Likes l
inner join ItemLike il on l.ItemLikeID = il.ItemLikeID
left outer join image i on il.imageid = i.imageid
left outer join video v on il.videoid = v.videoid
left outer join comment c on il.commentid = c.commentid
</code>```

Or you could use a NoSQL database and all of your problems will go away! </sarcasm>

Title: How to genericize foreign key references in table?

Body:
I am trying to design a table to store references to multiple tables as a "target" of the item in each row.

An example should clarify what I am trying to do:
Imagine you have 4 tables (images, videos, comments, likes)

with likes being similar to

```<code>CREATE TABLE `likes`
`target` int(11),
`user_id` int(11),
`created_at` timestamp
</code>```

How do you make it so the "target" could be a row of images, videos or comments (eg, you like an image, video or comment)

Also how would you go about representing this within your code? (abstract class Like and concrete classes for LikeImage, LikeImage, LikeComment?) or maybe have an interface ILikeable  and then the Like object has a ILikeable object on hand?

I'm running into this pattern more and more often making things such "like" (like an object) or "subscribing" (subscribe to changes on an object) to various targets and generating "notifications" (notify a user of a change on an object) that are generically able to target objects.

Thanks for sharing your knowledge.

Update:: Is there a nosql way to easily achieve this?

Body:
I see three different solutions from a DB design point of view. I am not sure how your ORM layer (entity framework) will look based on these designs, but I like to approach these things from a DB design first.

Option One

The one that you mentioned - but to enforce referential integrity you'd need to add another column:

CREATE TABLE 'likes' (
'target' int(11),
'targetTypeID' int(11),
'user_id' int(11),
'created_at' timestamp
)

So you'd then need a targetType table, which has 3 entries in it; Video, Image and Comment. Based on this table you can then write a trigger to enforce referential integrity - you would check the targetTypeID value and then check the corresponding target value. . A bit messy, but it'd work. If you wanted to make this easier you could add TargetTypeID as a column onto your Video, Image and Comment table, and then you can query it like so:

Select  l.*
from    Likes l
left outer join image i on l.target = i.imageid and l.targettypeid = i.targettypeid
left outer join video v on l.target = v.videoid and l.targettypeid = i.targettypeid
left outer join comment c on l.target = c.commentid and l.targettypeid = i.targettypeid

which will help you avoid accidently joining a "Video Like" row in the Like table to the wrong table, eg like a "Image" row. And yes if this is possible, it will definitely happen.

Option Two

Create your table like so:

CREATE TABLE 'likes' (
LikeID int primary key,
ImageID int null,
VideoID int null,
CommentID int null,
'user_id' int(11),
'created_at' timestamp
)

You can then put in a constraint (or trigger) that says either "ImageID" or "VideoID" or "CommentID" must be populated. The main benefit of this design is that you can fully enforce referential integrity using the DB. Downside of course is that you're "wasting" two columns which will always be null. The other downside is that your queries will look like this:

Select  l.*
from    Likes l
left outer join image i on l.imageid = i.imageid
left outer join video v on l.videoid = v.videoid
left outer join comment c on l.commentid = c.commentid

which is somewhat annoying. But maybe you won't need to do that kind of thing very often, especially if you put the common stuff (Eg, name, description) into the likes table.

Option Three

Using "inheritence" or a base table. Create a new table named "ItemLike":

create table ItemLike (
    ItemLikeID int,
    TargetTypeID int,
    ImageID int null,
    VideoID int null,
    CommentID int null,
)

and change your like table to be like this:

CREATE TABLE 'likes' (
    LikeID int primary key,
    ItemLikeID int foreign key,
    'user_id' int(11),
    'created_at' timestamp
)

very similar to the second answer but just adding another level of abstraction and might make your entity framework classes nicerer. Kind of pointless from a DB design perspective unless you want to make ItemLikeID nullable (can't see why you would) - but it might make your table partitioning easier if you get lots and lots of data in your like table. Your joins then look like this:

Select  l.*
from    Likes l
inner join ItemLike il on l.ItemLikeID = il.ItemLikeID
left outer join image i on il.imageid = i.imageid
left outer join video v on il.videoid = v.videoid
left outer join comment c on il.commentid = c.commentid

Or you could use a NoSQL database and all of your problems will go away! </sarcasm>


答:
A genericized approach I once used:

```<code>table Likable (
  id int not null primary key, -- the common ID
  user_id int not null, -- the creator of the likable asset
  created datetime,
  updated datetime,
  ... -- etc
);

table Post (
  id int not null primary key,
  title varchar,
  text varchar,
  ... -- etc
  foreign key (id) references Likable(id)
);

-- a Picture can only be attached to a Post
table Picture (
  id int not null primary key,
  title varchar,
  url varchar,
  width int,
  height int,
  post_id int not null,
  ... -- etc
  foreign key (id) references Likable(id),
  foreign key (post_id) references Post(id),
);

-- a Like can be added to anything Likable
table "Like" (
  id int not null primary key,
  target_id int not null, -- the asset
  user_id int not null, -- the user that liked it
  foreign key (target_id) references Likable(id)
);
</code>```

This allows you to make sure anything you attach a "like" to is a Picture, or a Post, but not anything else.

I think it is possible to explain this setup to SQLAlchemy; not sure about Django ORM.

Downsides:

you have to insert things twice and make sure you don't accidentally create a Likable without a linked or or Picture.

You have to travel to Likable for common fields; it can cost you an extra request if you're not careful.

Upsides:

Referential integrity across the board :)

Common ID space for likes, and it is easy to add more kinds (Video, Music, etc.).

Easy and consistent handling of common fields in Likable (in my case I had a lot of them).

Body:
A genericized approach I once used:

table Likable (
  id int not null primary key, -- the common ID
  user_id int not null, -- the creator of the likable asset
  created datetime,
  updated datetime,
  ... -- etc
);

table Post (
  id int not null primary key,
  title varchar,
  text varchar,
  ... -- etc
  foreign key (id) references Likable(id)
);

-- a Picture can only be attached to a Post
table Picture (
  id int not null primary key,
  title varchar,
  url varchar,
  width int,
  height int,
  post_id int not null,
  ... -- etc
  foreign key (id) references Likable(id),
  foreign key (post_id) references Post(id),
);

-- a Like can be added to anything Likable
table "Like" (
  id int not null primary key,
  target_id int not null, -- the asset
  user_id int not null, -- the user that liked it
  foreign key (target_id) references Likable(id)
);

This allows you to make sure anything you attach a "like" to is a Picture, or a Post, but not anything else.

I think it is possible to explain this setup to SQLAlchemy; not sure about Django ORM.

Downsides:

you have to insert things twice and make sure you don't accidentally create a Likable without a linked or or Picture.

You have to travel to Likable for common fields; it can cost you an extra request if you're not careful.

Upsides:

Referential integrity across the board :)

Common ID space for likes, and it is easy to add more kinds (Video, Music, etc.).

Easy and consistent handling of common fields in Likable (in my case I had a lot of them).


问:
Where should authentication be handled, in the server's code, or in the application's server-side code?
I'm developing a simple web application in node.js.  Users can log in from any page in the application, so I handle authentication in the server's code and logic, and the application's server-side code checks to see if a couple session variables are set.  If they are, the application continues with user-specific information.

I'm unsure if this is the best way to handle the authentication logic.  Should I move all authentication completely over to the application's code and only have the server listen and pass requests along, or, since the server is setting the session anyway, should I have it control back-end authentication logic as I'm handling it now?

In the end, what I'm really asking is: Conceptually, where should authentication be handled?  In the server's code, or in the application's server-side code?

Edit: To be more specific, it's a public application on the internet.  The logic that I'm questioning is entirely the server-side logic.  Thank you for pointing that out to me.  I edited my title to make it a little more accurate.

答:
First it's good that you are not considering client-side authentication as this can be spoofed.

The main problems I see with using the server's built-in mechanisms for authentication are:

Portability - Moving your application to a different server, becomes significantly more difficult.

A lack of separation between local server users and remote web application users, when looking in your user list could make it harder to administer both the server and the application.

If your application is hacked, they've already gained access at user level to your server. I wouldn't mind betting that this is significantly less secure than using separate authentication methods.

I recommend making your web application perform the authentication, perhaps using a community maintained library or by building it yourself. Store your users in a database table.

This overcomes the downsides listed.

I don't recommend using authentication mechanisms of other sites. The reasons for that are many, but to mention a few are:

Your visitor may not want to have an account with the 3rd party site.

It's poor practice to have one username/password for everything and this method is essentially doing that but with a veneer that makes people think it's ok.

It results in giving too much information to the 3rd party site (who share much of it with other sites which use their authentication mechanism).

The list is endless. I could add to it all day!