答:
Linking code (using the linker, e.g. ld often started by gcc or gfortran compilation commands) written in two different languages is implementation specific. It is often called foreign function interface. It depends upon calling conventions specific to the implementations.

On Linux, with code compiled by gfortran and gcc (both from the GCC compiler) is quite easy (in particular because both share a common middle-end and back-end layers of the Gnu Compiler Collection). The gfortran documentation has a chapter about mixed language programming

BTW, you can make two processes (e.g. running two different -or the same- programs, perhaps coded in two different languages) communicate using Inter-process communication; this is provided by the operating system so is OS specific. On Linux and POSIX you could use pipe(7)-s, socket(7)-s, in particular unix(7) ones (and poll(2) them appropriately in some event loop), shared memory (see shm_overview(7) & sem_overview(7) for synchronization with semaphores), etc. Read Advanced Linux Programming. You might be interested by Remote Procedure Calls (e.g. JSON-RPC, ....), MPI, etc...

PS. Don't call IPC linking. When talking about software, linking means using the linker (e.g. to merge & mix code from various object files and libraries into a single executable).

Title: Linking two or more different programming languages

Body:
I would like to ask how optimizer software written in C/C++ can be linked to simulator software written in FORTRAN or any other language. I have copied the section of journal article of Singh and Chakrabarty (2011).

In the present study, MODFLOW 2000 and MT3DMS 5.0 are
  linked as independent modules with the optimization code.
  Modifications are made to the codes of the simulators in such a
  way that they can be run through input files, and both of them
  are then compiled. One of the files required to run MODFLOW
  2000 is prepared by the optimization algorithm. This file contains
  the latest values of the decision variables. The NSGA II separately
  calls both MODFLOW 2000 and MT3DMS 5.0 in their compiled
  forms as independent modules. MODFLOW 2000 uses the file
  prepared by NSGA II to calculate hydraulic head and prepare
  an output file containing these values. Similarly, MT3DMS 5.0 calculates
  contaminant concentrations at selected locations and produces
  an output file containing the concentration values. The output
  files produced by the simulators are used by NSGA II as input files
  to produce updated values of the decision variables. The optimization
  problem, thus, runs until convergence. Obviously, writing of
  interface programs for linking codes written in different languages
  is altogether eliminated in this technique of linking.

I believe from here I can move forward with my research.
Thanks to you all.


问:
Dependency Inversion Principle
I have been studying also S.O.L.I.D. and watched this video:

https://www.youtube.com/watch?v=huEEkx5P5Hs

01:45:30 into the video he talks about the Dependency Inversion Principle and I am scratching my head?  I had to simplify it (if possible) to get it through this thick scull of mine and here is what I came up with.  Code on the marked My_modified_code my version, code marked Original DIP video version.  Can I accomplish the same with the latter code?

Original:

namespace simple.main
{
     class main
    {
        static void Main()
        {
            FirstClass FirstClass = new FirstClass(new OtherClass());
            FirstClass.Method();
            Console.ReadKey();

            //tempClass temp = new OtherClass();
            //temp.Method();
        }
    }

     public class FirstClass
     {
         private tempClass _LastClass;
         public FirstClass(tempClass tempClass)//ctor
         {
             _LastClass = tempClass;
         }

         public void Method()
         {
             _LastClass.Method();
         }
     }

    public abstract class tempClass{public abstract void Method();}

    public class LASTCLASS : tempClass
    {
        public override void Method()
        {
            Console.WriteLine("\nHello World!");
        }
    }

    public class OtherClass : tempClass
    {
        public override void Method()
        {
            Console.WriteLine("\nOther World!");
        }
    }
}
```

<p>My_modified_code:</p>

<pre class="lang-cpp prettyprint-override"><code>namespace simple.main
{
     class main
    {
        static void Main()
        {
            //FirstClass FirstClass = new FirstClass(new OtherClass());
            //FirstClass.Method();
            //Console.ReadKey();

            tempClass temp = new OtherClass();
            temp.Method();
        }
    }

     //public class FirstClass
     //{
     //    private tempClass _LastClass;
     //    public FirstClass(tempClass tempClass)//ctor
     //    {
     //        _LastClass = tempClass;
     //    }

     //    public void Method()
     //    {
     //        _LastClass.Method();
     //    }
     //}

    public abstract class tempClass{public abstract void Method();}

    public class LASTCLASS : tempClass
    {
        public override void Method()
        {
            Console.WriteLine("\nHello World!");
        }
    }

    public class OtherClass : tempClass
    {
        public override void Method()
        {
            Console.WriteLine("\nOther World!");
        }
    }
</code>```

答:
Congratulations on studying S.O.L.I.D.  These are some of my favorite principles.

The Video

01:45:30 is not when the video deals with The Dependency Inversion Principle (that's 1:26:38).  It's not even when it deals with Dependency Injection (that's 1:32:33 - accepting a dependency and 1:33:30 - injecting a dependency).  01:45:30 is when it deals with Dependency Injection Frameworks.

Your Code

Going from Original to My_modified_code, you remove FirstClass and call Method() on the OtherClass instance stored in temp as a tempClass.  This is a refactoring since it does not change the behavior of the program (except for the commented out Console.ReadKey()).  What is different is that rather than achieving polymorphism by composition and delegation in FirstClass (much like the Strategy Pattern does) you are now achieving polymorphism by subclassing and inheritance under tempClass (much like the Template Pattern).

What you've lost is the level of indirection that FirstClass was providing.  FirstClass could have suppressed the Method() call, could have changed what instance Method() was called on at any time, and could even have called something else entirely.

You've also lost your one and only Dependency Injection.  OtherClass was being injected into FirstClass as a tempClass in main before.  Now main is handling it directly.

But other than that, yeah it's behavior is pretty much the same.  Understand that the intent here wasn't to write the simplest code that behaves as you want.  It's to write code that will withstand changes without breaking.

Dependency Inversion Principle

This is about both high and low level modules/classes not depending on concrete classes, or details, whatever you want to call them.   This is why we see new only in main away from your client classes.  Instead they depend on abstractions like tempClass.

The reason for this is to protect against change.  If details aren't known then details can change without affecting anything else.  Anything you know about you have to care about.

Dependency Injection

This is how the details find their way into the client classes that don't know them except through their abstractions.

We used to just call injections "parameter passing" or "passing a reference around" but few people understood why it was important to do that.  So Fowler invented a new word for it in an attempt to (well, to sell books, but also) make clear that this is prefered to clients constructing things themselves.

Construction

Your simple example has all the construction happen in main.  It's important to know it doesn't have to only occur here.  You can have many classes dedicated to constructing and injecting dependencies into clients.  What is key is that clients should not know about them.

There are many creational patterns that can help with this.  The original Gang of Four creational patterns are a start but we've come a long way since then.  From Josh Bloch's builder pattern to Fluent Interfaces to internal Domain Specific Languages.  It's changed the way we test, and the way we write SQL queries.  These new creational patterns are also part of why Java 8 almost looks like a new language.

Tap into this power and you can hand tune the construction of your clients to suit your needs.  If, instead, you'd rather throw a completely generic construction solution at the problem then read on.

Dependency Injection Frameworks - Rant

Contrary to popular belief, and much marketing propaganda, Dependency Injection Frameworks do not help you invert dependencies (a good design does that).  They do not accept dependency injections (your client code, written in your native language, does that).  No, what Dependency Injection Frameworks actually do for you is solve the construction problem.

They can solve this by making you push all knowledge of your client object graph into xml configuration files or by making you decorate your classes with (sometimes proprietary) noise that lets you autowire based on class name or type or whatever.  Which to chose is the classic Configuration vs Convention debate.  Do you want absolute control or do you not want to have to think?

The only thing a Dependency Injection Framework (DIF) has to do with Dependency Injection(DI) is communication.  DI is how a DIF communicates the work it's done for your client classes as it builds them.  We call this communication the injection.

In other words, DI is what the framework expects YOU to support and accept in your clients.  You can support and accept DI with or without a framework.  If you don't, the framework won't do you much good.  Well, the framework might offer some hacky workarounds, but other than that...

Constructor, Setter, and Interface Injection are the three classic forms of injection that you don't need any proprietary framework magic to use.  Your language can do them on it's own.  The video used constructor injection at 1:32:33.

There are other forms of injection (annotations and reflection tricks come to mind), many of them proprietary.  If you're not careful you can find yourself writing code that is, ironically, dependent on your particular Dependency Injection Framework.  A situation that the Framework authors wouldn't mind at all. But your boss might.

The lesson of this rant is that using a Dependency Injection Framework is no substitute for understanding Dependency Injection (DI), or the Dependency Inversion Principle (DIP).  Really, they're just a handy way to construct objects, and certainly not the only one.

ContentLicense: CC BY-SA 3.0

Title: Dependency Inversion Principle


问:
Should I include `assembly` as programming language in the CV?
In the answer for one question someone wrote that assembly is not a language, it's a process. I tend to agree, since the assembly "language" is dependent on the architecture it will run on, which may differ quite a bit from one CPU to another.

So if you've written assembly for one architecture, does that mean you can include it in the CV under merely assembly along with the other programming languages? Or do you explicitly say that you've written assembly for that particular architecture?

EDIT: Changed 'dabbled' to 'written'. English isn't my native language and I misunderstood the term, thinking it meant that you've used it a lot instead of just a bit.

答:
I think the question about whether it's technically a language is a little irrelevant, though it never hurts to be accurate (so yes include the specific architecture if you do list it and probably put Assembly Language rather than Assembler, though I'd personally read the later as a reasonable shorthand rather than a mistake to be penalised).

The things I'd make sure I was thinking about more than this are:

1) The main thing:  will it help you get the job in question?  You should tweak your CV depending on the role and for each one ask yourself does this make me look a better candidate for this position.  There's no absolute, it's dependent and the job in question.

