S in SOLID - how/where do you draw the line? [closed] - solid-principles

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
So, single responsibility principle - class should change for one and only one reason but how do you effectively judge what that responsibility really is. Simple example:
public class UserManager
{
public void AddUser() { }
public void RemoveUser() { }
public void UpdateUser() { }
}
It can be argued that that any one of these would break SRP. So you end up using DI for two of them and end up with this:
public class UserManager
{
private UserRemover _remover;
private UserUpdater _updater;
public UserManager(UserRemover remover, UserUpdated updater)
{
_remover = remover;
_updater = updater;
}
public void AddUser() { }
public void RemoveUser() { }
public void UpdateUser() { }
}
What if there are more methods pertaining to user management? Would go down that road and keep on passing additional dependencies in a constructor? For any class having more than one public method it can be argued that it breaks SRP. Do you use common sense and go with option one or be purist and go with option two?

Single Responsibility Principle
A. What is the responsibility of UserManager?
What do you do when you update a User?
What do you do when you remove a User?
What do you do when you add a User?
If the methods are plain simple, they don't do MORE than to update a user in a DB. Than the responsibility of UserManager may be UserRepository, perhaps.
Or Maybe the responsibility of UserManager would be more like of a list of users. If you look at List object. Does it use many other sub classes? no. If this is your situation, you should rename UserManager the UserList object.
The main reason why you are unsure about the SRP principle in this situation is because the word MANAGER doesn't mean anything specific. Try to find a better name and you'll find your answer. It'll show up in the name if your class needs to access more specific objects.
Also, Your unit tests should help identifying the problem. Unit tests are a good way to reveal that kind of mystery.
Also, no purist would over architect that kind of problem ;) Remember, Premature Optimization is the root of all evils.

Related

What is the best way to create/save level data during runtime in Unity? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 months ago.
Improve this question
I am trying to make a mobile game where the player is allowed to create their own levels. At the moment the only data I am aiming to save for each level instance is the level name and author name.
I tried to get my head around scriptable objects as these instances of level data will not need to be attached to a gameobject/don't need to be a monobehaviour. But I am now extremely confused as to how one would persist these once they are created at runtime. There's not a lot of info out there about that and I see that serializing lists of scriptable objects using JsonUtility is barely talked about (so probably not something people do) and I have had trouble achieving successful serialization in this way.
In theory I could create a list of prefabs with monobehaviour scripts containing the data for each level and JSON serialize that, but that seems not very elegant and wasteful since I won't be instantiating these prefabs or monobehaviour scripts.
Would it be recommended that I don't use scriptable objects in this way for data persistence? What would be a better way to achieve this kind of save system?
"Best" will be subjective, but we can look at ScriptableObjects .. and then discard them for your purpose.
SO's have no inherit runtime serialisation mechanisms. For that reason, they'll be a burden to wrangle them to save player data. Not impossible, just cumbersome.
Your best bet is to do the serialisation yourself. Let's consider what a player might create a level with (as you didn't supply any of that info). We can assume prop type, a position, a rotation and a colour? That being the case, we could simply build out a little class (some like to call them POCOs for Plain Old Class Object).
public class Item
{
public string objectId {get;set;}
public Vector3 position {get;set;}
public Vector3 rotation {get;set;} // as a Euler rotation
public Color colour {get;set;}
}
Then to tie these together, you'd have a level container:
public class Level
{
public int levelNumber {get;set;}
public List<Item> items {get;set;}
}
Now, you might be saying "hold up, Unity won't serialise properties", and you'd be right. But here comes my suggest, use a different JSON serialiser. The JsonUtility JSON serialiser that Unity uses as pretty limited. For that reason, I'd use either Newtonsoft.Json or System.Text.Json (my preference). Both of those will be able to serialise properties. A benefit of System.Text.Json is that it's the one I use with Azure, so my classes and code don't need to be changed for the two environments, but that's just a benefit in that particular situation.
Now you've got your data structures. But you'd still need to decide what persistence mechanism you want to use. Save to local storage? To a web service and/or database? PlayerPrefs if you're using WebGL? Desktop is different to mobiles, WebGL can't store locally other than to "player prefs" which is implemented in the local datastore, and then there's pushing it to a remote server. So you'd need to then work out where you're going to save that data. The outdated option was to use binary serialisation. Security issues pushed that into the unsavory basket. JSON is plain text though, so needs to be run through an encryption service to make it secure if there's a chance the user could see and modify it.
We're now starting to get into a very broad area here. Because you might want to persist your data in one of a very many places, you'd have to be a bit more specific about where you'd like that to be.

