Is a low number of members in a class considered a code smell? [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 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 }
}

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.

OOP creating and copying an object that depends on one value

I am sorry but I didn't know what to call this post (if you have a better title please tell me in a comment).
Say for instance you have the following Object whose purpose is to create chart series of the data specified in the Constructor:
/**
* Helper to generate chart series
*/
public class ChartHelper
{
public System.Windows.Forms.DataVisualization.Charting.Chart ChartType { get; set; }
public String TimeType { get; set; }
private readonly List<IObject> _datalist;
private readonly TimeType _timeType;
private readonly DateTime _stopDate;
private readonly DateTime _startDate;
public ChartHelper(List<IObject> dataList, TimeType timeType, DateTime startDate, DateTime stopDate)
{
_startDate = startDate;
_stopDate = stopDate;
_datalist = dataList;
_timeType = timeType;
}
public System.Windows.Forms.DataVisualization.Charting.Chart GetChart()
{
CreateSeries(_startDate);
return ChartType;
}
private void CreateSeries(DateTime seriesTime)
{
//Do something
}
//More internal private methods
}
Now say for instance you have a program that creates 10 different Charts but only the value of the List<IObject> dataList changes.
Then you could do one of two things:
Create 10 different ChartHelper Objects
Use the same Object and change the dataList value
This is of course an example of how the problem could be presented when developing (ive met this problem several times)
My question is, is there a design pattern that helps you solve this issue ? Or is there a best practice method that would be useful for these situations? It is important for me to learn these methods as I wish to improve my own skills.
If only the data is different then I would recommend using the same class and creating 10 different objects from it.
If however the implementation of the CreateSeries would be different depending on the type of data, than this would be a candidate for the Strategy pattern. In that case you would extract the creation of the series behind an interface and provide implementations for the different kinds of series. You could then also have a factory that picks the correct strategy depending on the data and composes a chart (helper).

Where to find in-depth information about OOP? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I've found a lot of information on object oriented programming, but none of it seems to go into much detail. They always give you the shape example where cirlce, square, and retangle implement the interface. That's easy. I'm looking for something more real life and deeper into the process.
Does anybody have any good resources that are pretty in-depth? Or even code samples would be helpful.
That's a very broad question... Here's just a few links for you:
http://en.wikibooks.org/wiki/Object_Oriented_Programming
http://www.amazon.com/Object-Oriented-Programming-Peter-Coad/dp/013032616X
#Frankie - I've edited this for you having seen your comment. You're question is still very broad, but I'll try to provide a quick (very loosely thought) example of modeling some objects. The language I'll use is C#, though you can do it any OOP language you like.
We use Interfaces and Base Classes to represent very basic models. One of the defining differences between and Interface and a Base Class is that an Interface cannot be instantiated (think of it as a blueprint that cannot physically exist, just a design on paper)... a Base Class however can be instantiated (it can exist, and might be considered a prototype). Let's go from there...
Say we want to model vehicles... airplanes, cars, motorcycles, bicycles, etc. In our modeling brain we recognize that a Vehicle is the root of everything. Let's start then by defining a blueprint that works for all types of vehicles. For that we'll use an Interface
interface IVehicle
{
string Make;
string Model;
int Year;
}
Our interface now says, any object we build that implements this interface must have a Make, Model, and Year property. Now cars, bikes, motorcycles, etc. pop into our head, and we want to make classes for them... but we realize, lots of these vehicles have things in common. Let's make a prototype for all LandVehicles, and for that we'll use a Base Class that implements our blueprint interface IVehicle
public class LandVehicle : IVehicle
{
// We must physically implement the required members of the interface.
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
// Then we can add things specific to land vehicles.
public int NumberOfWheels { get; set; }
public int TopSpeed { get; set; }
}
Now we have a prototype to build from. Let's design a Car and a Cycle
public class Car : LandVehicle
{
// because LandVehicle is a real object, we do not have to re-implement its memebers,
// we can just add to them:
public int MaxPassengers { get; set; }
public bool IsLuxury { get; set; }
public string FuelType { get; set; }
}
public class Bicycle : LandVehicle
{
public string Type { get; set; } // mountain, race, cruiser, etc.
public int NumberOfGears { get; set; }
}
With that, we can instantiate Cars and Bicycle objects... but by using Base Classes, we could create many other types of LandVehicles without having to add our basic properties to each one. This is one of the things than makes OOP so extensible.
Furthermore with our Interface, we left it open enough to make other base classes, perhaps WaterVehicles, AirVehicles, etc... and thus classes that derive from them.
This is just the very tip of the iceberg, and a rather off-the-top-of-my-head example, but it should get you started. If you have more specific questions or a specific scenario you'd like to use as context, let me know and I'll help out more.

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.