2) Are you happy to be asked questions about it in an interview?  Is your knowledge current and up to a good standard?  Basically if you put it on your CV it's fair game for questions so make sure you're happy with that and that you feel however you do choose to present it represents your level of knowledge correctly.

3) And following on from that, where to put it?  Given that you say you've dabbled maybe the best solution is in an Other Interests section you can say "I have a wide interest in technology and have spent my own time investigating a range of languages and platforms outside my core skills set including 6800 (or whatever) Assembly Language.

ContentLicense: CC BY-SA 2.5


问:
Determining if an Algorithm is O (log n)
I'm refreshing my CS Theory, and I want to know how to identify that an algorithm O (log n) complexity.  Specifically, is there an easy way to identify it?

I know with O(n), you usually have a single loop; O(n^2) is a double loop; O(n^3) is a triple loop, etc.  How about O (log n)?

答:
You want to know if there is an easy way to identify if an algorithm is  O(log N).

Well: just run and time it. Run it for inputs 1.000, 10.000, 100.000 and a million.

If you see like a running time of 3,4,5,6 seconds (or some multiple) you can safely say it's O(log N).
If it's more like : 1,10,100,1000 seconds then it's probably O(N).
And if it's like 3,40,500,6000 seconds then it's O(N log N).


问:
How to implement a property on class A which refers to a property of a child object of class A
We have this code which, when simplified, looks like this:

```<code>public class Room
{
    public Client Client { get; set; }

    public long ClientId
    {
        get
        {
            return Client == null ? 0 : Client.Id;
        }
    }
}

public class Client
{
    public long Id { get; set; }
}
</code>```

Now we have three viewpoints.

1) This is good code because the Client property should always be set (i.e. not null) so the Client == null will never occur and the Id value 0 denotes a false Id anyway (this is the opinion of the writer of the code ;-))

2) You can not rely on the caller to know that 0 is a false value for Id and when the  Client property should always be set you should throw an exception in the get when the Client property happens to be null

3) When the Client property should always be set you just return Client.Id and let the code throw a NullRef exception when the Client property happens to be null.

Which of these is most correct? Or is there a fourth possibility?

答:
It smells like you should limit the number of states your Room class can be in.

The very fact that you're asking about what to do when Client is null is a hint that Room's state space is too large.

To keep things simple I wouldn't allow the Client property of any Room instance to ever be null.  That means the code within Room can safely assume the Client is never null.

If for some reason in the future Client becomes null resist the urge to support that state.  Doing so will increase your maintenance complexity.

Instead, allow the code to fail and fail fast.  After all, this is not a supported state.  If the application gets itself into this state you've already crossed a line of no return.  The only reasonable thing to do then is to close the application.

This might happen (quite naturally) as the result of an unhandled null reference exception.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答: Using a hidden object in the user interface (eg, a textbox) to store a value rather than define a properly-scoped and -typed variable.</p>


问:
REST autocomplete endpoint design
We're designing a rest endpoint for retreiving name autocompletion suggestions for hotel names.

Currently it's defined like this: GET /suggest/:term, so that if you queried `/suggest/hil' you would get responses like "Hilton Paris", "Hilton New York", etc.

One of our colleagues argues that this is against REST API design best practices, and that the search term should instead be a query parameter, i.e. /suggest?term=hilt.

Looking around other famous APIs, it seems that they all use a query parameter:

https://developers.google.com/places/webservice/autocomplete

https://swiftype.com/documentation/autocomplete

but I'd like to know why; whether the former is actually bad design and what guidelines would get me to make it a query parameter in the first place.

答:
There is couple of comments that I would suggest you.

You name your resource using verb instead of nouns. suggest is not really a good resource name. It give the client the idea that you are building a controller action and REST does not like it. suggestions is a better name. Now you can view it as a resource set of suggestions which is more RESTful.

Starting with the suggestions resource you have 2 way of viewing your API.

a. Each set of completions is a resource. In this case you can use the endpoint:  ./suggestions/hil. Thus you can view it as a single resource that yield all the suggestions begining with hil.

b. Each resource is an hotel name. In this case the endpoint would look like a query parameter. ./suggestions?begin-with=hil. This allow you to later design an API to add new hotel name.( POST ./suggestions with appropriate body). Query parameter has a more clear understanding for your client as it reveal the intention begin-with, contain, ...

My preference goes to b) as you might guess but I let you own judge for your preference. a) could have some advantage depending on your use case.

Title: REST autocomplete endpoint design


答:
Just a few considerations:

a) Why is there a getter specifically for the ClientId when there's already a public getter for the Client instance itself? I don't see why the information that the ClientId is a long has to be carved in stone in the signature of Room.

b) Regarding the second opinion you could introduce a constant Invalid_Client_Id.

c) Regarding opinion one and three (and being my main point): A room must always have a client? Maybe it's just semantics but this doesn't sound right. Maybe it would be more appropriate to have completely separate classes for Room and Client and another class that ties them together. Maybe Appointment, Reservation, Occupancy? (This depends on what you're actually doing.) And on that class you can enforce the constraints "must have a room" and "must have a client".

Title: How to implement a property on class A which refers to a property of a child object of class A

Body:
We have this code which, when simplified, looks like this:

```<code>public class Room
{
    public Client Client { get; set; }

    public long ClientId
    {
        get
        {
            return Client == null ? 0 : Client.Id;
        }
    }
}

public class Client
{
    public long Id { get; set; }
}
</code>```

Now we have three viewpoints.

1) This is good code because the Client property should always be set (i.e. not null) so the Client == null will never occur and the Id value 0 denotes a false Id anyway (this is the opinion of the writer of the code ;-))

2) You can not rely on the caller to know that 0 is a false value for Id and when the  Client property should always be set you should throw an exception in the get when the Client property happens to be null

3) When the Client property should always be set you just return Client.Id and let the code throw a NullRef exception when the Client property happens to be null.

Which of these is most correct? Or is there a fourth possibility?


答:
The second and third options should be avoided - the getter should not smack the caller with an exception they have no control over.

You should decide whether Client can ever be null. If so, you should provide a way for a caller to check whether it is null before accessing it (e.g., bool ClientIsNull property).

If you decide that Client can never be null, then make it a required parameter to the constructor and throw the exception there if a null is passed in.

