Is using Abstract classes to map common JSON fields a bad practice? - oop

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 7 hours ago.
Improve this question
I'm implementing some input data validators in my app and I ended up with an Abstract class containing common props that are mapped to JSON. I also created abstract and virtual methods to force derived classes to always keep the same validation algorithm pattern. I have not followed any Design Pattern and because of it I would like to know your opinion about my code.
My abstract class is something like that:
public abstract class DataValidation
{
[JsonProperty("cleaned")]
public string CleanedInput => _cleanedInput;
[JsonProperty("isValid")]
public bool IsValid => _isValid;
protected string _cleanedInput;
private bool _isValid;
public DataValidation(string input)
{
_cleanedInput = CleanInput(input);
_isValid = ValidateInput(_cleanedInput);
}
protected abstract bool ValidateData(string cleanedInput);
protected virtual string CleanInput(string input) => input.Trim();
}
And some derived classes where I perform validations like birth date or documents format:
public sealed class ClassA : DataValidation
{
public ClassA(string input) : base(input)
{
}
protected override bool ValidateData(string input)
{
// ... Logic to validate input.
// Returns true as an example.
return true;
}
}
And another class that overrides CleanInput method and returns invalid validation:
public sealed class ClassB : DataValidation
{
public ClassB(string input) : base(input)
{
}
protected override string CleanInput(string input) =>
return input.Trim().Replace(".", "").Replace("-", "");
protected override bool ValidateData(string input)
{
// ... Logic to validate input.
// Returns false as an example.
return false;
}
}
Finally, I serialize these objects and have a json like that:
// ClassA
{
"cleaned": "inputA_cleaned",
"isValid": true
}
// ClassB
{
"cleaned": "inputB_cleaned",
"isValid": false
}
What I did is considered to be a good or bad practice?

Related

