OOAD Design for furniture and testing [closed] - 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 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..
}

Related

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

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?

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.

How does abstractions help in DRY?

When we search "Don't repeat yourself" on Wikipedia, the first sentence is:
In software engineering, don't repeat yourself (DRY) is a principle of
software development aimed at reducing repetition of software
patterns, replacing them with abstractions...
I know that abstractions in software engineering mean hiding implementation complexity of how the behaviors of an API are realized, but it seems that "abstractions" in this sentence is not what I know before. Could someone explain to me what abstraction means here? It would be better if you could give me an example.
I know that abstractions in software engineering mean hiding
implementation complexity of how the behaviors of an API are realized
Yes it means that (absstraction#wikipedia) and very same concept can also be leveraged to reduce repetitions! Or in other words, it can be used to practice DRY.
Let me try to explain that with an example. First I'll show non DRY code (without abstraction), then with use of abstraction I'd try to reduce repetitions.
Let's assume that you wanted to build an email view model based on application form details filled out by applicant and there is an email view class which consumes this emailViewModel to show all non-null details from application form. You could write it like in below example (first attempt)
public class ApplicationForm
{
public AddressDetail AddressDetail { get; set; }
public CustomerDetail CustomerDetail { get; set; }
public ProductDetail ProductDetail { get; set; }
}
public class EmailViewModel
{
public EmailViewModel(ApplicationForm applicationForm)
{
Address = GetAddressDetail(applicationForm.AddressDetail);
Customer = GetCustomerDetail(applicationForm.CustomerDetail);
Product = GetProductDetail(applicationForm.ProductDetail);
}
public string Address { get; set; }
public string Customer { get; set; }
public string Product { get; set; }
}
//view code assume razor view
#if(Model.Address!=null)
{
// method for showing address
}
#if(Model.Customer!=null)
{
// method for showing customer
}
//and other properties
I've kept above code quite simple; only three properties and haven't showed declaration for conversion methods. What if there were 50 properties! In this first approach it would be cumbersome changes that you'd be making in three places. Now I'll show you second example code of how you could create an interface (a way of abstraction) implement DRY.
interface IFormDetail
{
IFormDetailView GetDetail();
}
interface IFormDetailView
{
string ShowView();
}
public class ApplicationForm
{
public List<IFormDetail> FormDetails {get;set;}
}
public class EmailViewModel
{
public EmailViewModel(ApplicationForm applicationForm)
{
if(applicationForm.FormDetails!=null)
{
FormDetails = new List<IFormDetailView>();
foreach(var detail in applicationForm.FormDetails)
{
FormDetails.Add(detail.GetDetail());
}
}
}
public List<IFormDetailView> FormDetails { get; set; }
}
//view code assume razor view
#f(Model.FormDetails!=null)
{
foreach(var detail in Model.FormDetails){
detail.ShowView();
}
}
In this second code example , when you've a new property, you'll only make one change when a new application form property is created.
So while we are hiding complexity of how detail is presented etc., we are also leveraging it to reduce repetition.

Parsing machine-generated SQL in SQL Server [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 6 years ago.
Improve this question
Ninjas,
this is a little bit hard.
I have an application's audit database based on SQL Server 2012. Inside there is a table with NTEXT column that contains raw text of sql queries. The queries are machine-like generated and they're not 'human friendly' readable (column is up to 20000 chars long, has a lot of aliases etc).
I am looking for a tool that allows me to parse that sql queries texts and will list all the columns and tables that are used in the query.
Up to now we've tried to figure out the algorithm on our own. But maybe there is a ready tool that will do it automaticly.
Thanks in advance for your help
Kaspar_
Create a new C# project. NuGet package id="Microsoft.SqlServer.TransactSql.ScriptDom" version="13.0.1601.5" targetFramework="net46"
Then you can do all kinds of cool things. Here is some sample code to capture parse errors. You will want to use the Parser that corresponds to your version of SQL Server naturally.
using Microsoft.SqlServer.TransactSql.ScriptDom;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace <EnterNamespaceHere>
{
public class ParsingError
{
public ParsingError(ParseError error)
{
Number = error.Number;
Offset = error.Offset;
Line = error.Line;
Column = error.Column;
Message = error.Message;
}
public int Column { get; private set; }
public int Line { get; private set; }
public string Message { get; private set; }
public int Number { get; private set; }
public int Offset { get; private set; }
public override string ToString()
{
return $"Error {Number} at offset {Offset} ({Line},{Column}): '{Message}'";
}
}
public static class TSqlHelper
{
public static bool ParseSyntax(string sql,
out IEnumerable<ParsingError> reportedErrors)
{
TSqlParser parser = new TSql130Parser(true);
IList<ParseError> errors;
using (StringReader rdr = new StringReader(sql))
{
parser.Parse(rdr, out errors);
}
if (errors != null && errors.Count > 0)
{
reportedErrors = errors.Select(
pe => new ParsingError(pe));
return false;
}
reportedErrors = null;
return true;
}
}
}

add multiple datatype using collection in c#

In one of the interview question i asked below question,i would like to ask you the same as i failed to answer and still not getting clear idea on it
here is the code
public class Bike
{
public Bike() { }
public virtual string GetBikedetails()
{
return "This is General Bike";
}
}
public class Honda : Bike
{
public Honda() { }
public override string GetBikedetails()
{
return "This is Honda Bike";
}
}
public class Hero : Bike
{
public Hero() { }
public override string GetBikedetails()
{
return "This is Hero Bike";
}
}
Now following question was asked with reference to above code
1.Make three instance of the class present
2.add them in a collection
3.iterate in a collection to get the object individually
Please respond with your answer.
You have already everything in place. Need only to create a List of Bike and add the elements of the specific derived type.
List<Bike> myList = new List<Bike>();
Bike b = new Bike();
Honda h = new Honda();
Hero r = new Hero();
myList.Add(b);
myList.Add(h);
myList.Add(r);
foreach(var x in myList)
Console.WriteLine(x.GetBikedetails());