Finally, the first option also contains a code smell. You should let Client deal with its own ID property. It seems like overkill to code a getter in a container class that simply calls a getter on the contained class. Just expose the Client as a property (otherwise, you'll end up duplicating everything a Client already offers).

```<code>long clientId = room.Client.Id;
</code>```

If Client can be null, then you'll at least give responsibility to the caller:

```<code>if (room.Client != null){
    long clientId = room.Client.Id;
    /* other code follows... */
}
</code>```

Body:
The second and third options should be avoided - the getter should not smack the caller with an exception they have no control over.

You should decide whether Client can ever be null. If so, you should provide a way for a caller to check whether it is null before accessing it (e.g., bool ClientIsNull property).

If you decide that Client can never be null, then make it a required parameter to the constructor and throw the exception there if a null is passed in.

Finally, the first option also contains a code smell. You should let Client deal with its own ID property. It seems like overkill to code a getter in a container class that simply calls a getter on the contained class. Just expose the Client as a property (otherwise, you'll end up duplicating everything a Client already offers).

long clientId = room.Client.Id;

If Client can be null, then you'll at least give responsibility to the caller:

if (room.Client != null){
    long clientId = room.Client.Id;
    /* other code follows... */
}


答:
REST services are typically focused on resources, with the path separator (forward slash) denoting sub-resources in a hierarchy. Resources are typically things ("nouns" in English) rather than actions ("verbs" in English).

To conform to this style, your "suggest" endpoint (a verb) could be named "suggestions" (a noun) because it provides access to suggestions. Just as an example, a sub-resource for suggestions might be individual suggestions with URLs like /suggest/Hilton%20New%20York where the response could be a link to the actual "Hilton New York" hotel resource.

Actions like "suggest" are typically represented through HTTP verbs, e.g. GET /suggestions/.

Your "term" is essentially a filter, which are typically passed through query parameters or in the request body. A more robust implementation is described in this SO answer.

Title: REST autocomplete endpoint design

Body:
We're designing a rest endpoint for retreiving name autocompletion suggestions for hotel names.

Currently it's defined like this: GET /suggest/:term, so that if you queried `/suggest/hil' you would get responses like "Hilton Paris", "Hilton New York", etc.

One of our colleagues argues that this is against REST API design best practices, and that the search term should instead be a query parameter, i.e. /suggest?term=hilt.

Looking around other famous APIs, it seems that they all use a query parameter:

https://developers.google.com/places/webservice/autocomplete

https://swiftype.com/documentation/autocomplete

but I'd like to know why; whether the former is actually bad design and what guidelines would get me to make it a query parameter in the first place.


问:
What is meant by XML/XSLT/XPath and asynchronous programming?
I understand that (1) XML/XSLT/XPath and (2) asynchronous programming may not be related to one another. My questions are:

When a C# developer job is advertised saying: "the following skill is required as mentioned in 1 and 2", what does it actually mean?

Lets say I need to master these two topics (1 and 2). What do I need to do to accomplish that skill? Are there books for intermediates that actually teach that info with practical scenarios and case studies?

Answers are much appreciated.

I have worked XML packet crafting for message exchange over the network, developed some amateur XML parsers for some projects and done message exchange for a client/server-based messaging system using asynchronous calls. But I really need to know and learn what the companies are looking for when they write these things (1 and 2) as requirements in their job advertisment.

Aggregate skills required for the specific job were:

ASP.NET 2.0 (OK)

Web Services  and .Net Remoting (OK)

XML/XSLT/XPath (?)

Asynchoronous Programming (?)

Windows Services (OK)

Javascript/XML/AJAX (OK)

Microsoft Silverlight/WPF (OK)

So firstly, it's clear that AJAX is not related to Asynchronous programming (in this very specific context) as it is written as a separate required skill (and I hope that it's not a mere redundancy). In normal cases, my deductions would have been the same like asynchronous programming means working with AJAX (asynchronous JavaScript with XML).

Secondly, making a web service in C# does not require any extensive experience with XSLT. In fact, exposing functions from a DLL (encapsulating business logic) is the simplest of any task with web services in C#. I wonder if there is some extra skill or experience that is needed?

答:
AJAX (Asynchronous JavaScript and XML) describes both of your bullet points. So it might have been better for the job description to say that outright. XSLT and XPath are just ways to use/structure/interact with the XML DOM.

When a C#.Net Developer-job is advertised saying, "the following skill is required as mentioned in 1 and 2", then what does it actually mean?

Sounds like they're gearing towards someone to write a web application, namely a C# web service. Given the 2 strong implications, this position looks like it'll have a lot of responsibility.

Lets say i need to master these two topics (1 and 2). What do i need to do to accomplish that skill?

I'm not a .NET developer, but here is a source I would go to if I were switching languages:

http://www.c-sharpcorner.com/articles/articlelisting.aspx?sectionid=1&subsectionid=133

Short answer: Web services are an advanced topic since essentially it's an API (Application Programming Interface) -- so it's crucial the person who writes the API has ample development experience since it will be used by other developers (which we'll use to interact ).


问:
How to make sure people call methods in the right order?

Situation

I'm designing a database abstraction layer for sql (mysql, sqlite) and mongoDb. The goal is to give the user/developer a library which is able to create queries for different databases. Without even knowing which type of database is queried.

Let's say we have a class which is able to create for example the where part (condition) of a query like (in case of sql):

```<code>name = 'Toni' AND age = 42 AND (status = 'ok' OR status = 'maybe-ok')
</code>```

The way to create this string is calling different methods of an object in a certain sequence.

The class which the object is derived from could look like (pseudo):

```<code>class ConditionCreator:
    private-field condition

    public-function and:
        self.condition += ' AND '
        return self
    end

    public-function or:
        self.condition += ' OR '
        return self
    end

    public-function block:
        self.condition += '('
        return self
    end

    public-function blockend:
        self.condition += ')'
        return self
    end

    public-function comparison(key, value):
        self.condition += key + ' = ' + value
        return self
    end

end
</code>```

And the calls to is should look like:

```<code>creator = new ConditinoCreator
creator.comparison('name', "'Toni'")
    .and()
    .comparison('age', 42)
    .and()
    .block()
        .comparison('status', "'ok'")
        .or()
        .comparison('status', "maybe-ok")
    .blockend()
</code>```

Problem

How would one make sure that the calls are in the correct order?

No comparison after a comparison

No operator (or, and) after an operator(or, and)

No operator after a block (

No comparison after a blockend )

The same number of blockend's ) and block's (

etc. pp.

Things I thought about:

Regex

My first thought was to add a second class variable to which every method (and, or, block, blockend, comparison) adds a character so that the sample would produce  this string caca(coc) after this string is generated one could do some regex magic on it to verify that the condition is valid.

Program it

As the title says one should program the rules from the Problem section manually. If this is the way to go how would this be done? Would one create a string like the one in the Regex solution and than test it against the rules?

Rely on the underlying database implementation

Do not test/validate the condition and rely on the database to throw errors (which is horrible to debug since every database gives a different level of output details and giving clear error messages is really hard).

Is there more?

Is there anything I'm missing completely?

答:
The fluent interface for a inner domain specific language is built on top of the Builder pattern. Ultimately, you are building up a representation that is to be used.

The solution is to then use a stateful builder (related: How should I handle incompatible configurations with the Builder pattern?).  The object that you return needs to be restricted to the set of methods that are appropriate to call on it.

For the code example:

```<code>creator = new ConditinoCreator
creator.comparison('name', "'Toni'")
    .and()
    .comparison('age', 42)
    .and()
    .block()
        .comparison('status', "'ok'")
        .or()
        .comparison('status', "maybe-ok")
    .blockend()
</code>```

the object returned by comparison only has the methods blockend, and and or.  Likewise, the object returned by and and or only has the methods block and comparison.

No, this will not completely handle all situations - you can still have issues with calling blockend when there is no block (you could make the block a special type of object too, but then you get into the fun of nested blocks) or the possibility of having a dangling and or or, but it will handle the majority of the situations and enforce some formality to the structure. This is in effect using the type system of the language to do the work for you.  The amount of ability you have to control this depends on the type system.

Technically, the way I've described the types above is that of a finite state table (and a regular language) and thus it can't do arbitrary nesting depth (which the corresponding inner language appears to support).  Looking at this as a state table can help you understand how to use it though.  Depending on the language, however, it may be possible to get a more powerful system. Some languages have a much more powerful type system that allow you to do crazy things or may be Turing complete, others are much more restrained.  Now, if you want to try to take advantage of a full Turing machine to recognize the inner language in the type system, it sounds like a good challenge, though one that has the danger of being too clever.

To avoid some of these problems:

Have a .build() at the end that returns the appropriate finalized type. This can avoid the dangling .and() or .or().

Instead of a .block().comparison().or().comparison().blockend() have .block(Comparison) be the method signature which uses an already existing comparison object (possibly one created in there).  Since each block is complete, arbitrary nesting isn't something that the type system needs to handle.

Taking both of these points, the sample code would look like:

```<code>Comparison comparitor = (new ComparisonBuilder())
    .comparison('name', "'Toni'")
    .and()
    .comparison('age', 42)
    .and()
    .block((new ComparisonCreator()).
        .comparison('status', "'ok'")
        .or()
        .comparison('status', "maybe-ok")
        .build()
    ).build()
</code>```

Body:
The fluent interface for a inner domain specific language is built on top of the Builder pattern. Ultimately, you are building up a representation that is to be used.

The solution is to then use a stateful builder (related: How should I handle incompatible configurations with the Builder pattern?).  The object that you return needs to be restricted to the set of methods that are appropriate to call on it.

For the code example:

creator = new ConditinoCreator
creator.comparison('name', "'Toni'")
    .and()
    .comparison('age', 42)
    .and()
    .block()
        .comparison('status', "'ok'")
        .or()
        .comparison('status', "maybe-ok")
    .blockend()

the object returned by comparison only has the methods blockend, and and or.  Likewise, the object returned by and and or only has the methods block and comparison.

No, this will not completely handle all situations - you can still have issues with calling blockend when there is no block (you could make the block a special type of object too, but then you get into the fun of nested blocks) or the possibility of having a dangling and or or, but it will handle the majority of the situations and enforce some formality to the structure. This is in effect using the type system of the language to do the work for you.  The amount of ability you have to control this depends on the type system.

Technically, the way I've described the types above is that of a finite state table (and a regular language) and thus it can't do arbitrary nesting depth (which the corresponding inner language appears to support).  Looking at this as a state table can help you understand how to use it though.  Depending on the language, however, it may be possible to get a more powerful system. Some languages have a much more powerful type system that allow you to do crazy things or may be Turing complete, others are much more restrained.  Now, if you want to try to take advantage of a full Turing machine to recognize the inner language in the type system, it sounds like a good challenge, though one that has the danger of being too clever.

To avoid some of these problems:

Have a .build() at the end that returns the appropriate finalized type. This can avoid the dangling .and() or .or().

Instead of a .block().comparison().or().comparison().blockend() have .block(Comparison) be the method signature which uses an already existing comparison object (possibly one created in there).  Since each block is complete, arbitrary nesting isn't something that the type system needs to handle.

Taking both of these points, the sample code would look like:

Comparison comparitor = (new ComparisonBuilder())
    .comparison('name', "'Toni'")
    .and()
    .comparison('age', 42)
    .and()
    .block((new ComparisonCreator()).
        .comparison('status', "'ok'")
        .or()
        .comparison('status', "maybe-ok")
        .build()
    ).build()


问:
Unable to convince on data hiding
I am working on a Selenium + java project where all Web Element in a class are declared as -

```<code>public class CheckoutPaymentConfirmpage extends WebPage{

public final Button btnPrintorder = new Button("//input[@id='but_Print']");
public final TextField txtpassword = new TextField("password", "//input[@id='pass']");

    // Some more elements here
    // Some page object methods here
}
</code>```

Now when ever test need to access these elements they are directly invoked over the object of CheckoutPaymentConfirmpage class
What ever little java (or OOPS) I know, has taught me that members should be as hidden as possible. Hence I would have had btnPrintorder and txtpassword declared private and would access them using getters or would have created methods in page object class to be used by tests.

But when I convey this to others they don't see much value in it as state of instance variable (i.e. btnPrintorder etc) would not be changed from one object to another for page object class (i.e. CheckoutPaymentConfirmpage etc)

Hence in this situation, is it ok to leave instance variable as public?

答:
If memory serves, the reasons for developing the technique of encapsulating members with accessor/mutator pairs are due to some historical problems associated with maintenance and quality control.

As a programs grows, is maintained, and new features added, some of the particular problems are:

A bug emerges where the value of the member is incorrect, but it is difficult to determine why it was set they way it was.  The value may even be used to for a different purpose by a caller.

The source of the values for that member change.  Rather than being set ahead of time, the value needs to be fetched rather that recited.

The encapsulation helps to solve the problem by ensuring that the class's maintainer has a function which can be modified to take control of the value being set or retrieve and ensure that it is correct.

This is similar to programming practices such as minimizing the scope of variables, and maximizing cohesion.  The approach also embodies the secure coding practice of validating and verifying inputs and outputs.   (A class represents one clear concern / state-machine, etc.)

Should this be applied to your particular situation?  Can you accurately predict and control the future of the software?  Consider that if you encapsulate and never need it, you've lost a few minutes of IDE generated functions.  If you don't do it and later need it, it can be economically expensive to fix, (especially in a larger program).

More concisely, encapsulating access to class members consistently as a rule is a typical technique for mitigating economic risks in software quality and maintenance.

Title: Unable to convince on data hiding


答:
I disagree with all three of the opinions. If Client can never be null, then don't even make it possible for it to be null!

Set the value of Client in the constructor

Throw an ArgumentNullException in the constructor.

So your code would be something like:

```<code>public class Room
{
    private Client theClient;

    public Room(Client client) {
        if(client == null) throw new ArgumentNullException();
        this.theClient = client;
    }

    public Client Client {
        get { return theClient; }
        set
        {
            if (value == null)
                throw new ArgumentNullException();
            theClient = value;
        }
    }

    public long ClientId
    {
        get
        {
            return theClient.Id;
        }
    }
}
</code>```

```<code>public class Client
{
    public long Id { get; set; }
}
</code>```

This is unrelated to your code, but you would probably be better off using an immutable version of Room by making theClient readonly, and then if the client changes, making a new room. This will improve the thread safety of your code in addition to the null safety of the other aspects of my answer. See this discussion on mutable vs immutable

Body:
I disagree with all three of the opinions. If Client can never be null, then don't even make it possible for it to be null!

Set the value of Client in the constructor

Throw an ArgumentNullException in the constructor.

So your code would be something like:

public class Room
{
    private Client theClient;

    public Room(Client client) {
        if(client == null) throw new ArgumentNullException();
        this.theClient = client;
    }

    public Client Client {
        get { return theClient; }
        set
        {
            if (value == null)
                throw new ArgumentNullException();
            theClient = value;
        }
    }

    public long ClientId
    {
        get
        {
            return theClient.Id;
        }
    }
}

public class Client
{
    public long Id { get; set; }
}

This is unrelated to your code, but you would probably be better off using an immutable version of Room by making theClient readonly, and then if the client changes, making a new room. This will improve the thread safety of your code in addition to the null safety of the other aspects of my answer. See this discussion on mutable vs immutable


问:
When is it appropriate to use expression bodied members?
C# 6 introduces expression-bodied members, which allow for simplified code in methods and properties that only return the result of an expression:

```<code>public override string ToString()
{
     return string.Format("{0} {1}", _field1, _field2);
}
</code>```

becomes:

```<code>public override string ToString() =>
    string.Format("{0} {1}", _field1, _field2);
</code>```

Since we now have two exactly equivalent and valid syntaxes, some rule of thumb must be used to decide which to use. When is the new alternative appropriate?

答:
From C#/.NET Little Wonders: Expression-Bodied Members in C# 6:

So, should you use this?  It all comes down to style.  My gut would be to limit this to simple expressions and statements that can clearly be understood at first glance.

(emphasis, mine; see Update 1 below)

More from the Summary of the article above:

So C# 6 now gives us the ability to specify get-only property and method bodies with expressions.  This can help reduce the syntax burden of very simple methods to make your code more concise.

However, with all things, use your judgment on whether it fits for any given situation.  When an expression is very long or complex, using the full body syntax may still be more readable.

And another quote about performance, because performance problems can also play into when it's appropriate to use a certain language feature:

Now, you may ask, does this have any performance implications at runtime?  Actually, the answer is no.  This is simply syntactical sugar that expands into the same IL as writing the full body.  It does not create a delegate, it is simply borrowing the lambda expression syntax to simplify writing simple bodies that result in an expression.

(emphasis, the author)

Update 1: @JörgWMittag said

This makes no sense. "limit this to simple expressions and statements"? Huh? It doesn' even work with statements, only with expressions!

It appears the original author may have misspoke. To clarify, from The New and Improved C# 6.0:

Expression bodied functions are another syntax simplification in C# 6.0. These are functions with no statement body. Instead, you implement them with an expression following the function declaration.

To be clear, this doesn't make a method or property an Expression. It utilizes the Expression syntax to reduce the lines of code (and numbers of curly braces).

My original recommendation still stands: Use it when it makes your code obvious and easier to understand, not simply because you can use it.

ContentLicense: CC BY-SA 4.0


问:
Support Multiple versions of Mobile apps
We are building a suite of native mobile applications to supplement our existing application that currently only supports a web interface to the server. The application can be installed and hosted by clients on their own infrastructure or hosted by ourselves for clients who want to make use of it. Big enterprise customers typically chose to self-host whilst smaller customers choose our hosting option.

We need to support multiple versions of the application. Not all customers want to upgrade at the same time. With the web interface, supporting multiple versions are not difficult as the web interface automatically uses the server version associated with its server installation. With mobile applications where you typically only have a single app available in the App Stores, the support for different levels of the Server API and functionality in the mobile app becomes a challenge. I'm interested to know how other people are solving the issue. To my mind you have options like:

Support multiple versions of the app in the app store.

Build support into the mobile applications to automatically determine the API version of the server it is talking to and route calls to the relevant server API endpoints. Also introduce use some kind of feature toggle mechanism to enable/disable functionality in the mobile application based on what's available in the different server versions.

Do not use the app store for deploying your app. Points users to a version specific URL they can use to download and install the app.

Option 1 - IMO will create confusion for the users of the app. There also isn't a nice migration path from one version of the app to the next as it really is two separate applications.

Option 2 - on the other hand can quickly become very complex if you take into account that your UI visuals now basically need to adapt to whatever functionality is available in the version of the server API it is talking to. It also needs to support the different versions of the server API calls it need to make.

Option 3 - is possible in the Android world when doing side-loading of your app, but as far as I know not supported in iOS and I'm not sure what the picture will be for Windows 10 mobile apps going forward.

What other approaches are there to tackling the issue? Please don't debate the fact that we are writing native apps. That's not what I'm asking. I'm looking for guidance on how other people are tackling the issue of supporting multiple versions of the same native mobile app talking to different versions of a server API.

答:
API versioning is fine but this would require more some work at the UI Layer
a) The UI needs to know which version of the API to invoke depending upon the configuration ( use a properties file or a resource file on the client device)

b) Also the server needs to have support for multiple versions of the API's.

Does the server API only cater to Mobile clients or does it have other clients as well . If it caters to other clients then for the Mobile only you might want to get a wrapper API that basically calls server API at one end with versioning support.

Basically versioning is tough at the server API if there are the other clients like public API's that are served by the server API otherwise it is simple .

My 2 cents .


问:
Should an application configuration interface be broken into multiple interfaces to reduce feature creep?
My windows service is neatly separated into 5 components - each with their own interface and pulled together by a bootstrapper. One of my requirements is to provide configuration options in my app.config for the different pieces of the application.

I started with the following interface:

```<code>public interface IConfiguration
{
    /// <summary>
    /// The amount of time database records are allowed to be in the system before they're removed.
    /// </summary>
    TimeSpan OldSignalValuePurgePeriod { get; }

    /// <summary>
    /// The lowest log level that will be written to the log file.
    /// </summary>
    LogSeverity MinimumLogSeverity { get; }

    /// <summary>
    /// The period of time to wait for a signal metadata response before re-requesting it.
    /// </summary>
    TimeSpan SignalMetadataRerequestPeriod { get; }
}
</code>```

which I'd planned to pass a constructed instance of to each of my components requiring configuration. The thing is, each of the above properties is a configuration option for a different component. There's a very good chance I will be adding some more properties at a later date to this interface. Obviously I'm populating the properties of the interface in the implementing object's constructor by reading the app.config file.

What I'm struggling with is this: since each component doesn't care about the configuration options of the other components, how can I separate this interface into pieces specific to each component that isn't a pain to construct, and one that Jimmy will understand immediately?

I've thought of doing something like this:

```<code>public interface IRepositoryConfiguration
{
    TimeSpan OldSignalValuePurgePeriod { get; }
}

public interface ILoggingConfiguration
{
    LogSeverity MinimumLogSeverity { get; }
}

public interface IDataManagerConfiguration
{
    TimeSpan SignalMetadataRerequestPeriod { get; }
}

public class ConfigurationImplementation
    : IRepositoryConfiguration,
      ILoggingConfiguration,
      IDataManagerConfiguration
{

}
</code>```

where each component takes an instance of their own configuration interface, but I feel like that is overkill and starts to get unmanageable.

Input?

答:
I think it makes perfect sense to group multiple configuration options into an interface, when they obviously belong together. But as long as you only have one option per domain, it seems indeed overengineered. However as soon as you get multiple options concerning the same domain (e.g. three options about logging) then you should move them to their own nested interface.

When you have LOTS of options, you might want to compose the different domains explicitly in a IConfgurationWrapper * to avoid overloading your ConfigurationImplementation with too many members.

```<code>public interface IConfigurationWrapper{
  IDataManagerConfiguration DataManager {get;}
  ILoggingConfiguration Logging {get;}
  IRepositoryConfiguration Repository {get;}
}
</code>```

(*) I'm quite sure there's a better name than "*Wrapper"

OwnerDisplayName: Brandon

Body:
I think it makes perfect sense to group multiple configuration options into an interface, when they obviously belong together. But as long as you only have one option per domain, it seems indeed overengineered. However as soon as you get multiple options concerning the same domain (e.g. three options about logging) then you should move them to their own nested interface.

When you have LOTS of options, you might want to compose the different domains explicitly in a IConfgurationWrapper * to avoid overloading your ConfigurationImplementation with too many members.

public interface IConfigurationWrapper{
  IDataManagerConfiguration DataManager {get;}
  ILoggingConfiguration Logging {get;}
  IRepositoryConfiguration Repository {get;}
}

(*) I'm quite sure there's a better name than "*Wrapper"


答:
As long as all your configuration options come from a file, using interfaces does not bring you any benefit, since your configuration file can only provide fixed values. Even if you have to deal with more than one option per service, I do not see any convincing reason for using interfaces. You can still utilize simple "data objects" for the configuration  and create a configuration class like this one:

```<code>public class Configuration
{
     public Configuration()
     { /* logic for getting the values from config file */}

     public RepositoryConfiguration RepositoryConfiguration{get; private set;}
     public LoggingConfiguration LoggingConfiguration{get; private set;}
     public DataManagerConfiguration{get; private set;}
}
</code>```

The data objects for the individual configurations of your services can simply look like this:

```<code>public class DataManagerConfiguration
{
    public TimeSpan SignalMetadataRerequestPeriod { get; private set;}
    // ... add more values here
}
</code>```

The DataManager constructor will then look like this:

```<code> public DataManager(IRepository repository, ILogger logger, DataManagerConfiguration dmc)
 {...}
</code>```

As you see, still one additional parameter to the ctor, regardless of how many values are inside the class DataManagerConfiguration. And providing config values for testing purposes will typically result in less boilerplate code than creating a mock interface implementation.

Some remarks:

not coupling the different services to one big configuration class is probably a good idea, regardless of your decision for data objects or interfaces

if the data objects encapsulate just one integral type, you can even omit the "wrapping" data class as long as you do not really need it.

Title: Should an application configuration interface be broken into multiple interfaces to reduce feature creep?

Body:
My windows service is neatly separated into 5 components - each with their own interface and pulled together by a bootstrapper. One of my requirements is to provide configuration options in my app.config for the different pieces of the application.

I started with the following interface:

```<code>public interface IConfiguration
{
    /// <summary>
    /// The amount of time database records are allowed to be in the system before they're removed.
    /// </summary>
    TimeSpan OldSignalValuePurgePeriod { get; }

    /// <summary>
    /// The lowest log level that will be written to the log file.
    /// </summary>
    LogSeverity MinimumLogSeverity { get; }

    /// <summary>
    /// The period of time to wait for a signal metadata response before re-requesting it.
    /// </summary>
    TimeSpan SignalMetadataRerequestPeriod { get; }
}
</code>```

which I'd planned to pass a constructed instance of to each of my components requiring configuration. The thing is, each of the above properties is a configuration option for a different component. There's a very good chance I will be adding some more properties at a later date to this interface. Obviously I'm populating the properties of the interface in the implementing object's constructor by reading the app.config file.

What I'm struggling with is this: since each component doesn't care about the configuration options of the other components, how can I separate this interface into pieces specific to each component that isn't a pain to construct, and one that Jimmy will understand immediately?

I've thought of doing something like this:

```<code>public interface IRepositoryConfiguration
{
    TimeSpan OldSignalValuePurgePeriod { get; }
}

public interface ILoggingConfiguration
{
    LogSeverity MinimumLogSeverity { get; }
}

public interface IDataManagerConfiguration
{
    TimeSpan SignalMetadataRerequestPeriod { get; }
}

public class ConfigurationImplementation
    : IRepositoryConfiguration,
      ILoggingConfiguration,
      IDataManagerConfiguration
{

}
</code>```

where each component takes an instance of their own configuration interface, but I feel like that is overkill and starts to get unmanageable.

Input?

Body:
As long as all your configuration options come from a file, using interfaces does not bring you any benefit, since your configuration file can only provide fixed values. Even if you have to deal with more than one option per service, I do not see any convincing reason for using interfaces. You can still utilize simple "data objects" for the configuration  and create a configuration class like this one:

public class Configuration
{
     public Configuration()
     { /* logic for getting the values from config file */}

     public RepositoryConfiguration RepositoryConfiguration{get; private set;}
     public LoggingConfiguration LoggingConfiguration{get; private set;}
     public DataManagerConfiguration{get; private set;}
}

The data objects for the individual configurations of your services can simply look like this:

public class DataManagerConfiguration
{
    public TimeSpan SignalMetadataRerequestPeriod { get; private set;}
    // ... add more values here
}

The DataManager constructor will then look like this:

 public DataManager(IRepository repository, ILogger logger, DataManagerConfiguration dmc)
 {...}

As you see, still one additional parameter to the ctor, regardless of how many values are inside the class DataManagerConfiguration. And providing config values for testing purposes will typically result in less boilerplate code than creating a mock interface implementation.

Some remarks:

not coupling the different services to one big configuration class is probably a good idea, regardless of your decision for data objects or interfaces

if the data objects encapsulate just one integral type, you can even omit the "wrapping" data class as long as you do not really need it.


问:
Token or ASP.NET Identity based security in ASP.NET Web API 2

Background

I have a Web API 2 project, without any extension of ASP.NET MVC or ASP.NET projects. The API will only be used to communicate between the server and Windows 8, Windows Phone 8.1 and iOS applications. No website will consume the API. The API makes it possible for a user to manage products in a warehouse. A user can add, remove, and check products ín the database.

```<code>public class User
{
    public int Id { get; set; }
    [Required]
    public string UserName { get; set; }
    [Required]
    public string DisplayName{ get; set; }
    [Required]
    public bool IsEnabled {get; set;}
}
</code>```

Nothing fancy - just a model for Entitiy Framework. Of course a model for the product also exists. Notice, I don't require any password from my users, since this is not important for the data security. The users of the API will never know each others UserName - only each others DisplayName.

The problems

The problem is regarding security in Web API. I do not want to expose my API to the whole world - just the applications. So i have done a lot research, and from the research I have the following to scenario:

Scenario #1

The best way to ensure a high level of security in my API is to:

Use SSL

Use token-based authentication of the clients

use a token with a very short expiration time

not to use the ASP.NET Identity

to use Message Handlers instead of Action Filters

Add a UserToken field to User model and generate a token for each user

Scenario #2

The best way to ensure a high level of security in my API is to:

use SSL

use ASP.NET Identity to do username and password approach

use a token-based approach based on the authentication of ASP.NET Identity

The Questions

What is the best approach? Scenario #1 or #2?

In general, what is the best way to secure an API?

Is the best way one of my scenarios?

Please feel free to add/remove items from the two scenarios, but also to add new and more secure scenarios.

答:
I would vote in favor #1, because I find it slightly easier to understand what's going on and control the behavior. We used this approach to build a fairly large enterprisey apps without too much fuss. It also is easily customizable, if needed (e.g. would 1 token per user suffice? Would you need multiple token if user simultaneously logs in from multiple devices?).
However, it depends - as always. Both are totally viable approaches, so basically whatever you're more comfortable with, if it has all the features you need when another one doesn't.

In our case #1 was easier to implement and covered all our needs, your case might be different... or not.


答:
If a null Client property is a supported state, consider using a NullObject.

But most likely this is an exceptional state, so you should make it impossible (or just not very convenient) to end up with a null Client:

```<code>public Client Client { get; private set; }

public Room(Client client)
{
    Client = client;
}

public void SetClient(Client client)
{
    if (client == null) throw new ArgumentNullException();
    Client = client;
}
</code>```

If it is not supported however, do not waste time on half baked solutions. In this case:

```<code>return Client == null ? 0 : Client.Id;
</code>```

You've 'solved' the NullReferenceException here but at a great cost! This would force all callers of Room.ClientId to check for 0:

```<code>var aRoom = new Room(aClient);
var clientId = aRoom.ClientId;
if (clientId == 0) RestartRoombookingWizard();
else ContinueRoombooking(clientid);
</code>```

Strange bugs can arize with other devs (or yourself!) forgetting to check the "ErrorCode" return value at some point in time.

Play it safe en fail fast. Allow the NullReferenceException to be thrown and "gracefully" catch it somewhere higher up the call stack instead of allowing the caller to mess things up even more...

On a different note, if you are so keen to expose the Client and also the ClientId think about TellDontAsk. If you ask too much from objects instead of telling them what you want to achieve, you may end coupling everything together, making change more difficult later on.

Body:
If a null Client property is a supported state, consider using a NullObject.

But most likely this is an exceptional state, so you should make it impossible (or just not very convenient) to end up with a null Client:

public Client Client { get; private set; }

public Room(Client client)
{
    Client = client;
}

public void SetClient(Client client)
{
    if (client == null) throw new ArgumentNullException();
    Client = client;
}

If it is not supported however, do not waste time on half baked solutions. In this case:

return Client == null ? 0 : Client.Id;

You've 'solved' the NullReferenceException here but at a great cost! This would force all callers of Room.ClientId to check for 0:

var aRoom = new Room(aClient);
var clientId = aRoom.ClientId;
if (clientId == 0) RestartRoombookingWizard();
else ContinueRoombooking(clientid);

Strange bugs can arize with other devs (or yourself!) forgetting to check the "ErrorCode" return value at some point in time.

Play it safe en fail fast. Allow the NullReferenceException to be thrown and "gracefully" catch it somewhere higher up the call stack instead of allowing the caller to mess things up even more...

On a different note, if you are so keen to expose the Client and also the ClientId think about TellDontAsk. If you ask too much from objects instead of telling them what you want to achieve, you may end coupling everything together, making change more difficult later on.


答:
So you have a 5 neatly separated components, which I suppose you can reuse later with different code. Yet you thinking of having a single interface shared between those components, which will provide a bunch of irrelevant config properties, e.g. we can assume that 80% of properties will not be relevant for each of the component.

Doesn't seem logical to me... does it to you?

@Doc Brown has a good point - having an interface for configuration is generally an overkill, unless you're actually having a complex configuration pulling from different data sources/doing some processing.


问:
Is **kwargs an antipattern?
We have a lot of code in our internal codebase that calls our libraries internally - these libraries often have a lot of arguments (think matplotlib) and our code is often doing only a specific task and simply passes the **kwargs on to the next function called.

E.g.:

```<code>def our_method(dataframe, **kwargs):
    result = do_something_with_data(dataframe)
    external_module.draw(result, **kwargs)
</code>```

While **kwargs prevents us from repeating all the parameters in our method declaration, it also makes it extremely opaque which arguments are valid when calling our_method - I have to know which method is called, which I often don't want to know.

What is your take on this?

答:
How is your code used by developers? In other words, what exactly do they do to determine which arguments should be used and how?

If they rely on documentation automatically generated from your code, and the generator has no clue what to do with **kwargs, this is indeed problematic. Instead of finding the list of arguments and their meaning in the documentation, they have absolutely no information except the vague “it takes some arguments”.

This problem may probably be solved by documenting the method manually, replacing the documentation generated automatically. This requires extra work from the implementer of the method, but remember, code (and its documentation) is read much more frequently than it's written.

If code is their documentation, the developers who use the method with **kwargs need two additional steps: they need not only to look at the signature of the method, but also at its actual implementation, in order to find the other method it actually calls. Then, they need to go to this other method to finally find what they were looking for.

This doesn't involve a lot of effort, but still, the effort should be repeated, again and again. The worst part is that you can't help them by adding documentation: if you comment your method, listing the actual arguments, there is a big risk that the next version of the library your method calls will have different arguments, and your documentation will be outdated, since nobody will recall that it needs to be kept up to date.

My recommendation is to rely on **kwargs only for methods which have a reduced scope. Private methods (and by private in a context of Python, I mean methods starting by _) which are used in few places in the class are good candidates, for example. On the other hand, methods which are used by dozens of classes all over the code base are very bad candidates.

After all, it shouldn't take too much effort to rewrite the arguments of a method you call within the method you write. Hopefully, most methods don't take more than six to eight arguments, and if they do, ask yourself if you shouldn't be refactoring the code. In all cases:

Making arguments explicit within your method doesn't require a lot of effort,

You may want, later, to validate the arguments anyway (although if you rely only on this point to make arguments explicit, you violate YAGNI).

Title: Is **kwargs an antipattern?


问:
How do you approach transitive dependency conflicts that are only known at run-time?
How do you normally approach transitive dependency issues that occur at run-time in large software projects?

For the past three weeks, I have been trying to start a component of a large piece of software within another component of the software, but it intermittently dies due to transitive dependency issues that are only known at run-time.

By transitive dependency issues, I mean that certain dependencies of a given project's dependencies collide with other dependencies at run-time, causing instability, or instant failure.

There are hundreds, upon hundreds of dependencies in use, and there are approximately 50 sub-projects associated with the tool that are worked on in isolation by other teams, where all modules have deeply nested dependencies between each other. Nobody knows what all of the sub-projects are used for, given the scale, and complexity of the project.

In this situation, would you try to generate a visual representation of the DAG for each of the dependencies of the affected component, and attempt to determine where collisions may occur at run-time? I have no control over how dependencies are managed in other sub-projects, and cannot change any Java code that has been written by other developers

The solutions I've come up with only work for an hour, or two, and then they stop working due to changes in upstream components. An example of an upstream component is an artifact on which the project that I am working on is dependent on which is built at an earlier stage in the CI pipeline.

At other's requests, I am going to include information on what technology is being used, at the risk of having the question closed for providing too much information, or the body getting too long:

Maven is used for dependency management; and

Spring is used as a DI container;

Most of the dependency issues involve overlapping bean contexts as a result of the contexts of other modules being loaded at run-time

The product works properly, and there are smorgasbords of unit tests, and integration tests to elude to the functional correctness of the program

In general, I am looking for a language-agnostic approach to identifying ways of resolving dependency conflicts without enumerating through all possible combinations of a given project's dependencies.

I cannot re-architect the project, add additional quality gates, push for paradigm shifts across the company, or switch languages as a resolution.

答:
Consider this me just thinking out loud here.
Depending on requirements/time constraints I might consider this:

1) create a list of interfaces and their implementations (using reflection, if available)