Bulk-Insert to MySQL in Entity-Framework Core [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
I have a list consisting of ~10,000 objects (let's say of class Person) that I need to insert to a MySQL table. If I use the regular DbContext.SaveChanges(), it takes 60-70 seconds to issue, which I need to reduce drastically. I've found several extensions for bulk-insertions:
EF extensions (not free, so no option)
BulkExtensions (no MySQL, only SQL Server)
EFBulkInsert (no MySQL,only SQL Server)
...
Unfortunately, non seem to exist for MySQL databases. Does anybody know of one for MySQL? If not, could anyone give me an approach as to how I could make my own or adjust the aforementioned solutions? Thank you!
Z.EntityFramework.Extensions.EFCore is a paid solution that might help solve your problem.
It is has support for both .NET and .NET Core!
I stumbled upon the same situation as the person who asks this question, but the answers above are very unclear. Here's how you can implement bulk-insert in a .NET Core 3.1 application:
1.I added the following nuget package into my application: Z.EntityFramework.Extensions.EFCore
2.I added a parameterless constructor in my DataContext class like this:
public YourDataContextClass()
{
}
3.In your business logic where you have a list of objects and want to bulk insert:
EntityFrameworkManager.ContextFactory = _context => new YourDataContextClass();
_context.BulkInsert(lstObjects);
// no need to call SaveChanges() / SaveChangesAsync(). BulkInsert() / BulkInsertAsync()
// saves into DB itself
If you want to use async version then:
await _context.BulkInsertAsync(lstObjects, cancellationToken);
For more info on above points: https://entityframework-extensions.net/bulk-insert
What this line EntityFrameworkManager.ContextFactory = _context => new YourDataContextClass(); do?
As per their documentation:
The context factory is a function Func<DbContext, DbContext> that
provides the current DbContext as a parameter and require to return a
new DbContext. The current DbContext is passed in a parameter in case
you need to create a working context that depends on the current
context configuration or type.
For more information about it, follow this link:
https://entityframework-extensions.net/context-factory
Have you trying disabling traking inside the dbContext you may write:
ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

Dependency Injection - Is it ever a good idea to create instances in a class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Ever since I learned about Dependency Injection I am having hard time to decide whether something should be injected or created inside a class.
Consider the following sample that does not use DI:
class Car
{
private Wheels _wheels;
private Chasis _chasis;
private Fuel _fuel;
public Car()
{
_wheels = new Wheels();
_chasis = new Chasis();
_fuel = new Fuel();
}
public ExhaustGas Exhaust
{
get
{
return new ExhaustGas();
}
}
}
What of these instances, that are created inside the Car would you inject? If so how do you decide?
Here is my reasoning:
Fuel - Since fuel is obtained from external sources and I can definitely see reasons for the fuel to change, I'd add abstraction to it (IFuel) and inject it.
Wheels - Even though the wheels are part of the car, you can certainly change the wheels easily. So I say it should be injected as well.
Chasis - This one takes more thought. Chassis is a very essential part of the car so getting it as an external dependency seems a little weird. However, you can certainly run tests on the Chasis alone and the Car could be tested with a dummy (even though I am not sure whether it should). Should such an essential part of the object be injected?
ExhaustGas - This one is even harder. I could inject a factory that creates IExhaustGas on demand but I am not sure whether I should. Should I not inject this instance as factory because it is created on demand? If not, what should be my reasoning in this case?
I'd love to hear your opinion on the variables I presented here and a more generic reasoning on how you decide when to inject something and when not to.
As a rule of thumb, all external dependencies should be injected. The reason is simple: you want to be able to mock dependencies for testing and have the flexibility to substitute them later when necessary.
To deal with the complexity of injecting everything, there are several strategies. If you only want to inject a few things, make it optional:
class Foo {
private _bar
private _baz
public Foo(Bar bar = null, Baz baz = null) {
if (!bar) bar = new Bar;
if (!baz) baz = new Baz;
_bar = bar
_baz = baz
}
}
This still has all the advantages of dependency injection while avoiding the necessary instantiation madness.
Alternatively, use factories like CarDependencyFactory, which can instantiate all required dependencies in one class. Optionally make that optional too.
Dependency injection containers/managers/frameworks can help as well. The bottom line is though that you should inject everything, unless you are really really sure the dependency will never need to be replaced and it is okay to couple one piece of code to another.
Also see How Not To Kill Your Testability Using Statics.

Linq-to-sql datacontext class design question?

I'm using linq-to-sql in a web scenario only. I know it is recommended to always wrap the datacontext in a using but in a web scenario only, the kind of scenario I'm designing for, this is really not necessary because each page will spawn and die in very short time.
Given that background, I've looked at extended some of my linq-to-sql classes as such
public partial class aspnet_User
{
MainDataContext _dc = new MainDataContext();
public MainDataContext DataContext
{
get
{
return _dc;
}
set
{
_dc = value;
}
}
public static aspnet_User GetUser(Guid guid)
{
//Here I load the user and associated child tables.
//I set the datacontext for the aspnet_User with the local DC here
}
//_dc.SubmitChanges()
public SaveUser()
So, this is the design construct I've employed and it appears to work well for my case. Part of my problem is I'm using this built-in membership structure and trying to add to it which is easier then recreating my own but has certain limitations. Granted, the exact composition of interface to the object isn't ideal because some the functionality is stratified across the database tables, for better or worse.
My question is, for some of the child objects, such as aspnet_Membership, I've also extended that with its own DC. But, there is no mechanism yet for me to update all the childrens DC without setting each manually.
I'd like to see various design solutions that require a minimum of coding that could address this in a somewhat elegant way.
Also, any detailed and specific suggestions about the stratification of the objects might be appreciated. This could be a kill 2 bird with one stone.
You really should manipulate the Membership through the methods provided natively by the System.Web.Security.MembershipProvider classes. It's not advisable to manipulate the database tables in the ASP.NET Membership database directly.
If you want to wrap the System.Web.Security.MembershipProvider in your own custom class, that's fine; in fact, ASP.NET MVC does exactly that to make it easier to perform unit testing. But that's not really a DataContext, as such.

Enums in AS3 / Flash / Flex? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
One thing I really like about AS3 over AS2 is how much more compile-time type-checking it adds. However, it seems to be somewhat lacking in that there is no type-checked enumeration structure available. What's a good (best / accepted) way to do custom enumerated types in AS3?
your answer after the jump :-)
Enumerations with classes
Just wanted to share my way
I recently discovered that as3commons library has a good base helper class Enum for enums implemetation.
In order to be a true enum it needs to both:
Enforce type safety
Prevent rogue instances
Few of the simple solutions do both, and the base classes that do are overly complex IMO.
My current favourite is the following style - safe and simple, and shouldn't confuse anyone:
public final class FruitEnum {
private static const CREATE:Object = {};
public static const APPLE:FruitEnum = new FruitEnum(CREATE);
public static const ORANGE:FruitEnum = new FruitEnum(CREATE);
public static const BANANA:FruitEnum = new FruitEnum(CREATE);
public function FruitEnum(permission:Object) {
if (permission !== CREATE){
throw new Error("Enum cannot be instantiated from outside");
}
}
}
CAVEAT: I have seen rare circumstances where a variable initialisation reads an enum const before it set, but in those cases the problem applied equally to other const-based enum emulations.
I know, this is a little outdated and does not exactly answer your question, but you might wanna check out Haxe. You can also use it to generate AS3 for you, plus there are many other reasons to use it. But this'd really get off topic...