Object Oriented Programming - Best Practice? - object

Which of the following would you go with?
And based on object oriented programming which one is the best practice?
A
Class Note
{
//Some properties, etc
public static Note getNoteFromServer();
public void UpdateNoteOnServer();
}
B
Class Note
{
//Some properties, etc
}
Class NoteManager
{
public static Note getNoteFromServer();
public static UpdateNoteOnServer(Note);
}

I would say option B. In that way you separate concerns: you have a Note that can be reused anywhere (and not necessarily on a networked application), and you have a manager class that only cares with server communication.
You may also think on implement logic for multiple servers. For example, you may want to comunicate with data formats like JSON or XML. You may implement an interface (example, interface INoteManager) and then implement two classes with servers for each of the data types I mentioned (example, NoteManagerXml and NoteManagerJson).
The main point on this question is sepration of concerns. Hope I've helped! :)

To take a different viewpoint from my other answer, I'd suggest that your division into Note/NoteManager is the wrong one - not because Note has anything wrong with it, but because the term Manager is a bit of a code smell because it's very generic, inviting the use of the class as a general dumping ground.
If the class is responsible for note persistence, call it NoteRepository.
If it's responsible for validating the content of a single note, move the logic onto the Note.
If it's responsible for creating notes, providing a number of convenience methods for easily creating notes, call it NoteFactory.
And if it's responsible for all of the above, split it into separate pieces because it's doing too much.

That's a pretty opinion based question you're asking there.
You're essentially asking (if I understand correctly) whether it is better to have a Class which contains only properties and another class to manage that object (Example B) or to have a class which does everything (Example A).
It really depends. If we're planning on using a MVC kind of framework, Example B would fit better, with Note being your Model, and NoteManager being the controller.
Personally, I would go with a hybrid of A and B, where NoteManager is handling controller actions, but the Model still has methods of its own to do things like managing a singleton instance. So maybe something like this?
Class Note
{
//Some properties, etc
public static Note getInstance(noteIdentifier);
public void saveNote();
}
Class NoteManager
{
// This handles view validation and calls Note.saveNote();
public static UpdateNoteOnServer(Note);
}

I think A is better, for 1 reason:
It implements the Object Oriented
paradigm to the letter.
The problem i see with B is that a static method that receives an instance of the same class sounds redundant to me because, why would you use a static method to apply behaviour to an instance of the same class? The whole idea behind classes and instances is that Classes are the frame and instances cookies, if you need different cookies, modify your frame and get new ones.

It seems to depend on how its going to be used in your program. If Note is the only class or is the parent class for derived classes then there is no point and having a "Manager", Keep It Simple Stupid (KISS). However if the Manager has to deal with other classes via Interfaces then I can see having a seperate class.

As per my experience best practice is , as long as things are separated DRY is best practice. you can extends note to notemanager
Class Note
{
//Some properties, etc
}
Class NoteManager
{
public static Note getNoteFromServer();
public static UpdateNoteOnServer(Note);
}

I'd choose B, unless you want to end up like poor ol' PHP:
get_note_from_server_and_print_the_response($note, 'PHP, why must you be so disorganized?')
But seriously, it may seem intuitive to do A at the moment, but you'll eventually split A up, as those server operations will require more and more related functions, until you have a mammoth Note class which contains every function in your program...

"It Depends"
One of the things it depends upon is the language of implementation.
If you are working in C# or Java, then you'll likely want to go with the Note/NoteManager approach as this gives you the most flexiblity of implementation - because static members in those languages a kind of second class citizens.
To illustrate, in Delphi's original Object Pascal lanaguage, methods and properties that could be accessed without an instance were known as class members, not static members, and they could be virtual, and therefore overridden in descendent classes.
If you're working with a language that provides features like "virtual class (static) members" and a few others, then you might want to merge Note/NoteManager together.

I would go with "B"
Reason why is that you may require "Note" to be used with another type of Controller class, like what you have done for NoteManager.
Also gives you the ability to dissociate your Data Objects or DTO's or Model away from your actual controller classes.

C
Class Note
{
//Some properties, etc
public static Note LoadFrom(Whatever);
public void SaveTo(Whatever);
}