2) create a sort of wrapper around your DI. When a DI is asked to provide concrete implementation, see if there's a DI rule already in place; if rule exists - just return what your DI provides; otherwise if there's a single implementation of an interface and you're able to create a instance - log, and return an instance; otherwise log and fail.

Depends on how involved you want to get, I guess, but eventually you just want to have a complete list of what requires what - this solution will eventually generate that list.

However, arguably this is a lot of work and is not reliable - what if you have an odd condition requiring certain dependency once in a blue moon?

What do you mean when you say "changes in upstream components" ?


问:
Should "special" roles exist in an ARO system?
Right now we're implementing a (honestly overly complex) role-based permissions system where users will be assigned to roles and those roles will be granted permissions on some combination of resources. Fairly traditional, and I think fairly straightforward to implement database-wise by linking a table of users with a table of roles linked to a table of permissions, which have a reference to the resource type they're a permission for and a simple bitmask identifying the CRUD permissions they've been granted.

That said, we've got two edge cases involved:

First, there are administrator users who have unique permissions which can't be granted to users. Some of these are specific features which don't really map nicely with database tables and resources and are specifically available only to administrator users

Second, since we're a multi-tenant system we have a group of in-house users who can access any database. While the tenant's users all sit within the same database as the tenant's data, these support users all sit in a separate database; otherwise they act as administrator users, occasionally with additional permissions specifically available only to them (again)

