I have always wondered about this, especially in C/Java style languages. For exa
ID: 644202 • Letter: I
Question
I have always wondered about this, especially in C/Java style languages. For example, consider the first 3 lines of this C# code:
lock (serviceLock)
using (var client = new ServiceClient())
try
{
// Do something
client.DoSomething();
}
catch (System.ServiceModel.FaultException ex)
{
// Handle error
addLog(ex.ToString());
}
This usage has always seemed somewhat questionable to me. However, the alternative is not very practical either (3+ levels deep of indentation for a service call). Apart from pure aesthetics, is there any practical reason to add or not to add the extra brackets in this case?
Explanation / Answer
The lock and using blocks are for programmer convenience, but are not required. If you find less indented code easier to read. You can write the same thing using the non-code-block version of the same C# features.
Monitor.Enter(serviceLock);
var client = new ServiceClient();
try
{
client.DoSomething();
}
catch(FaultException ex)
{
addLog(ex.ToString());
}
finally
{
Monitor.Exit(serviceLock);
client.Dispose();
}
The above does the same thing, but there is no readability issue or confusion as to what it's doing.
The alternative approach is to use blocks and break everything into separate functions.
public function foo()
{
lock(serviceLock)
{
fooService();
}
}
private function fooService()
{
using(ServiceClient client = new ServiceClient())
{
fooClientTry(client);
}
}
private function fooClientTry(ServiceClient client)
{
try
{
fooClient(client);
}
catch(System.ServiceModel.FaultException ex)
{
addLog(ex.ToString());
}
}
private function fooClient(ServiceClient client)
{
// work....
}
I prefer the above approach. It looks like a lot more work/code but it's easier to maintain because each function performs a single task. When you get into multiple nested blocks this approach keeps everything only a few indentations.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.