Related

What are pure virtual methods in UML?

I am attempting to understand how I should use the realization of interfaces and the implementation of abstract classes in UML. I came across the post at https://stackoverflow.com/a/13438187/700543 whereby the poster states that pure virtual methods are interfaces whilst those that are part pure virtual methods are abstract classes. Is anyone able to give me a real world scenario and not one based on code?
An Interface is only a "class skeleton" for library users to extend, and as you said, methods cannot be implemented. An Abstract class can have implemented methods. I will give you a real life example:
Imagine I provide an Interface for people to implement sorting functions and I also provide a Class for bench marking sorting functions. My bench marking class only needs to know what methods of the Interface it needs to call in order to perform the bench marking, it does not know how they are implemented. Therefore, inside the bench marking class you might only see something like sortInterfaceInstace.getNumberOfSwap(), whereas sortInterfaceInstance is only known to be of sortInterface type at compile time, and not of any specific user sort implementation.
If you need implemented methods, use abstract instead of interfaces.
An interface only describes how something can be used, it provides none of the underlying implementation of how it gets done, i.e. a class with only pure virtual functions. An English analogy for an interface may be an adjective.
One example of an interface is a Movable interface. This interface may provide one pure virtual function move which tells the object to move to a given location. However, how it moves there is not implemented.
An abstract class on the other hand differs from an interface in that it provides some of the implementation details, but not all of them. These are conceptually high-level items that can be manipulated in certain ways, but when you get down to it the high-level item doesn't really exists or make sense by itself.
For example, say we have an abstract Shape class. The shape can have a certain origin which can be tracked independent of what Shape it is. The functions to transform the shape can be declared and implemented in the Shape class, saving the hassle of having to provide the same implementation in each sub-class. However, when you try to get the area or perimeter of the shape it's difficult to answer this without knowing more about the shape.

how to draw class diagram that shows a call to a static method of another class

How do i model a call to a static method in a class diagram ? Can someone show me a link to a class diagram that has done that?
for example there's a class called Animal. and i have another class called Vertibrates, and it has a method which is static (and this is the only method in that class). My Animal class will be using this static method of the class Vertibrate. Therefore how can i model it in class diagram ?
You don't. Well, not in a class diagram at least. Instead, you should use sequence chart diagrams to express method calls (whether static or dynamic).
You can't model the call directly in a class diagram (as #Imontrieux says), but you can model the relationship (i.e., that Animal uses (calls) static methods in Vertibrate; BTW, the correct spelling is Vertebrate), which I suspect is actually what you meant.
You use a UML dependency for this, not an association (since the latter are for associations between instances of the classes at each end)--- see How to show usage of static methods UML Classdiagram.
Great question. One thing the GoF do in Design Patterns is used notes to demonstrate intended uses. For example, from the section on the Command Pattern:
Command Pattern
While #user1315906 is technically correct that you don't model such things in Class Diagrams, but rather in Use Case or Sequence Diagrams, if it makes sense to note how something is intended to be used in a Class Diagram, you can use a note :)

Why must overloaded operators be declared public?