Normally the level of specificity required for these users makes me want to move the roles into the application code, but I can't do that because tenants need to be able to manage and assign their own roles, up to and including the creation of new administrators. What this boils down to is that users will likely end up having some combination of roles and attribute-based access control in place: roles for most users, attributes lookup for special cases. So basically hybridizing ARO and attribute-based access control.

My alternative solution here is to create hardcoded roles in the database, potentially reserving the first ~10 or so IDs in my roles table for "special" roles with hardcoded behaviour. Which also feels nasty.

Which approach should I take? Or better yet, is there an alternative approach I haven't thought of as yet?

答:
Preferable any type of user action should be controlled in the same way. Administrators as just users (don't tell them I said that :-)), just with a set different set of permissions.

Perhaps these permissions do not fit in the current permissions model because the model is only applied to basic database actions.

A permission system involves more. Any action that is not allowed by all users should be regulated by the permission system. That includes actions like being able to view or export data.

And if some user users may circumvent the application and directly access the database, any important change or access should be captured in audit data that cannot be modified by the same person.

A more complex system also includes the contents of the data. Sometimes a user may only perform a function on part of the data.

Storing permissions directly in the code seems a bad idea to me. It's not possible to change at runtime and you need extra care when making code changes to make sure the permissions are enforced in all situation.

I suggest looking at a permission system that covers all actions of all types of users in the same way.

That may involve having to change the system that needs to be controlled.


问:
Would combining enums with static strings in java be sloppy?
Currently my team has a number of constants defined as static final strings.  I want to be able to iterate over these strings as if they were an enum in one location, but everywhere else they are used just as constant strings.  The other developers do not want them as Enums because they don't want to have to add a .value to the enum every time they want to use the constants, feeling it's too verbose and thus cumbersome.

It seems like the easiest way to maintain the way others have done things while still getting the convenience of iterating (without getting into reflection) is to do both.  Have an enum, but in addition define a static final field which is set equal to the enum's value for each enum, so that others can choose to use the static string most of the time, but have the enum to fall back on when they want a true "Enum".

However, somehow this feels wrong to me, even though it meets the two desired needs.  Is there a better way of making these strings iterable?

答:
Yes.

Whether or not you need to use enums is a different story, but:

If you use both enums and String constants you will need a way to keep these values in synch in your code. The enums you are iterating over need to match the constants used by your peers. Maintaining this code is going to be difficult. Someone at some point is going to come along and change an enum and then not update your constant String values accordingly--or vice versa.

This is a good place where you can take advantage of methods in Enum objects, I have used this many times in the past. By explicitly providing the constant in the enum itself and using a method to return the constant from the enum, you are going to tie the enum's value and it's String representation together in the same place, making code maintenance much easier.

I think duplicating these values in your code is inevitably going to end up in diverging representations of what you really want.


问:
How does the Scrum Master participate in Daily Stand-Ups?
We have a professional Scrum Master consultant [*] who recently joined our project. Unfortunately, we don't know her name (she never introduced herself to us, she just came in one day and said "we are having a daily stand-up"), and she doesn't seem to do much else except chair a daily stand up meeting  - when I half-jokingly asked her to also give daily feedback in the meeting, she was quite affronted, saying it's the Scrum Master's job to "facilitate, not participate".

This seems fairly anti-Agile (having worked on other agile projects, where the teams were self directed), which is supposed to be egalitarian, but I am not sure about how it works in the Scrum Methodology. I suspect she doesn't do much all day, and that's the reason for her defensiveness on this issue.

Does the Scrum Master take part in the "yesterday, today, impediments" spiel during the stand-up meeting, or is their role to just chair ("facilitate") the meeting?

[*] We weren't actually told what her job is, we just assume, since she calls herself the Scrum Master

答:
Scrum Master do not give their status update, but they are there to facilitate the stand up meeting. Their role is to make sure meeting starts on time, everyone in the meeting gives their status updates within their time frame, take action when any team-member has roadblocks in completing their task.

FYI, we are using our daily stand up meeting online at http://www.standup.report which also allows our offshore team to participate and facilitate the meeting process by adding/modifying team-member's submitted tasks online.


问:
How to create a re-usable, command based messaging system
I am having trouble writing a simple command based system for a chatroom. I want users to be able to do chat actions such as

/j myChatRoom or /join myChatRoom

/w user12 Hello or /whisper user12 Hello

etc

I've spent a while and all I can come up with are crazy substring and indexof searches, trying to chop off pieces of the entire string and find a command and arguments. I feel like there could be a regex that could tell me if this string has one argument, for joining and leaving rooms, or two arguments, for private messages. I just can't think of a logical way.

答:
If it was me, I'd do something similar to the following, utilising split() and switch:

```<code>public void ProcessInput(string lineOfInput)
{
    string[] parts = lineOfInput.Split(' ');

    switch (parts[0])
    {
        case "/j":
        case "/join":
            JoinChannel(parts[1]);
            break;

        case "/w":
        case "/whisper":
            SendPM(parts);
            break;

        default:
            SendMessage(parts);
            break;
    }
}
</code>```

There's no reason to go overly complex here.

Body:
If it was me, I'd do something similar to the following, utilising split() and switch:

public void ProcessInput(string lineOfInput)
{
    string[] parts = lineOfInput.Split(' ');

    switch (parts[0])
    {
        case "/j":
        case "/join":
            JoinChannel(parts[1]);
            break;

        case "/w":
        case "/whisper":
            SendPM(parts);
            break;

        default:
            SendMessage(parts);
            break;
    }
}

There's no reason to go overly complex here.


问:
Single complex or multiple simple autoload functions
Using the spl_autoload_register(), should I use a single autoload function that contains all the logic to determine where the include files are or should I break each include grouping into it's own function with it's own logic to include the files for the called function?  As the places where include files may reside expands so too will the logic of a single function.  If I break it into multiple functions I can add functions as new groupings are added, but the functions will be copy/pastes of each other with minor alterations.

Currently I have a tool with a single registered autoload function that picks apart the class name and tries to predict where it is and then includes it.  Due to naming conventions for the project this has been pretty simple.

```<code>if has namespace
  if in template namespace look in Root\Templates
  else look in Root\Modules\Namespace
else
  look in Root\System
if file exists include
</code>```

But we are starting to include Interfaces and Traits into our codebase and it hurts me to include the type of a thing in it's name.  So we are looking at instead of a single autoload function that digs through the class name and looks for the file and has increasingly complex logic to it, we are looking at having multiple autoload functions registered.  But each one follows the same pattern and any time I see that I get paranoid about code copying.

```<code>function systemAutoloadFunc
  logic to create probable filename
  if filename exists in system include it and return true
  else return false

function moduleAutoloadFunc
  logic to create probable filename
  if filename exists in modules include it and return true
  else return false
</code>```

Every autoload function will follow that pattern and the last of each function if filename exists, include return true else return false is going to be identical code.  This makes me paranoid about having to update it later across the board if the file_exists include pattern we are using ever changes.  Or is it just that, paranoia and the multiple functions with some identical code is the best option?

答:
Registering multiple autoloaders lets you separate different naming conventions for directory and file names and will be easier to maintain in the long run.

Imagine needing to add or remove functionality for the autoloader. Should you need to dive into a monolithic function or simply tweak or add a smaller function?

Similar calls to "file_exists() / include() / return" can be put into a helper function instead of copypasting that code.

```<code>function autoload_attempt($path){
    if (file_exists($path)) {
        include $path;
        return true;
    } else return false;
}

spl_autoload_register(function($class){
    $path = ... naming logic ...
    return autoload_attempt($path);
});
</code>```

Registering different ones also gives you easier control over what order they are invoked. For example, if you want to have a master override directory, you would register that first.

From the manual: http://php.net/manual/en/function.spl-autoload-register.php

If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

Body:
Registering multiple autoloaders lets you separate different naming conventions for directory and file names and will be easier to maintain in the long run.

Imagine needing to add or remove functionality for the autoloader. Should you need to dive into a monolithic function or simply tweak or add a smaller function?

Similar calls to "file_exists() / include() / return" can be put into a helper function instead of copypasting that code.

function autoload_attempt($path){
    if (file_exists($path)) {
        include $path;
        return true;
    } else return false;
}

spl_autoload_register(function($class){
    $path = ... naming logic ...
    return autoload_attempt($path);
});

Registering different ones also gives you easier control over what order they are invoked. For example, if you want to have a master override directory, you would register that first.

From the manual: http://php.net/manual/en/function.spl-autoload-register.php

If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.


问:
Does ReaderWriterLockSlim provide thread safety and speed efficiency (compared to a traditional lock) when using a List?
I have a list, to which I write once in every update Loop and then I spawn some tasks which create read that List and create a duplicate to manipulate that data.
More or less it's List.ToList() call to create a new list instead of using it by reference. Each task manipulates that data in it's own and produces it's results.
Currently I am using a traditional lock in the form of

```<code>lock(LockObject){
//write stuff
}
</code>```

when writing and

```<code>lock(LockObject){
localList=List.ToList();
}
</code>```

when reading.

Would using the ReaderWriterLockSlim object instead of the way I am doing it now provide me with any benefits speed-wise? Also is the ToList() method considered a read in this case?

Clarification Edit

The readers create a copy because they manipulate the data
differently, each one of them removes or adds data to the List on
their own way. (some might add previous data they still need while
others remove data they do not need. Also the update loop occurs
once every few seconds so it is common.

Sometimes if the data input is really fast an update/write loop might start before all the readers have completed their processing (but if they get the updated data instead is no problem for me).

Basically the readers are there for presenting current data to
others. So if data is changed before they even start presenting them
that's ok. As long as they do not try to process data while they are
being update (which would probably throw an exception)

答:
It depends. Using a reader/writer lock rather than a critical section can be beneficial if read operations are noticeably more common than write operations. But I think you could probably achieve more by changing your application architecture.

If writes are rare, you can probably get much better performance by treating the collection as immutable and producing an entirely new list when it changes. You can then use Interlocked.CompareExchange to update the reference to the list in a thread-safe way. This should prevent readers needing to make a defensive copy (which should be a huge win if reading is more common than writing) and remove the need for locking.

Alternatively, if writing is more common than reading, it may be worth evaluating a ConcurrentStack as a replacement for the list. This provides an atomic ToArray method that can be used to make copies without needing locks. Alternatively, if order isn't important in your list, a ConcurrentBag may perform better.

Edit after clarification

I still think you would be better off copying the list when you modify it, as this allows you to do away with the lock entirely. Even if the readers need to change the list contents during processing, this would be better refactored to use a streaming style, e.g. LINQ to Objects, so that these operations do not actually duplicate the data. See Martin Fowler Refactoring with Loops and Collection Pipelines for more about converting existing code to this style.

Failing that, I imagine you'd see a small gain switching to the reader/writer lock, but unless lock contention is unusually problematic for your application I doubt it'll be noticeable.


问:
How to implement a property on class A which refers to a property of a child object of class A
We have this code which, when simplified, looks like this:

```<code>public class Room
{
    public Client Client { get; set; }

    public long ClientId
    {
        get
        {
            return Client == null ? 0 : Client.Id;
        }
    }
}

public class Client
{
    public long Id { get; set; }
}
</code>```

Now we have three viewpoints.

1) This is good code because the Client property should always be set (i.e. not null) so the Client == null will never occur and the Id value 0 denotes a false Id anyway (this is the opinion of the writer of the code ;-))

