can we add such feature? synchronized(null) ==> i.e NO-OP

Paul Backus snarwin at gmail.com
Fri Aug 26 18:51:06 UTC 2022


On Friday, 26 August 2022 at 17:33:16 UTC, mw wrote:
> The following is the usage pattern I want:
>
> ```
> void foo(lots of params) {
>   Object lock = (a particular condition) ? realLock : null;
>
>   synchronized(lock) {
>     // lots of complex code block here
>   }
>
> }
> ```
>
> i.e depending on a a particular condition, the complex code 
> block either need to be sync-protected, or not needed.
>
> Method foo() has lots of params, I try to avoid refactor the 
> inner code block into a separate method.

I think the easiest way to do this is with a nested function:

```d
void foo(/* lots of params */) {
     Object lock = /* condition */ ? realLock : null;

     void innerBlock() {
         // lots of complex code here
     }

     if (lock)
         synchronized(lock) innerBlock();
     else
         innerBlock();
}
```

Since `innerBlock` has access to `foo`'s parameters via its 
context, you should not need to do any complicated refactoring.


More information about the Digitalmars-d mailing list