Better strategy than constructor injection or not? [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 3 years ago.
Improve this question
I am new to .NET Core, as far as I learned from Microsoft docs, we register services in Startup.ConfigureServices and inject them into classes through the constructors.
Something like the code below
Startup
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICar, Car>();
services.AddScoped<IPeople, People>();
}
}
Controller
public class CarController : ControllerBase
{
private readonly ICar _car;
private readonly IPeople _people;
public CarController(ICar car, IPeople people)
{
_car = car;
_people = people;
}
[HttpGet]
public ActionResult Get()
{
var result = _people.Talk() + _car.Run();
return Ok(result);
}
}
But one of my colleagues uses another strategy to achieve the injection, according to what he said, we could write less lines and the injection only happens when we invoke the properties.
(Sorry, I can't tell what is the name of this strategy.)
Startup (same as above)
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICar, Car>();
services.AddScoped<IPeople, People>();
}
}
Controller
public class CarController : ControllerBase
{
private readonly IServiceProvider _serviceProvider;
private ICar Car => _serviceProvider.GetRequiredService<ICar>();
private IPeople People => _serviceProvider.GetRequiredService<IPeople>();
public CarController(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
[HttpGet]
public ActionResult Get()
{
var result = People.Talk() + Car.Run();
return Ok(result);
}
}
I am not sure is this correct or not.
Can someone point out the pros and cons between these two strategies?
Thank you.
This is way too close to a service locator , for which there are many (good) reasons not to use.
I can see some specific problems with the second solution. The first being that if the resource is registered as transient (services.AddTransient<ICar, Car>();), then each call of the property will return a new instance. This might be too surprising a behavior to expect from a property.
Next problem is a performance. Calling GetRequiredService is not free. And calling it each time a property is accessed might cause performance issues.
Both could be solved by getting the services in the constructor, like this :
private ICar Car;
private IPeople People;
public CarController(IServiceProvider serviceProvider)
{
Car = serviceProvider.GetRequiredService<ICar>();
People = serviceProvider.GetRequiredService<IPeople>();
}
But that still doesn't solve the problem of service locator, like it not being clear what dependencies a class is using and tying the class to the specific IoC provider. And really, you can save yourself the work and just declare the dependencies in the constructor at this point.

OOAD Design for furniture and testing [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 8 years ago.
Improve this question
This question was asked in a interview.
A furniture can be made of one or more material. There are various furniture types like chair, table, sofa etc.
A furniture test is dependent on material & furniture type. Few tests are choakable, fire resistable, WithStands100KgWeight etc
Design this in OOAD. The design should follow Open Close principle and should be optimistic such that in future if new furniture is added, it should not need more code change.
Initially suggested with
class Furniture{
List<Material> materials;
boolean supportsTest(Test test);
}
class Chair extends Furniture{
boolean supportsTest(Test test){
// check material and based on type return true/false
}
Interviewer said that a furniture is a furniture, it should not say that it supports this test or not. Any alternative solution? Thanks.
Based on your description and the interviewer's comment, this is what comes to my mind:
// An interface so that it's separate from Furniture class
interface FurnitureTest {
bool IsSupportedBy(Furniture furniture);
}
// Sample test, can add as many as you like
class FireResistable : FurnitureTest {
public bool IsSupportedBy(Furniture furniture) {
return furniture.Type.Name == ! "Mirror" && /* just to use the Type property */
!furniture.HasMaterial(x => x == "Wood");
}
}
///
/// Other class definitions.
///
// Open to extension
class Chair : Furniture { /* additional properties */ }
class Table : Furniture { /* additional properties */ }
// Closed to modification
class Furniture {
public FurnitureType FurnitureType { get; private set; }
private IList<Material> materials;
public Furniture(FurnitureType type, IList<Material> materials) {
this.materials = materials;
}
public bool HasMaterial(string materialName) {
return materials.Any(x => x.Name == materialName);
}
}
class FurnitureType {
public string Name { get; set; }
// ...other properties
}
class Material {
public string Name { get; set; }
// other properties..
}

ninject binding for specify class

if I have the interface interfaceA
public interface IInterfaceA
{
void MethodA();
void MethodB();
}
and I have the classA
class ClassA:IInterfaceA
{
public void MethodA()
{
}
public void MethodB()
{
}
}
it's ok that I use ninject's bind,but when it comes that I have a method that called MethodC,I think the method should only exists in classA(just for classA) and should not be defined in InterfaceA,so how to use ninject'bind when just calling like this:
var a = _kernel.get<IInterfaceA>()
should I convert the result into ClassA ? (is that a bad habbit?) or there are another solution
Usually this is needed when you want interface separation but need both interfaces to be implemented by the same object since it holds data relevant to both interfaces. If that is not the case you would be able to separate interfaces and implementation completely - and then you should do so.
For simplicitys sake i'm going to asume Singleton Scope, but you could also use any other scope.
Create two interfaces instead:
public interface IInterfaceA {
{
void MethodA();
}
public interface IInterfaceC {
void MethodC();
}
public class SomeClass : IInterfaceA, IInterfaceC {
....
}
IBindingRoot.Bind<IInterfaceA, IInterfaceB>().To<SomeClass>()
.InSingletonScope();
var instanceOfA = IResolutionRoot.Get<IInterfaceA>();
var instanceOfB = IResolutionRoot.Get<IInterfaceB>();
instanceOfA.Should().Be(instanceOfB);
Does this answer your question?

design pattern query

i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.

Ninject, Generic Referential Bindings

I think this falls under the concept of contextual binding, but the Ninject documentation, while very thorough, does not have any examples close enough to my current situation for me to really be certain. I'm still pretty confused.
I basically have classes that represent parameter structures for queries. For instance..
class CurrentUser {
string Email { get; set; }
}
And then an interface that represents its database retrieval (in the data layer)
class CurrentUserQuery : IQueryFor<CurrentUser> {
public CurrentUserQuery(ISession session) {
this.session = session;
}
public Member ExecuteQuery(CurrentUser parameters) {
var member = session.Query<Member>().Where(n => n.Email == CurrentUser.Email);
// validation logic
return member;
}
}
Now then, what I want to do is to establish a simple class that can take a given object and from it get the IQueryFor<T> class, construct it from my Ninject.IKernel (constructor parameter), and perform the ExecuteQuery method on it, passing through the given object.
The only way I have been able to do this was to basically do the following...
Bind<IQueryFor<CurrentUser>>().To<CurrentUserQuery>();
This solves the problem for that one query. But I anticipate there will be a great number of queries... so this method will become not only tedious, but also very prone to redundancy.
I was wondering if there is an inherit way in Ninject to incorporate this kind of behavior.
:-
In the end, my (ideal) way of using this would be ...
class HomeController : Controller {
public HomeController(ITransit transit) {
// injection of the transit service
}
public ActionResult CurrentMember() {
var member = transit.Send(new CurrentUser{ Email = User.Identity.Name });
}
}
Obviously that's not going to work right, since the Send method has no way of knowing the return type.
I've been dissecting Rhino Service Bus extensively and project Alexandria to try and make my light, light, lightweight implementation.
Update
I have been able to get a fairly desired result using .NET 4.0 dynamic objects, such as the following...
dynamic Send<T>(object message);
And then declaring my interface...
public interface IQueryFor<T,K>
{
K Execute(T message);
}
And then its use ...
public class TestCurrentMember
{
public string Email { get; set; }
}
public class TestCurrentMemberQuery : IConsumerFor<TestCurrentMember, Member>
{
private readonly ISession session;
public TestCurrentMemberQuery(ISession session) {
this.session = session;
}
public Member Execute(TestCurrentMember user)
{
// query the session for the current member
var member = session.Query<Member>()
.Where(n => n.Email == user.Email).SingleOrDefault();
return member;
}
}
And then in my Controller...
var member = Transit.Send<TestCurrentMemberQuery>(
new TestCurrentMember {
Email = User.Identity.Name
}
);
effectively using the <T> as my 'Hey, This is what implements the query parameters!'. It does work, but I feel pretty uncomfortable with it. Is this an inappropriate use of the dynamic function of .NET 4.0? Or is this more the reason why it exists in the first place?
Update (2)
For the sake of consistency and keeping this post relative to just the initial question, I'm opening up a different question for the dynamic issue.
Yes, you should be able to handle this with Ninject Conventions. I am just learning the Conventions part of Ninject, and the documentation is sparse; however, the source code for the Conventions extension is quite light and easy to read/navigate, also Remo Gloor is very helpful both here and on the mailing list.
The first thing I would try is a GenericBindingGenerator (changing the filters and scope as needed for your application):
internal class YourModule : NinjectModule
{
public override void Load()
{
Kernel.Scan(a => {
a.From(System.Reflection.Assembly.GetExecutingAssembly());
a.InTransientScope();
a.BindWith(new GenericBindingGenerator(typeof(IQueryFor<>)));
});
}
}
The heart of any BindingGenerator is this interface:
public interface IBindingGenerator
{
void Process(Type type, Func<IContext, object> scopeCallback, IKernel kernel);
}
The Default Binding Generator simply checks if the name of the class matches the name of the interface:
public void Process(Type type, Func<IContext, object> scopeCallback, IKernel kernel)
{
if (!type.IsInterface && !type.IsAbstract)
{
Type service = type.GetInterface("I" + type.Name, false);
if (service != null)
{
kernel.Bind(service).To(type).InScope(scopeCallback);
}
}
}
The GenericBindingGenerator takes a type as a constructor argument, and checks interfaces on classes scanned to see if the Generic definitions of those interfaces match the type passed into the constructor:
public GenericBindingGenerator(Type contractType)
{
if (!contractType.IsGenericType && !contractType.ContainsGenericParameters)
{
throw new ArgumentException("The contract must be an open generic type.", "contractType");
}
this._contractType = contractType;
}
public void Process(Type type, Func<IContext, object> scopeCallback, IKernel kernel)
{
Type service = this.ResolveClosingInterface(type);
if (service != null)
{
kernel.Bind(service).To(type).InScope(scopeCallback);
}
}
public Type ResolveClosingInterface(Type targetType)
{
if (!targetType.IsInterface && !targetType.IsAbstract)
{
do
{
foreach (Type type in targetType.GetInterfaces())
{
if (type.IsGenericType && (type.GetGenericTypeDefinition() == this._contractType))
{
return type;
}
}
targetType = targetType.BaseType;
}
while (targetType != TypeOfObject);
}
return null;
}
So, when the Conventions extension scans the class CurrentUserQuery it will see the interface IQueryFor<CurrentUser>. The generic definition of that interface is IQueryFor<>, so it will match and that type should get registered for that interface.
Lastly, there is a RegexBindingGenerator. It tries to match interfaces of the classes scanned to a Regex given as a constructor argument. If you want to see the details of how that operates, you should be able to peruse the source code for it now.
Also, you should be able to write any implementation of IBindingGenerator that you may need, as the contract is quite simple.