2) You can not rely on the caller to know that 0 is a false value for Id and when the  Client property should always be set you should throw an exception in the get when the Client property happens to be null

3) When the Client property should always be set you just return Client.Id and let the code throw a NullRef exception when the Client property happens to be null.

Which of these is most correct? Or is there a fourth possibility?

答:
As of c# 6.0, which is now released, you should just do this,

```<code>public class Room
{
    public Room(Client client)
    {
        this.Client = client;
    }

    public Client Client { get; }
}

public class Client
{
    public Client(long id)
    {
        this.Id = id;
    }

    public long Id { get; }
}
</code>```

Raising a property of Client to Room is an obvious breach of encapsulation and the DRY principle.

If you need to access the Id of a Client of a Room you can do,

```<code>var clientId = room.Client?.Id;
</code>```

Note the use of the Null Conditional Operator, clientId will be an long?, if Client is null, clientId will be null, otherwise clientId will have the value of Client.Id.

Body:
As of c# 6.0, which is now released, you should just do this,

public class Room
{
    public Room(Client client)
    {
        this.Client = client;
    }

    public Client Client { get; }
}

public class Client
{
    public Client(long id)
    {
        this.Id = id;
    }

    public long Id { get; }
}

Raising a property of Client to Room is an obvious breach of encapsulation and the DRY principle.