Object Oriented Design for a Chess game [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 am trying to get a feel of how to design and think in an Object Oriented manner and want to get some feedback from the community on this topic. The following is an example of a chess game that I wish to design in an OO manner. This is a very broad design and my focus at this stage is just to identify who is responsible for what messages and how the objects interact each other to simulate the game. Please point out if there are elements of bad design (high coupling, bad cohesion etc.) and how to improve on them.
The Chess game has the following classes
Board
Player
Piece
Square
ChessGame
The Board is made up of squares and so Board can be made responsible for creating and managing Square objects. Each piece also is on a square so each piece also has a reference to the square it is on. (Does this make sense?). Each piece then is responsible to move itself from one square to another.
Player class holds references to all pieces he owns and is also responsible for their creation (Should player create Pieces?) . Player has a method takeTurn which in turn calls a method movePiece which belongs to the piece Class which changes the location of the piece from its current location to another location. Now I am confused on what exactly the Board class must be responsible for. I assumed it was needed to determine the current state of the game and know when the game is over. But when a piece changes it's location how should the board get updated? should it maintain a seperate array of squares on which pieces exist and that gets updates as pieces move?
Also, ChessGame intially creates the Board and player objects who in turn create squares and pieces respectively and start the simulation. Briefly, this might be what the code in ChessGame may look like
Player p1 =new Player();
Player p2 = new Player();
Board b = new Board();
while(b.isGameOver())
{
p1.takeTurn(); // calls movePiece on the Piece object
p2.takeTurn();
}
I am unclear on how the state of the board will get updated. Should piece have a reference to board? Where should be the responsibility lie? Who holds what references? Please help me with your inputs and point out problems in this design. I am deliberately not focusing on any algorithms or further details of game play as I am only interested in the design aspect. I hope this community can provide valuable insights.
I actually just wrote a full C# implementation of a chess board, pieces, rules, etc. Here's roughly how I modeled it (actual implementation removed since I don't want to take all the fun out of your coding):
public enum PieceType {
None, Pawn, Knight, Bishop, Rook, Queen, King
}
public enum PieceColor {
White, Black
}
public struct Piece {
public PieceType Type { get; set; }
public PieceColor Color { get; set; }
}
public struct Square {
public int X { get; set; }
public int Y { get; set; }
public static implicit operator Square(string str) {
// Parses strings like "a1" so you can write "a1" in code instead
// of new Square(0, 0)
}
}
public class Board {
private Piece[,] board;
public Piece this[Square square] { get; set; }
public Board Clone() { ... }
}
public class Move {
public Square From { get; }
public Square To { get; }
public Piece PieceMoved { get; }
public Piece PieceCaptured { get; }
public PieceType Promotion { get; }
public string AlgebraicNotation { get; }
}
public class Game {
public Board Board { get; }
public IList<Move> Movelist { get; }
public PieceType Turn { get; set; }
public Square? DoublePawnPush { get; set; } // Used for tracking valid en passant captures
public int Halfmoves { get; set; }
public bool CanWhiteCastleA { get; set; }
public bool CanWhiteCastleH { get; set; }
public bool CanBlackCastleA { get; set; }
public bool CanBlackCastleH { get; set; }
}
public interface IGameRules {
// ....
}
The basic idea is that Game/Board/etc simply store the state of the game. You can manipulate them to e.g. set up a position, if that's what you want. I have a class that implements my IGameRules interface that is responsible for:
Determining what moves are valid, including castling and en passant.
Determining if a specific move is valid.
Determining when players are in check/checkmate/stalemate.
Executing moves.
Separating the rules from the game/board classes also means you can implement variants relatively easily. All methods of the rules interface take a Game object which they can inspect to determine which moves are valid.
Note that I do not store player information on Game. I have a separate class Table that is responsible for storing game metadata such as who was playing, when the game took place, etc.
EDIT: Note that the purpose of this answer isn't really to give you template code you can fill out -- my code actually has a bit more information stored on each item, more methods, etc. The purpose is to guide you towards the goal you're trying to achieve.
Here is my idea, for a fairly basic chess game :
class GameBoard {
IPiece config[8][8];
init {
createAndPlacePieces("Black");
createAndPlacePieces("White");
setTurn("Black");
}
createAndPlacePieces(color) {
//generate pieces using a factory method
//for e.g. config[1][0] = PieceFactory("Pawn",color);
}
setTurn(color) {
turn = color;
}
move(fromPt,toPt) {
if(getPcAt(fromPt).color == turn) {
toPtHasOppositeColorPiece = getPcAt(toPt) != null && getPcAt(toPt).color != turn;
possiblePath = getPcAt(fromPt).generatePossiblePath(fromPt,toPt,toPtHasOppositeColorPiece);
if(possiblePath != NULL) {
traversePath();
changeTurn();
}
}
}
}
Interface IPiece {
function generatePossiblePath(fromPt,toPt,toPtHasEnemy);
}
class PawnPiece implements IPiece{
function generatePossiblePath(fromPt,toPt,toPtHasEnemy) {
return an array of points if such a path is possible
else return null;
}
}
class ElephantPiece implements IPiece {....}
I recently created a chess program in PHP (website click here, source click here) and I made it object oriented. Here are the classes I used.
ChessRulebook (static) - I put all my generate_legal_moves() code in here. That method is given a board, whose turn it is, and some variables to set the level of detail of the output, and it generates all the legal moves for that position. It returns a list of ChessMoves.
ChessMove - Stores everything needed to create algebraic notation, including starting square, ending square, color, piece type, capture, check, checkmate, promotion piece type, and en passant. Optional additional variables include disambiguation (for moves like Rae4), castling, and board.
ChessBoard - Stores the same information as a Chess FEN, including an 8x8 array representing the squares and storing the ChessPieces, whose turn it is, en passant target square, castling rights, halfmove clock, and fullmove clock.
ChessPiece - Stores piece type, color, square, and piece value (for example, pawn = 1, knight = 3, rook = 5, etc.)
ChessSquare - Stores the rank and file, as ints.
I am currently trying to turn this code into a chess A.I., so it needs to be FAST. I've optimized the generate_legal_moves() function from 1500ms to 8ms, and am still working on it. Lessons I learned from that are...
Do not store an entire ChessBoard in every ChessMove by default. Only store the board in the move when needed.
Use primitive types such as int when possible. That is why ChessSquare stores rank and file as int, rather than also storing an alphanumeric string with human readable chess square notation such as "a4".
The program creates tens of thousands of ChessSquares when searching the move tree. I will probably refactor the program to not use ChessSquares, which should give a speed boost.
Do not calculate any unnecessary variables in your classes. Originally, calculating the FEN in each of my ChessBoards was really killing the program's speed. I had to find this out with a profiler.
I know this is old, but hopefully it helps somebody. Good luck!