In my current Android project I am investigating the use of Kotlin. I am rewriting a 100% Java Android app to 100% Kotlin. I'm stuck with attempting to implement my Java step builders though. These are useful as they force the user to populate all required variables before they can execute the associated function/command. I cannot find any examples of how to achieve this in Kotlin, does Kotlin have a better alternative that ensures a class has all it's fields populated before a function can be executed?
jeudi 28 février 2019
Java singleton concurrent issue demonstrated by debuging on byte code or assembly code
Java singleton patten:
public class Singleton {
static Singleton instance;
static Singleton getInstance(){
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
If there are two threads: A and B, they call getInstance(), probably one of the threads will get a instance of not complettely constructed. But if you run those pieces of code many many times, you may not get the wrong result. I guess it's because executing the byte code or assembly code is very fast. If control the executing steps, debug the byte code or assembly code line by line alternately, the wrong result can be reproduced.
Java singleton patten issue(or volatile) is talk a lot on the web. But it's hard to find some useful, authentic practice code to run arbitrary times to produce the wrong result.
Are there any useful blogs/articles tell these?
Design question regarding Factory Pattern
I want to inject a type IGameScoreSource
into a class but I'm stumped how to go about it.
static class GamesScoreSourceFactory
{
public IGameScoreSource GetGameScoreSource(GameScoreSourceType gameScoreSourceType)
{
switch(gameScoreSourceType)
{
case FromFile:
return new GameScoreFile();
case FromDB:
return new DatabaseRepos();
case FromThirdPartyAPI:
return new ThirdPartyWrapper();
}
}
}
I have two questions for two different scenarios.
All three cases magically figure out where to source the parameters. So for GameScoreFile
it knows what file path to look at, for DatabaseRepos
it knows where to find the connection string.
Presumably, these locations are hard-coded in the concrete classes. But what if I wanted to change the locations? Assuming scores.txt was hard coded what if instead I wanted rand_scores.txt?
So:
static class GamesScoreSourceFactory
{
public IGameScoreSource GetGameScoreSource(GameScoreSourceType gameScoreSourceType, string param)
{
switch(gameScoreSourceType)
{
case FromFile:
return new GameScoreFile(string param);
case FromDB:
return new DatabaseRepos(string param);
case FromThirdPartyAPI:
return new ThirdPartyWrapper(ThirdPartyConfig conf{IPAddress = ipAddress, Port = port});
}
}
}
The first two cases were fine but the third case doesn't because it takes a config object.
Do I have to create another factory class? But won't the calling code have to know which Factory object to invoke, and as result becomes a Factory in itself?
I'm not sure how to handle this... If this is a duplicate please link me.
How does a system with an LRU cache in a layer before actually accessing the database maintain the most updated information?
Assume you have a system that primarily reads large amounts of data, like pinpoint locations in coordinate form. You can set up an LRU cache in some layer before he actual database to prevent the database from being accessed constantly and redundantly.
However, in typical implementations of such a cache, what are the mechanisms in place to the deal with, for example, if data infrequently but definitely will be modified and/or deleted? Say this happens at a rate of 1/100 or 1/1000 where such a cache is very efficient. Are there any common solutions to this? Does the application communicate with the cache to check and see if such an item would be dropped? Many caches I see do not seem to have any mechanism in place. Is there some kind of reoccurring cache validation that the server runs?
Seperation of concerns - Controlling 2 dependant entities by using a service?
I have 2 services, a profileService which knows how to manipulate Profile models (laravel eloquent). And a listService which knows how to manipulate List models. A profile has a one to many relation with the List model. The relations are defined in those eloquent models.
Now, the question i have is about separation of concerns. I intend to let the profile service only do stuff with profiles. And the listService only with lists.
What kind of design pattern / construction would i need to do the following while respecting my intentions:
I want a destroyProfile method on the profile method which can delete the profile, and cause its related lists also to be deleted.
What i am thinking of is the following. I think i need a third service like class that the profileService can use to delete both models. But i am not sure what would be a nice way to do it.
Would you like to share your thoughts?
Thanks in advance!
J.
C# Exception handling and code maintenance [on hold]
I have a validator class in this, I will be validating(Empty or Not and duplicate) the data type values like string, int, GUID, List etc.
For this, I am throwing Argument null exception in case of value null or empty and custom exceptions for UserNotFound, duplicate, a record not found etc.
Previously I used to throw the exception directly like below,
**throw new ArgumentNullException(paramName);**
But, I feel it be huge change If the custom exception class name changes or any modifications related to that.
Because I will be using those custom and predefined exceptions in 30+ applications.
Now I restructured it in below manner,
1. A class which throws all custom exceptions,
2. Usage of those custom exceptions here,
Can anyone confirm whether it is okay or not?
If it is okay, what type of benefits I will get from this I was unable to understand.
Let us know your thoughts on this.
Executing error while executing sed command
Below given sed command is working fine on online BASH & KSH shell, but getting an error "Illegal operation --r" while trying to run it on linux server.
I'm trying to make a regex to parse "MFBBMYKLAXXX" from first line.
echo "{1:F01MFBBMYKLAXXX2474811384}{2:O3001434181108BKKBTHBKBXXX12203020241811081534N}{3:{108:241C182AFFD4403C}}{4: :15A:
:20:10168957
:22A:NEWT
:94A:BILA
:22C:BKKBBK8308MFBBKL
:82A:BKKBTHBK
:87A:MFBBMYKL
:15B:
:30T:20181108
:30V:20181109
:36:32,8308 :32B:THB2500000,
:53A:/610165
BKKBTHBK
:57A:BKKBTHBK
:33B:USD76148,01
:53A:CHASUS33
:57A:/04058664
BKTRUS33
:58A:MFBBMYKL
:15C:
:24D:ELEC/REUTERS D-3000
-}{5:{CHK:4117CD0206B7}}{S:{COP:S}} " | sed -rn 's/.{1:F01([A-Z]{12})./\1/p'
Thanks in advance :)
Merging duplicate code that use different objects
I use two api calls to get data about vehicleUtils depending on contentFilter. I have very similar code for both (drivers and vehicles). What i tried to do is to extract the code into a single method and apply Strategy pattern like they suggest here Refactoring methods, but i could not figure out how to implement it. Am i using a good approach or is there any better way?
if (contentFilter.equalsIgnoreCase(Contentfilters.VEHICLES.toString())) {
VuScores vuScores = new VuScores();
List<VehicleVuScores> vehicleVuScoresList = new ArrayList<>();
List<VehicleUtilization> vehicleUtilizations = RestClient.getVehicles(request).join().getVehicleUtilizations();
if (Objects.nonNull(vehicleUtilizations)) {
vehicleUtilizations.forEach(vehicleUtilization -> {
vuScores.getVehicleVuScores().forEach(vehicleVuScore -> {
vehicleVuScore.getScores().setTotal(vehicleUtilization.getFuelEfficiencyIndicators().getTotal().getValue());
vehicleVuScore.getScores().setBraking(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(3).getIndicators().get(0).getValue());
vehicleVuScore.getScores().setCoasting(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(3).getIndicators().get(1).getValue());
vehicleVuScore.getScores().setIdling(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(0).getIndicators().get(0).getValue());
vehicleVuScore.getScores().setAnticipation(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(3).getValue());
vehicleVuScore.getScores().setEngineAndGearUtilization(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(1).getValue());
vehicleVuScore.getScores().setStandstill(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(0).getValue());
vehicleVuScore.getScores().setWithinEconomy(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(1).getIndicators().get(7).getValue());
vehicleVuScore.setAvgFuelConsumptionPer100Km(vehicleUtilization.getMeasures().getTotal().getAverageConsumption().getValue());
vehicleVuScore.setAvgSpeedDrivingKmh(vehicleUtilization.getMeasures().getTotal().getAverageSpeed().getValue());
vehicleVuScore.setEngineLoad(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(1).getIndicators().get(1).getValue());
vehicleVuScore.setTotalDistanceInKm(vehicleUtilization.getMeasures().getDriving().getDistance().getValue());
vehicleVuScore.setTotalTime(Math.toIntExact(vehicleUtilization.getMeasures().getTotal().getTime().getValue()));
vehicleVuScoresList.add(vehicleVuScore);
});
});
vuScores.setVehicleVuScores(vehicleVuScoresList);
}
return CompletableFuture.completedFuture(vuScores);
} else if (contentFilter.equalsIgnoreCase(Contentfilters.DRIVERS.toString())) {
VuScores vuScores = new VuScores();
List<DriverVuScores> driverVuScoresList = new ArrayList<>();
List<VehicleUtilization> vehicleUtilizations = RestClient.getDrivers(request).join().getVehicleUtilizations();
if (Objects.nonNull(vehicleUtilizations)) {
vehicleUtilizations.forEach(vehicleUtilization -> {
vuScores.getDriverVuScores().forEach(driverVuScores -> {
driverVuScores.getScores().setTotal(vehicleUtilization.getFuelEfficiencyIndicators().getTotal().getValue());
driverVuScores.getScores().setBraking(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(3).getIndicators().get(0).getValue());
driverVuScores.getScores().setCoasting(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(3).getIndicators().get(1).getValue());
driverVuScores.getScores().setIdling(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(0).getIndicators().get(0).getValue());
driverVuScores.getScores().setAnticipation(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(3).getValue());
driverVuScores.getScores().setEngineAndGearUtilization(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(1).getValue());
driverVuScores.getScores().setStandstill(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(0).getValue());
driverVuScores.getScores().setWithinEconomy(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(1).getIndicators().get(7).getValue());
driverVuScores.setAvgFuelConsumptionPer100Km(vehicleUtilization.getMeasures().getTotal().getAverageConsumption().getValue());
driverVuScores.setAvgSpeedDrivingKmh(vehicleUtilization.getMeasures().getTotal().getAverageSpeed().getValue());
driverVuScores.setEngineLoad(vehicleUtilization.getFuelEfficiencyIndicators().getGroupIndicators().get(1).getIndicators().get(1).getValue());
driverVuScores.setTotalDistanceInKm(vehicleUtilization.getMeasures().getDriving().getDistance().getValue());
driverVuScores.setTotalTime(Math.toIntExact(vehicleUtilization.getMeasures().getTotal().getTime().getValue()));
driverVuScoresList.add(driverVuScores);
});
});
vuScores.setDriverVuScores(driverVuScoresList);
}
return CompletableFuture.completedFuture(vuScores);
}
Typescript conditional types inferred by high order function
I have a function that can return a sync or async result
type HookHandler<T> = (context: MyClass<T>) => boolean | Promise<boolean>;
and a class that takes a list of that functions
class MyClass<T> {
constructor(private handlers: Array<HookHandler<T>>) {
}
public invokeHandlers() : boolean | Promise<boolean> {
// invoke each handler and return:
// - Promise<boolean> if exist a handler that return a Promise<T>
// - boolean if all handlers are synchronous
}
}
I was wondering if there is any chance to make typescript infer the return type of the invokeHandlers()
based on the given handlers. Consider that all the handlers are declared at design time:
const myClassSync = new MyClass<MyType>([
(ctx) => true,
(ctx) => false
]);
const myClassAsync = new MyClass<MyType>([
async (ctx) => Promise.resolve(true),
async (ctx) => Promise.reject()
]);
const myClassMix = new MyClass<MyType>([
async (ctx) => Promise.resolve(true),
(ctx) => true
]);
Can I make the return type of invokeHandlers()
dependent of the types of the current given hanlders without an explicit casting? So for example
// all handlers are sync, infer boolean
const allHandlersAreOk: boolean = myClassSync.invokeHandlers()
// all handlers are async, infer Promise<boolean>
const allAsyncHandlersAreOk: Promise<boolean> = await myClassAsync.invokeHandlers()
// at least one handler is async, infer Promise<boolean>
const allMixedHandlersAreOk: Promise<boolean> = await myClassMix.invokeHandlers()
I can obviously return a simple Promise<boolean>
, but I would loose the possibility to call the invokeHandlers()
in synchronous contexts, and it want to avoid that.
Any suggestions or other design choice to face the problem? Thank you!
What design pattern would be most appropriate
Suppose we have a set of several service classes (A,B,C,D,E,F), and the number of classes is quite large and may change. There are also classes that use them. First, i don't want to write long constructors. Secondly, for example, a new service class appears today, then it needs to be added to classes A, B, C, and tomorrow another service class, which is used by D, E, F. What design pattern would be most appropriate in this case?
mercredi 27 février 2019
Using the Step Builder pattern for the creation of a complex object that contains an instance variable that is a list
Let's say I want to construct an instance of the following object:
private class ComplexObject {
private int param1; // Required Parameter
private int param2; // Required Parameter
private int param3; // Required Parameter
private List<Integer> listParam4; // This list should contain atleast one Integer
private ComplexObject() {
this.listParam4 = new ArrayList<Integer>();
}
}
I'm trying to use the Step Builder pattern to construct this object, so that a user sets the value of the parameters in order. The main problem that I'm facing is with creating an interface for the last step. I want to expose the build()
method after the user has provided atleast one integer that I can add in listParam4
. At the same time I also want to give the user the option of providing more integers to add to the list before calling the build()
method. I would really appreciate if someone can provide me a way of doing this or suggest an alternative approach in case I'm approaching this problem incorrectly.
Here is the code that I currently have to achieve this:
public interface SetParam1Step {
SetParam2Step setParam1(int param1);
}
public interface SetParam2Step {
SetParam3Step setParam2(int param2);
}
public interface SetParam3Step {
AddToParam4ListStep setParam3(int param3);
}
public interface AddToParam4ListStep {
// Not sure how to create this interface
}
public static class ComplexObjectBuilder implements SetParam1Step, SetParam2Step, SetParam3Step, AddToParam4ListStep {
private int param1;
private int param2;
private int param3;
private List<Integer> listParam4;
private ComplexObjectBuilder() {
// Prevent Instantiation
}
@Override
public AddToParam4ListStep setParam3(int param3) {
this.param3 = param3;
return this;
}
@Override
public SetParam3Step setParam2(int param2) {
this.param2 = param2;
return this;
}
@Override
public SetParam2Step setParam1(int param1) {
this.param1 = param1;
return this;
}
// Needs to implement the build() method and the methods that would eventually be added to the AddToParam4ListStep interface.
public static SetParam1Step newInstance() {
return new ComplexObjectBuilder();
}
}
Inherited Composite Class
I am working on a pattern and would like to know if this is a good practice to follow - I have class A as super class and classes B and C are child classes (inherited from class A). I want to build a relationship as "B is a Composite class that can have type of A as a property" (i.e B can have a nested type of A) . Is this a valid relationship I can build ? Is there any issues you see in this relationship
How to implement a stack using Factory pattern
Recently i came across a problem where the requirement was to implement a stack and it's functionality(push, pop, overflow, underflow) using factory design pattern in C#. Can anyone please help me on how to do this? Thanks.
Spring jpa: order by field of a nested collection conditional member
This question is not specific. I'm just a junior developer asking for advice with overwhelming task. If it's not how things are done here at Stackoverflow, please tell.
Let's imagine we need an app to monitor government messages. We have the following model:
@Entity
class Message {
@Id
@Column(name = "MESSAGE_ID")
private Integer id;
@OneToMany
@JoinColumn(name = "MESSAGE_ID", referencedColumnName = "MESSAGE_ID")
private List<Dispatch> dispatches;
private String text;
//getters & setters
}
@Entity
class Dispatch {
@Id
@Column(name = "DISPATCH_ID")
private Integer id;
private String destination; //few dozen of different destinations
@OneToMany
@JoinColumn(name = "DISPATCH_ID", referencedColumnName = "DISPATCH_ID")
private List<Status> statuses;
//getters & setters
}
@Entity
class Status {
@Id
@Column(name = "STATUS_ID")
private Integer id;
private String code; //one of those: "SENT", "DELIVERED", "READ"
private Date registered;
//getters & setters
}
Controller and repository look like this:
@RestController
class MessageController {
@Autowired
private MessageRepository repository;
@GetMapping("/messages")
public Page<Message> getMessagesSorted(Pageable pageable) {
return repository.findAll(pageable);
}
}
interface MessageRepository extends JpaRepository<Message, Integer> {
}
And if we call our API like "../messages?size=50&page=3&sort=id, asc" we'll get exactly what we want: 4-th page with 50 elements sorted by id.
But next thing we want is to sort messages by the date they were read, delivered or sent to specific destination. For example "../messages?sort=sentToMoscow, desc"
First thought is to make custom method in repository and annotate it with @Query.
But there's gonna be a lot of different sorting scenarios. And more importantly, we are using JPA Criteria API (or Spring Specifications) to dynamically build other filtering restrictions.
One thing I came up with is @Formula:
class Message {
/*
...
*/
@Formula("(select * from " +
"(select s.saved from message m " +
"join dispatch d on d.message_id = m.message_id " +
"join status s on s.dispatch_id = d.dispatch_id " +
"where m.message_id = message_id " +
"and d.destination = 'MOSCOW' and s.code = 'SENT') " +
"where rownum = 1)")
private Date sentToMoscow;
//getters & setters
}
But it looks ugly even when it's alone. If I add more, it will be a disaster.
So the question is how can I implement sorting and keep my job?
How to avoid using global in C to detect setting of variable?
I have function foo() which is called from two different code flows. Lets say these two code flows have two different functions calling foo()
bar() and tar()
I want to do make some decision on the basis of which function(bar() or tar()) has called foo(). Currently, I am setting global variable IN_BAR = 1; in case of bar() and IN_BAR = 0; in case of tar. Then I check the value of "IN_BAR" in foo() and do something.
int IN_BAR = 0; // global
void bar () {
...
IN_BAR = 1;
foo();
IN_BAR = 0;
..
}
void tar() {
...
foo();
...
}
void foo() {
...
if (IN_BAR)
do_this();
else
do_that();
}
Currently, there is a lot of places (in codebase) which look like this. I want to avoid using globals and setting & resetting of global variables. Is there way to handle the above mentioned situation? Or is there a design flaw here?
Is it a good idea to create a CRUD Manager?
Environment: I am working with microservice architecture with java programming language. In my project, there are couple of service classes and each service class have a separate controller class above. The project also uses Spring data, so we have repository classes, too.
The job of the controller classes is just providing the rest path and calling the related service class.
Service classes do all the work with help of some manager classes for complex computations. Each service class has more than 15 methods.
Repository classes just do the db calling as a standard usage in every project.
The db has approximately 10 tables.
The problem: When I do many repository calls from a service class I need to create so many try and catch blocks to handle exceptions coming from the db. I created some private methods in the service classes to do these calls from one point to prevent creating more try and catch blocks. But I still need to copy these private methods to make the same repository call from another service class. This causes code repetition.
My solution: I think to create a CRUD Manager which handles the repository calls and exceptions coming from the db using static methods. So that I can handle the exceptions at one point and can do the same repository call without duplicating my code.
The Question: Is it a good practice to create a CRUD Manager? Is there any cons to create a CRUD Manager? Do you have other suggestions?
Microservices and the "single point of failure" concept
One concept I don't entirely understand is the single point of failure. It seems to me that whenever you have multiple services, say A
, B
and C
, involved in an entire system, then if any of them is down the system as a whole can't do anything that useful (If the system could be useful without B
, then why is B
even needed in the first place?).
For example, let's say we have a pipeline such that A
publishes an event that is consumed by B
and then B
publishes a message that is consumed by C
and this flow of data is how the whole system serves its purpose.
A ===> B ===> C
Maybe C
is the service that processes credit card information: the business isn't really running if no money is coming in!
Since this is a messaging system, these services are "independent" in the sense that if one goes down it does not cause another to go down. Ok, but if B
goes down then C
won't receive any new messages and the entire system isn't serving it's purpose. So, what difference does it make having separate services A
, B
and C
rather than one service ABC
?
Difference between Dispatcher and event emitter when using flux in an React application?
In flux flow, we dispatch actions to store --> store will handle action and emit event --> the views listens to the event and give a call to the store to get the data.
Here I am confused since the time I am using react, For emitting an event from the store why should we use event emitter library and why not dispatcher?
Is there any specific reason that every one use some emitting library while emitting the change from the store instead of Dispatcher?
Is there any good solution to resolve cross-reference between two class in c++?
My use case is following
class Caller
{
init(){ Callee.init(); }
callMeByCalle() { //do something }
}
class Callee
{
init(){ //initialize to receive IPC call from another process }
onHandlerIPC { //call A class's callMeByCalle() in here }
}
Maybe I can pass the instance of A class when I call init() of Callee. But I think it could cause a cross-reference problem. Is there any formal or famous solution for this situation?
Efficient multi-row vector
I need an efficient implementation of a vector with multiple rows, each having the same number of columns, which is not too ugly in C++. Currently I have the following:
class BaseVector {
protected: // variables
int64_t _capacity;
int64_t _nColumns;
protected:
template<typename taItem> void Allocate(taItem * &p, const int64_t nItems) {
p = static_cast<taItem*>(MemPool::Instance().Acquire(sizeof(taItem)*nItems));
if (p == nullptr) {
__debugbreak();
}
}
template<typename taItem> void Reallocate(taItem * &p, const int64_t newCap) {
taItem *np;
Allocate(np, newCap);
Utils::AlignedNocachingCopy(np, p, _nColumns * sizeof(taItem));
MemPool::Instance().Release(p, _capacity * sizeof(taItem));
p = np;
}
// Etc for Release() operation
public:
explicit BaseVector(const int64_t initCap) : _capacity(initCap), _nColumns(0) { }
void Clear() { _nColumns = 0; }
int64_t Size() const { return _nColumns; }
};
class DerivedVector : public BaseVector {
__m256d *_pRowA;
__m256i *_pRowB;
uint64_t *_pRowC;
uint8_t *_pRowD;
// Etc. for other rows
public:
DerivedVector(const int64_t nColumns) : BaseVector(nColumns) {
Allocate(_pRowA, nColumns);
Allocate(_pRowB, nColumns);
Allocate(_pRowC, nColumns);
Allocate(_pRowD, nColumns);
// Etc. for the other rows
}
void IncSize() {
if(_nColumns >= _capacity) {
const int64_t newCap = _capacity + (_capacity >> 1) + 1;
Reallocate(_pRowA, newCap);
Reallocate(_pRowB, newCap);
Reallocate(_pRowC, newCap);
Reallocate(_pRowD, newCap);
// Etc. for other rows
_capacity = newCap;
}
_nColumns++;
}
~DerivedVector() {
// Call here the Release() operation for all rows
}
};
The problem with this approach is that there can be 30 rows, so I have to type manually (and repeat myself) 30 times Allocate
, 30 times Reallocate
, 30 times Release
, etc.
So is there a way in C++ to keep this code DRY and fast? I am ok with macros, but not heavy polymorphism in each access to a cell in the vector because this would kill performance.
Multi inheritance and design pattern
In the facebook-python-business-sdk library, I've seen something that I thought it was bad practice :
AdAccountUserMixin's get_pages() method uses self.iterate_edge() which is neither a method of this class nor a parent.
AbstractCrudObject implements this method.
And then, AdAccountUser inherits from these two classes. That's why an object of AdAccountUser can use the method get_pages().
Minimal example :
class Bar:
def bar(self, x):
return x
class Foo:
def foo(self, x):
return self.bar(x)
class Test(Foo, Bar):
def test(self, x):
return self.foo(x)
t = Test()
t.test(5) # returns 5
Is this a design pattern, something that you see everyday or just a bad practice ?
Wrap RabbitMQ Connection in a singleton class
I have read that when I use RabbitMQ the best practice is to use one connection per process, so I would like to create a singleton class for the rabbitmq connection. I would like to use the Lazy version of Singleton from: Implementing the Singleton Pattern in C#
I write this class:
public class RabbitConnection
{
private static readonly Lazy<RabbitConnection> Lazy = new Lazy<RabbitConnection>(() => new RabbitConnection());
private RabbitConnection()
{
IConnectionFactory connectionFactory = new ConnectionFactory
{
HostName = "127.0.0.1",
Port = 5672,
UserName = "Username",
Password = "********"
};
Connection = connectionFactory.CreateConnection();
}
public static RabbitConnection Instance
{
get { return Lazy.Value; }
}
public IConnection Connection { get; }
}
And use this like:
var channel = RabbitConnection.Instance.Connection.CreateModel();
channel.QueueDeclare("myQueue", true, false, false, null);
....
Is this implementation right or wrong? Thank you
DI & MVC: What's the point of dependency injection in controllers?
Short ver
Sometimes I see a piece of code where a dependency is injected into the constructor of a controller, but what advantage does it offer?
Long ver
Let's assume that you're seeing code like the following one.
//ASP.NET
public class SampleController : Controller
{
private IDependency dependency;
public SampleController(IDependency dependency)
{
this.dependency = dependency;
}
}
Or, if you prefer PHP, let's have a look at the following one
//PHP with Laravel
namespace App\Http\Controllers;
class SampleController extends Controller
{
private $dependency;
public function __construct(Dependency $dependency)
{
$this->dependency = $dependency;
}
}
As far as I know, Dependency Injection is meant to decouple a client from its dependency, so that...
- the client can use different dependencies at run time (with a setter method)
- updating the dependency class is less likely to force you to update the client too
...etc.
However, controllers are not instantiated,
$service = new Service();
$controller = new Controller($service);
//you don't do such a thing, do you?
....nor do controllers use setter functions (usually).
Nonetheless, I still see this approach on the internet, including ASP.NET's doc.
Is it really beneficial to inject a dependency into a controller rather than instantiating a class within the constructor with the new
keyword? (If so, how does this approach improve your code?)
mardi 26 février 2019
Nodejs Design Pattern for splitting business and server logic
need some help on logging in nodejs.
In my company, we have several micro-services like cart, orders, payments & also we have lot of internal libs which can also some functions shared between micro-services.
we are following the below pattern in our code base
- routes (defined the routes)
- handlers (here the route handler for all the routes declared)
- managers (this is where business logic lies, these files does not have request / server) - These are pure functions which can be reused even if we change the framework
Let say i create a request-id at server.ext(‘onRequest’) and attach it to request.id to mark every unique requests. Now i can use that reqId logging until handlers alone.
Let also consider in this case i am using pino logger, where every request decorated with request.logger / even hapi has request.log and server.log()
1. Now how can i track the request even in the manager files without passing request / server object.
2. How to track requests between micro-services ?
3. How to track the requests between lib's ?
I have went through cls-hooked
module (using async_hooks) looks like it has memory leaks and increases cpu usage and it is still experimental.
How do you guys manage this in your application ?
Do you pass the requestId as param for every function all along the way to the libraries ?
When does improving program cohesion worsen coupling?
I recently took an exam on design principles & patterns, and one of the questions in the exam was as follows : "Sometimes improving program cohesion may worsen coupling, give an example."
From what I understand, cohesion is how focused a class/module is on fixing a problem it was created to fix, or better, how good is it at doing it job. Does it do jobs it should not be doing? Then move that part to a different class/module.
Coupling is the level of dependency between many classes/modules. Meaning that a good class/module will work regardless of whether or not we introduce major changes to a different module/class.
A way I used to explain this to myself is this example : A bartenders job is to make coffee and other drinks. A good bartender should do his job, which is making said coffee, and this increases his cohesion, but if he starts mopping the floor and serving customers, he is breaking away from his job, and thus the cohesion is lost. A good bartender also should not be affected by other staff members, meaning that his coupling is low. I other words, if the cleaning lady does not show up to work one morning, his job should be unaffected.
So if my understanding is correct, this means that increasing cohesion should not have a negative impact on coupling, just like telling a bartender to focus on coffee more won't make him more dependent on the cleaning lady.
Am I missing something? Is my understanding of cohesion/coupling flawed? Sorry for the long read!
Pattern match interface for Java 8 showing compiler Warning
I am building a command line tool that should validate some logic and if that fails it should print the error and exit, some of that logic could throw a runtime exception. I am using below java BiConsumer Interface.
BiConsumer<Consumer<T>,String> tryOrDie =
(block,msg)->
{
try
{
block.accept((T) this);
}
catch (Throwable t)
{
log.error(t.getMessage(), t);
log.error(msg);
System.exit(-1);
}
};
So for example if my block would get other processes running this tool. This could be called like this to get other UNIX java processes with the name of this program (MyProgram)
final String currentPid=ManagementFactory.getRuntimeMXBean().getName();
currentPid=currentPid.substring(0,currentPid.indexOf("@"));
String GET_ALERT_PID="ps -ef | grep MyProgram | grep -v grep | tr -s ' ' | cut -d ' ' -f 2";
tryOrDie.accept(y->{
otherPids = new BufferedReader(new InputStreamReader(Wrap.startProcess(GET_ALERT_PID))).lines().map(String::trim)
.filter(pid -> !pid.equalsIgnoreCase(currentPid))
.collect(Collectors.toList());
}, "Could not determine if other running processIds of IsawsvcAlert were running");
The code works as expected, however I still get compiler warning Type safety: Unchecked cast from IsawsvcAlert to T on line
block.accept((T) this);
Could this cause any memory leak or another issue? Is there any help to remove this type safety in the compiler? That would be helpful.
What's the difference between Design pattern, Architectural pattern, Architectural style, and Architecture?
Can anyone please describe the differences between Design pattern, Architectural pattern, Architectural style, and Architecture? Thanks in advance.
How to implement simple MVC design patern in swift?
I am new to MVC design pattern. I created "DataModel" it will make an API call, create data, and return data to the ViewController using Delegation and "DataModelItem" that will hold all data. How to call a DataModel init function in "requestData" function. Here is my code.
protocol DataModelDelegate:class {
func didRecieveDataUpdata(data:[DataModelItem])
func didFailUpdateWithError(error:Error)
}
class DataModel: NSObject {
weak var delegate : DataModelDelegate?
func requestData() {
}
private func setDataWithResponse(response:[AnyObject]){
var data = [DataModelItem]()
for item in response{
if let tableViewModel = DataModelItem(data: item as? [String : String]){
data.append(tableViewModel)
}
}
delegate?.didRecieveDataUpdata(data: data)
}
}
And for DataModelItem :
class DataModelItem{
var name:String?
var id:String?
init?(data:[String:String]?) {
if let data = data, let serviceName = data["name"] , let serviceId = data["id"] {
self.name = serviceName
self.id = serviceId
}
else{
return nil
}
}
}
Controller :
class ViewController: UIViewController {
private let dataSource = DataModel()
override func viewDidLoad() {
super.viewDidLoad()
dataSource.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
dataSource.requestData()
}
}
extension ViewController : DataModelDelegate{
func didRecieveDataUpdata(data: [DataModelItem]) {
print(data)
}
func didFailUpdateWithError(error: Error) {
print("error: \(error.localizedDescription)")
}
}
Does single responsibility principal ideally means striving for a class that has a single member function?
I know about single responsibility principal that class should have responsibility for one thing, or should have only one reason to change or should just do one thing.
The question is about the art of achieving this goal.
Should we be essentially striving for a class that have essentially just have ONE main method and of course it may have other helper methods?
In other words, we are kind of replacing a traditional long function with a class?
For example
class ExportFile
{
public:
virtual void Export(string fileName) = 0;
};
class ExportExcel : public ExportFile
{
public:
virtual void Export(string fileName) //= 0;
{
cout << "Export data to excel" << endl;
}
};
int main()
{
string fileName = "c:\\test\\myfile.dat";
ExportFile * excelExport = new ExportExcel();
excelExport->Export(fileName);
return 0;
}
I do see advantages this way that I can implement different strategies easily if I want to export file to say a pdf because I only have to override one simple function and create other internal functions as needed.
I guess I am looking for validation. Could this be frown upon that this class is too light, does too little and it should be better left as method of some other class?
Apply Value Object (Stringly Typed) in PHP
What is the best way to prevent wrong states in an object? This is the source of my question.
Basically my curiosity started with the intention of not letting a class exist with wrong values. Prevent programmers from making mistakes in class implementations and extensions.
I did not want a class to even bother to have to deal with a wrong value. I just wanted it not to be started if a wrong value of a given status or type was passed.
I work a lot with types in string, due to a demand for legacy code. For this I find it interesting to work with "value objects". That aparently is the primary design idea. I tried to go for something with stringly-typed (another new term I just found out).
So below I have the first example. The scenario is: a class need a type and instead invoke a string 'type_x' invoke a class and this class solving the value if it is valid. This class is the one we will see below.
/**
* StringlyTypeSecondOption
*/
class StringlyTypeFirstOption
{
private $type;
public static function type_1()
{
return new self('type_1');
}
public static function type_2()
{
return new self('type_2');
}
private function __construct(string $type)
{
$this->type = $type;
}
public function __toString()
{
return $this->type;
}
}
echo StringlyTypeFirstOption::type_2(); //here its ok
echo StringlyTypeFirstOption::type_3(); //here we have an error cause type_3 doesnt exists
This is a very good example because we havent no if or throw exception or any logic of verification. Is oop on its own. And I think its good.
And now we have the second example. Will provide a solution for the same problem I proposed.
class StringlyTypeSecondOption
{
private $type;
const TYPE1 = 'type_1';
const TYPE2 = 'type_2';
private const ALLOWED_TYPES = [StringlyTypeSecondOption::TYPE1, StringlyTypeSecondOption::TYPE2];
public static function factory($type)
{
if (!in_array($type, StringlyTypeSecondOption::ALLOWED_TYPES, true)) {
throw new Exception("Invalid type: {$type}");
}
return new self($type);
}
private function __construct(string $type)
{
$this->type = $type;
}
public function __toString()
{
return $this->type;
}
}
echo StringlyTypeSecondOption::factory('type_2'); //here its ok
echo StringlyTypeSecondOption::factory('type_3'); //here we have an exception cause type_3 doesnt exists
Is a very good example too but I already have some logic and is not so pure like the first one. But solve the problem like a charm too.
Both imlementations have strengths and weaknesses (I think). But if there is a consolidated design that fixes allowed values for a state of a class, what its name how to implement and what is the best oop beatiful and designed strategy to prevent an invalid value in an object?
I think this is more a discussion over an exact solution. If this was not the right place I ask the moderators to direct me to a better channel.
Thanks advance!
Database design that support only softdelete and softupdate
We have a requirement to design a relational database database. Requirement is given below
- Tables should allow only insert.
- Every table will have "LastUpdatedDate" and "LastUpdatedAuthor" information.
- If the table requires delete operation on records, then table will have "EffectiveStartDate" and "EffectiveEndDate".
- Every table will have Effective Start Date column.
- Every Update will be treated as an insert with latest timestamp in LastupdatedDate field with Author name.
- Every Delete will update the rocod's EffectiveEndDate to previous date and considered as inactive records.
- Tables should not suppert hard delete and soft delete.
Based on this requirement, my colleague has designed a table as below.
USER_IDINT PRIMARY KEY
STREETVARCHAR(50) NOT NULL,
ZIPCODEVARCHAR(50) NULL DEFAULT NULL,
LAST_CHANGED_USERVARCHAR(50) NOT NULL,
LAST_CHANGED_DTTIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
PREVIOUS_RECORD_IDVARCHAR(50) NULL DEFAULT NULL,
EFFECTIVE_START_DTDATE NOT NULL,
EFFECTIVE_END_DTDATE NOT NULL,
Here, if we need to update a record, we will create a new record and old records Effective end date will be updated with past date and a new record will be created with changed data. Also, PREVIOUS_RECORD_ID of the old record will be updated with new records ID and PREVIOUS_RECORD_ID of the new record will be "Null".
Do you think this is a good approach, especially updating PREVIOUS_RECORD_ID ? what are the problems with this approach. What is the best design pattern for this requirement.
lundi 25 février 2019
Multiple Receivers in a command's execute method in command pattern
I have a command which is implementing the Execute() method defined in ICommand interface.I need to call the actions which are defined in multiple receivers,How do we instantiate multiple receiver objects in the Execute() method?.Can we use multiple receivers in a single Command object?
Using Command design pattern to eliminate duplicate code
Let's say I have a program which can create and delete files. And I have 2 different ways of doing that - either execute external utilities, which already deal with these actions, or implement the creation and deletion from within my program. I want to have the choice of both and select the appropriate one dynamically, during runtime. So I would have interfaces and implementations similar to this:
class IFile:
def create():
pass
def delete():
pass
class ExecFile(IFile):
def create():
# Call an external executable
def delete():
# Call an external executable
class ImplFile(IFile):
def create():
# Implement creation of the file
def delete():
# Implement deletion of the file
This way, I can select either of them during runtime and use it. But what if I decide to create another implementation, which is a mix between ExecFile
and ImplFile
, therefore the create()
function will be the same as in ExecFile
but delete the same as in ImplFile
(or some combination of them). I thought of solving this problem using the command design pattern and do something like the following:
class IFile:
def create():
pass
def delete():
pass
class IFileAction:
def exec():
pass
class ExecCreateFile(IFileAction):
def exec():
# Call an external executable to create file
class ImplCreateFile(IFileAction):
def exec():
# Implement creation of the file
class ExecDeleteFile(IFileAction):
def exec():
# Call an external executable to delete file
class ImplDeleteFile(IFileAction):
def exec():
# Implement deletion of the file
class ExecFile(IFile):
def create():
ExecCreateFile().exec()
def delete():
ExecDeleteFile().exec()
class ImplFileIFile(IFile):
def create():
ImplCreateFile().exec()
def delete():
ImplDeleteFile().exec()
class ExecImplFile(IFile):
def create():
ExecCreateFile().exec()
def delete():
ImplDeleteFile().exec()
Question: Would it be appropriate to use this design pattern in this particular case, or something better could be done? My only concern here is that if the example was more sophisticated, let's say I added an option to get file size, get file owner, etc..., I would end up creating multiple classes of type IFileAction, which basically perform only one action.
P.S This might be a bad example, but couldn't think of anything better. Also, the question does not particularly refer to Python, just used it in order to show a code example.
Functional Programming: How to handle complex data without bloated functions?
Lets say in your program you have defined a complex car object. That object holds a very long list of predefined key value pairs (wheels
,engine
,color
, lights
, amountDoors
etc.), each being either a part number or a list of part number, or a specific value.
//** PSEUDO CODE:
var inputCar = {
"engine": "engine-123",
"lights": ["light-type-a", "light-type-b"],
"amountDoors": 6,
etc ... lets assume a lot more properties
}
Lets also assume, this object is already as simple as possible and can not be further reduced.
Additionally we have a list of settings, that tells us more information about the part numbers and is different for each kind of part. For the engine it could look like this:
var settingsEngine = [
{ "id": "engine-123", weight: 400, price: 11000, numberScrews: 120, etc ... },
{ "id": "engine-124" etc ... }
]
With all the settings being bundled in a main settings object
settings = { settingsEngine, settingsWheel, settingsLight ... }
Now we have different functions that are supposed to take a Car
and return certain values about it, like weight, price or number of screws.
To calculate those values its necessary to match the IDs from the input car, with those from the settings, and also apply some logic to get the exact data of complex parts (to figure out what the autobody looks like, we need to see how many doors there are, how big the wheels are etc.).
Getting the price would also be different and arbitrarily complex for each part of the car. Each part of the pricing could need to access different parts and information about the car, so just mapping over a parts list wouldn't suffice. (For the price of the paint job we would need the total surface area of all parts with the same color etc.)
One idea would be to create an inbetween object, that has resolved all the details about the car that are shared between the price and weight calculations and can then be used to calculate the weight, price etc.
One implementation could look like that:
var detailedCar = getDetailedCar(inputCar, settings);
var priceCar = getPriceCar(detailedCar);
var weightCar = getWeightCar(detailedCar);
This way part of the work has only to be done once. But in this example detailedCar
would be an even more complex object than the initial input object, and therefor so would be the parameter of getPriceCar
- making it also really hard to test, because we would always need a full car object for each test case. So I am not sure if that is a good approach.
Question
What is a good design pattern for a program that handles complex input data that can't be further simplified in a functional programming style/with pure functions/composition?
How can the the result be easily unit-testable given a complex, interdependent input?
Which Design patten to use in this situation?
I'm working on project where I send scan request to Nessus and Nessus send the results to my application. I want to use the return scan results and extract if there are vulnerabilities if so. I want to rank these vulnerabilities automatically using CVSS and send the results to ServiceNow ( another application via API). this should be done automatically.
which DRP to use in this situation? enter image description here
The meaning of Factory Pattern
What is the main meaning of using Factory Pattern?
- At the beginning we have a Simple Factory
class FanFactory : IFanFactory
{
public IFan CreateFan(FanType type)
{
switch (type)
{
case FanType.TableFan:
return new TableFan();
case FanType.CeilingFan:
return new CeilingFan();
case FanType.ExhaustFan:
return new ExhaustFan();
default:
return new TableFan();
}
}
}
Although it violates the Principle of SOLID, it seems logical. Using one factory object I can create any other.
- Factory method
static void Main(string[] args)
{
IFanFactory fanFactory = new PropellerFanFactory();
IFan fan = fanFactory.CreateFan();
fan.SwitchOn();
Console.ReadLine();
}
In this case, I could do as well:
IFan fan = new PropellerFan();
fan.SwitchOn();
What was the purpose of Factory Method? You can not see the simplification of the code in it. If we use inheritance in classes and in a child we add a method other than in the parent, then everything loses meaning.
dimanche 24 février 2019
What is the 8 elements in the Gang of Four Book?
can you guys help me briefly describe the (8) elements in the Gang of Four Book about design pattern.
Thank you.
Python - Observer design pattern, sending data between Observers?
thanks for taking a look,
I'd like to start out by saying that I've taken a good look at similar questions on Stackoverflow, but they were not satisfactory.
I'm implementing the Observer design pattern for a project in python. The idea is that you have classes (Observers) that listen for (observe) a certain event, and when that event occurs it triggers all the callback functions associated with that event.
My issue is that I've hit a roadblock with this pattern - and the pattern is not at fault. Most of the events that can occur in my program are simply fired and thereby trigger the appropriate callbacks, and no other data or information is required between observers (GOOD). However, there is one scenario in which I would like to fire a specific event AND send some data to the associated callback. I realize this isn't really something you'd try to do with the observer pattern (it's meant to decouple things), so I'm open to alternative/additional patterns that are more suited.
Below you'll find a minimal example of what I'm trying to achieve. It works, but I don't really like it. Here are my Observer and Event classes:
class Observer:
observers = []
def __init__(self):
self.observers.append(self)
self.events = {}
def observe(self, event_type, callback):
self.events[event_type] = callback
class Event:
from enum import Enum
class Type(Enum):
ACTION_PROGRAM_START = 0
ACTION_SEND_DATA = 1
def __init__(self, event_type, auto_fire=True, data=None):
self.event_type = event_type
self.data = data
if auto_fire:
self.fire()
def fire(self):
for observer in Observer.observers:
if self.event_type in observer.events:
callback = observer.events[self.event_type]
try:
callback()
except TypeError:
callback(data=self.data)
And here are the classes that inherit from Observer:
class DataGenerator(Observer):
def __init__(self):
super(DataGenerator, self).__init__()
self.observe(Event.Type.ACTION_PROGRAM_START, self.on_program_start)
def on_program_start(self):
print("DataGenerator on_program_start triggered")
def send_data(self):
data = [1, 2, 3]
Event(Event.Type.ACTION_SEND_DATA, data=data)
class DataDisplay(Observer):
def __init__(self):
super(DataDisplay, self).__init__()
self.observe(Event.Type.ACTION_PROGRAM_START, self.on_program_start)
self.observe(Event.Type.ACTION_SEND_DATA, self.on_send_data)
def on_program_start(self):
print("DataDisplay on_program_start triggered")
def on_send_data(self, *, data):
print(f"DataDisplay got data {data}")
def main():
dataGenerator = DataGenerator()
dataDisplay = DataDisplay()
Event(Event.Type.ACTION_PROGRAM_START)
dataGenerator.send_data()
return 0
if __name__ == "__main__":
from sys import exit
exit(main())
Program output:
DataGenerator on_program_start triggered
DataDisplay on_program_start triggered
DataDisplay got data [1, 2, 3]
As you can see, there are events (ACTION_PROGRAM_START) whose associated callbacks (on_program_start) do not accept any additional data (which is the norm in this pattern). However, the DataGenerator must send data to the DataDisplay, and I would like to do it by way of an Event (or something that feels like an Event, if that makes sense). I would like for the DataGenerator not to know about the DataDisplay, which is why the impulse is to somehow "pack" the data along with the Event.
As I'm sure you've noticed, the hacky way I've managed to implement this is by simply trying to invoke a given event's associated callback with no arguments, and if that fails, provide the optional data parameter. DataDisplay.on_send_data is the only callback that takes advantage of this - in my actual project, there are many more event types, and all of them except one actually use the optional data parameter in this way. It is for this reason that I would also like to avoid changing the signature of all my callbacks to accept optional data parameters, because there is really only one callback that takes advantage of it.
So I guess the real question is this: Is this solution really as hacky as I think? My solution really seems to go against the grain of the observer pattern. I was thinking about using decorators in some way, but I can't seem to realize the idea. Any help is appreciated - sorry if it's broad.
Is Android's View.OnClickListener usage in Views is an example of Strategy pattern?
Is OnClickListener in android an example of Strategy pattern ? In another Stackoverflow question accepted answer says it is Observer Pattern.
Similar Code to understand the question.
public interface OnClickListener{
void onClick(View view);
}
public class Button extends View{
private OnClickListener listener;
void clicked(){
//some code
if(listener != null){
listener.onClick(this);
}
//some other code
}
public void setOnClickListener(OnClickListener listener){
this.listener = listener;
}
}
My reasoning to believe its strategy pattern and not observer pattern :
- Here we see
Button
class does not has a list of listeners(Observers) but can have only one listener. - It delegates a part of method to its instance member : listener.
OnClickListener
is similar to a strategy where user code implements an strategy (method) to be invoked once button is clicked.
How to avoid need for User code knowing and instantiating concrete Strategy in Strategy Pattern
Strategy pattern decouples the context code and strategies (or algorithm or policy) being used by it. It has an advantage over 'Template Pattern' as it enables dynamic behavior change and uses composition with delegation to achieve it. Below is such example.
public class Context{
private Policy policy;
public void setPolicy(Policy policy){
this.policy = policy;
}
public performTask(){
policy.apply(); // delegate policy apply to separate class
this.contextualWOrk();
}
}
public interface Policy{
void apply();
}
public class PolicyX{
public void apply(){
//Policy X implementation
}
}
public class PolicyY{
public void apply(){
//Policy Y implementation
}
}
Now the Code using above code
public class User{
public void init(Context context){
context.setPolicy(new PolicyX());
context.performTask();
}
}
Above we see the user code has to know and supply concrete Policy to Context. We can have 'Factory method pattern' but still in such a case user code will have to know the concrete Factory class. This requires user code to instantiate and know about existence of such concrete implementations.
To prevent this a simple solution can be having a static method taking input as string or enum and using 'switch-case' or multiple 'if-else' statements deciding which class to instantiate and provide the implementation to user code. But again this violates 'OCP' as in case of addition of a new type will require the code to be modified.
How this can be made to follow principles in simple application (I am not sure may be with some configurations Spring and other frameworks solves such issues).
Any hints or key points to solve this in simple application will be helpful.
I have a big pojo with exhaustive data and i want to create attribute sets out of them efficiently that different services may use
The problem statement is simple. I have a big pojo with several properties and i want to logically organize them into sets.
eg.
class A{
Property prop1, prop2, prop3..... propn;
}
I want to have several property sets.
Eg. -
Set A has { prop1, prop3, prop5, propn}
Set B has {prop1, prop2, prop4, prop5}
Set C has {prop1, prop2, propn_1, propn}
....
Suppose, some service A wants setA of data i could return that. Or if some service wants setA&setB, i could do that as well.
My question is:
Can this be elegantly represented in java OOP design. Is there any design pattern that can fit here. Plus it would be really great if i could just return a abstract or generic pojo from the layer thats interacts with the pojo A. At the api layer, if I could just do returnedPojo.build() or something like that and just serialize - that would be great.
TIA.
How does an LRU cache fit into the CAP theorem?
I was pondering this question today. An LRU cache in the context of a database in a web app helps ensure Availability with fast data lookups that do not rely on continually accessing the database.
However, how does an LRU cache in practice stay fresh? As I understand it, one cannot garuntee Consistency along with Availibility. How is a frequently used item, which therefore does not expire from the LRU cache, handle modification? Is this an example where in a system that needs C over A, an LRU cache is not a good choice?
Clarifying composition relationships
I have read that for composition relationships, component objects must exist during the life cycle of the container, and the container deletion may destroy the component objects.
If there are three classes Home, Office and HomeOffice, can it be said that the relationship between HomeOffice and Home/Office is composition as without Home and office, HomeOffice cannot exist. I am unsure as I saw some conflicting answers on composition that the container deletion must destroy component objects.
samedi 23 février 2019
How to avoid multiple times if elif elif else condition using python design pattern and solid principle
-
I want to refactor the code using python design pattern and solid principle.
-
In my code there are multiple if elif elif else conditions. but i want to remove the multiple if elif condition
if self.description and self.bank and self.split: print("India") elif self.train: print("Maharashtra") elif self.split: print("Pune") else: print("Mumbai)
How can i refactor the multple if elif elif else condition using python solid principles and design patterns?
Is it feasible and suitable if Builder Pattern construct object from database value instead of parameter input
Designing one of the application, here one of the scenario is like,
1) pull data from database Or API and 2) post to API
so, It looks like, this suite to Builder design pattern as follow:
I did not see example where builder pattern is used to construct object by reading data from database. Is it suitable pattern while constricting object from database or API retrieved data OrElse, its wrong design ? Example:
public class ResultBuilder
{
private IList<Parts> _parts;
private IList<Dealers> _dealers;
private int resultSetId;
public ResultBuilder(int resultSetId)
{
this.resultSetId = resultSetId;
}
public ResultBuilder PrepareParts()
{
//call to PartsService and pull from database based on resultSetId and prepare List<Parts>.
}
public ResultBuilder PrepareDealer()
{
//call to DealerService and pull from database and prepare List<Dealer>.
}
public IList<Dealers> Build()
{
//Build Dealers and Parts mapping for Dealer.Parts and return;
}
}
client: ResultBuilder.PrepareParts().PrepareDealer().Build();
Design approach for identifying domain and redirecting to api
We have developed an "api/logapi/api" which sits on abc.com domain (prod) and dev.abc.com(pre prod) which is a relative path.
It is accessed as "abc.com/logapi/api" for prod and dev.abc.com/logapi/api for pre prod
This api is called under a component wrapper(React JS) which makes call and sends logs to Prepared and prod environments
Problem: When this api is consumed in different domain then this fails because since its a relative path , the other domain gets appended and fails.
In that case this API fails. How to avoid this problem ?
My Solution: I will maintain a config where I list all the different domains and its environments like below
[
{
url: xyz.com,
env: prod
},
{
url: dev.gbh.com,
env: pre - prod
},
{
url: qa.xyz.com,
env: pre - prod
}
]
My Log component when accessed from different domain will react the Window location and compare it with the matching URL In config file Iam maintaining.
If I find a match I will get env whtether its Prod or Pre prod, then I will call my abc.com api with ABSOLUTE URL.
I am looking for a more best practice solution.
Is overriding dependency prodivers considered bad style?
I am reimplementing something like Python Dependency Injector in D programming language. I want to build a pure dependency injection framework for D.
Is overriding of providers considered bad style? It seems that overriding of providers is clearly a nonlocal dependency and nonlocal dependencies are usually considered a bad style by OOP theoretics.
So should I or should I not implement overriding of providers in my pure dependency injection framework for D?
Adding Custom Design To My Python Application
I've been looking around for different frameworks or GUIs so I can add my own designs made with prototyping software. So far I found a lot of information but it's not very clear. It's easy to design a Javascript Application but it seems to complicate for Python. Any advise?
DDD - how to model aggregate root?
I have a domain called product_catalog. In my domain a Brand can owns many products. (1 to Many relationship) A category could have many products, and a product could belong to many categories. It's a N-to-M relationship.
If I design product as the aggregate root, it will make no sense to retrieve product to create a brand. Besides that, I need to retrieve all brands and make it possible for the user create more brands So I suspect that Brand is an aggregate root too. Is that right?
What about categories and product?
How to create a tree-hierarchical structure with unique behavior for every type combination?
Assume:
- There is some module whose interface is
IA
. - There is some module
B
, that takes in a parameter an instance ofIA
, and whose behavior depends upon the type of thatIA
,
meaning (pseudo code, no specific language)
class B{
IA ia;
B(IA ia){
this.ia = ia;
}
doStuff(){
if(type(this.ia)==A1){
print("A1");
}
if(type(this.ia)==A2){
print("A2");
}
}
}
I realize I could add some public method foo
to ia
, and thus the code would simplify to
class B{
IA ia;
B(IA ia){
this.ia = ia;
}
doStuff(){
this.ia.foo();
}
}
My question is twofold:
-
What is the correct design to achieve this if I (for some reason) can't change
IA
, meaning, I can't addfoo()
? -
What is the correct (scalable) design if I am allowed to change
IA
but the same problem now repeats forA1
,A2
, and so on, meaning
the final desired behavior is
class B{
IA ia;
B(IA ia){
this.ia = ia;
}
doStuff(){
if(type(this.ia)==A1){
if(type(this.ia.iz)==Z1){
print("A1Z1");
print("unique treatment");
}
if(type(this.ia.iz)==Z2){
print("A1Z2");
print("special treatment");
}
}
if(type(this.ia)==A2){
if(type(this.ia.iz)==Z1){
print("Z1A2");
print("one of a kind treatment");
}
if(type(this.ia.iz)==Z2){
print("Z2A2");
print("Wow treatment");
}
}
}
}
and can repeat more times.
Please notice Z1 and Z1 are the same for A1 and A2!. And again, the same can go on, IZ
can contain IX
of several types, with unique behaviors
I wonder if case 2 is at all separate of modular, in the sense that, the behavior is unique for every type-combination, and no behavior can really be extracted to a more abstract level.
I still don't like the type checking, and wonder if there is something that can be done which looks better.
Pattern module issues (NLP learning)
I've been learning NLP text classification via book "Text Analytics with Python". It's required several modules to be installed in a virtual environment. I use Anaconda env. I created a blank env with Python 3.7 and installed required pandas, numpy, nltk, gensim, sklearn... then, I have to install Pattern. The first problem is that I can't install Pattern via conda because of a conflict between Pattern and mkl_random.
(nlp) D:\Python\Text_classification>conda install -c mickc pattern Solving environment: failed
UnsatisfiableError: The following specifications were found to be in conflict:
- mkl_random
- pattern
Use "conda info <package>" to see the dependencies for each package.
It's impossible to remove mkl_random because there're related packages: gensim, numpy, scikit-learn etc. I don't know what to do, I didn't find any suitable conda installations for Pattern that is accepted in my case. Then, I installed Pattern using pip. Installation was successful. Is it okay to have packages from conda and from pip at the same time?
The second problem, I think, is connected with the first one. I downloaded the book's example codes from https://github.com/dipanjanS/text-analytics-with-python/tree/master/Old-First-Edition/source_code/Ch04_Text_Classification, added brackets to Python 2.x 'print' functions and run classification.py The program raised an exception:
Traceback (most recent call last):
File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 609, in _read
raise StopIteration
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "classification.py", line 50, in <module>
norm_train_corpus = normalize_corpus(train_corpus)
File "D:\Python\Text_classification\normalization.py", line 96, in normalize_corpus
text = lemmatize_text(text)
File "D:\Python\Text_classification\normalization.py", line 67, in lemmatize_text
pos_tagged_text = pos_tag_text(text)
File "D:\Python\Text_classification\normalization.py", line 58, in pos_tag_text
tagged_text = tag(text)
File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\en\__init__.py", line 188, in tag
for sentence in parse(s, tokenize, True, False, False, False, encoding, **kwargs).split():
File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\en\__init__.py", line 169, in parse
return parser.parse(s, *args, **kwargs)
File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 1172, in parse
s[i] = self.find_tags(s[i], **kwargs)
File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\en\__init__.py", line 114, in find_tags
return _Parser.find_tags(self, tokens, **kwargs)
File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 1113, in find_tags
lexicon = kwargs.get("lexicon", self.lexicon or {}),
File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 376, in __len__
return self._lazy("__len__")
File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 368, in _lazy
self.load()
File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 625, in load
dict.update(self, (x.split(" ")[:2] for x in _read(self._path) if len(x.split(" ")) > 1))
File "C:\Users\PC\Anaconda3\envs\nlp\lib\site-packages\pattern\text\__init__.py", line 625, in <genexpr>
dict.update(self, (x.split(" ")[:2] for x in _read(self._path) if len(x.split(" ")) > 1))
RuntimeError: generator raised StopIteration
I don't understand what is happening. Is the exception raised because my installation with pip, or the problem is in the wrong or deprecated code in the book... and is it possible to install Pattern in conda with all other necessary packages.
Thank you in advance!
How to implement Decorator pattern in Spring Boot
I know how to implement and use a decorator pattern without Spring.
Because in this pattern you yourself control the process of creating components and you can perform dynamic behavior adding.
Below is an example of implementation without using Spring:
public class SimpleDecoratorApp {
public static void main(String[] args) {
SimplePrinter simplePrinter = new SimplePrinter();
Printer decorated = new UpperCasePrinterDecorator(
new AddAsterisksPrinterDecorator(simplePrinter)
);
decorated.print("hello"); // *** HELLO ***
}
}
interface Printer {
void print(String msg);
}
class SimplePrinter implements Printer {
@Override
public void print(String msg) {
System.out.println(msg);
}
}
abstract class PrinterDecorator implements Printer {
protected Printer printer;
public PrinterDecorator(Printer printer) {
this.printer = printer;
}
}
class UpperCasePrinterDecorator extends PrinterDecorator {
public UpperCasePrinterDecorator(Printer printer) {
super(printer);
}
@Override
public void print(String msg) {
String s = msg.toUpperCase();
this.printer.print(s);
}
}
class AddAsterisksPrinterDecorator extends PrinterDecorator {
public AddAsterisksPrinterDecorator(Printer printer) {
super(printer);
}
@Override
public void print(String msg) {
msg = "*** " + msg + " ***";
this.printer.print(msg);
}
}
I am interested in how to implement the same example but with the help of spring beans.
Because I don’t quite understand how to maintain flexibility in the ability to simply wrap with any number of decorators.
Because as I understand it - it will be implemented fixed in some separate component and I will have to create dozens of various separate components with the combinations of decorators I need.
vendredi 22 février 2019
How should this plugin system (of diagram transformations) work?
This is a code-free question as obviously my project is quite big, and there's no specific problem to show you. I have a UX design question. I'm looking for those who know at least what a functor is to answer. Below is a screen shot of the state of the app before a user might click the "Functor" plugin button on the left.
They have arrow "f" selected so the Functor plugin button would then highlight showing that it's enabled because the user selected something it can work with: an arrow that is connected to a domain and range.
However, some plugins may require the ability to look at the whole graph themselves and analyze all possible applications. I might show this to the user with a slider that goes through the applications of a plugin and highlights each one individually as the user slides the slider.
So I'll probably want to use both approaches since a Functor only requires a single arrow and it would be ridiculous to slider through all arrows of the diagram.
Any other ideas or features that you'd like to see?
Clean way to implement messagebox pattern in react
Is there a clean way to implement a message box pattern in react like so?
import MessageBox from "MessageBox";
class MyComponent {
render () {...}
onDeleteButtonClick = async (data) => {
let result = await MessageBox.show("Delete?", "Sure you want to delete this?", MessageBox.Buttons.OkCancel);
if(result === MessageBox.Result.Ok) {
// do delete
}
}
There does not seem to be a way to this without resorting to refs, breaking promise rules (making deferreds), or doing DOM trickery (having a wrapper that renders a component).
I built a component that followed my API above, except with a callback, but it required a ref and felt like I wasn't building things the react way.
Why does .net core encourage you to create interfaces for all of your dependencies?
I am reading Microsoft's documentation on dependency injection, and I keep seeing the same pattern. The author will define some kind of service, create an interface for the service, and then add the interface to the service collection as an injectable dependency.
public class MyService : IMyService {
}
_
public interface IMyService {
}
Then in startup, in your ConfigureServices method, you register your service like this
services.AddScoped<IMyService>();
Then in a controller or another class, you will inject the interface as a dependency
public class SampleDataController : Controller {
private readonly IMyService _service;
public SampleDataController(IMyService service) {
_service = service;
}
It seems to me like you could just as easily do away with the interface. What are the benefits of defining your dependencies in this way?
Design Pattern for RateLimited API calls
I have a service class, which needs to call different apis from other service. But each API have some limits, So I am using Guava's Ratelimiter to enforce the limit of the operation
@Singleton
public class A {
private final RateLimiter apiCallX;
private final int timeoutInSecondsForAPIX;
private final RateLimiter apiCallY;
private final int timeoutInSecondsForAPIY;
@Inject
public A ( @Named("apiCallXRateLimiter") apiCallX,
@Named("apiCallXRateLimiter") apiCallY,
@Named("apiCallXRateLimiter") apiCallZ,
){
this.apiCallX = apiCallX;
...
}
public ResponseX callAPIX (){
...
}
public ResponseY callAPIY (){
...
}
private modelTransformer(){ //each for request and response and for each call.
...
}
}
I am thinking to use inheritance to avoid clustering all the operation calls from this class. What are the other design patterns I could use in this scenario?
Ioc Inversion of Control is pattern?
https://www.tutorialsteacher.com/ioc/introduction
there are information about Ioc. According to the information here , Ioc is principle
but
according to here ("The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code")
Ioc is pattern
which one is right ?
How Adapter Pattern Resolve Dependencies?
I have a question with the Adapter Pattern. I am implementing this pattern because I have a third-party library and don’t want to depend upon it.
However, I dont’t get why creating the IAdapter and the Adapter in the same proyect will remove a dependency.
Because if the third-party library changes, the package need to be recompiled, so also any class that uses the IAdapter also needs to be recompiled.
Does the IAdapter and the Adapter must be in different packages?
Template method and inheritance or composition
I have next classes:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Admin {
private String name;
private int age;
}
And I have some operations with template method pattern implimentation. Base Class with algorithm:
public abstract class Operation<T> {
public void process(T t){
System.out.println(t);
updateName(t);
System.out.println(t);
}
protected abstract void updateName(T t);
}
two childs with implementation template method:
@Component
public class UserOperation extends Operation<User> {
@Override
protected void updateName(User user) {
String newName = user.getName().toUpperCase();
user.setName(newName);
}
}
@Component
public class AdminOperation extends Operation<Admin> {
@Override
protected void updateName(Admin admin) {
String name = admin.getName();
StringBuilder builder = new StringBuilder();
builder.append(name);
StringBuilder reverse = builder.reverse();
admin.setName(reverse.toString());
}
}
My questions:
1) How do I rewrite this code to use the composition?
2) Do I understand correctly that when using the template method, I attach to inheritance?
The template method is a great way to avoid duplication. But if it binds me to inheritance, what other ways are there to avoid code duplication? in my example, how can I use composition? (replace the template method with something else?)
Backend/App: Pattern for Changed Text Detection
I am implementing an Android app in Cordova which communicates with a REST API backend. The app uses i18n by Cordova using JSON dictionaries with translations. However, some more dynamic texts are provided by the backend to enable flexibility such that they can be changed without the need of updating the app.
For accepting the Terms of Service and the Data Protection Policy, a mechanism is required which detects whether the user already accepted the current version. As there is no user profile in the backend (just an ID derived by the device ID), it should be implemented client-side.
Approach 1: My approach was to just take a hash (MD5, SHA3 or similar) of the text and store it with a accepted flag into the local storage. If the user restarts the app, the hash from the backend's response is recalculated and compared. If the hash changed, the user needs to re-accept the terms.
However, this solution does not work well with i18n. Because if the user changes the language, the text received also changes and as a result, the user needs to reaccept the terms though the terms did not necessarily change.
Of course, the idea could be simply extended to hash the text of all given languages. Although I think it is not a well-designed and extensible solution.
Approach 2: My next idea was to generate a server-based identification attribute for each text, like a GUID. This could be implemented in a way such that each update (there's an POST
endpoint for that) of a text bundle (multiple languages) automatically generates a new GUID. The same GUID is then sent—independent of the desired text language—to the app.
What do you think about the approaches? Are there any more broadly used and straightforward concepts for that?
jeudi 21 février 2019
How was UIAlertViewController's initializer implemented?
This is a design question. I am creating a custom view controller programmatically, but when I try to customize the initializer for it, I must call designated initializer on its superclass.
Either:
init(nibName: String?, bundle: Bundle?)
or
init?(coder: NSCoder)
The problem is, one requires a decoder, which I don't intend to provide with my custom initializer, and another which requires a nibName and I don't intend to use a nib. I'm doing this programmatically.
How was UIAlertViewController implemented so that its initializer can function without taking a nib and an instance of NSCoder?
Where do the common utilities go in Strategy pattern
I need to enable 2 components of my software according to multiple conditions. So, I am thinking to use strategy pattern. On high level, based on the parameter, I will check which software component eligibility need to be checked (I may need to check both sometimes). Both of the strategies will be using some common methods & parameters. But from the tutorials, I couldn't get the information regarding where should these common parameters exist & how these will be accessed by the strategies. I am implementing this in java. Please suggest.
Version number in event sourcing aggregate?
I am building Microservices. One of my MicroService is using CQRS and Event sourcing. Integration events are raised in the system and i am saving my aggregates in event store also updating my read model.
My questions is why we need version in aggregate when we are updating the event stream against that aggregate ? I read we need this for consistency and events are to be replayed in sequence and we need to check version before saving. I still can't get my head around this since events are raised and saved in order , so i really need concrete example to understand what benefit we get from version and why we even need them.
Many thanks,
Imran
Loose coupling for logging classes
I'm trying to make a class (actually 2) that will encapsulate some specific logging/telemetry technology. They are used in a decorator to log requests, like so:
var manager = new SpecificTelemetryManager();
....
public void PostRequest(string body)
{
var telem = manager.Start();
controller.PostRequest();
manager.Stop(telem);
}
I have this:
ITelemetryManager.cs
public interface ITelemetryManager
{
ITelemetryOperation Start(string operationName);
void Stop(ITelemetryOperation op);
}
ITelemetryOperation.cs
public interface ITelemetryOperation<T> : IDisposable
{
T Operation { get; set; }
void AddCustomProperties(IDictionary<string, string> customProperties);
}
SpecificTelemetryManager.cs (does not compile)
public class SpecificTelemetryHandler : ITelemetryManager
{
private Client _client { get; set; }
public SpecificTelemetryHandler()
{
_client = new Client();
}
public ITelemetryOperation Start(string name)
{
return new SpecificTelemetryOperation(_client.Start(name));
}
public void Stop(ITelemetryOperation op)
{
_client.StopOperation(op.Operation); // !!! THIS DOESNT KNOW THE TYPE
}
}
SpecificTelemetryOperation.cs
public class SpecificTelemetryOperation : ITelemetryOperation<SomeMicrosoftClass>
{
public SomeMicrosoftClass Operation { get; set; }
public ApplicationInsightsTelemetryOperation(SomeMicrosoftClass op)
{
Operation = op;
}
public void AddCustomProperties(IDictionary<string, string> customProperties)
{
Operation.Props.AddRange(customProperties);
}
public void Dispose()
{
Operation.Dispose();
}
}
Can anyone please provide some ideas on how to keep ITelemetryManager typeless (non generic) (so it won't be ITelemetryManager<Iwhatever>
) and make sure that outside classes (the decorator) don't know what type of telemetry operations they are working on (Microsoft, AWS, Google, etc...). I want SpecificTelemetryManager
and SpecificTelemetryOperation
to have all the concrete classes that they would be referencing.
Design pattern for overcoming the reverse constructor order?
I have the following problem:
The base class expects to receive some data but the data is initialized by the derived class constructor which in C# is called after the base constructor was called.
Simplified example:
class Base
{
string _s;
protected Base(string s)
{
_s = s.ToLower();
}
}
class Derived : Base
{
public Derived(string path) : base(...)
{
// string can only be initialized at this point
}
}
Question:
How can I run some code in derived class first, so I can pass the result to the base constructor ?
Implementation of construction + view pattern example
Was working through an example of a design pattern called Constructor + View by the author that was explained through types but was having trouble figuring out the implementation.
This is the module signature:
module User : {
type t;
type view = { name: string, age: int };
let make: (~name:string, ~age:int) => option(t);
let view: t => view;
};
So User.t
is hidden but from one function you can pattern match the user record
At first was thinking User.t
and User.view
could have the same fields:
module User: {
type t;
type view = { name: string, age: int, };
let make: (~name: string, ~age: int) => option(t);
let view: t => view;
} = {
type t = { name: string, age: int, };
type view = { name: string, age: int, };
let make = (~name, ~age) => Some({name, age});
let view = t => {name: t.name, age: t.age};
};
But got an error that looks like it can't tell the difference between view
and t
:
Values do not match:
let make: (~name: string, ~age: int) => option(view)
is not included in
let make: (~name: string, ~age: int) => option(t)
Tried a couple more things, the first just taking out make
and trying to get the view
function to work but same issue:
module User: {
type t;
type view = { name: string, age: int, };
let view: t => view;
} = {
type t = { name: string, age: int, };
type view = { name: string, age: int, };
let view = t => {name: t.name, age: t.age};
};
with error:
Values do not match:
let view: view => view
is not included in
let view: t => view
The second try was for having the view
type be a subset of the fields (which was the use case I was hoping to use this pattern) but this has the same error as above:
module User: {
type t;
type view = { name: string, age: int, };
let view: t => view;
} = {
type t = { name: string, age: int, email: string };
type view = { name: string, age: int, };
let view = t => {name: t.name, age: t.age};
};
My question here is if there's a way to implement something to fit the first module signature with User.view
being the same fields or subset of fields as User.t
? Can make it work if the records have different fields or if I separate the records by modules but curious about that specific use case.
the best way to get an action result
I'm curious if getting an action result is a valid approach, and if it is then how to do that?
For example let's say I have a page with form for creating entities, after successful entity creation I'd like to redirect user to entity's detail view, otherwise (on failure) update the form by error messages. I'd like to perform that without mixing up application layers (eg. to not redirect user in epic/effect after success).
I have a few approaches to this problem in mind:
-
dispatch a "trigger" action (
entity_add
), then dispatch a success (entity_add_success
) or failure (entity_add_failure
) action somewhere in my epic/effect, wait for failure or success action and do an action - this approach has a noticable drawback: other entities may be created meanwhile and how to distinguish the failure/success actions of entities in that case? -
dispatch a trigger action with additional callback parameter which should be called when action result becomes determined, this approach has a drawback as well (not as big as the previous one though): possibility of creating callback hell.
-
give up at using flux in that case, use services directly, design drawback: mixing application layers
I'd be glad to hear any ideas.
Where to transform Redux state for use in UI
I have a list of "Events":
{
id: 1,
description: "Did something",
date: <date>,
eventTypeId: 1
}
I fetch these Events in componentDidUpdate and then they are passed to my component as a prop form redux connect mapStateToProps - they come from a "selector" - getEvents.
I want to display them on react-big-calendar which wants them in this format -
Event {
title: string,
start: Date,
end: Date,
allDay?: boolean
resource?: any,
}
Where do I transform them from my object to the react-big-calendar object?
It seems like this must occur in the component, so if I switch to another calendar libary, my redux code would remain unchanged.
Is there a standard pattern for doing this? Should I just do this directly in my render method?
render() {
let bigCalEvents = this.props.events.map(e => <big cal event>);
....
}
Or is there a better way to do this?
Looking for a Design Pattern or Library
Is there a specific design pattern I could use to generate a string expression with some nested conditions?
Given:
Builder.red().and().blue().or(white().and().black()).toString()
Result should be:
red and blue or ( white and black )
Initially I started using the builder pattern (maybe it's not the appropriate one) but I got stuck when I had to generate the nested condition. Ideally the usage should be like in the above snippet (method chaining).
I need that for a java project (version 8) and the generated expression will be used as spring expression language (couldn't find a spring utility class that does that).
How do i make a tree data structure that can hold two differnet generic types for parent and children
I am ashamed to admit that I am sitting on this problem for many many hours. But I just want to implement it the way I have it structured in the diagramm below....
I want to model the world with continents/countrys/states and citys in it. Each model has a reference to its parent and a list of references to its children except the world only has children (because there cant be a parent to it) and the city only has a parent-reference because it doesnt go deeper. (I want to implement it that for example "World" does not have a parent field, likewise "city" does not have a List < Children > field.
I was about to implement it in a tree data structure like following (I left out the implementations):
To give you an idea of the code of the interfaces I included the bare minimum of it here:
public interface IRoot<TChild>
{
List<TChild> Children { get; set; }
void AddChild(TChild child);
}
public interface ILeaf<TParent>
{
TParent Parent { get; set; }
}
public interface INode<TParent, TChild> : IRoot<TChild>, ILeaf<TParent> { }
And a little code of the implementation:
public class Root<TChild> : IRoot<TChild>
{
public List<TChild> Children { get; set; }
public void AddChild(TChild child) { //... }
}
public class Leaf<TParent> : ILeaf<TParent>
{
public TParent Parent { get; set; }
}
public class Node<TParent, TChild> : INode<TParent, TChild>
{
private IRoot<TChild> root;
private ILeaf<TParent> leaf;
//...
}
Lastly the code of the classes I want to structure:
public class World : Root<Continent> { }
public class Continent : Node<World, Country> { }
public class Country : Node<Continent, State> { }
public class State : Node<Country, City> { }
public class City : Leaf<City> { }
Here comes the Problem:
Now to Add a child object in Root.AddChild(TChild) I need to access < TChlid >.Parent so I would need to constraint the generic TChild to "ILeaf< IRoot < TChild >>" like this:
public class Root<TChild> : IRoot<TChild> where TChild : ILeaf<Root<TChild>>
{
public void AddChild(TChild child)
{
child.Parent = this;
}
}
But doing this, I get the Error
CS0311 C# The type cannot be used as type parameter in the generic type or method. There is no implicit reference conversion from to.
At this line
public class World : Root<Continent> { }
If anyone can help me figure the problem out and find a solution I would sooo appreciate it