If you need to access the Id of a Client of a Room you can do,

var clientId = room.Client?.Id;

Note the use of the Null Conditional Operator, clientId will be an long?, if Client is null, clientId will be null, otherwise clientId will have the value of Client.Id.


问:
When estimating with a fresh team on a new project, is there a reason not to use default velocity for estimating?
Generally when estimating using an Agile points system on an experienced project team, the points have meaning relative based on past experience - that take into account:

understanding of the business domain

skill and experience of the team

obvious traps in the technical environment (service integrations and environment issues)

So based on the past velocity of the team - you can forecast how long a project is likely to take.

Now imagine a completely new team thrown into a new business problem domain, new technical environment, with unknown skill levels. You can estimate with points, but you have no velocity track record.

Now you can augment this lack of historic velocity with a 'default velocity' - with the caveats that the three factors above are unknown, and so your tolerance for delivery date is much higher.

But is there an agile reason not to do this?

My question is: When estimating with a fresh team on a new project, is there a reason not to use default velocity for estimating?

答:
Yes there is a reason - because a default velocity is meaningless.

The velocity is the speed at which your team can progress tasks, but that measure is created by using the sped at which your team has completed tasks. That's the only way of calculating a velocity.

So by using a default one, you might as well stick your finger in the air and say "finished by Tuesday", or "107534 points per sprint".