I wanted to overload an operator in a class , and have it private so that it could only be used from within the class.
However, when I tried to compile I got the error message "User-defined operator ... must be declared static and public:
Why do they have to be public?
To answer half part of your question you may see the blog post by Eric Lippert.
Why are overloaded operators always static in C#?
Rather, the question we should be asking ourselves when faced with a
potential language feature is "does the compelling benefit of the
feature justify all the costs?" And costs are considerably more than
just the mundane dollar costs of designing, developing, testing,
documenting and maintaining a feature. There are more subtle costs,
like, will this feature make it more difficult to change the type
inferencing algorithm in the future? Does this lead us into a world
where we will be unable to make changes without introducing backwards
compatibility breaks? And so on.
In this specific case, the compelling benefit is small. If you want to
have a virtual dispatched overloaded operator in C# you can build one
out of static parts very easily. For example:
public class B {
public static B operator+(B b1, B b2) { return b1.Add(b2); }
protected virtual B Add(B b2) { // ...
And there you have it. So, the benefits are small. But the costs are
large. C++-style instance operators are weird. For example, they break
symmetry. If you define an operator+ that takes a C and an int, then
c+2 is legal but 2+c is not, and that badly breaks our intuition about
how the addition operator should behave.
For your question's other part: Why they should be public.
I was not able to find any authentic source, but IMO, if they are not going to be public, and may be used inside a class only, then this can be done using a simple private method, rather than an overloaded operator.
You may see the blog post by RB Whitaker
Operator Overloading
All operator overloads must be public and static, which should make
sense, since we want to have access to the operator throughout the
program, and since it belongs to the class as a whole, rather than any
specific instance of the class.

DDD and Factories

Hi I have a few questions regarding Domain Driven Design and using Factories / Factory Methods.
Per the Domain Driven Design Blue Book (Eric EVan's Book) it states that complex constructors should be encapsulated inside Factories / Factory Methods / Builders so there is a consistent place where you check all the invariants, so my question is regarding this:
Let's say I am developing a magic organizer application where you can make CRUD like operations on magic effects (like a post on a blog + several attributes like effect duration, materials used (list of strings), patter associated with the magic effect) and some of the invariants are that a magic effect must always have a title, a content of the magic effect, a duration and an optional patter and must be published by a user registered in the application.
So since I have quite a few invariants I have a EffectBuilder that builds MagicEffect objects and checks all the invariants.
Is it ok to do something like this in the user class?
public class User {
// Several attributes and business methods
public MagicEffect publishEffect(final String title, final String content, final Long duration, final Collection<String> elements) [
EffectBuilder builder = new EffectBuilder();
builder.withAuthor(this);
builder.withTitle(title);
builder.withContent(content);
builder.withDuration(duration);
builder.withElements(elements);
return builder.build();
}
};
Or should I do something like:
public class User {
// Several attributes and business methods
public EffectBuilder publishEffect() [
EffectBuilder builder = new EffectBuilder();
builder.withAuthor(this);
return builder;
}
};
And somewhere else
User user = userRepository.findById(userId);
MagicEffect effect = user.publishEffect().withTitle(title).withContent(content).withDuration(duration).withElements(elements).build();
userRepository.save(user);
I mean the first example I have a huge method with huge amount of parameters but I make sure all the invariants are set in the effect when it's built, in the other scenario I programatically improve the code readability by having a fluent interface but I canot make sure the invariants are met 100% of the time.
Which is the better approach? Is there a more balanced approach of doing it?
Thanks
Pablo
I think that your second approach is better. The whole point of Builder is to avoid large list of parameters like you have in your first example. Builder is not responsible for enforcing invariants in the object that it builds. Object itself enforces them. I think it is perfectly fine to have an instance of EffectBuilder without Title or with a default title. As long as the MagicEffect itself enforces 'Every effect should have a title' invariant.

Shared Domain Logic?

Take for example:
CreateOrderTicket(ByVal items As List(Of OrderItems)) As String
Where would you put this sort of logic given:
CreateOrder should generate a simple list ( i.e. Item Name - Item Price )
PizzaOrderItem
SaladBarOrderItem
BarOrderItem
Would you recommend:
Refactoring common to an abstract class/interface with shared properties a method called CreateOrderTicket
Or,
Creating a common service that exposes a CreateOrderTicket
We obviously would not want three createOrderTicket methods, but adding methods, inheriting, overloading and using generics seem like a high cost just to abstract one behaviour..
Assume for the sake of a simple example that (currently) there is no OrderItem baseclass or interface..
Help!! :)
p.s. Is there a way to overload without forcing all inheriting objects to use the same name?
Abstract base class sounds like the best option in this situation. Of course it all depends on what kind of shared behaviour these items have. Without knowing more, I'd guess all of these order items have Name and Price for example - and in future you might add more common stuff.
Without a shared base class which contains the Name and Price properties, you'll probably have troubles implementing a CreateOrderTicket method which takes a list containing more than 1 kind of orders.
Also I don't think inheriting from an abstract base class would be that high cost as technically the objects already derive from the Object base class. (Though I don't think this is completely equal to a custom base class.)
VB.Net can implement methods from an interface using a different name than the one specified in the interface but don't think the same goes for overriding abstract functionality.

Resources