How to go about starting a method chain in Object Oriented Programming? [closed] - oop

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Imagine having two objects, A and B, and B is dependent on A. Now you need to first call a method on object A (let's say checkUpdates), and then call one on object B (relayInfo).
If OOP is your preferred approach is it best practice to
call A.checkUpdates() and then B.relayInfo() from B (or wherever)
OR call A.checkUpdates() which directly calls B.relayInfo() on a reference of B?
In short should you have these objects call methods on each other in a ping-pong-like manner, or should one of them (or a controller object) call methods sequentially for both of them?

Let the dependent object be responsible for this task
public class Main {
public static void main(String[] args) {
B b = new B(new A());
b.relayInfo();
}
}
class A {
void checkUpdates() {
System.out.println("checkUpdates()");
}
}
class B {
final A a;
B(A a) {
this.a = a;
}
void relayInfo() {
if (a == null) {
return;
}
a.checkUpdates();
System.out.println("relayInfo()");
}
}

Related

Deep Module vs SRP [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 6 months ago.
Improve this question
i have a message object that i can add content to. The message can also be sent. Is it better to provide a "deep module" that hides the dispatcher from the client, or is it better to have only one responsibility per class?
Example: expose the dispatcher
class Message {
void add(String key, String value) { ... }
}
class Dispatcher {
Result send(Message message) { ... }
}
class DispatcherFactory {
Dispatcher create() { return new DefaultDispatcher(); }
}
Example: Hide the dispatcher
class MessageFactory {
Message create() { return new Message(DefaultDispatcher()); }
}
class Message {
Message(Dispatcher dispatcher) { ... }
void add(String key, String value) { ... }
Result send() {
return dispatcher.dispatch(content);
}
}
In my opinion the latter is easier to use and also testable, but violates the SRP. Which one is better?
In my opinion the latter is easier to use and also testable, but violates the SRP
it does not violate SRP as implementation of Dispatcher class is located in Dispatcher class. If Message class would have implentation of Dispatcher class, then it will be violtion of SRP class.
Which one is better?
In my view, the second implementation is better if you can slightly modify your implementation of MessageFactory Mediator pattern.
Let me show an example:
class MessageFactory {
Message create(DefaultDispatcher defaultDispatcher)
{ return new Message(defaultDispatcher); }
}
UPDATE:
If you want to have relationship publisher and subscriber. I mean publisher send messages to subscribers, then you can use Observer pattern.
As wiki says about Observer pattern:
The observer pattern is a software design pattern in which an object,
named the subject, maintains a list of its dependents, called
observers, and notifies them automatically of any state changes,
usually by calling one of their methods.

Is a low number of members in a class considered a code smell? [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 currently making a simple to-do list program using the MVC pattern, and thus have a model class for the Notebook. However, something feels "off" as it has a very low number of members.
The Notebook is composed of categories, which are composed of To-do lists, which are composed of Items.
What I cannot place is whether this is a case poor analysis (e.g. there are more members and responsibilities I am just missing them..) or perhaps a code smell that the class is not needed (in that case I'm not sure what to do as I could just have a list of categories in that controller, but then I don't have a notebook entity modelled which seems wrong as well).
Below is the very simple class I have:
class Notebook
{
private String title;
private List<Category> categories;
public Notebook(String title, List<Category> categories)
{
}
public void setCategories(List<Category> categories)
{
}
public List<Category> getCategories()
{
}
}
I often have this issue where it feels like I am making classes for the sake of it and they have a very number of members/responsibilities, so it would be nice to know whether I am stressing for no reason or not.
Not necessarily, there is the concept in Domain Driven Design of what is called a "Standard Type". Which is really a basic primitive wrapped in an object class. The idea is that the primitive contains no information about what information it contains, it's just a string/int/whatever. So by having say an object that surrounds the primitive and ensures that it is always valid ensures that the object has a meaning far beyond just the primitive it contains e.g. a Name is not just a string, it's a Name.
Here's an example taken from the comments of Velocity
public class Velocity
{
private readonly decimal _velocityInKPH;
public static Velocity VelocityFromMPH(decimal mph)
{
return new Velocity(toKph(mph));
}
private Velocity(decimal kph)
{
this._velocityInKPH = kph;
}
public decimal Kph
{
get{ return this._velocityInKPH; }
}
public decimal Mph
{
get{ return toMph(this._velocityInKPH); }
}
// equals addition subtraction operators etc.
private static decimal ToMph(decimal kph){ // conversion code }
private static decimal ToKph(decimal mph){ // conversion code }
}

JDK and overriding? [duplicate]

This question already has answers here:
method overriding in Java
(6 answers)
Closed 9 years ago.
I've got a question about overriding methods. OK, we've got an OOP here, I can understand what result I'll got. But.. How does the jdk resolve, what implementation to use in each case?
public class One {
One() {
run();
}
public void run() {
System.out.println("One");
}
}
public class Two extends One {
#Override
public void run() {
System.out.println("Two");
}
}
public class Test {
public static void main(String[] args) {
One test = new Two();
}
}
I'm really sorry for not very good code listing, I was in a hurry. Changes added.
First of all the way the classes have been declared is wrong and also static menthods do not take part in overriding, because static methods are not bound to objects.
Java is going to look up the function in the vtable for Two. If it's not found, it'll look in the vtable for One. In this case, it's found (and directly noted with #Override), so it's used.
https://stackoverflow.com/a/1543311/431415
Basically, it's going to go from most specific to least specific, looking for a function that matches.

How to avoid circular reference OOAD design

I have Class structure like below, this below scenario will create a cyclic reference. How to avoid this situation?
public class classA
{
public classA()
{
classB b= new classB();
b.classBMethod();
}
public void classAMethod()
{
Console.WriteLine("Class A Method");
}
}
public class classB
{
public classB()
{
classC c = new classC();
c.classCMethod();
}
public void classBMethod()
{
Console.WriteLine("Class B Method");
}
}
public class classC
{
public classC()
{
classA a = new classA();
a.classAMethod();
}
public void classCMethod()
{
Console.WriteLine("Class C Method");
}
}
How to avoid circular reference? Please tell me different alternatives to design this
Your code does not have a circular reference problem.
Circular reference occurs when you start following references and end up where you started. In your case, what you do is declaring local variables and then you have:
new ClassA()-> (calls) -> new ClassB()->(calls)->new ClassC()->calls->new ClassA()-> (calls) -> new ClassB()->(calls)-> etc forever
The GC is smart enough to resolve circular references, but what you are doing is fundamentally flawed. Perhaps you should explain what you are trying to achieve instead.
This is creating a spiral data-structure to which there is no end.
However, the simplest way to solve this riddle and still be able to start with any class (A,B, or C), is to add a public boolean flag to the objects that determines if a cycle has occurred. If this flag is false you continue, if it is true you stop the cycle. If instead you are trying to create this spiral with no end, you may need to add an update method called once per frame to avoid an overload of operations in an instance.
I could give a less vague answer if I knew exactly what you were trying to create with this type of logic. I'm sorry if this was unclear.

how to create a DAL using petapoco [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
I need to create a DAL and repositories using petapoco. The difficulty that comes in, is that I dont know how it manages its connections.
If I was using dapper I know how the connection process flows because I control it. I don't know what are the best practices in creating a DAL with petapoco.
public class UserRepository
{
public IEnumerable<User> All()
{
var db = new PetaPoco.Database("Sqlite_Connection");//this line
var s = db.Query<User>("SELECT * FROM Users");
return s.ToList();
}
}
I would like to place var db = new PetaPoco.Database("Sqlite_Connection");//this line
in my DALHelper class as a static property but I'm worried about scalability
I don't recommend using a static since you can get errors like "There is already an open DataReader associated with this Command" because the same connection is used by different request accesing the same resource.
Two options:
1. Create the connection in a controller base class
public class BaseController : Controller
{
protected DatabaseWithMVCMiniProfiler _database;
protected override void OnActionExecuting(ActionExecutingContext filterCon )
{
base.OnActionExecuting( filterCon );
_database = new DatabaseWithMVCMiniProfiler( "MainConnectionString");
}
}
2. Static method creating one connection per request
public static class DbHelper {
public static Database CurrentDb() {
if (HttpContext.Current.Items["CurrentDb"] == null) {
var retval = new DatabaseWithMVCMiniProfiler("MainConnectionString");
HttpContext.Current.Items["CurrentDb"] = retval;
return retval;
}
return (Database)HttpContext.Current.Items["CurrentDb"];
}
}
A static property will be fine for the Initialization.
PetaPoco will open and close the connection each time, unless you are using a transaction. This isn't usually an issue due to connection pooling.
If you are using this in a web application then you should instantiate one PetaPoco database per request.