问:
Python beginner question with Assigning Variables
Coming from C# and now getting my hands dirty with Python.

From what I understand, Python is strongly typed:

https://stackoverflow.com/questions/11328920/is-python-strongly-typed

As stated in the example from the SO link above:

```<code>bob = 1
bob = "bob"
</code>```

I seem to remember reading somewhere that these are 2 separate variables, instead of the same variable changing from an "int" to a "str" (reassignment).

I can see that both vars had different ID's.

Some clarification please?

答:
The value of bob is 1 as of the first line of code which assigns 1 to a variable named bob. Then the string "bob" is assigned to the variable bob, replacing the value of 1. It's the same variable, just with different values. This is dynamic typing since the program will be type checked when these lines of code are executed.

"Strong" and "Weak" typing are imprecise terms but Python fits within the "Strong" group. For example:

```<code>test1 = 1
test2 = "this is a string"

test3 = test1 + test2 #This will fail at runtime.
</code>```

Specifically the error will be this:

```<code>Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    test3 = test1 + test2
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

If Python were weakly typed, this would have worked, probably as string concatenation. Explicit casting of test1 via the str() function would be required to do the same in Python proper.

The differing addresses for 1 and "bob" in the initial example have to do with 1 and "bob" both being alias for objects. Since they are not the same object, they have different addresses. bob the variable name is just a label for one of those two object references. Specifically, whichever was last assigned to it.

Body:
The value of bob is 1 as of the first line of code which assigns 1 to a variable named bob. Then the string "bob" is assigned to the variable bob, replacing the value of 1. It's the same variable, just with different values. This is dynamic typing since the program will be type checked when these lines of code are executed.

"Strong" and "Weak" typing are imprecise terms but Python fits within the "Strong" group. For example:

test1 = 1
test2 = "this is a string"

test3 = test1 + test2 #This will fail at runtime.

Specifically the error will be this:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    test3 = test1 + test2
TypeError: unsupported operand type(s) for +: 'int' and 'str'

If Python were weakly typed, this would have worked, probably as string concatenation. Explicit casting of test1 via the str() function would be required to do the same in Python proper.

The differing addresses for 1 and "bob" in the initial example have to do with 1 and "bob" both being alias for objects. Since they are not the same object, they have different addresses. bob the variable name is just a label for one of those two object references. Specifically, whichever was last assigned to it.


问:
TDD Red-Green-Refactor and if/how to test methods that become private
as far as I understand it, most people seem to agree that private methods should not be tested directly, but rather through whatever public methods call them. I can see their point, but I have some problems with this when I try to follow the "Three Laws of TDD", and use the "Red - green - refactor" cycle. I think it's best explained by an example:

Right now, I need a program that can read a file (containing tab-separated data) and filter out all columns that contain non-numerical data. I guess there's probably some simple tools available already to do this, but I decided to implement it from scratch myself, mostly because I figured it could be a nice and clean project for me to get some practice with TDD.

So, first, I "put the red hat on", that is, I need a test that fails. I figured, I'll need a method that finds all the non-numerical fields in a line. So I write a simple test, of course it fails to compile immediately, so I start writing the function itself, and after a couple of cycles back and forth (red/green) I have a working function and a complete test.

Next, I continue with a function, "gatherNonNumericColumns" that reads the file, one line at a time, and calls my "findNonNumericFields"-function on each line to gather up all the columns that eventually must be removed. A couple of red-green-cycles, and I'm done, having again, a working function and a complete test.

Now, I figure I should refactor. Since my method "findNonNumericFields" was designed only because I figured I would need it when implementing "gatherNonNumericColumns", it seems to me that it would be reasonable to let "findNonNumericFields" become private. However, that would break my first tests, since they would no longer have access to the method they were testing.

So, I end up with a private methods, and a suite of test that test it. Since so many people advice that private methods should not be tested, it feels like I've painted myself into a corner here. But where exactly did I fail?

I gather I could have started out at a higher level, writing a test that tests what will eventually become my public method (that is, findAndFilterOutAllNonNumericalColumns), but that feels somewhat counter to the whole point of TDD (at least according to Uncle Bob): That you should switch constantly between writing tests and production code, and that at any point in time, all your tests worked within the last minute or so. Because if I start out by writing a test for a public method, there will be several minutes (or hours, or even days in very complex cases) before I get all the details in the private methods to work so that the test testing the public method passes.

So, what to do? Is TDD (with the rapid red-green-refactor cycle) simply not compatible with private methods? Or is there a fault in my design?

答:
You don't do TDD based on what you expect the class will do internally.

Your test cases should be based on what the class/functionality/program has to do to the external world. In your example, will the user ever be calling your reader class with to find all the non-numerical fields in a line?

If the answer is "no" then it's a bad test to write in the first place. You want to write the test on functionality at a class/interface level -- not the "what will the class method have to implement to get this to work" level, which is what your test is.

The flow of TDD is:

red (what is the class/object/function/etc doing to the external world)

green (write the minimal code to make this external world function work)

refactor (what is the better code to make this work)

It is NOT to do "because I will need X in the future as a private method, let me implement
it and test it first." If you find yourself doing this, you are doing the "red" stage incorrectly. This appears to be your issue here.

If you find yourself frequently writing tests for methods which become private methods you are doing one of a few things:

Not correctly understanding your interface/public level use cases well enough to write a test for them

Dramatically changing your design and refactoring away several tests (which may be a good thing, depending on whether that functionality is tested in newer tests)

ContentLicense: CC BY-SA 3.0


问:
Is directly using Make considered obsolete?
So I have been coming across many comments/posts/etc regarding creating makefiles directly, and how it is a silly thing to do in 2015. I am aware of tools such as CMake, and I actually use CMake quite often. The thing is, CMake is just creating the Makefile for you and helping to remove the tedium of doing it yourself. Of course it adds a lot of other great features... but its still a Makefile in the end.

So my question is, is the 'obsolete' talk regarding make referring to the entire Make utility, or just the idea of manually writing your own Makefiles? I do not use an IDE for C/C++ development at all (just emacs), so I have always written Makefiles.

If Make is considered outdated, what should a C/C++ dev be using to build small, personal projects?

答:
This answer complements @lxrec answer.

Makefiles can be used for many things, not just creating a program/library from source code. Build systems such as CMake or autotools are designed to take code, and build it in such a way as to fit into the user's platform (i.e. find libraries or specify correct compile options). You could for example have a makefile which helps automate some release tasks, such as: build a zip file containing code with the version derived from git; run tests against your code; upload said zip file to some hosting service. Some build systems (such as automake) might provide an easy way to do this, others may not.

That's not to say you need to use makefiles for this, you could use a scripting language (shell, python etc.) for such tasks.


问:
Is there any harm in having classes made up mostly of inherited classes?
Say I have a few base classes:

HasPosition supplies a 2D location, and methods to "move".

IsDisplayable defines how a class will be displayed in a given graphics library (say, curses), and methods to change its representation.

HasHealth supplies a health value and methods hurt and heal.

If I multiply-inherit all 3 into a single class, Entity, I'll have a class that can be displayed, moved, and hurt (a starting point for a game entity).

This could be added to and mixed to yield any number of classes.

Is there anything wrong with this approach? Is it at all typical to have "top level" classes that are more or less made up of several other base classes?

I'm trying to create  reusable set-up to use to create games using Pdcurses, and wondered if this was a good way to set up my classes.

答:
Is there anything wrong with this approach? Is it at all typical to have "top level" classes that are more or less made up of several other base classes?

Yes, and yes.

Historically, it has been common practice among game engine developers to build their game entities in exactly the way you describe. I have, in fact, several well-regarded books that describe an inheritance model for game entities.

However, in the last couple decades, developers observed that inheritance is inherently limiting:

Modifying the game logic to add new features requires modifying the game engine.

Entity relationships must be hard-coded.

Entity data is, by necessity, spread across large areas of memory, incurring large performance penalties for tight per-system update loops. (For example, while doing physics on sets of objects.)

Instead, what has come into vogue among game developers (and for good reason) is data-driven entity systems.

In an entity-component system, there are several performance and extensibility advantages:

Modifying game logic can be done trivially by attaching a new component to an entity.

Entity components can be allocated in batches, to keep similar data close together; this allows, for example, a physics system to quickly perform its calculations on data that literally streams into the CPU's cache, with great performance benefits.

Entity relationships can be defined at run-time, so that entities can be constructed entirely external to the engine, in a scripting engine, or even over the network.

Faster turnaround on new features--new components and component systems touch fewer parts of your codebase, requiring less work in the long run.

Data-driven design like this, and entity component systems in general are a frequent topic over on gamedev.stackexchange.com.


答:
Let me provide a different, yet typical, answer: it depends.

A lot of people (me included) have troubles with inheritance hierarchies such as the ones @greyfade mentioned in the other answer. The clean code mantra "prefer composition over inheritance" stems from exactly that.

However, by understanding the problems that are at the root of inheritance hierarchies you can still get the best of both worlds. Keep in mind though, that this is heavily dependent on your language and your self-discipline.

What you have described is something that simply was not possible in a language like Java (prior to Java 8, which got default interfaces now), but readily accepted in C++ before and more modern languages like C# or Scala. In order to save themselves the tedious discussions originating from the above-mentioned troubles though, they chose to call these "mixins" or "traits" (as opposed to "multiple" "inheritance" - two words that are readily attackable by everyone with a basic CS degree). Yet in essence, your description sounds just like you're doing that.

What's important in a trait-based approach, just as well as in one based on composition (instead of inheritance), is to focus on two primary advantages:

You want to be able to reuse one of these "things" without having to bother about the others

and want to be able to change or replace one of these, again without having to care too much about the others.

Clearly, when you have a full hierarchy of things in a large tree, it is near to impossible to get these two advantages for an implementation class that sits somewhere in the middle of that tree. Nevertheless, when you work with traits/mixins, or essentially do the same thing via self-discipline in C++ in that you do inherit multiple times, but not form a hierarchy that has a depth greater than a single inheritance step, then you have technically used inheritance, yet you get to keep all those advantages.

You can reuse each of the individual parts independently, or even exchange them with reasonably little work. Yet this system does not save you from potentially creating intangible class hierarchies again (but then again, neither does a hammer save you from hitting your head with it).

Disclaimer;
With regards to entity systems, I am personally not convinced of their superiority over traits. Both are way better than creating a big inheritance hierarchy though. Also I'm not in the gaming industry, so other effects (like the mentioned fast memory accesses) may also be important enough to your use case to justify choosing one way over the other. As usual, there is no silver bullet (unless you create one in your game) and everything has its pros and cons. Just make sure you understand the downsides of whichever way you choose.

In response to the add-on comment question(s):

It's not like the different approaches differ by being suitable or not for a simple game. I don't believe you have scalability issues with either. Traits/Mixins are quite successfully being used in rather large systems and scale well, especially because they are so nicely composable. No idea how scalability came up, but it's not really an issue for either approach here as far as I can tell.

Addressing your comment, as far as I understand it data-driven doesn't mean you have a standard composition via an attribute in your class. So your Entity class doesn't directly refer to a Position class, because that would again result in higher coupling than intended. To add a "component" to an entity you would still have to go into that class. As far as I can tell, and please be aware I'm no expert on that, the idea is to decouple your Entity from having to know the concrete "component" thing at all, but instead rely on some intermediate representation. A very simplified example may be that your entity is a key-value store and your Health component results in a "health" -> 10 entry into that store. This way, the outside world can add components to the entity, without the entity itself having to know anything about these components.

I'm not sure if I understand the gaming gurus idea correctly though (corrections from someone who knows better are always welcome), but I am under the impression that with this approach you sacrifice a lot of compile-time safety and reasoning abilities as the trade-off to gain very low coupling (hence the good scripting options with Lua and such) and potentially faster implementation possibilities (by memory alignments of this component data to optimize memory/cache accesses). Assuming that is correct, I could still not claim one way to be the right one. We all have our preferences and outside requirements that should be satisfied as best as possible.

Title: Is there any harm in having classes made up mostly of inherited classes?

Body:
Say I have a few base classes:

HasPosition supplies a 2D location, and methods to "move".

IsDisplayable defines how a class will be displayed in a given graphics library (say, curses), and methods to change its representation.

HasHealth supplies a health value and methods hurt and heal.

If I multiply-inherit all 3 into a single class, Entity, I'll have a class that can be displayed, moved, and hurt (a starting point for a game entity).

This could be added to and mixed to yield any number of classes.

Is there anything wrong with this approach? Is it at all typical to have "top level" classes that are more or less made up of several other base classes?

I'm trying to create  reusable set-up to use to create games using Pdcurses, and wondered if this was a good way to set up my classes.


问:
What is the advantage of currying?
I just learned about currying, and while I think I understand the concept, I'm not seeing any big advantage in using it.

As a trivial example I use a function that adds two values (written in ML). The version without currying would be

```<code>fun add(x, y) = x + y
</code>```

and would be called as

```<code>add(3, 5)
</code>```

while the curried version is

```<code>fun add x y = x + y
(* short for val add = fn x => fn y=> x + y *)
</code>```

and would be called as

```<code>add 3 5
</code>```

It seems to me to be just syntactic sugar that removes one set of parentheses from defining and calling the function. I've seen currying listed as one of the important features of a functional languages, and I'm a bit underwhelmed by it at the moment. The concept of creating a chain of functions that consume each a single parameter, instead of a function that takes a tuple seems rather complicated to use for a simple change of syntax.

Is the slightly simpler syntax the only motivation for currying, or am I missing some other advantages that are not obvious in my very simple example? Is currying just syntactic sugar?

答:
My limited understanding is such:

1) Partial Function Application

Partial Function Application is the process of returning a function that takes a lesser number of arguments. If you provide 2 out of 3 arguments, it'll return a function that takes 3-2 = 1 argument. If you provide 1 out of 3 arguments, it'll return a function that takes 3-1 = 2 arguments. If you wanted, you could even partially apply 3 out of 3 arguments and it would return a function that takes no argument.

So given the following function:

```<code>f(x,y,z) = x + y + z;
</code>```

When binding 1 to x and partially applying that to the above function f(x,y,z) you'd get:

```<code>f(1,y,z) = f'(y,z);
</code>```

Where: f'(y,z) = 1 + y + z;

Now if you were to bind y to 2 and z to 3, and partially apply f'(y,z) you'd get:

```<code>f'(2,3) = f''();
</code>```

Where: f''() = 1 + 2 + 3;

Now at any point, you can choose to evaluate f, f' or f''. So I can do:

```<code>print(f''()) // and it would return 6;
</code>```

or

```<code>print(f'(1,1)) // and it would return 3;
</code>```

2) Currying

Currying on the other hand is the process of splitting a function into a nested chain of one argument functions. You can never provide more than 1 argument, it's one or zero.

So given the same function:

```<code>f(x,y,z) = x + y + z;
</code>```

If you curried it, you would get a chain of 3 functions:

```<code>f'(x) -> f''(y) -> f'''(z)
</code>```

Where:

```<code>f'(x) = x + f''(y);

f''(y) = y + f'''(z);

f'''(z) = z;
</code>```

Now if you call f'(x) with x = 1:

```<code>f'(1) = 1 + f''(y);
</code>```

You are returned a new function:

```<code>g(y) = 1 + f''(y);
</code>```

If you call g(y) with y = 2:

```<code>g(2) = 1 + 2 + f'''(z);
</code>```

You are returned a new function:

```<code>h(z) = 1 + 2 + f'''(z);
</code>```

Finally if you call h(z) with z = 3:

```<code>h(3) = 1 + 2 + 3;
</code>```

You are returned 6.

3) Closure

Finally, Closure is the process of capturing a function and data together as a single unit. A function closure can take 0 to infinite number of arguments, but it's also aware of data not passed to it.

Again, given the same function:

```<code>f(x,y,z) = x + y + z;
</code>```

You can instead write a closure:

```<code>f(x) = x + f'(y, z);
</code>```

Where:

```<code>f'(y,z) = x + y + z;
</code>```

f' is closed on x. Meaning that f' can read the value of x that's inside f.

So if you were to call f with x = 1:

```<code>f(1) = 1 + f'(y, z);
</code>```

You'd get a closure:

```<code>closureOfF(y, z) =
                   var x = 1;
                   f'(y, z);
</code>```

Now if you called closureOfF with y = 2 and z = 3:

```<code>closureOfF(2, 3) =
                   var x = 1;
                   x + 2 + 3;
</code>```

Which would return 6

Conclusion

Currying, partial application and closures are all somewhat similar in that they decompose a function into more parts.

Currying decomposes a function of multiple arguments into nested functions of single arguments that return functions of single arguments. There's no point in currying a function of one or less argument, since it doesn't make sense.

Partial application decomposes a function of multiple arguments into a function of lesser arguments whose now missing arguments were substituted for the supplied value.

Closure decomposes a function into a function and a dataset where variables inside the function that were not passed in can look inside the dataset to find a value to bind against when asked to evaluate.

What's confusing about all these is that they can kind of each be used to implement a subset of the others. So in essence, they're all a bit of an implementation detail. They all provide similar value in that you don't need to gather all values upfront and in that you can reuse part of the function, since you've decomposed it into discreet units.

Disclosure

I'm by no means an expert of the topic, I've only recently started learning about these, and so I provide my current understanding, but it could have mistakes which I invite you to point out, and I will correct as/if I discover any.

Title: What is the advantage of currying?

Body:
My limited understanding is such:

1) Partial Function Application

Partial Function Application is the process of returning a function that takes a lesser number of arguments. If you provide 2 out of 3 arguments, it'll return a function that takes 3-2 = 1 argument. If you provide 1 out of 3 arguments, it'll return a function that takes 3-1 = 2 arguments. If you wanted, you could even partially apply 3 out of 3 arguments and it would return a function that takes no argument.

So given the following function:

f(x,y,z) = x + y + z;

When binding 1 to x and partially applying that to the above function f(x,y,z) you'd get:

f(1,y,z) = f'(y,z);

Where: f'(y,z) = 1 + y + z;

Now if you were to bind y to 2 and z to 3, and partially apply f'(y,z) you'd get:

f'(2,3) = f''();

Where: f''() = 1 + 2 + 3;

Now at any point, you can choose to evaluate f, f' or f''. So I can do:

print(f''()) // and it would return 6;

or

print(f'(1,1)) // and it would return 3;

2) Currying

Currying on the other hand is the process of splitting a function into a nested chain of one argument functions. You can never provide more than 1 argument, it's one or zero.

So given the same function:

f(x,y,z) = x + y + z;

If you curried it, you would get a chain of 3 functions:

f'(x) -> f''(y) -> f'''(z)

Where:

f'(x) = x + f''(y);

f''(y) = y + f'''(z);

f'''(z) = z;

Now if you call f'(x) with x = 1:

f'(1) = 1 + f''(y);

You are returned a new function:

g(y) = 1 + f''(y);

If you call g(y) with y = 2:

g(2) = 1 + 2 + f'''(z);

You are returned a new function:

h(z) = 1 + 2 + f'''(z);

Finally if you call h(z) with z = 3:

h(3) = 1 + 2 + 3;

You are returned 6.

3) Closure

Finally, Closure is the process of capturing a function and data together as a single unit. A function closure can take 0 to infinite number of arguments, but it's also aware of data not passed to it.

Again, given the same function:

f(x,y,z) = x + y + z;

You can instead write a closure:

f(x) = x + f'(y, z);

Where:

f'(y,z) = x + y + z;

f' is closed on x. Meaning that f' can read the value of x that's inside f.

So if you were to call f with x = 1:

f(1) = 1 + f'(y, z);

You'd get a closure:

closureOfF(y, z) =
                   var x = 1;
                   f'(y, z);

Now if you called closureOfF with y = 2 and z = 3:

closureOfF(2, 3) =
                   var x = 1;
                   x + 2 + 3;

Which would return 6

Conclusion

Currying, partial application and closures are all somewhat similar in that they decompose a function into more parts.

Currying decomposes a function of multiple arguments into nested functions of single arguments that return functions of single arguments. There's no point in currying a function of one or less argument, since it doesn't make sense.

Partial application decomposes a function of multiple arguments into a function of lesser arguments whose now missing arguments were substituted for the supplied value.

Closure decomposes a function into a function and a dataset where variables inside the function that were not passed in can look inside the dataset to find a value to bind against when asked to evaluate.

What's confusing about all these is that they can kind of each be used to implement a subset of the others. So in essence, they're all a bit of an implementation detail. They all provide similar value in that you don't need to gather all values upfront and in that you can reuse part of the function, since you've decomposed it into discreet units.

Disclosure

I'm by no means an expert of the topic, I've only recently started learning about these, and so I provide my current understanding, but it could have mistakes which I invite you to point out, and I will correct as/if I discover any.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
Annotations for PHP would be great, One feature that would stand out for upcoming years.
This feature will help to write big frameworks with clean code.</p>

ContentLicense: CC BY-SA 2.5


问:
Are any side effects not concrete side effects?
In Chapter 23 of "Object Oriented Software Construction" (1988), Betrand Meyer makes a distinction between side effects, concrete side effects, and abstract side effects.

Meyer defines a side effect in the following quote:

A change performed by a function is known as a side effect to indicate that it is ancillary to the function’s official purpose of answering a query."

And he defines a concrete side effect in a definition box as:

A function produces a concrete side effect if its body contains any of the following: an assignment, assignment attempt or creation instruction whose target is an attribute, or a procedure call.

This distinction is hard for me to understand though, since I cannot think of an examples of functions which produce side effects but which do not produce concrete side effects. Meyer does not give us any either.

Would Meyer say that side effect and concrete side effect are synonymous? Or are there a class of side effects which are not concrete side effects?

(Note, the answer is not abstract side effects, since abstract side effects are themselves concrete side effects.)

答:
Heating the processor and losing time by useless computations is a side effect which is generally ignored, so could be considered as not very concrete. It is not concrete according to the quoted definition of Meyer.

This is why compilers are permitted to optimize useless code like

```<code> /// spend some time busy waiting in a useless computation
 for (int i=1; i<10000000; i++)
    (void) log(5.0*i);
</code>```

into an empty block.

This looks silly, but a lot of benchmark related questions are wrong because the compiler optimize code -by ignoring it-

BTW, at the lowest physical level, every computation has a thermal side effect.

So we always think in terms of some abstract machine, and we always ignore some uninteresting side effects (and care about some other side effects, notably interesting input or output). Sometimes you might even consider some debugging output as some ignored side effect. Some people are on the contrary very concerned about the energy consumption (e.g. for wearable devices) and they don't abstract that side effect.

Body:
Heating the processor and losing time by useless computations is a side effect which is generally ignored, so could be considered as not very concrete. It is not concrete according to the quoted definition of Meyer.

This is why compilers are permitted to optimize useless code like

 /// spend some time busy waiting in a useless computation
 for (int i=1; i<10000000; i++)
    (void) log(5.0*i);

into an empty block.

This looks silly, but a lot of benchmark related questions are wrong because the compiler optimize code -by ignoring it-

BTW, at the lowest physical level, every computation has a thermal side effect.

So we always think in terms of some abstract machine, and we always ignore some uninteresting side effects (and care about some other side effects, notably interesting input or output). Sometimes you might even consider some debugging output as some ignored side effect. Some people are on the contrary very concerned about the energy consumption (e.g. for wearable devices) and they don't abstract that side effect.


问:
Handling source code table alignment
Sometimes there is need to have tables (big or small) in source code.

```<code>ItemType const SomeTable[] = {
    //   id  name  min  max
    ITEM( 3, "Foo", 70, 180),
    ITEM(13, "Bar", 30,  50),
    ITEM(14, "Baz", 30,  60),
    ITEM(60, "Abc",  1,   4),
};
</code>```

Over time new lines are added and existing ones changed:

```<code>ItemType const SomeTable[] = {
    //   id  name  min  max
    ITEM( 3, "Foo", 70, 180),
    ITEM(13, "BetterBar", 30,  50),
    ITEM(14, "Baz", BAZ_MIN, BAZ_MAX),
    ITEM(60, "Abc",  1,   4),
    ITEM(80, "AAAAAA", 0, A_COUNT),
    ITEM(81, "BBB  BBBB B", 0, B_COUNT),
};
</code>```

That looks horrible. We can fix the alignment:

```<code>ItemType const SomeTable[] = {
    //   id  name               min      max
    ITEM( 3, "Foo"        ,      70,     180),
    ITEM(13, "BetterBar"  ,      30,      50),
    ITEM(14, "Baz"        , BAZ_MIN, BAZ_MAX),
    ITEM(60, "Abc"        ,       1,       4),
    ITEM(80, "AAAAAA"     ,       0, A_COUNT),
    ITEM(81, "BBB  BBBB B",       0, B_COUNT),
};
</code>```

Looks better, but the actual change is lost. If you look at the version control diff, it's nearly impossible to see what was added as whole table has been rewritten. This is especially bad if tables are several hundred lines big, as they tend to be.

Estimating table sizes in advance is possible, but in practice they tend to be off: either too small, in which case they were useless, or too big in which case lot of readability is lost.

Surely someone has figured out a good strategy for handling these cases. It doesn't have to be perfect system, as long as it is reasonably readable.

Following things are out of the scope of the question:

Using external data files: Target platform may not have file system.

Using external script/conversion tool to convert data file into code: Introduces extra dependency, which may not be possible or preferred.

I'd like to keep this question language agnostic, but typical situation where I have this problem is in embedded C projects. For example, special purpose library for several different platforms. So I basically have only have the preprocesser at my disposal, and X-macros only go so far.

答:
One possible kludge which would allow you to keep you change history but align your code correctly would be to comment out the entire existing table. And add a new correctly aligned table after it.

This would/should be recorded as just two changes in the source code.

After the new table been saved in the repository you can delete the commented out section on the next change (again logged as a single change!).

This may or may not work depending on how clever your version control software is.

On a more general note I (nearly always when I am being good and someone may be watching) code tables like this as a separate class/function. This helps keep the main body of the code readable and allows for easy switching to an external file/xml/database/web service at a later date.

Title: Handling source code table alignment


答:
If you look at the version control diff, it's nearly impossible to see
  what was added as whole table has been rewritten

Then don't look at the version control diff.

For instance WinMerge, which is free & runs on both Windows & Linux has an option " Line differences with Whitespace: Ignoring all".

Couldn't you use that? It won't show those alignment adjustments as changed lines.

And if your version control diff doesn't offer something similar, then why not email and ask them to add it? Or code it yourself, if your version control is FOSS.

Title: Handling source code table alignment

Body:
Sometimes there is need to have tables (big or small) in source code.

```<code>ItemType const SomeTable[] = {
    //   id  name  min  max
    ITEM( 3, "Foo", 70, 180),
    ITEM(13, "Bar", 30,  50),
    ITEM(14, "Baz", 30,  60),
    ITEM(60, "Abc",  1,   4),
};
</code>```

Over time new lines are added and existing ones changed:

```<code>ItemType const SomeTable[] = {
    //   id  name  min  max
    ITEM( 3, "Foo", 70, 180),
    ITEM(13, "BetterBar", 30,  50),
    ITEM(14, "Baz", BAZ_MIN, BAZ_MAX),
    ITEM(60, "Abc",  1,   4),
    ITEM(80, "AAAAAA", 0, A_COUNT),
    ITEM(81, "BBB  BBBB B", 0, B_COUNT),
};
</code>```

That looks horrible. We can fix the alignment:

```<code>ItemType const SomeTable[] = {
    //   id  name               min      max
    ITEM( 3, "Foo"        ,      70,     180),
    ITEM(13, "BetterBar"  ,      30,      50),
    ITEM(14, "Baz"        , BAZ_MIN, BAZ_MAX),
    ITEM(60, "Abc"        ,       1,       4),
    ITEM(80, "AAAAAA"     ,       0, A_COUNT),
    ITEM(81, "BBB  BBBB B",       0, B_COUNT),
};
</code>```

Looks better, but the actual change is lost. If you look at the version control diff, it's nearly impossible to see what was added as whole table has been rewritten. This is especially bad if tables are several hundred lines big, as they tend to be.

Estimating table sizes in advance is possible, but in practice they tend to be off: either too small, in which case they were useless, or too big in which case lot of readability is lost.

Surely someone has figured out a good strategy for handling these cases. It doesn't have to be perfect system, as long as it is reasonably readable.

Following things are out of the scope of the question:

Using external data files: Target platform may not have file system.

Using external script/conversion tool to convert data file into code: Introduces extra dependency, which may not be possible or preferred.

I'd like to keep this question language agnostic, but typical situation where I have this problem is in embedded C projects. For example, special purpose library for several different platforms. So I basically have only have the preprocesser at my disposal, and X-macros only go so far.


问:
Converting from byte[ ] to user defined type
I am working on a network simulator designed in java with the basic function of routing messages through a network. I am trying to take a Message object, encrypt it using an encryption utility that gives output as byte  [ ] and then need it to continue performing the routing function through the network. The routing part makes use of a host of pre-defined methods that take Message type as argument. The problem I am facing is converting back from byte [ ] output to this Message type. I tried a couple of things.

First I tried to serialize the object, encrypt it and then tried to de-serialize the output and cast it into type Message. It did not work as it gave invalid stream header.

Secondly I tried to create a sub class EncryptedMessage that extended Message. I tried to cast the output of the encryption utility as type EncryptedMessage also did not work- gave the same error.  I have understood that while serializing this cannot be done.

I declared a variable data of type byte[ ] in EncryptedMessage and tried to assign the byte[ ] output to this but it also did not work as I eventually needed to get the output as Message only.

Is there a simple way to convert this byte[ ] output back to type Message so that it can be used further for calling all the methods functions etc.

答:
This depends entirely on how your encryption method works.  There is a well-known way to serialize and deserialize a class instance in java to its byte form, however you shouldn't mistake this for encryption.  Encryption would be an operation to be performed on the byte array itself to transform it into something difficult to reverse without a proper key of some sort.  In this case, retrieving the original message is simply a matter of reversing the encryption and then reinterpreting the bytes as its original class instance.

Now if you are hashing Message into a byte array, you'll find you'll never be able to retrieve the original message.  This is done intentionally, and in fact it isn't meant to encrypt, but rather to check the validity of sensitive data without having to necessarily keep that sensitive data in memory.  For example if you wanted to make sure an entered password is correct, you could hash the password and check it with other hashed passwords on your database.  You can know if the password is correct without having to save the passwords on the database.

Otherwise, I would expect you to have an encryption method (AES, TKIP, WPA2 for instance) and that encryption method would most likely require some sort of input from you.  This is a private key and when you decrypt the bytes, you'd need to provide this same private key in order to retrieve the original value.  You should consider the additional complication that in Java, you can't create an instance of a type that isn't in classpath, so you would likely need to provide the class name or interface as well.

The more sophisticated encryption method is public-key cryptography in which both ends have a public and private key.  Combining their public key and your private key gives you the shared secret key required to encrypt and decrypt to and from byte arrays.  However like the above method, you would also need to provide Message class or interface in order to decrypt, meaning both parties need to have Message in classpath.


答:
1) Shorter array/object syntax, a la JavaScript (as previously mentioned)

2) Allow const variables to allow the result of a calculation like define() does.

3) Chaining directly from the constructor: new User()->name('Ryan');

4) Array dereferencing: something_that_returns_array()[4];

5) Expanded SPL support. SPL does a decent job of reimagining string and array functions (among other things) as objects. Expanding SPL could solve a lot of gripes about the language being so janky.

6) Using ArrayObject() should be as transparent as using array(). You should be able to do things like array_filter($array_object_instance) without doing array_filter($array_object_instance->getArrayCopy()). Even better, of course, would be $array_object_instance->filter().

7) Full-on Unicode would be nice.

8) Stop doing weird automatic type conversions. For example, you should not be able to echo a SimpleXMLElement object without first explicitly typecasting it as a string. Or at least, throw something when it happens (e.g., in strict mode, or whatever mode error_reporting(-1) is).

9) Support for either multiple threads, or some sort of evented/asynchronous callbacks. This matters most when trying to upload large files via cURL. Instead of old-skool threads, something like Apple's Grand Central Dispatch would be nice. Or even something JavaScript-like where you can make async requests and define callbacks.

10) Consistent naming/order (i.e. needle haystack) would be nice, but I think this could be better solved with SPL.

11) An officially supported interactive PHP shell, like IRB. Facebook has one called phpsh that was written in Python, but it lacks the polish I would like to see.

12) For the Reflection API, add support for (a) docblock comments on constants (global & class), and (b) support for parsing PHPDoc-like comments into a sensible data structure. There's a PECL package called "docblock" that attempts to do this, but it doesn't appear that the author got very far.

EDIT: 13) I would also love to see the ability to use ! and ? in function names -- like Ruby can.

Title: What features would you like to have in PHP?

Body:
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.


问:
Entire webpage obfuscation
I want to obfuscate all the webpages of my website. I Googled through some free tools like HTML and Javascript obfuscation but don't know how effective they are.

First of all, does it makes sense to obfuscate a webpage that could comprise of variety of codes like Javascript, PHP etc.

Secondly, how effective is this method?

答:
There is a way to make a text illegible for search engines and web crawlers while maintaining it readable for humans:

You encode your text using some simple substitution cipher, such as ROT13 or Atbash.

You apply to that text an special font (whose symbols have been unordered) that makes readable the encoded text, by reversing the substitution previously made.

I created an project at Github, called TuringFonts, that provides some resources and examples for implement this hack.

Title: Entire webpage obfuscation


问:
How to unit test logic in crud app
Apologies if this question has been asked before, I've seen similar questions, but nothing quite the same.

I am writing a web application which uses http calls to write and read from a back end database, as well as performing operations on the data.

All of my public methods are along the lines of:

```<code>writeToDatabase(data){
    performOperationsOnData(data)
    databaseHandler.connectToDatabase()
    databaseHandler.insertDataToDatabase(data)
}
</code>```

I would like to unit test my performOperationsOnData() method logic, but this is a private method, because it never needs to be called from outside the class.

I have written integration tests, which check that the data is written correctly to the database in general, but when the logic is reasonably complicated I don't really want to be connecting to the database or a mock for every possible path through the logic.

What would be the correct way to test this logic? I am particularly interested in finding out if the structure of the method I have shown should be done differently to make it more testable, or is the answer just lots of mocking and dependency injection for the database?

Similar questions:

How can I use unit tests and TDD to test an app that relies mostly on database CRUD operations?

https://stackoverflow.com/questions/842476/applying-tdd-when-the-application-is-100-crud

答:
It sounds like the logic in performOperationsOnData() could justifiably be put in its own class.

It looks like the class with the writeToDatabase(data) method is currently responsible for too much.  It is orchestrating your Business Logic and Data Persistence Logic.  Orchestrating is fine, as long as that is the class' only responsibility.

So, here's how I would go forward:

Move your Business Logic from performOperationsOnData() to a new class

Move your Data Persistence Logic (connectToDatabase() and insertDataToDatabase(data)) to a new class

Inject those new classes as dependencies into your current Orchestrator class

Unit test the Business Logic class

Integration test the Orchestrator class

Title: How to unit test logic in crud app


问:
How can I automatically test my app on multiple OSes?
I have a Python based desktop app that can run on Windows, Linux, and Mac. Each time I make an update, I would like to test that it works on each OS, because I have already had several OS-specific bugs.

I know that I could install different operating systems on VMs and login to each VM to run the test suite, each time I make an update. But is there a more automated approach?

答:
Multiple VMs is the way to go, but you should not really have to "login to each VM to run the test suite": you should be able to automate that part.

You can set up all VMs to look at a common shared folder of the host machine, and run a process on each VM which checks the contents of that folder, say, once a second.  When a new version of the app is written to that folder by the host machine, each VM should pick it up and run the tests on it.

You could even have each VM store the results of the tests into that same folder and have them displayed by the host machine on one screen.  (Or simply have the host machine give a summary, like "all OK" or "win: success; linux: success; mac: failed".)


答:
What if you auto-generate the file which contains the table declaration?

Since it is auto-generated, you never need to diff that legible file itself. Diffing the input file will show only truly changed lines, since you will never reformat the input file to make it more legible.

Q.E.D  :-)

Title: Handling source code table alignment


问:
Why the recent shift to removing/omitting semicolons from Javascript?
It seems to be fashionable recently to omit semicolons from Javascript. There was a blog post a few years ago emphasising that in Javascript, semicolons are optional and the gist of the post seemed to be that you shouldn't bother with them because they're unnecessary. The post, widely cited, doesn't give any compelling reasons not to use them, just that leaving them out has few side-effects.

Even GitHub has jumped on the no-semicolon bandwagon, requiring their omission in any internally-developed code, and a recent commit to the zepto.js project by its maintainer has removed all semicolons from the codebase. His chief justifications were:

it's a matter of preference for his team;

less typing

Are there other good reasons to leave them out?

Frankly I can see no reason to omit them, and certainly no reason to go back over code to erase them. It also goes against (years of) recommended practice, which I don't really buy the "cargo cult" argument for. So, why all the recent semicolon-hate? Is there a shortage looming? Or is this just the latest Javascript fad?

答:
I don’t leave them out, but i change the rules when to insert them.

The rules most people use is

Before each line ending

Except the line ends with a } coming from a function statement

But only a function statement, not assignment to a function literal

My rule is: At the beginning of every single line starting with a opening brace/bracket.

Mine is simpler, therefore easier to follow and less prone from bugs. Also the low number of semicolons makes it easy to find bugs made by leaving it out.

Another argument is that the infamous return\nvalue bug comes from not knowing about ASI. My rule forces you to know about ASI, so people using my rule are less likely to fall into the trap of that bug.


问:
Consistent snapshot
Suppose process A has a consitent snapshot of some entities. And it is constantly receiving updates for this enteties. Now client B connecting to A and it should receive the consistent snapshot of entities that A has and then it should receive all the updates that A receives.

Normally if it would synchronous request I would take a read lock on A's snapshot and writelock on A's updates, which would allow me to transfer state to B.

The question is can we make this process asynchronous? It means that request from B to A is asynchronous?

Can we use CHANDY–LAMPORT or LAI–YANG algorithms here? I'm pretty new to distributed algorithms, so looking for some expertise.

答:
Overview

This is one way to solve that problem.  imagine a request.  It contains information defining the request (is it an update of data, or is it a request for the current data), and way for the requester to be notified that the request has been actioned, and of its results.

Next up, you have a queue.  You place the request into the queue, and at some point later you are notified of the results of your request.  You can do this synchronously by blocking, but an async callback or event notification is preferable.

Finally you have an agent (or worker) that processes the requests one at a time.  That way requests for the current state are always consistent.  As its a single thread there is no need for locking on the objects ensuring quick access.

Implementation

This system is usually implemented using a message queue, with a single consumer.  see details of using a message queue in an RPC style Rabbit MQ Tutorial.  But the pattern can be scaled down to a single application running on a server using a thread safe FIFO queue object.

Title: Consistent snapshot


问:
Is there any way to establish a direct connection between 2 mobile devices over internet?
In the company I’m working we have our own iOS\Android\WP apps which allow our employees to share  a certain type of files to each other. This app works through our server but recently we encountered a situation when  some of our employees need to reach to each other, they’re even in the same building, but can’t due to a restricted connection to the internet outside of the country. Installing a server in this country is out of the question so now we’re looking for an alternative solution.

Is there any way to make two mobile devices with the app to connect directly to each other in order to exchange information? Using e-mail or any other common communication is out of the question since files sent from one app to another had to be processed and displayed in a very specific way (it’s complex technical specifications) plus policy of our company strictly prohibits usage of a 3rd party servers to exchange information.

The problem we’re facing is that since both devices are simply using a local mobile ISP it’s impossible to establish a direct TCP connection because both devices don’t have an external IP address which could be used to reach this device. So as far as we can tell trying to connect 2 devices directly over the internet is a lost cause. Are we correct in this assumption? Maybe we’re overlooking some possibility to achieve our goal?

I will appreciate any ideas.

答:
I'm not sure this is a realistic answer because it's a bit heavyweight.

If you can't trust the networks your users are connected to, you could always have them fallback to a network you can rely on.

So, for example, if your users are in a country that restricts access to your corporate server, have your mobile client fallback to using Tor.

You can configure Tor to use only exit nodes in your corporate server's country, ensuring unhindered access to it.


答:
Can you connect both the mobile devices to the same WiFi network?

Mobile apps can open ports and make network connections, and you can use this functionality to have apps talk directly to each other.

There are a number of practical difficulties, including how to find the IP address of the other device, and how to authenticate connections. I expect your app will require significant changes; if it's designed to work client/server, moving to peer-to-peer can be a major change.

Do you have to use mobile apps? If this was a Windows app that just opened a file, it would be easy to transfer such a file using a USB stick, direct copy, etc.

Title: Is there any way to establish a direct connection between 2 mobile devices over internet?

Body:
In the company I’m working we have our own iOS\Android\WP apps which allow our employees to share  a certain type of files to each other. This app works through our server but recently we encountered a situation when  some of our employees need to reach to each other, they’re even in the same building, but can’t due to a restricted connection to the internet outside of the country. Installing a server in this country is out of the question so now we’re looking for an alternative solution.

Is there any way to make two mobile devices with the app to connect directly to each other in order to exchange information? Using e-mail or any other common communication is out of the question since files sent from one app to another had to be processed and displayed in a very specific way (it’s complex technical specifications) plus policy of our company strictly prohibits usage of a 3rd party servers to exchange information.

The problem we’re facing is that since both devices are simply using a local mobile ISP it’s impossible to establish a direct TCP connection because both devices don’t have an external IP address which could be used to reach this device. So as far as we can tell trying to connect 2 devices directly over the internet is a lost cause. Are we correct in this assumption? Maybe we’re overlooking some possibility to achieve our goal?

I will appreciate any ideas.


问:
Confusion about Constructors and properties
So im doing a project with a guy and I see in His code something like this:

```<code>  public class Foo()
{
   private string example;

   public String Example
   {
      { get; set; }
   }

   public Foo(string exampleIn)
   {
      Example = exampleIn;
   }
}
</code>```

and as far as i can remember Im used to this kind of code:

```<code>  public class Foo()
{

 public Foo(string exampleIn)
   {
      Example = exampleIn;
   }
   public String Example
   {
      { get; set; }
   }

}
</code>```

without the private part, whats the difference of these 2 constructors?
Could i make the:

```<code>public String Example
       {
          { get; set; }
       }
</code>```

to

```<code> private String Example
       {
          { get; set; }
       }
</code>```

答:
What you are looking at are Properties, not constructors. The way the other person does them:

```<code>   private string example;

   public String Example
   {
      { get; set; }
   }
</code>```

Make me think that he might have wanted to do something like so:

```<code>   private string example;

   public String Example
   {
      get {return this.example;}; set {this.example = value;};
   }
</code>```

The above approach is usually used when one wants to perform extra operations such as validation on the data being passed to and fro the class itself.

To answer your question, public and private are known as Access Modifiers and essentially define from where can classes, methods and variables be accessed. Setting object properties to private is unusual since setting them as private will make them accessible only to elements from within their class, and object properties are usually used to exposed certain fields to other objects, outside your class.

Body:
What you are looking at are Properties, not constructors. The way the other person does them:

   private string example;

   public String Example
   {
      { get; set; }
   }

Make me think that he might have wanted to do something like so:

   private string example;

   public String Example
   {
      get {return this.example;}; set {this.example = value;};
   }

The above approach is usually used when one wants to perform extra operations such as validation on the data being passed to and fro the class itself.

To answer your question, public and private are known as Access Modifiers and essentially define from where can classes, methods and variables be accessed. Setting object properties to private is unusual since setting them as private will make them accessible only to elements from within their class, and object properties are usually used to exposed certain fields to other objects, outside your class.


答:
Making your property private would hide it from the rest of the application.  This is probably not what you want.

The first code example specifies a private backing field which never actually gets used.  This is probably not what you want either.

The { get; set; } you're seeing is the syntax for automatically implemented properties.  This is syntactic sugar in C#.  It means the backing field is automatically generated at compile time.  When using auto-properties you don't need to defined a backing field of your own.

Also, the issues you're having here have nothing to do with your constructor.

Title: Confusion about Constructors and properties

Body:
So im doing a project with a guy and I see in His code something like this:

```<code>  public class Foo()
{
   private string example;

   public String Example
   {
      { get; set; }
   }

   public Foo(string exampleIn)
   {
      Example = exampleIn;
   }
}
</code>```

and as far as i can remember Im used to this kind of code:

```<code>  public class Foo()
{

 public Foo(string exampleIn)
   {
      Example = exampleIn;
   }
   public String Example
   {
      { get; set; }
   }

}
</code>```

without the private part, whats the difference of these 2 constructors?
Could i make the:

```<code>public String Example
       {
          { get; set; }
       }
</code>```

to

```<code> private String Example
       {
          { get; set; }
       }
</code>```


问:
Web Service and Message Queue
We're looking at creating a web services/REST API layer that will be consumed by web and mobile clients.

To make the solution more robust I was considering putting the commands from PUT, POST, and PATCH onto a message queue, which would mean that they would then be executed asynchronously.

Is there a standard HTTP response from a RESTful API that indicates that a command will be executed asynchronously?

Edit

Actually, if anyone had any thoughts on how sensible it is to have a message queue behind a web services layer I'd be interested to hear them.

答: You miss the opportunity to report errors that may occur while processing the message. That way the consumer of your service can never be sure if the call was successful.</p>

Title: Web Service and Message Queue


答:
The successful creation of the task to do whatever was successful.  This means that one should be looking in the 2xx block of the response codes.

In this block one jumps out as the correct answer quite quickly:

202 Accepted

  The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.

You may also wish to look at the 201 response for situations where the resource (the task) has been created, and you just want to say that.

201 Created

  The request has been fulfilled and resulted in a new resource being created.

This, however does not imply the asynchronous nature of the interaction and instead implies that it is there, somewhere.

Title: Web Service and Message Queue

Body:
We're looking at creating a web services/REST API layer that will be consumed by web and mobile clients.

To make the solution more robust I was considering putting the commands from PUT, POST, and PATCH onto a message queue, which would mean that they would then be executed asynchronously.

Is there a standard HTTP response from a RESTful API that indicates that a command will be executed asynchronously?

Edit

Actually, if anyone had any thoughts on how sensible it is to have a message queue behind a web services layer I'd be interested to hear them.


答:
Use 200 Ok

The setup you propose is common with a service orientated architecture (SOA). When using asynchronous messaging you typically have a flow like:

```<code>--> Request
<-- Delivery acknowledgement
<-- Process acknowledgement
--> Delivery acknowledgement
</code>```

It is typical to use 200 Ok for a successful delivery acknowledgement. I would expect this to be widely documented online, although I just had a quick look for a reference and couldn't find one.

The process acknowledgement is a separate HTTP transaction, in the reverse direction, and this allows you to report any errors during processing.

Title: Web Service and Message Queue

Body:
Use 200 Ok

The setup you propose is common with a service orientated architecture (SOA). When using asynchronous messaging you typically have a flow like:

--> Request
<-- Delivery acknowledgement
<-- Process acknowledgement
--> Delivery acknowledgement

It is typical to use 200 Ok for a successful delivery acknowledgement. I would expect this to be widely documented online, although I just had a quick look for a reference and couldn't find one.

The process acknowledgement is a separate HTTP transaction, in the reverse direction, and this allows you to report any errors during processing.


问:
How to unit test a top level method
I'm trying to unit test a small program I wrote.

My problem is that I can't see an easy way to unit test my top level class (Matcher) that exposes a single public method (MatchAll).

I do have tests for my inner classes, but they are largely trivial.

Let me present a problem and a sketch of my solution:

Problem: Given list of people, list of their preferred teams and rankings for each team, find a match that both maximizes team rank and takes candidate preferences into consideration.

My solution:

Candidate - Holds a list of preferred teams and a rank score for each respective team

Team - Holds list of accepted candidates. As long as the team has room, it accepts any candidate.
Once it fills up, it only accepts candidates that improve its score. It also purges the candidate with lowest score.

Team exposes the following methods:

IsBetterMatch

Add

PurgeWeakest

Matcher - Contains the list of candidates and list of teams and implements the core logic of assigning candidates to a team.

My matching logic is as follows (Pseudocode):

```<code>function Matchall()
    while candidates != empty
        c <- candidates.getFirst()
        for each t in c.teams
            betterMatch = t.IsBetterMatch(c)
            if betterMatch
                weakest = t.purgeWeakest()
                t.Add(c)
                candidates.add(weakest)
</code>```

Assuming team methods are thoroughly tested, how would you suggest to test this function?

The tests that I can think of for this function are very complex both to formulate and to setup.

For example:

When two candidates have same rank and want the same team and the team has room for only one, the first one should be assigned to the team. Second one should be assigned to another team down his preference list.

It seems to me that they fall more under the integration tests category, which is why I'm confused. It's my understanding that the unit tests should be short and simple to write

答:
In order to test a method which accepts no arguments and returns no results you have to fiddle with the state that it works on, invoke it, and then examine the state that it modified by side-effect.  I would strongly advice against doing that, and if that's how your top-level method has to be, then it is untestable as far as I am concerned.  (Not objectively untestable, but not worth the effort in my opinion.)

What you can do, however, is to turn your top-level method into nothing but a wrapper which simply invokes a mid-level method that accepts arguments, works on nothing but the arguments that it accepts, and returns a result.

Then, you can test the mid-level method by passing it sample arguments and checking to make sure that it returns expected results.

Title: How to unit test a top level method


答:
Perhaps you might want to take a look at DHT:

https://en.wikipedia.org/wiki/Distributed_hash_table

It's what peer-to-peer software like BitTorrent, Freenet, RetroShare, or Tox build upon.


问:
Python - Service, how to get a code review
I am usually a PHP and Delphi developer and have been getting into Python lately.

I am developing an app and would love to get some feedback on the code, there are few things which I would love to tidy up myself but I am sure there are other things.

Where / how is a good way to get in touch with an experienced Python dev? Paying is no problem.

答:
I guess the best Pythonistas can be found here:

http://mail.python.org/mailman/listinfo/python-list

Also you can try these guys:

https://stackoverflow.com/badges/51/python


问:
MVC: Creare sub folders under View
I am working on a small ERP Application and using MVC5 for it.

I have several Modules in the application and each module contain several web pages (Views, you can say).

i.e: for School application
I have LibraryManagement/Hostel Management

Now under view folder I want to create my folder structure as following:

Views

Library [Physical Folder]

BookManagement  [Controller]

Add/Edit/Delete Book Detail. [Action Based Views]

Issue Book.

Generate Library Card

Hostel [Physical Folder]

RoomInfo [Controller Name]

AddRoom [Action Based View]

EditRoom [Action Based View]

ListRoom [Action Based View]

Assign Room [Controller]

AssignRoom [Action Based View]

Manage Fees

EditFeesInfo [Action Based View]

Please help me how can I create this structure in MVC 5.

答:
MVC is a separation of concerns, hence, your controllers should never be in your Views folder (and vice versa). If I were you, I'd simply create a folder "Library" and "Hostel" in your project root. Then add a "Controllers" and "Views" folder for each. I suppose both share the same Models, so I'd put these in a separate folder in the root.

If you really want to separate the "Library" and "Hostel" part in your application, you can work with Areas.

Title: MVC: Creare sub folders under View


问:
Pass by value result with exceptions
I have a doubt with the pass-by-value-result method. As far as I understood, it passess the value of the parameter to the function, and then get the result as the function ends. But what happens with exceptions? I mean, with the following code:

```<code>int x = 1
void g(value-result int y) {
     y = 5
     throw E;
}
try {
    g(x);
} catch E {
    // do nothing
};
print_value(x);
</code>```

What is the printed value? At the time the exception is throw, the local variable of g is equal to 5. However, the function does not terminate correctly, so my question is: does the y=5 statement actually modify the variable x, and then it is printed 5, or since an exception is thrown, then the function does not terminate correctly and thus 5 is not given as result to x, and hence it is printed 1? My guess is that since an exception is an abnormal termination, x should not take 5. Is this correct?

答: Ultimately, it depends on the specification of the particular language that you are using, but in general, pass-by-value-result (Wikipedia) means that the original value of the caller will not be modified until the function returns, so the only reasonable thing to expect is that the value should remain unchanged in the event of an exception, because when an exception is thrown the function cannot really be said to return.</p>

Title: Pass by value result with exceptions


问:
Transforming XML to JSON in C++
Working with XML in C++ seems a bit of a pain and I'm looking at a way to output JSON.

I've stumbled on two different approaches:

A) XSLT transformations:
http://controlfreak.net/xml-to-json-in-xslt-a-toolkit/

B) Dedicated library such as this:
https://github.com/Cheedoong/xml2json

I'm new to programming so pursuing an avenue is a very time consuming process. If possible id like to get some feedback on what might be a more recommended approach before I start.

I'm pulling in about 5000 xml entities and outputting json with curl to another server

Any help or advice would be appreciated.

答:
From the comments... if everything else you have is C++ then the best answer is to write it in C++, building a mish-mash of different bits of programming languages is a right PitA to maintain and support. </p>

<p>So, if you have C++ and need to resolve XML to JSON, it seems obvious to use the xml2json library that you linked to. It comes with sources so you can modify it to suit any needs that it doesn't cater for, and should be the simplest answer to drop it into an existing component. You already have curl so this removes the need to come up with a different networking solution too. </p>

Title: Transforming XML to JSON in C++

Body:
From the comments... if everything else you have is C++ then the best answer is to write it in C++, building a mish-mash of different bits of programming languages is a right PitA to maintain and support.

So, if you have C++ and need to resolve XML to JSON, it seems obvious to use the xml2json library that you linked to. It comes with sources so you can modify it to suit any needs that it doesn't cater for, and should be the simplest answer to drop it into an existing component. You already have curl so this removes the need to come up with a different networking solution too.


问:
Web developer sending port in web service from server to client
I'm working on a project where I have two websites (client and a server).
I've opened web service and I'm trying to "send" a picture from my server to the client

```<code>[WebMethod]
public string PictureUrl(string id)
{
    return "http://localhost:49400/Website13/images/" + "PICTURE NAME";
}
</code>```

It works only when I know the port for my web service. What I'm looking for is if there's any method where I can get the port of my we service even if it changes, and making the code "looking" like this :

```<code>[WebMethod]
public string PictureUrl(string id)
{
    return "http://localhost:" + GET_PORT_METHOD + "/Website13/images/" + "PICTURE NAME";
}
</code>```

and the, I'll be able to use this method in my client and receive the picture. (it's like uploading a picture into an online website and then getting the URL, but since It's only a project I'm not buying a domain my server will not be online).

答:
You can avoid this issue by using a host name without a port and leaving the mapping of that host name to the target port to the server. This way, when the port changes (which is something you do on the server) you can change the mapping as well (which would also be on the server).

Depending on the web server you are using, you could use Host Headers (IIS) or Name-Based Virtual Hosts (Apache). This way, you define 'http://myservice/images' as the URL and let the webserver handle what port the URL goes to.

On a more low-level approach you could scan all the ports (probably the worst option), or implement something similar to the way DHCP works where your client broadcasts a message via UDP and the server (who knows the address for the client from the broadcast) responds with the information. But there is nothing in your question that you couldn't solve using the above method without resolving to these more extreme implementations.


答:
Similar to paj28's answer, but if both mobile devices can use WiFi, then there's an easy solution.

Have both devices connect to your server over WiFi(they seem to be capable of doing this anyways, so I'm assuming this won't be a problem)

Have the server record their connection information(Name, IP address)

Pass all connection information to all connected clients

Connected clients now have enough information to directly connect to each other without the server mediating the connection, and it stays within the LAN of your building.

In this situation you enable peer-to-peer connections but avoid the nasty business of finding peers.  The server records the information necessary for peers to connect to each other, and you can either push that information out periodically or have the clients poll that information from the server so it only goes out on an on-demand basis.


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答:
Short enough to be optimized correctly

Methods should be so short as to do exactly one thing. The reason for this is simple: so your code can be properly optimized.

In a JIT-ted language like Java or C#, it is important that your methods be simple so that the JIT-compiler can produce code quickly. Longer, more complicated methods naturally require more JIT time. Also, JIT compilers only offer a handful of optimizations and only the simplest of methods benefit from this. This fact was even called out in Bill Wagner's Effective C#.

In a lower-level language, like C or C++, having short methods (maybe a dozen or so lines) is also important because that way you minimize the need for storing local variables in RAM rather than in a register. (Aka 'Register Spilling'.) Note however that in this unmanaged case, the relative cost of each function call can be pretty high.

And even in a dynamic language, like Ruby or Python, having short methods also helps out in compiler optimizations as well. In a dynamic language the more 'dynamic' a feature, the harder it is to optimize. For example, a long method which takes an X and could return an Int, Float, or String will likely perform far slower than three separate methods which each only return a single type. This is because, if the compiler knows exactly what type the function will return, it can optimize the function call site as well. (E.g., not checking for type conversions.)

ContentLicense: CC BY-SA 4.0


问:
"One of some"-type
Say that you have some different classes that does not really have any functionality in common, but somewhere in your program, you need one of them (which one is not necessarily important) because they have a functionality in that context. What is the best way to do that?

I know that you can take an Object and use instanceof to check whether it is one of those types, but I am looking for a way to let the type system ensure that it will just be one of those types. Or is that impractical/impossible?

What I thought about doing was to create an empty interface and implement it in all the classes that needed it. but I have seen that you are supposed to use annotations instead of a marker interface, but I am not sure if that applies in this situation because I do not really care about run-time information. Another thing I am worried about is that implementing that interface in those classes will cause spaghetti code. Those classes should not really have to know anything about how they are used elsewhere.

答:
Here's a barebones generic implementation for two alternatives:

```<code>public abstract class Either<A, B> {
    private Either() { /* prevent outside subclassing */ }

    public static Either<A, B> ofA(A a) {
        return new OptionA<A, B>(a);
    }

    public static Either<A, B> ofB(B b) {
        return new OptionB<A, B>(b);
    }

    public abstract <R> R match(Function<? super A, R> ifA, Function<? super B, R> ifB);

    private static final OptionA<A, B> extends Either<A, B> {
        private final A value;

        private OptionA(A value) { this.value = value; }

        @Override
        public <R> R match(
                Function<? super A, R> ifA,
                Function<? super B, R ifB) {
            return ifA.apply(value);
        }
    }

    private static final OptionB<A, B> extends Either<A, B> {
        private final B value;

        private OptionB(B value) { this.value = value; }

        @Override
        public <R> R match(
                Function<? super A, R> ifA,
                Function<? super B, R> ifB) {
            return ifB.apply(value);
        }
    }
}
</code>```

You box up objects of one of two types into an Either and then use match to call a function based on which type the boxed object has. The combination of a private constructor and final inner subclasses ensures OptionA and OptionB are the only possible subclasses of Either, so unless you start messing around with casting, if you get your hands on an Either<Integer, String> you know it can only contain an Integer or a String.

It should be fairly straightforward to:

Extend this to 3+ alternatives.

Add convenience methods like boolean hasA() or A getA() throws NoSuchElementException() for times when match would be too verbose.

Use a visitor interface with two methods instead of two individual Functions (but the Functions are more concise if you use lambdas)

Choose other names for the alternatives (e.g. Left/Right or First/Second instead of A/B).

Add equals, hashCode, and all that stuff.

Add null-checking.

Add caching in the factory methods.

See also How do you encode Algebraic Data Types in a C#- or Java-like language?.

Title: "One of some"-type

Body:
Here's a barebones generic implementation for two alternatives:

public abstract class Either<A, B> {
    private Either() { /* prevent outside subclassing */ }

    public static Either<A, B> ofA(A a) {
        return new OptionA<A, B>(a);
    }

    public static Either<A, B> ofB(B b) {
        return new OptionB<A, B>(b);
    }

    public abstract <R> R match(Function<? super A, R> ifA, Function<? super B, R> ifB);

    private static final OptionA<A, B> extends Either<A, B> {
        private final A value;

        private OptionA(A value) { this.value = value; }

        @Override
        public <R> R match(
                Function<? super A, R> ifA,
                Function<? super B, R ifB) {
            return ifA.apply(value);
        }
    }

    private static final OptionB<A, B> extends Either<A, B> {
        private final B value;

        private OptionB(B value) { this.value = value; }

        @Override
        public <R> R match(
                Function<? super A, R> ifA,
                Function<? super B, R> ifB) {
            return ifB.apply(value);
        }
    }
}

You box up objects of one of two types into an Either and then use match to call a function based on which type the boxed object has. The combination of a private constructor and final inner subclasses ensures OptionA and OptionB are the only possible subclasses of Either, so unless you start messing around with casting, if you get your hands on an Either<Integer, String> you know it can only contain an Integer or a String.

It should be fairly straightforward to:

Extend this to 3+ alternatives.

Add convenience methods like boolean hasA() or A getA() throws NoSuchElementException() for times when match would be too verbose.

Use a visitor interface with two methods instead of two individual Functions (but the Functions are more concise if you use lambdas)

Choose other names for the alternatives (e.g. Left/Right or First/Second instead of A/B).

Add equals, hashCode, and all that stuff.

Add null-checking.

Add caching in the factory methods.

See also How do you encode Algebraic Data Types in a C#- or Java-like language?.


问:
I don't understand the arguments against operator overloading
I just read one of Joel's articles in which he says:

In general, I have to admit that I’m a little bit scared of language features that hide things. When you see the code

```<code>i = j * 5;
</code>```

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it.

(Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as abstraction) one of the key ideas of object-oriented programming? Everytime you call a method a.foo(b), you don't have any idea what that might do. You have to find out what types a and b are, something which might be declared somewhere  altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer?

And how is j * 5 any different from j.multiply(5), which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of j and peek inside the multiply method, because lo and behold, j might be of a type that has a multiply method that does something terribly witty.

"Muahaha, I'm an evil programmer that names a method multiply, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading!

If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all.

Please enlighten me.

答:
I perfectly understand you do not like Joel's argument about hiding. Me neither. It's indeed much better to use '+' for things like built-in numerical types or for your own ones like, say, matrix. I admit this is neat and elegant to be able to multiply two matrices with the '*' instead of '.multiply( )'. And after all we've got the same kind of abstraction in both cases.

What hurts here is the readability of your code. In a real-life cases, not in the academic example of matrix multiplication. Especially if your language allows to define operators that are not initially present in the language core, for instance =:=. A lot of extra questions arise at this point. What is that damn operator about? I mean what is the precedence of that thing? What is the associativity? In which order is the a =:= b =:= c really executed?

That is already an argument against operator overloading. Still not convinced? Checking the precedence rules took you no more then 10 sec? Ok, let's go further.

If you start to use a language that allows operator overloading, for instance that popular one whose name begins with 'S', you will quickly learn that library designers love to override operators. Of course they are well educated, they follow the best practices (no cynicism here) and all their APIs make perfect sense when we look at them separately.

Now imagine you have to use a few APIs that make heavy use of operators overloading together in a one piece of code. Or even better - you have to read some legacy code like that. This is when the operator overloading really sucks. Basically if there is a lot of overloaded operators in one place they will soon start to mingle with the other non alpha-numerical characters in your program code. They will mingle with non alpha-numerical characters that are not really operators but rather some more fundamental language grammar elements that define things like blocks and scopes, shape flow control statements or denote some meta thingies. You will need to put the glasses and move your eyes 10 cm closer to the LCD display to understand that visual mess.


问:
What exactly makes the Haskell type system so revered (vs say, Java)?
I'm starting to learn Haskell. I'm very new to it, and I am just reading through a couple of the online books to get my head around its basic constructs.

One of the 'memes' that people familiar with it have often talked about, is the whole "if it compiles, it will work*" thing - which I think is related to the strength of the type system.

I'm trying to understand why exactly Haskell is better than other statically typed languages in this regard.

Put another way, I assume in Java, you could do something heinous like bury
ArrayList<String>() to contain something that really should be ArrayList<Animal>(). The heinous thing here is is that your string contains elephant, giraffe, etc, and if someone puts in Mercedes - your compiler won't help you.

If I did do ArrayList<Animal>() then, at some later point in time, if I decide my program isn't really about animals, it's about vehicles, then I can change, say, a function that produces ArrayList<Animal> to produce ArrayList<Vehicle> and my IDE should tell me everywhere there is a compilation break.

My assumption is that this is what people mean by a strong type system, but it's not obvious to me why Haskell's is better. Put another way, you can write good or bad Java, I assume you can do the same in Haskell (i.e stuff things into strings/ints that should really be first-class data types).

I suspect I'm missing something important/basic.

I would very happy to be shown the error of my ways!

答:
A related SO question.

I assume you can do the same in haskell (i.e stuff things into strings/ints that should really be first class datatypes)

No, you really can't - at least not in the same way that Java can. In Java, this sort of thing happens:

```<code>String x = (String)someNonString;
</code>```

and Java will happily try and cast your non-String as a String. Haskell does not allow this sort of thing, eliminating a whole class of runtime errors.

null is part of the type system (as Nothing) so needs to be explicitly asked for and handled, eliminating a whole other class of runtime errors.

There's a bunch of other subtle benefits too - especially around reuse and type-classes - that I don't have the expertise to know well enough to communicate.

Mostly though, it is because Haskell's type system allows a lot of expressiveness. You can do a whole lot of stuff with only a few rules. Consider the ever-present Haskell tree:

```<code>data Tree a = Leaf a | Branch (Tree a) (Tree a)
</code>```

You've defined an entire generic binary tree (and two data constructors) in a fairly readable one line of code. All just using a few rules (having sum types and product types). That is 3-4 code files and classes in Java.

Especially among those prone to revere type systems, this sort of conciseness/elegance is highly valued.

Body:
A related SO question.

I assume you can do the same in haskell (i.e stuff things into strings/ints that should really be first class datatypes)

No, you really can't - at least not in the same way that Java can. In Java, this sort of thing happens:

String x = (String)someNonString;

and Java will happily try and cast your non-String as a String. Haskell does not allow this sort of thing, eliminating a whole class of runtime errors.

null is part of the type system (as Nothing) so needs to be explicitly asked for and handled, eliminating a whole other class of runtime errors.

There's a bunch of other subtle benefits too - especially around reuse and type-classes - that I don't have the expertise to know well enough to communicate.

Mostly though, it is because Haskell's type system allows a lot of expressiveness. You can do a whole lot of stuff with only a few rules. Consider the ever-present Haskell tree:

data Tree a = Leaf a | Branch (Tree a) (Tree a)

You've defined an entire generic binary tree (and two data constructors) in a fairly readable one line of code. All just using a few rules (having sum types and product types). That is 3-4 code files and classes in Java.

Especially among those prone to revere type systems, this sort of conciseness/elegance is highly valued.


问:
Pathfinding in a 3d world with obstacles?
What are some methods for pathfinding in a 3d world?

Object X needs to move from Point A to Point B but it might have to avoid things like asteroids, planets or gas pockets that makes the object slower.

The program uses an octtree and is not "tile" or "grid" based.

E.g.:

What kind of pathfinding system does games like Homeworld 2, Sins of a solar empire and similar use?

There would be a lot of objects flying around in this 3d space, each having it's starting point A and destination point B but each would have to periodically update it's path in order to avoid the other objects.

I have implemented the A* algorithm before by myself. The best I can think of is using a flow field but I perceived it to be very ineffective in large scale.

Since flow fields need to be calculated on a large area, doing so for hundreds or even thousands of objects can become a slow process. Supreme Commander 2 uses flow fields for pathfinding and it's possible to have hundreds of units. Under the hood, the pathfinding is very simple, though. It only works for finding paths that are simple because finding the way out of a very simple labyrinth is a problem and would cause units to phase through the walls/buildings.

Using a flow field for the purpose sounds, to me at least, as a good decision. Alas, I'm unsure if it's a wise choice when the flow fields need to be updated often so that other objects can be avoided. Or is there maybe a technique for calculating everything from start to finish before moving the objects? If there is, I don't know what it's called or how to find information about it.

答:
What are some methods for pathfinding in a 3d world?

The same as a 2D world.

Most pathfinding algorithms work on graphs, and will happily work with an arbitrary number of paths from a node. You might have some challenges building that graph from your existing data structures; and you might need to change your distance/heuristic for how "good" a path is, but the methods for pathfinding itself does not change.


答:
Quite an old question, however I'm surprised no one has mentioned:

Minification: If you happen to minify a JavaScript snippet that doesn't explicitly end the statements with a semi-colon character, you might end up having a hard time trying to figure out what is wrong with a snippet that was just working before the minification and now doesn't work.

Ambiguity: Semi-colons are optional, true, however by eliminating them from the source-code, you might leave some ambiguous scenarios to the parser to decide on its own. If you are writing a 100 lines of code for an online shop, yes, maybe it doesn't matter, but more serious tasks would require a 100% clarity.

Long time ago I read a very nice analogy about something else but it's very true in this case also: (In our case) Eliminating the semi-colons is like crossing at a red light. You might be okay in the end or you might get hit by a truck.

Why it's becoming more popular these days?

I personally believe having JavaScript runs on the server-side had a lot of effects on the JavaScript community itself. In our case, obviously no one is going to minify the JavaScript on the server-side (as the source-code is not supposed to ship to the client's web browser), so having no semi-colons looks much safer which is true; however the other developers who learn from these books, articles and videos, they unfortunately dismiss the fact that JavaScript on the server-side is not exactly the same as JavaScript in the client-side.

Title: Why the recent shift to removing/omitting semicolons from Javascript?

Body:
It seems to be fashionable recently to omit semicolons from Javascript. There was a blog post a few years ago emphasising that in Javascript, semicolons are optional and the gist of the post seemed to be that you shouldn't bother with them because they're unnecessary. The post, widely cited, doesn't give any compelling reasons not to use them, just that leaving them out has few side-effects.

Even GitHub has jumped on the no-semicolon bandwagon, requiring their omission in any internally-developed code, and a recent commit to the zepto.js project by its maintainer has removed all semicolons from the codebase. His chief justifications were:

it's a matter of preference for his team;

less typing

Are there other good reasons to leave them out?

Frankly I can see no reason to omit them, and certainly no reason to go back over code to erase them. It also goes against (years of) recommended practice, which I don't really buy the "cargo cult" argument for. So, why all the recent semicolon-hate? Is there a shortage looming? Or is this just the latest Javascript fad?


答:
JDT

There are specific implementation answers to this problem developed by various software stacks, see JDTs answer.

Router

I think a fairly simple solution is to get your router to do this for you. You can define a mapping between incoming requests at a known and static port on the router and the server (including the port number) the requests should be forwarded to.

Registry

The general problem though of trying to refer to an endpoint (host + port of a web service) when you don't know all the variables has been solved in large enterprises by using a registry service (e.g. WSRR). A third application at a known location in the network that will answer the question: Where is this web service? Whenever the webservice changes its host or port it needs to up date the registry with its new location.

Config Store

The more modern equivalent of the registry is to keep a distributed config store, such as Apache ZooKeeper, up to date with the location of all the systems in your network. This can act the other way round to the registry, in that you can update the config store with what you would like the network configuration to look like and watchers will respond to that change by spinning up the service at the required location.

Title: Web developer sending port in web service from server to client

Body:
I'm working on a project where I have two websites (client and a server).
I've opened web service and I'm trying to "send" a picture from my server to the client

```<code>[WebMethod]
public string PictureUrl(string id)
{
    return "http://localhost:49400/Website13/images/" + "PICTURE NAME";
}
</code>```

It works only when I know the port for my web service. What I'm looking for is if there's any method where I can get the port of my we service even if it changes, and making the code "looking" like this :

```<code>[WebMethod]
public string PictureUrl(string id)
{
    return "http://localhost:" + GET_PORT_METHOD + "/Website13/images/" + "PICTURE NAME";
}
</code>```

and the, I'll be able to use this method in my client and receive the picture. (it's like uploading a picture into an online website and then getting the URL, but since It's only a project I'm not buying a domain my server will not be online).