下面两个函数中最专业的代码风格是什么?
如果函数变得更复杂和更大(例如有 20 个检查)怎么办?
注意:我需要在每次检查后做一些事情,所以我不能将所有内容连接到一个 if 语句中,例如:
if (vehicle.isBus) && (vehicle.numberOfWheels == 6) && (vehicle.motorVersion == 2019)
//first alternative
public bool validate(Vehicle vehicle)
{
if(vehicle.isBus)
{
//do some stuff here related to vehicle.isBus
if (vehicle.numberOfWheels == 6)
{
//do some stuff here related to vehicle.numberOfWheels
if (vehicle.motorVersion == 2019)
{
//do some stuff here related to vehicle.motorVersion
return true;
}
}
}
return false;
}
//second alternative
public bool validate(Vehicle vehicle)
{
if (!vehicle.isBus)
{
return false;
}
//do some …Run Code Online (Sandbox Code Playgroud) 我对在后台队列上运行 CoreData 代码有一些困惑。
我们可以使用一些方法使用 NSManagedObjectContext 在后台线程上执行 CoreData 代码。
viewContext.perform { /*some code will run on the background thread*/ }
viewContext.performAndWait{ /*some code will run on the background thread*/ }
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么我应该使用这些函数而不是使用普通方式使用 DispatchQueue 在后台线程上运行一些代码
DispatchQueue.global(qos: .background).async {
/*some code will run on the background thread*/
}
Run Code Online (Sandbox Code Playgroud)