✅ Code improvement

Hey guys, just wondering if there's a better way to do the function i did.
14 Replies
Mąż Zuzanny Harmider Szczęście
if you want the code in some more readable space: https://paste.mod.gg/bgbysrsbzqco/0
BlazeBin - bgbysrsbzqco
A tool for sharing your source code with the world!
Angius
Angius3w ago
foreach (var config in Config.Tiles.BaseGeneration)
{
if (config.Value is ForegroundTileConfig fconfig)
{
if (fconfig.Max < tilesnapshot.Count(r => r.Tile.Type == config.Key))
{
if (config.Value.SpawnChance > Random.NextDouble())
{
var tl = tilesnapshot.OrderBy(r => Random.Next()).First();
if (fconfig.SpawnableOn.Contains(tl.Tile.Type))
{
if (tilesnapshot.Count(r => Tile.Collides(r.Tile, tl.Tile)) < 2)
{
await UpdateTileType(tl, config.Key);
transforms++;
}
}
}
}
}
}
foreach (var config in Config.Tiles.BaseGeneration)
{
if (config.Value is ForegroundTileConfig fconfig)
{
if (fconfig.Max < tilesnapshot.Count(r => r.Tile.Type == config.Key))
{
if (config.Value.SpawnChance > Random.NextDouble())
{
var tl = tilesnapshot.OrderBy(r => Random.Next()).First();
if (fconfig.SpawnableOn.Contains(tl.Tile.Type))
{
if (tilesnapshot.Count(r => Tile.Collides(r.Tile, tl.Tile)) < 2)
{
await UpdateTileType(tl, config.Key);
transforms++;
}
}
}
}
}
}
could certainly be improved. Generally, it's a good idea to reduce nesting and "fail fast", so rather than
while(true)
{
if (foo is 5)
{
if (bar is 6)
{
DoStuff()
}
}
}
while(true)
{
if (foo is 5)
{
if (bar is 6)
{
DoStuff()
}
}
}
I would write
while(true)
{
if (foo is not 5) continue;
if (bar is not 6) continue;
DoStuff();
}
while(true)
{
if (foo is not 5) continue;
if (bar is not 6) continue;
DoStuff();
}
Angius
Angius3w ago
tilesnapshot.OrderBy(r => Random.Next()).First()
tilesnapshot.OrderBy(r => Random.Next()).First()
could also be made more performant by using
tilesnapshot[Random.Next(0, tilesnapshot.Count)]
tilesnapshot[Random.Next(0, tilesnapshot.Count)]
Instead of sorting the whole collection just get the item at random index Besides that, it seems fine I'm not familiar with Unity enough to tell whether stuff like using the lock instead of some concurrent collection is a good choice
Mąż Zuzanny Harmider Szczęście
not unity, wpf
Angius
Angius3w ago
Ah, huh, that Random threw me off Unity has static methods on Random class, while in C# you need an instance, and static methods are on Random.Shared instead
Mąż Zuzanny Harmider Szczęście
public Random Random = new Random();
public Random Random = new Random();
Angius
Angius3w ago
Ah lol
Mąż Zuzanny Harmider Szczęście
wanna see the whole code to see where i could improve ?
Angius
Angius3w ago
You could post a Github link to #code-review
Mąż Zuzanny Harmider Szczęście
id have to post it on gh
Angius
Angius3w ago
It's a good idea to keep your code there anyway
Mąż Zuzanny Harmider Szczęście
i was going to do that, just later ok, posting it on #code-review

Did you find this page helpful?