You start off with a blank velocity and work out what it is as you go. By the end of the project you'll know what the velocity of your team is. Unfortunately, until the end of the project that velocity value will just be an estimate that gets progressively more accurate (ie you start off with a wildly wrong number, and it gets closer and closer to reality after each sprint)


答:
I want to be able to iterate over these strings as if they were an enum in one location, but everywhere else they are used just as constant strings.

So define a list (or vector or array), load the necessary items into it and iterate over that.

If you really only need it in one location, define and load it there.  If there's a chance that you might want to use it again then define it alongside the static String values.

Title: Would combining enums with static strings in java be sloppy?

Body:
Currently my team has a number of constants defined as static final strings.  I want to be able to iterate over these strings as if they were an enum in one location, but everywhere else they are used just as constant strings.  The other developers do not want them as Enums because they don't want to have to add a .value to the enum every time they want to use the constants, feeling it's too verbose and thus cumbersome.

It seems like the easiest way to maintain the way others have done things while still getting the convenience of iterating (without getting into reflection) is to do both.  Have an enum, but in addition define a static final field which is set equal to the enum's value for each enum, so that others can choose to use the static string most of the time, but have the enum to fall back on when they want a true "Enum".

However, somehow this feels wrong to me, even though it meets the two desired needs.  Is there a better way of making these strings iterable?


问:
Pattern for passing in a field as a parameter
I'm writing a Rails app which uses ActiveRecord ORM and a Postgres DB. I've got two attributes which are similar but are separate fields in the database. The assignment and saving of these is kinda complicated so I've put that side of things in their own method. The pseudo-code is as follows

```<code>myObject.attr_a = get_the_stuff_from( ref_one )
myObject.attr_b = get_the_stuff_from( ref_two )

myObject.assign_and_save( attr_a )
myObject.assign_and_save( attr_b )
</code>```

Basically, how can I tell the assign_and_save method to distinguish between attr_a and attr_b so that they get saved into their respective columns in the database. I was thinking of using an additional flag for the method signature, but I think that stunts its re-usability.

What would you recommend?

答:
Given that you're using Rails, the most common way to achieve what you're trying to do is to use a before_save or before_create ActiveRecord callback.

```<code>class Model < AR::Base
  before_save :normalize_attributes

  private

  def normalize_attributes
    # Whatever logic you need
  end
end

my_object.attr_a = get_the_stuff_from(ref_one)
my_object.attr_b = get_the_stuff_from(ref_two)
my_object.save
</code>```

Depending on your logic, maybe get_the_stuff_from is better located in the model itself, so you might prefer something like:

```<code>class Model < AR::Base

  def set_attributes(stuff_for_a: nil, stuff_for_b: nil)
    # Something like, depending on your logic:
    self.a ||= get_the_stuff_from(stuff_for_a)
    self.b ||= get_the_stuff_from(stuff_for_b)
  end

  private

  def get_the_stuff_from(ref)
    # Whatever logic you need
  end
end

# Either
my_object.set_attributes(stuff_for_a: ref_one)
my_object.set_attributes(stuff_for_b: ref_two)

# Or
my_object.set_attributes(stuff_for_a: ref_one,
                         stuff_for_b: ref_two)

my_object.save
</code>```

But I don't know enough of your logic to say if the ||= is enough, but hopefully this will help.

Body:
Given that you're using Rails, the most common way to achieve what you're trying to do is to use a before_save or before_create ActiveRecord callback.

class Model < AR::Base
  before_save :normalize_attributes

  private

  def normalize_attributes
    # Whatever logic you need
  end
end

my_object.attr_a = get_the_stuff_from(ref_one)
my_object.attr_b = get_the_stuff_from(ref_two)
my_object.save

Depending on your logic, maybe get_the_stuff_from is better located in the model itself, so you might prefer something like:

class Model < AR::Base

  def set_attributes(stuff_for_a: nil, stuff_for_b: nil)
    # Something like, depending on your logic:
    self.a ||= get_the_stuff_from(stuff_for_a)
    self.b ||= get_the_stuff_from(stuff_for_b)
  end

  private

  def get_the_stuff_from(ref)
    # Whatever logic you need
  end
end

# Either
my_object.set_attributes(stuff_for_a: ref_one)
my_object.set_attributes(stuff_for_b: ref_two)

# Or
my_object.set_attributes(stuff_for_a: ref_one,
                         stuff_for_b: ref_two)

my_object.save

But I don't know enough of your logic to say if the ||= is enough, but hopefully this will help.


答:
Functional programming languages consist only of expressions, so most have had a feature like this from essentially the beginning.  You use it when you have a relatively short, often frequently repeated, expression that can be replaced by an even shorter, much more meaningful name.

A common example would be predicates that are used elsewhere, like:

```<code>public static bool isOdd(int num) => (num % 2) == 1;
</code>```

If the expression is too long, it's better to split it up into separate functions or perhaps one function with named intermediate results.  If it's short, but you can't think of a good name, you're better off just copying the expression rather than creating a terrible name like condition1 or something.

Title: When is it appropriate to use expression bodied members?

Body:
C# 6 introduces expression-bodied members, which allow for simplified code in methods and properties that only return the result of an expression:

```<code>public override string ToString()
{
     return string.Format("{0} {1}", _field1, _field2);
}
</code>```

becomes:

```<code>public override string ToString() =>
    string.Format("{0} {1}", _field1, _field2);
</code>```

Since we now have two exactly equivalent and valid syntaxes, some rule of thumb must be used to decide which to use. When is the new alternative appropriate?

Body:
Functional programming languages consist only of expressions, so most have had a feature like this from essentially the beginning.  You use it when you have a relatively short, often frequently repeated, expression that can be replaced by an even shorter, much more meaningful name.

A common example would be predicates that are used elsewhere, like:

public static bool isOdd(int num) => (num % 2) == 1;

If the expression is too long, it's better to split it up into separate functions or perhaps one function with named intermediate results.  If it's short, but you can't think of a good name, you're better off just copying the expression rather than creating a terrible name like condition1 or something.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
The use of the synchronized keyword in Java.

Not that there is anything wrong with using synchronized when it is used right. But in the code I work with, it seems that every time someone tries to write threadsafe code, they get it wrong. So I know that if I see this keyword, I have to be extra carefull about the reste of the code ...