Deep Module vs SRP [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 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.

Related

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 }
}

OO Design Principle - Open Closed Principle

I have a Layout Manager Class and this class designed for setting datagrid layout.
Code:
class LayoutManager
{
private object _target;
public LayoutManager(object aDataGrid)
{
_target = aDataGrid;
}
public void SaveLayout(string strProfileID)
{
}
public void LoadLayout(string strProfileID)
{
}
//in future I might add below function
public void ResetLayout()//OtherFunction0
{
}
public void OtherFunction1()
{
}
public void OtherFunction2()
{
}
}
According to OCP "a Class should be open for extension, but closed for modification". If I add the new function in LayoutManager Class, is this action violate the OCP? If yes, what is the proper way to design the class?
I don't think that adding methods to a class in general violates the OCP prinicple,
as this in fact extends the class's behviour.
The problem is if you change existing behaviours.
So that if the code on your added methods might change the behaviour of the existing methods
(because it changes the object's state) that would be a violation.
The correct way to follow the SOLID principals, is to make an interface:
ILayoutManager with the interfaces you want , with documented behaviours.
The class LayoutManager would implement this interface.
Other new methods might be added in a new interface, say ILayoutFoo or added to the existing interface, as long as they won't break the contract of the documented behaviour in the existing methods.
It's not possible to directly answer this without some concrete code.
Generally speaking though, the upshot of the OCP is that when classes derive from your base class and then override methods, the internal invariants shouldn't break because that's modification. There shouldn't be any way for the derived class to change those parts of the class' behaviour. The derived classes can change behaviour or add new functionality by using the parts exposed by the base class.
Whenever we speak about Open-Closed Principle, one important issue comes into play, which is called Strategic Closure.
It should be clear that no significant program can be 100% closed. In general, no matter how “closed” a module is, there will always be some kind of change against which it is not closed. Since closure cannot be complete, it must be strategic. That is, the designer must choose the kinds of changes against which to close his design. This takes a certain amount of prescience derived from experience. The experienced designer knows the users and the industry well enough to judge the probability of different kinds of changes. He then makes sure that the open-closed principle is invoked for the most probable changes.
For example in famous sample of Shape class you just grantee that your program (in side of Client and Shape)just is closed for modification about adding new shape.
public class Shape {
public draw() {
}
}
public class Circle extends Shape {
#Override
public void draw() {
// implementation special to Circle
}
}
public class Client {
...
public drawMyShape(Shape shape) {
shape.draw();
}
...
}
According to this Strategy, when you are designing your program, you should make a decision about the sections that you want to be closed to changes. Therefore, in your example, when you were designing your program, if you decided that your entity (in this case it is GraphCalculator class) should be closed for modification and open to extension regarding to adding new functionality, adding new function in this example violates Open-Closed Principle, due to the fact that it changes implementation in side of client and GraphCalculator class. And solution can be using abstraction, which is mentioned in previous answers.

What is the strategy pattern with reversed flow of control?

In my understanding the strategy pattern is used to make behaviour interchangable. This involves that the responsibility of the strategy is defined in an interface, to which the client may then delegate calls. E.g. suppose a value can be obtained in different ways, the interface would have a method "getValue()".
My question concerns the case where the flow of control is opposite. For example if the concrete strategy initiates the request "onValueChanged()" on the client (suppose it has a reference to the client or a callback interface).
Is this still considered a strategy pattern?
Update - added the following source code example:
interface DataSupplierCb
{
void onValueChanged(int a);
}
interface DataSupplier
{
void check();
}
// NOTE 1: Data supplier knows how the get the value
class ConcreteDataSupplier : public DataSupplier
{
void check()
{
myDataSupplierCb.onValueChanged(47);
}
}
class Client : public DataSupplierCb
{
void onValueChanged(int a)
{
// NOTE 2: Client knows what to do with the value
}
void changeDataSupplier(int i)
{
if (i == 1)
{
myCurrentDataSupplier = new ConcreteDataSupplier(this);
}
}
}
No. That would not be the strategy pattern. In the strategy pattern, the strategy interface, and the concrete strategy implementations do not know about the client.
The client knows about the strategy interface, and knows nothing about the actual implementations.
The goal of this pattern is the ability of replacing one strategy with another without modifying the client. A strategy is usually some sort of algorithm.
What you are describing seems to be closer to the Observer design pattern in which there is a subject and one or several observers implementing a common interface (or inheriting from a common base class). The subject is the object that is being observerved, and the observers are objects that need to be notified whenever the subject changes. e.g: the subject can be some kind of data source, and one observer can be an histogram view, and another a pie chart view.
http://en.wikipedia.org/wiki/Observer_pattern
http://en.wikipedia.org/wiki/Strategy_pattern
If the intent of the DataSupplier interface to allow your Client to swap in, and delegate to, different concrete data-fetching implementations then yes it can be considered a strategy. Your Client is shielded from the details (aka strategy) used to fetch the value as expected in the use of the Strategy pattern. And the fact that the Client reference is passed to the Strategy is fine and common:
(From the GoF)
"Strategy and Context interact to implement the chosen algorithm. A
context may pass all data required by the algorithm to the strategy
when the algorithm is called. Alternatively, the context can pass
itself as an argument to Strategy operations. That lets the strategy
call back on the context as required."
The Context for you is Client.
Now that all being said, rare is a solution that uses only one pattern. Your notification does seem to use the Observer pattern as another poster commented, and that is fine.
What I don't like about what you have implemented though is that your Strategy is a pure interface. Not always a bad thing, but in this case, with that notification callback, an interface does not provide a guarantee that the notifictaion callback is going to happen. Interfaces only guarantee the method signatures. I would recommend using the Template pattern in a base class to derrive the strategies from.
abstract class DataSupplier
{
protected ClientInterface _client;
// ctor takes in context
public DataSupplier(ClientInterface client)
{
_client - client;
}
public void check()
{
int priorValue = 46;
int newValue = OnGetValue();
if (priorValue != newValue)
_client.onValueChanged(newValue)
}
protected abstract int OnCheck();
}
And then:
class ConcreteDataSupplier : DataSupplier
{
// Check, and notification, are handled by the base. We only need
// to implement the actually data fetching
int OnGetValue()
{
return someValue;
}
}
With this approach, I know the notification will be handled. I don't need to worry about an implementor forgetting it in a new strategy later.

Dependencies inside an object

I have this code
class Duck {
protected $strVocabulary;
public function Learn() {
$this->strVocabulary = 'quack';
}
public function Quack() {
echo $this->strVocabulary;
}
}
The code is in PHP but the question is not PHP dependent.
Before it knows to Quack a duck has to Learn.
My question is: How do I make Quack() invokable only after Learn() has been called?
No, that does not violate any OOP principle.
A prominent example is an object who's behavior depends on whether a connection is established or not (e.g. function doNetworkStuff() depends on openConnection()).
In Java, there is even a typestate checker, which performs such checks (whether Duck can already Quack()) at compile time. I often have such dependencies as preconditions for interfaces, and use a forwarding class whose sole purpose is protocolling and checking the state of the object it forwards to, i.e. protocol which functions have been called on the object, and throw exceptions (e.g. InvalidStateException) when the preconditions are not met.
A design pattern that handles this is state: It allows an object to alter its behavior when its internal state changes. The object will appear to change its class. The design pattern book from the Gang of Four also uses the example above of a network connection either being established or not.
If you want to fix the order then you can use an abstract base class where in the function quack() you call learn() first and then abstract method doquack() (some other good name, and this will have to be implemented by each derived class).
My question is: How do I make Quack() invokable only after Learn() has
been called?
you can separate concerns:
class EnrolleeDuck {
public function Learn() {
return new AlumnusDuck('quack');
}
}
class AlumnusDuck
{
protected $strVocabulary;
public function __construct(&strVocabulary) {
&this->strVocabulary = &strVocabulary;
}
public function Quack() {
echo $this->strVocabulary;
}
}
It's my first lines in PHP, feel free to correct

How to enforce a "has a" relationship and protect the object that "is had"

Given the following code:
Class User{
Task m_Task;
public function getTask("Do work") { return m_Task; }
}
Class Project{
Task m_Task;
public function getTask("Do work") { return m_Task; }
}
Class Task {
private m_Name;
public Task(name) { m_Name = name; }
}
Class Evil {
new Task = Error
}
In a language that does not support multiple inheritance, nested classes, or private classes, (private constructor not an option), how can you design a requirement that Task is only ever instantiated through User or Project? Ideally using only language constructs instead of code. Is there a design pattern?
Not quite an answer, you can construct a task from elsewhere but you need a valid task instance to do it..
public class Task {
public Task (User u, String name)
{
if (u==null) throw new UnsupportedOperationException("that's cheating");
this.name=name;
}
}
Utlimately, if you're creating the requirement that Task be external to user then something else needs to be able to load task's constructor so I don't think it's possible.
What's the purpose of this question? Does this relate in any way to some real-world situation?
It seems somewhat quixotic, but I suppose you write Task a constructor that requires a User as an argument and does some handshaking back and forth to link the User to the Task, requiring that the User does not already have a Task.